repo
string | commit
string | message
string | diff
string |
---|---|---|---|
benjamw/pharaoh | a13f456d20ee45f188387f0b2625ea24d6c33083 | reordered priorities | diff --git a/todo.txt b/todo.txt
index 25cc6d3..f27e27c 100644
--- a/todo.txt
+++ b/todo.txt
@@ -1,39 +1,39 @@
+- build game reader for saved games
+
- update scripts
- use yepnope and cdn
+- add showdown to messages (JS port of Markdown, in zz_scripts_js)
+
+- fully convert times to UTC in MySQL and back to user's timezone
+ everywhere dates are output
+
- there are errors when trying to re-send invites
- make sure everything is working with the invites
- i didn't find any errors =(
- it may be something to do with the resend button being shown
- before it should be, or that the resnd time checker is off
+ before it should be, or that the resend time checker is off
somehow. it's basically failing due to being too new
- make hover tooltips better
- add ability to hit own laser from side as option
- for revisions for setups, allow the same name for the setup and when
a user creates a revision or edits their setup, it creates a new
setup and inactivates the previous setup, and then either sort by
create date, or add a field in the table called revision and
increment that and when we pull the setup, order by created or
revision number, and use the most recent.
- add more stats:
player's most played setup
player's favorite setup
player's worst setup
player's favorite opponent
win-loss per opponent
etc...
-- build game reader for saved games
-
- don't show success messages if email is not sent for things like
- nudge, that are only email dependent
-
-- fully convert times to UTC in MySQL and back to user's timezone
- everywhere dates are output
-
-- add showdown to messages (JS port of Markdown, in zz_scripts_js)
\ No newline at end of file
+ nudge, that are only email dependent
\ No newline at end of file
|
benjamw/pharaoh | b9df9b6148469ca68a5af606b9cca30e0e4eb764 | Removed unneeded method call to fix invite error | diff --git a/invite.php b/invite.php
index 960b66d..a109395 100644
--- a/invite.php
+++ b/invite.php
@@ -1,274 +1,271 @@
<?php
require_once 'includes/inc.global.php';
// this has nothing to do with creating a game
// but I'm running it here to prevent long load
// times on other pages where it would be run more often
GamePlayer::delete_inactive(Settings::read('expire_users'));
Game::delete_inactive(Settings::read('expire_games'));
Game::delete_finished(Settings::read('expire_finished_games'));
if (isset($_POST['invite'])) {
- $Game = new Game( );
-
// make sure this user is not full
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
Flash::store('You have reached your maximum allowed games !', false);
}
test_token( );
try {
- $game_id = $Game->invite( );
- $Game->save( );
+ Game::invite( );
Flash::store('Invitation Sent Successfully', true);
}
catch (MyException $e) {
Flash::store('Invitation FAILED !', false);
}
}
// grab the full list of players
$players_full = GamePlayer::get_list(true);
$invite_players = array_shrink($players_full, 'player_id');
// grab the players who's max game count has been reached
$players_maxed = GamePlayer::get_maxed( );
$players_maxed[] = $_SESSION['player_id'];
// remove the maxed players from the invite list
$players = array_diff($invite_players, $players_maxed);
$opponent_selection = '';
$opponent_selection .= '<option value="">-- Open --</option>';
foreach ($players_full as $player) {
if ($_SESSION['player_id'] == $player['player_id']) {
continue;
}
if (in_array($player['player_id'], $players)) {
$opponent_selection .= '
<option value="'.$player['player_id'].'">'.$player['username'].'</option>';
}
}
$groups = array(
'Normal' => array(0, 0),
'Eye of Horus' => array(0, 1),
'Sphynx' => array(1, 0),
'Sphynx & Horus' => array(1, 1),
);
$group_names = array_keys($groups);
$group_markers = array_values($groups);
$setups = Setup::get_list( );
$setup_selection = '<option value="0">Random</option>';
$setup_javascript = '';
$cur_group = false;
$group_open = false;
foreach ($setups as $setup) {
$marker = array((int) $setup['has_sphynx'], (int) $setup['has_horus']);
$group_index = array_search($marker, $group_markers, true);
if ($cur_group !== $group_names[$group_index]) {
if ($group_open) {
$setup_selection .= '</optgroup>';
$group_open = false;
}
$cur_group = $group_names[$group_index];
$setup_selection .= '<optgroup label="'.$cur_group.'">';
$group_open = true;
}
$setup_selection .= '
<option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>';
$setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n";
}
$setup_javascript = substr(trim($setup_javascript), 0, -1);
if ($group_open) {
$setup_selection .= '</optgroup>';
}
$meta['title'] = 'Send Game Invitation';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">//<![CDATA[
var setups = {
'.$setup_javascript.'
};
/*]]>*/</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/invite.js"></script>
';
$hints = array(
'Invite a player to a game by filling out your desired game options.' ,
'<span class="highlight">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' ,
);
// make sure this user is not full
$submit_button = '<div><input type="submit" name="invite" value="Send Invitation" /></div>';
$warning = '';
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
$submit_button = $warning = '<p class="warning">You have reached your maximum allowed games, you can not create this game !</p>';
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="send"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="player_id" value="{$_SESSION['player_id']}" />
{$warning}
<div><label for="opponent">Opponent</label><select id="opponent" name="opponent">{$opponent_selection}</select></div>
<div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup" class="options">Show Setup</a></div>
<div><label for="color">Your Color</label><select id="color" name="color"><option value="random">Random</option><option value="white">Silver</option><option value="black">Red</option></select></div>
<div class="random_convert options">
<fieldset>
<legend>Conversion</legend>
<p>
If your random game is a v1.0 game, you can convert it to play v2.0 Pharaoh.<br />
Or, if your random game is a v2.0 game, you can convert it to play v1.0 Pharaoh.<br />
</p>
<p>
When you select to convert, more options may be shown below.
</p>
<div><label class="inline"><input type="checkbox" id="rand_convert_to_1" name="rand_convert_to_1" /> Convert to 1.0</label></div>
<div><label class="inline"><input type="checkbox" id="rand_convert_to_2" name="rand_convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .random_convert -->
<div class="pharaoh_1 options">
<fieldset>
<legend>v1.0 Options</legend>
<p class="conversion">
Here you can convert v1.0 setups to play v2.0 Pharaoh.<br />
The conversion places a Sphynx in your lower-right corner facing upwards (and opposite for your opponent)
and converts any double-stacked Obelisks to Anubises which face forward.
</p>
<p class="conversion">
When you select to convert, more options will be shown below, as well as the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_2" name="convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .pharaoh_1 -->
<div class="pharaoh_2 p2_box options">
<fieldset>
<legend>v2.0 Options</legend>
<p class="conversion">
Here you can convert the v2.0 setups to play v1.0 Pharaoh.<br />
The conversion removes any Sphynxes from the board and converts any Anubises to double-stacked Obelisks.
</p>
<p class="conversion">
When you select to convert, the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_1" name="convert_to_1" /> Convert to 1.0</label></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="move_sphynx" name="move_sphynx" /> Sphynx is movable</label></div>
</fieldset>
</div> <!-- .pharaoh_2 -->
<fieldset>
<legend><label class="inline"><input type="checkbox" name="laser_battle_box" id="laser_battle_box" class="fieldset_box" /> Laser Battle</label></legend>
<div id="laser_battle" class="options">
<p>
When a laser gets shot by the opponents laser, it will be disabled for a set number of turns, making that laser unable to shoot until those turns have passed.<br />
After those turns have passed, and the laser has recovered, it will be immune from further shots for a set number of turns.<br />
After the immunity turns have passed, whether or not the laser was shot again, it will now be susceptible to being shot again.
<span class="pharaoh_2"><br />You can also select if the Sphynx is hittable only in the front, or on all four sides.</span>
</p>
<div><label for="battle_dead">Dead for:</label><input type="text" id="battle_dead" name="battle_dead" size="4" /> <span class="info">(Default: 1; Minimum: 1)</span></div>
<div><label for="battle_immune">Immune for:</label><input type="text" id="battle_immune" name="battle_immune" size="4" /> <span class="info">(Default: 1; Minimum: 0)</span></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_front_only" name="battle_front_only" checked="checked" /> Only front hits on Sphynx count</label></div>
<!-- <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_hit_self" name="battle_hit_self" /> Hit Self</label></div> -->
<p>You can set the "Immune for" value to 0 to allow a laser to be shot continuously, but the minimum value for the "Dead for" value is 1, as it makes no sense otherwise.</p>
</div> <!-- #laser_battle -->
</fieldset>
{$submit_button}
<div class="clr"></div>
</div></form>
<div id="setup_display"></div>
EOF;
// create our invitation tables
list($in_vites, $out_vites, $open_vites) = Game::get_invites($_SESSION['player_id']);
$contents .= <<< EOT
<form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv" id="invites">
EOT;
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no received invites to show</p>' ,
'caption' => 'Invitations Received' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" /><input type="button" id="decline-[[[game_id]]]" value="Decline" />', false) ,
);
$contents .= get_table($table_format, $in_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no sent invites to show</p>' ,
'caption' => 'Invitations Sent' ,
);
$table_format = array(
array('Invitee', '###ifenr(\'[[[invitee]]]\', \'-- OPEN --\')') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '###\'<input type="button" id="withdraw-[[[game_id]]]" value="Withdraw" />\'.((strtotime(\'[[[create_date]]]\') >= strtotime(\'[[[resend_limit]]]\')) ? \'\' : \'<input type="button" id="resend-[[[game_id]]]" value="Resend" />\')', false) ,
);
$contents .= get_table($table_format, $out_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no open invites to show</p>' ,
'caption' => 'Open Invitations' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" />', false) ,
);
$contents .= get_table($table_format, $open_vites, $table_meta);
$contents .= <<< EOT
</div></form>
EOT;
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer( );
|
benjamw/pharaoh | 5a82a87ea09f66be755471be347b7a26c84c72fc | minor adjustments to mysql query return | diff --git a/classes/mysql.class.php b/classes/mysql.class.php
index 261b978..2616570 100644
--- a/classes/mysql.class.php
+++ b/classes/mysql.class.php
@@ -1,910 +1,916 @@
<?php
/*
+---------------------------------------------------------------------------
|
| mysql.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
| based on works by W. Jason Gilmore
| http://www.wjgilmore.com; http://www.apress.com
|
+---------------------------------------------------------------------------
|
| > MySQL DB Queries module
| > Date started: 2005-09-02
|
| > Module Version Number: 0.9.2
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
class Mysql
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
protected $link_id; // MySQL Resource ID
protected $query; // MySQL query
protected $result; // Query result
protected $query_time; // Time it took to run the query
protected $query_count; // Total number of queries executed since class inception
protected $error; // Any error message encountered while running
protected $_host; // MySQL Host name
protected $_user; // MySQL Username
protected $_pswd; // MySQL password
protected $_db; // MySQL Database
protected $_page_query; // MySQL query for pagination
protected $_page_result; // MySQL result for pagination
protected $_num_results; // Number of total results found
protected $_page; // Current pagination page
protected $_num_per_page; // Number of records per page
protected $_num_pages; // number of total pages
protected $_error_debug = false; // Allows for error debug output
protected $_query_debug = false; // Allows for output of all queries all the time
protected $_log_errors = false; // write to log file when an error is encountered
protected $_log_path = './'; // Path to the MySQL error log file
protected $_email_errors = false; // send an email when an error is encountered
protected $_email_subject = 'Query Error'; // the email subject for the email message
protected $_email_from = '[email protected]'; // the email address to send error reports from
protected $_email_to = '[email protected]'; // the email address to send error reports to
static private $_instance; // Instance of the MySQL Object
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** protected function __construct
* Class constructor.
* Initializes the host, user, pswd, and db vars.
*
* @param array optional configuration array
* @return void
*/
protected function __construct($config = null)
{
if (empty($config) && isset($GLOBALS['_DEFAULT_DATABASE'])) {
$config = $GLOBALS['_DEFAULT_DATABASE'];
}
// each of these can be set independently as needed
$this->_error_debug = false; // set to true for output of errors
$this->_query_debug = false; // set to true for output of every query
if (empty($config)) {
throw new MySQLException(__METHOD__.': Missing MySQL configuration data');
}
$this->_host = $config['hostname'];
$this->_user = $config['username'];
$this->_pswd = $config['password'];
$this->_db = $config['database'];
$this->_log_path = (isset($config['log_path'])) ? $config['log_path'] : './';
$this->query_time = 0;
$this->query_count = 0;
try {
$this->_log(__METHOD__);
$this->_log('===============================');
$this->connect_select( );
}
catch (MySQLException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor.
* Closes the mysql connection.
*
* @param void
* @action close the mysql connection
* @return void
*/
/*
public function __destruct( )
{
$this->_log(__METHOD__.': '.$this->link_id);
$this->_log('===============================');
return; // just stop doing this
@mysql_close($this->link_id);
$this->link_id = null;
self::$_instance = null;
}
*/
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! property_exists($this, $property)) {
throw new MySQLException(__METHOD__.': Trying to access non-existent property ('.$property.')');
}
if ('_' === $property[0]) {
throw new MySQLException(__METHOD__.': Trying to access _private property ('.$property.')');
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MySQLException(__METHOD__.': Trying to access non-existent property ('.$property.')');
}
if ('_' === $property[0]) {
throw new MySQLException(__METHOD__.': Trying to access _private property ('.$property.')');
}
$this->$property = $value;
}
/** public function set_settings
* Sets the given settings for the object
*
* @param array settings array
* @action updates the settings
* @return void
*/
public function set_settings($settings)
{
$valid = array(
'log_errors',
'log_path',
'email_errors',
'email_subject',
'email_from',
'email_to',
);
foreach ($valid as $key) {
if (isset($settings[$key])) {
$var = '_'.$key;
$this->$var = $settings[$key];
}
}
}
/** public function test_connection
* Tests the connection to the MySQL
* server, and reconnects if needed
*
* @param void
* @action reconnects to the server
* @return void
*/
public function test_connection( )
{
if ( ! mysql_ping( )) {
mysql_close($this->link_id);
$this->connect_select( );
$this->_log('RECONNECT ++++++++++++++++++++++++++++++++++++++ '.$this->link_id);
}
}
/** public function connect
* Connect to the MySQL server.
*
* @param void
* @action connect to the mysql server
* @return void
*/
public function connect( )
{
$this->link_id = @mysql_connect($this->_host, $this->_user, $this->_pswd);
if ( ! $this->link_id) {
$this->error = mysql_errno( ).': '.mysql_error( );
throw new MySQLException(__METHOD__.': There was an error connecting to the server');
}
}
/** public function select
* Select the MySQL database.
*
* @param string [optional] database name
* @action select the mysql database
* @return void
*/
public function select($database = null)
{
if ( ! is_null($database)) {
$this->_db = $database;
}
if ( ! @mysql_select_db($this->_db, $this->link_id)) {
$this->error = mysql_errno($this->link_id).': '.mysql_error($this->link_id);
throw new MySQLException(__METHOD__.': There was an error selecting the database');
}
}
/** public function connect_select
* Connects to the server AND selects the default database in one function.
*
* @param string [optional] database name
* @action connect to the mysql server
* @action select the mysql database
* @return void
*/
public function connect_select($database = null)
{
if ( ! is_null($database)) {
$this->_db = $database;
}
try {
$this->connect( );
$this->select( );
}
catch (MySQLException $e) {
throw $e;
}
$this->_log(__METHOD__.': '.$this->link_id);
$this->_log('-------------------------------');
}
/** public function set_error
* Set the error level based on a bitwise value.
*
* @param int value (0 = none, 3 = all)
* @action set the error level
* @return void
*/
public function set_error($val)
{
$this->_error_debug = (0 != (1 & $val));
$this->_query_debug = (0 != (2 & $val));
}
/** public function query
* Execute a database query
* If no query is passed, it executes the last saved query.
*
* @param string [optional] SQL query string
* @param int [optional] number of tries
* @action execute a mysql query
* @return mysql result resource
*/
public function query($query = null, $tries = 0)
{
if ( ! is_null($query)) {
$this->query = $query;
}
if (is_null($this->query)) {
throw new MySQLException(__METHOD__.': No query found');
}
$backtrace_file = $this->_get_backtrace( );
$this->_log(__METHOD__.' in '.basename($backtrace_file['file']).' on '.$backtrace_file['line'].' : '.$this->query);
if (empty($this->link_id)) {
$this->connect_select( );
}
$done = true; // innocent until proven guilty
// start time logging
$time = microtime_float( );
$this->result = @mysql_query($this->query, $this->link_id);
$this->query_time = microtime_float( ) - $time;
if ($this->_query_debug && empty($GLOBALS['AJAX'])) {
$this->query = trim(preg_replace('/\\s+/', ' ', $this->query));
if (('cli' == php_sapi_name( )) && empty($_SERVER['REMOTE_ADDR'])) {
echo "\n\nMYSQL - ".basename($backtrace_file['file']).' on '.$backtrace_file['line']."- {$this->query} - Aff(".$this->affected_rows( ).") (".number_format($this->query_time, 5)." s)\n\n";
}
else {
echo "<div style='background:#FFF;color:#009;'><br /><strong>".basename($backtrace_file['file']).' on '.$backtrace_file['line']."</strong>- {$this->query} - <strong>Aff(".$this->affected_rows( ).") (".number_format($this->query_time, 5)." s)</strong></div>";
}
}
if ( ! $this->result) {
if ((5 >= $tries) && ((2013 == mysql_errno($this->link_id)) || (2006 == mysql_errno($this->link_id)))) {
// try reconnecting a couple of times
$this->_log('RETRYING #'.$tries.': '.mysql_errno($this->link_id));
$this->test_connection( );
return $this->query(null, ++$tries);
}
$extra = '';
if ($backtrace_file) {
$line = $backtrace_file['line'];
$file = $backtrace_file['file'];
$file = substr($file, strlen(realpath($file.'../../../')));
$extra = ' on line <strong>'.$line.'</strong> of <strong>'.$file.'</strong>';
}
$this->error = mysql_errno($this->link_id).': '.mysql_error($this->link_id);
$this->_error_report( );
if ($this->_error_debug) {
if (('cli' == php_sapi_name( )) && empty($_SERVER['REMOTE_ADDR'])) {
$extra = strip_tags($extra);
echo "\n\nMYSQL ERROR - There was an error in your query{$extra}:\nERROR: {$this->error}\nQUERY: {$this->query}\n\n";
}
else {
echo "<div style='background:#900;color:#FFF;'>There was an error in your query{$extra}:<br />ERROR: {$this->error}<br />QUERY: {$this->query}</div>";
}
}
else {
$this->error = 'There was a database error.';
}
$done = false;
}
if ($done) {
// if we just performed an insert, grab the insert_id and return it
- if (preg_match('/^\s*(INSERT|REPLACE)/i', $this->query)) {
+ if (preg_match('/^\s*(?:INSERT|REPLACE)\b/i', $this->query)) {
$this->result = $this->fetch_insert_id( );
}
$this->query_count++;
return $this->result;
}
- // no result found
- return false;
+ if (preg_match('/^\s*SELECT\b/i', $this->query)) {
+ // no result found
+ return false;
+ }
+ else {
+ // query performed successfully
+ return true;
+ }
}
/** public function affected_rows
* Return the number of affected rows from the latest query.
*
* @param void
* @return int number of affected rows
*/
public function affected_rows( )
{
$count = @mysql_affected_rows($this->link_id);
return $count;
}
/** public function num_rows
* Return the number of returned rows from the latest query.
*
* @param void
* @return int number of returned rows
*/
public function num_rows( )
{
$count = @mysql_num_rows($this->result);
if ( ! $count) {
return 0;
}
return $count;
}
/** public function insert
* Insert the associative data array into the table.
* $data['field_name'] = value
* $data['field_name2'] = value2
* If the field name has a trailing space: $data['field_name ']
* then the query will insert the data with no sanitation
* or wrapping quotes (good for function calls, like NOW( )).
*
* @param string table name
* @param array associative data array
* @param string [optional] where clause (for updates)
* @param bool [optional] whether or not we should replace values (true / false)
* @action execute a mysql query
* @return int insert id for row
*/
public function insert($table, $data_array, $where = '', $replace = false)
{
$where = trim($where);
$replace = (bool) $replace;
if ('' == $where) {
$query = (false == $replace) ? ' INSERT ' : ' REPLACE ';
$query .= ' INTO ';
}
else {
$query = ' UPDATE ';
}
$query .= '`'.$table.'`';
if ( ! is_array($data_array)) {
throw new MySQLException(__METHOD__.': Trying to insert non-array data');
}
else {
$query .= ' SET ';
foreach ($data_array as $field => $value) {
if (is_null($value)) {
$query .= " `{$field}` = NULL , ";
}
elseif (' ' == substr($field, -1, 1)) { // i picked a trailing space because it's an illegal field name in MySQL
$field = trim($field);
$query .= " `{$field}` = {$value} , ";
}
else {
$query .= " `{$field}` = '".sani($value)."' , ";
}
}
$query = substr($query, 0, -2).' '; // remove the last comma (but preserve those spaces)
}
$query .= ' '.$where.' ';
$this->query = $query;
$return = $this->query( );
if ('' == $where) {
return $this->fetch_insert_id( );
}
else {
return $return;
}
}
/** public function multi_insert
* Insert the array of associative data arrays into the table.
* $data[0]['field_name'] = value
* $data[0]['field_name2'] = value2
* $data[0]['DBWHERE'] = where clause [optional]
* $data[1]['field_name'] = value
* $data[1]['field_name2'] = value2
* $data[1]['DBWHERE'] = where clause [optional]
*
* @param string table name
* @param array associative data array
* @param bool [optional] whether or not we should replace values (true / false)
* @action execute multiple mysql queries
* @return array insert ids for rows (with original keys preserved)
*/
public function multi_insert($table, $data_array, $replace = false)
{
if ( ! is_array($data_array)) {
throw new MySQLException(__METHOD__.': Trying to multi-insert non-array data');
}
else {
$result = array( );
foreach ($data_array as $key => $row) {
$where = (isset($row['DBWHERE'])) ? $row['DBWHERE'] : '';
unset($row['DBWHERE']);
$result[$key] = $this->insert($table, $row, $where, $replace);
}
}
return $result;
}
/** public function delete
* Delete the row from the table
*
* @param string table name
* @param string where clause
* @action execute a mysql query
* @return result
*/
public function delete($table, $where)
{
$query = "
DELETE
FROM `{$table}`
{$where}
";
$this->query = $query;
try {
return $this->query( );
}
catch (MySQLException $e) {
throw $e;
}
}
/** public function multi_delete
* Delete the array of data from the table.
* $table[0] = table name
* $table[1] = table name
*
* $where[0] = where clause
* $where[1] = where clause
*
* If recursive is true, all combinations of table name
* and where clauses will be executed.
*
* If only one table name is set, that table will
* be used for all of the queries, looping through
* the where array
*
* If only one where clause is set, that where clause
* will be used for all of the queries, looping through
* the table array
*
* @param mixed table name array or single string
* @param mixed where clause array or single string
* @param bool optional recursive (default false)
* @action execute multiple mysql queries
* @return array results
*/
public function multi_delete($table_array, $where_array, $recursive = false)
{
if ( ! is_array($table_array)) {
$recursive = false;
$table_array = (array) $table_array;
}
if ( ! is_array($where_array)) {
$recursive = false;
$where_array = (array) $where_array;
}
if ($recursive) {
foreach ($table_array as $table) {
foreach ($where_array as $where) {
$result[] = $this->delete($table, $where);
}
}
}
else {
if (count($table_array) == count($where_array)) {
for ($i = 0, $count = count($table_array); $i < $count; ++$i) {
$result[] = $this->delete($table_array[$i], $where_array[$i]);
}
}
elseif (1 == count($table_array)) {
$table = $table_array[0];
foreach ($where_array as $where) {
$result[] = $this->delete($table, $where);
}
}
elseif (1 == count($where_array)) {
$where = $where_array[0];
foreach ($table_array as $table) {
$result[] = $this->delete($table, $where);
}
}
else {
throw new MySQLException(__METHOD__.': Trying to multi-delete with incompatible array sizes');
}
}
return $result;
}
/** public function fetch_object
* Execute a database query and return the next result row as object.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return mysql next result object row
*/
public function fetch_object($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_object($this->result);
return $row;
}
/** public function fetch_row
* Execute a database query and return result as an indexed array.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array indexed mysql result array
*/
public function fetch_row($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_row($this->result);
if ( ! $row) {
$row = array( );
}
return $row;
}
/** public function fetch_assoc
* Execute a database query and return result as an associative array.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array associative mysql result array
*/
public function fetch_assoc($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_assoc($this->result);
if ( ! $row) {
$row = array( );
}
return $row;
}
/** public function fetch_both
* Execute a database query and return result as both
* an associative array and indexed array.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array associative and indexed mysql result array
*/
public function fetch_both($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_array($this->result, MYSQL_BOTH);
if ( ! $row) {
$row = array( );
}
return $row;
}
/** public function fetch_array
* Execute a database query and return result as
* an indexed array of both indexed and associative arrays.
* This method returns the entire result set in a single call.
*
* @param string [optional] SQL query string
* @param int [optional] SQL result type ( One of: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH )
* @action [optional] execute a mysql query
* @return array indexed array of mysql result arrays of type $result_type
*/
public function fetch_array($query = null, $result_type = MYSQL_ASSOC)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$arr = array( );
while ($row = @mysql_fetch_array($this->result, $result_type)) {
$arr[] = $row;
}
return $arr;
}
/** public function fetch_value
* Execute a database query and return result as
* a single result value.
* This method only returns the single value at index 0.
* Each subsequent call to this method returns the next value.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return mixed single mysql result value
*/
public function fetch_value($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_row($this->result);
if (false !== $row) {
return $row[0];
}
else {
// no data found
return null;
}
}
/** public function fetch_value_array
* Execute a database query and return result as
* an indexed array of single result values.
* This method returns the entire result set in a single call.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array indexed array of single mysql result values
*/
public function fetch_value_array($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$arr = array( );
while ($row = @mysql_fetch_row($this->result)) {
$arr[] = $row[0];
}
return $arr;
}
/** public function paginate NOT TESTED
* Paginates a query result set based on supplied information
* NOTE: It is not necessary to include the SQL_CALC_FOUND_ROWS
* nor the LIMIT clause in the query, in fact, including the
* LIMIT clause in the query will probably break MySQL.
*
* @param int [optional] current page number
* @param int [optional] number of records per page
* @param string [optional] SQL query string
* @return array pagination result and data
*/
public function paginate($page = null, $num_per_page = null, $query = null)
{
if ( ! is_null($page)) {
$this->_page = $page;
}
else { // we don't have a page, either increment, or set equal to 1
$this->_page = (isset($this->_page)) ? ($this->_page + 1) : 1;
}
if ( ! is_null($num_per_page)) {
$this->_num_per_page = $num_per_page;
}
else {
$this->_num_per_page = (isset($this->_num_per_page)) ? $this->_num_per_page : 50;
}
if ( ! $this->_page || ! $this->_num_per_page) {
throw new MySQLException(__METHOD__.': No pagination data given');
}
if ( ! is_null($query)) {
$this->_page_query = $query;
// add the SQL_CALC_FOUND_ROWS keyword to the query
if (false === strpos($query, 'SQL_CALC_FOUND_ROWS')) {
$query = preg_replace('/SELECT\\s+(?!SQL_)/i', 'SELECT SQL_CALC_FOUND_ROWS ', $query);
}
$start = ($this->_num_per_page * ($this->_page - 1));
// add the LIMIT clause to the query
$query .= "
LIMIT {$start}, {$this->_num_per_page}
";
$this->_page_result = $this->fetch_array($query);
if ( ! $this->_page_result) {
// no data found
return array( );
}
$query = "
SELECT FOUND_ROWS( ) AS count
";
$this->_num_results = $this->fetch_value($query);
$this->_num_pages = (int) ceil($this->_num_results / $this->_num_per_page);
}
else { // we are using the previous data
if ($this->_num_results < ($this->_num_per_page * ($this->_page - 1))) {
return array( );
}
$query = $this->_page_query;
$start = $this->_num_per_page * ($this->_page - 1);
// add the LIMIT clause to the query
$query .= "
LIMIT {$start}, {$this->_num_per_page}
";
$this->_page_result = $this->fetch_array($query);
if ( ! $this->_page_result) {
// no data found
return array( );
}
}
// clean up the data and output to user
$output = array( );
$output['num_rows'] = $this->_num_results;
$output['num_per_page'] = $this->_num_per_page;
$output['num_pages'] = $this->_num_pages;
$output['cur_page'] = $this->_page;
$output['data'] = $this->_page_result;
return $output;
}
/** public function fetch_insert_id
* Return the insert id for the most recent query.
*
* @param void
* @return int previous insert id
*/
public function fetch_insert_id( )
{
return @mysql_insert_id($this->link_id);
}
|
benjamw/pharaoh | ca5122bb24e32ab889751467f33f1c2a1eb600bc | minor speed improvement by removing is_readable call | diff --git a/includes/func.global.php b/includes/func.global.php
index f1ca927..447ad93 100644
--- a/includes/func.global.php
+++ b/includes/func.global.php
@@ -1,296 +1,296 @@
<?php
/** function call [dump] [debug]
* This function is for debugging only
* Outputs given var to screen
* or, if no var given, outputs stars to note position
*
* @param mixed optional var to output
* @param bool optional bypass debug value and output anyway
* @action outputs var to screen
* @return void
*/
function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false)
{
if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) {
return false;
}
if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) {
$contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>';
}
else {
// begin output buffering so we can escape any html
// and print_r is better at catching recursion than var_export
ob_start( );
if ( ! function_exists('xdebug_disable')) {
if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings
print_r($var);
}
else {
if (is_array($var) || is_object($var)) {
print_r($var);
}
else {
var_dump($var);
}
}
}
else {
var_dump($var);
}
// end output buffering and output the result
if ( ! function_exists('xdebug_disable')) {
$contents = htmlentities(ob_get_contents( ));
}
else {
$contents = ob_get_contents( );
}
ob_end_clean( );
}
$j = 0;
$html = '';
$debug_funcs = array('dump', 'debug');
if ((bool) $show_from) {
$called_from = debug_backtrace( );
if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) {
++$j;
}
$file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT']));
$line0 = $called_from[$j]['line'];
$called = '';
if (isset($called_from[$j + 1]['file'])) {
$file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT']));
$line1 = $called_from[$j + 1]['line'];
$called = "{$file1} : {$line1} called ";
}
elseif (isset($called_from[$j + 1]['class'])) {
$called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called ';
}
$html = "<strong>{$called}{$file0} : {$line0}</strong>\n";
}
if ( ! $new_window) {
$color = '#000';
if ($error) {
$color = '#F00';
}
echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n";
}
else { ?>
<script language="javascript">
myRef = window.open('','debugWindow');
myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">');
myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>');
myRef.document.write('\n<hr /></pre>\n\n');
</script>
<?php }
}
function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); }
function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); }
/** function load_class
* This function automagically loads the class
* via the spl_autoload_register function above
* as it is instantiated (jit).
*
* @param string class name
* @action loads given class name if found
* @return bool success
*/
function load_class($class_name) {
$class_file = CLASSES_DIR.strtolower($class_name).'.class.php';
if (class_exists($class_name)) {
return true;
}
- elseif (file_exists($class_file) && is_readable($class_file)) {
+ elseif (file_exists($class_file)) {
require_once $class_file;
return true;
}
else {
throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found');
}
}
/** function test_token
* This function tests the token given by the
* form and checks it against the session token
* and if they do not match, dies
*
* @param bool optional keep original token flag
* @action tests tokens and dies if bad
* @action optionally renews the session token
* @return void
*/
function test_token($keep = false) {
call($_SESSION['token']);
call($_POST['token']);
if (DEBUG || ('games' == $_SERVER['HTTP_HOST'])) {
return;
}
if ( ! isset($_SESSION['token']) || ! isset($_POST['token'])
|| (0 !== strcmp($_SESSION['token'], $_POST['token'])))
{
die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.');
}
// renew the token
if ( ! $keep) {
$_SESSION['token'] = md5(uniqid(rand( ), true));
}
}
/** function test_debug
* This function tests the debug given by the
* URL and checks it against the globals debug password
* and if they do not match, doesn't debug
*
* @param void
* @action tests debug pass
* @return bool success
*/
function test_debug( ) {
if ( ! isset($_GET['DEBUG'])) {
return false;
}
if ( ! class_exists('Settings') || ! Settings::test( )) {
return false;
}
if ('' == trim(Settings::read('debug_pass'))) {
return false;
}
if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) {
return false;
}
$GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG'];
$GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG'];
return true;
}
/** function expandFEN
* This function expands a packed FEN into a
* string where each index is a valid location
*
* @param string packed FEN
* @return string expanded FEN
*/
function expandFEN($FEN)
{
$FEN = preg_replace('/\s+/', '', $FEN); // remove spaces
$FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s
$xFEN = str_replace('/', '', $FEN); // remove the row separators
return $xFEN;
}
function replace_callback($match) {
return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]);
}
/** function packFEN
* This function packs an expanded FEN into a
* string that takes up less space
*
* @param string expanded FEN
* @param int [optional] length of rows
* @return string packed FEN
*/
function packFEN($xFEN, $row_length = 10)
{
$xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces
$xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators
$xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators
$FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s
return $FEN;
}
/** function ife
* if-else
* This function returns the value if it exists (or is optionally not empty)
* or a default value if it does not exist (or is empty)
*
* @param mixed var to test
* @param mixed optional default value
* @param bool optional allow empty value
* @param bool optional change the passed reference var
* @return mixed $var if exists (and not empty) or default otherwise
*/
function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) {
if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) {
if ((bool) $change_reference) {
$var = $default; // so it can also be used by reference
}
return $default;
}
return $var;
}
/** function ifer
* if-else reference
* This function returns the value if it exists (or is optionally not empty)
* or a default value if it does not exist (or is empty)
* It also changes the reference var
*
* @param mixed var to test
* @param mixed optional default value
* @param bool optional allow empty value
* @action updates/sets the reference var if needed
* @return mixed $var if exists (and not empty) or default otherwise
*/
function ifer( & $var, $default = null, $allow_empty = true) {
return ife($var, $default, $allow_empty, true);
}
/** function ifenr
* if-else non-reference
* This function returns the value if it is not empty
* or a default value if it is empty
*
* @param mixed var to test
* @param mixed optional default value
* @return mixed $var if not empty or default otherwise
*/
function ifenr($var, $default = null) {
if (empty($var)) {
return $default;
}
return $var;
}
|
benjamw/pharaoh | ff7b8fd5f32f5c38beafccf92afa104e13f93658 | fixed issue with message reply and forward subject lines | diff --git a/classes/message.class.php b/classes/message.class.php
index db41ce8..d8bfca0 100644
--- a/classes/message.class.php
+++ b/classes/message.class.php
@@ -1,910 +1,910 @@
<?php
/*
+---------------------------------------------------------------------------
|
| message.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Messaging module
| > Date started: 2008-01-04
|
| > Module Version Number: 1.0.1
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
// TODO: exceptions
class Message
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property MESSAGE_TABLE
* Stores the name of the message table
*
* @param string
*/
const MESSAGE_TABLE = T_MESSAGE;
/** const property GLUE_TABLE
* Stores the name of the glue table
* that joins users to messages
*
* @param string
*/
const GLUE_TABLE = T_MSG_GLUE;
/** protected property _user_id
* Stores the id of the user
*
* @param int
*/
protected $_user_id;
/** protected property _can_send_global
* Stores a flag letting us know if
* the user can send global messages or not
*
* @param bool
*/
protected $_can_send_global;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/** protected property _DEBUG
* Holds the DEBUG state for the class
*
* @var bool
*/
protected $_DEBUG = false;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int user id
* @param bool optional global flag, if set, user can send global messages
* @action instantiates object
* @action deletes expired messages and glue table entries from the database
* @return void
*/
public function __construct($user_id, $global = false)
{
call(__METHOD__);
if (empty($user_id)) {
throw new MyException(__METHOD__.': No user id given');
}
$Mysql = Mysql::get_instance( );
$this->_user_id = (int) $user_id;
$this->_can_send_global = (bool) $global;
$this->_mysql = $Mysql;
if (defined('DEBUG')) {
$this->_DEBUG = DEBUG;
}
// remove any expired messages
$query = "
SELECT DISTINCT message_id
FROM ".self::GLUE_TABLE."
WHERE expire_date < NOW( )
AND expire_date IS NOT NULL
";
$message_ids = $this->_mysql->fetch_value_array($query);
if ($message_ids) {
$this->_mysql->multi_delete(array(self::GLUE_TABLE, self::MESSAGE_TABLE), " WHERE message_id IN (".implode(',', $message_ids).") ");
}
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
$this->$property = $value;
}
/** public function get_inbox_list
* Retrieves the list of messages in the inbox
* both unread and total
*
* @param void
* @return array inbox data
*/
public function get_inbox_list( )
{
call(__METHOD__);
$query = "
SELECT G.*
, IF('' <> M.subject, M.subject, '<No Subject>') AS subject
, P.player_id AS sender_id
, P.username AS sender
, IF(G.send_date IS NOT NULL, G.send_date, G.create_date) AS order_date
, IF(GT.from_id IS NOT NULL, 1, 0) AS global
FROM ".self::GLUE_TABLE." AS G
LEFT JOIN ".self::MESSAGE_TABLE." AS M
ON M.message_id = G.message_id
LEFT JOIN ".Player::PLAYER_TABLE." AS P
ON P.player_id = G.from_id
LEFT JOIN ".self::GLUE_TABLE." AS GT
ON (GT.message_id = G.message_id
AND GT.to_id = 0)
WHERE G.to_id = {$this->_user_id}
AND G.from_id <> {$this->_user_id}
AND (G.send_date < NOW( )
OR G.send_date IS NULL
)
AND G.deleted = 0
ORDER BY order_date DESC
";
$results = $this->_mysql->fetch_array($query);
return $results;
}
/** public function get_outbox_list
* Retrieves the list of messages in the outbox
*
* @param void
* @return array outbox data
*/
public function get_outbox_list( )
{
call(__METHOD__);
// NOTE: DO NOT LOOK FOR SEND DATE, we sent it, we want to see it, ALWAYS...
// that way, we can delete it before it gets sent, if we so desire
// look for our own entry, and if found, run the query to find the recipients
$query = "
SELECT G.*
, IF('' <> M.subject, M.subject, '<No Subject>') AS subject
, ((G.send_date < NOW( )) || G.send_date IS NULL) AS sent
FROM ".self::GLUE_TABLE." AS G
LEFT JOIN ".self::MESSAGE_TABLE." AS M
ON M.message_id = G.message_id
WHERE G.from_id = {$this->_user_id}
AND G.to_id = {$this->_user_id}
AND G.deleted = 0
ORDER BY M.create_date DESC
, M.message_id DESC
, G.to_id ASC
";
$result = $this->_mysql->fetch_array($query);
if ($result) {
foreach ($result as $key => $row) {
// grab all the recipients of this message
$query = "
SELECT *
FROM ".self::GLUE_TABLE."
WHERE message_id = '{$row['message_id']}'
AND to_id <> {$this->_user_id}
ORDER BY to_id ASC
";
$recipients = $this->_mysql->fetch_array($query);
// add the recipients to the message
if ($recipients) {
foreach ($recipients as $recipient) {
if (0 == $recipient['to_id']) {
$row['recipient_data'][] = array(
'id' => $recipient['to_id'] ,
'name' => 'GLOBAL' ,
'viewed' => true
);
break;
}
$row['recipient_data'][] = array(
'id' => $recipient['to_id'] ,
'name' => $GLOBALS['_PLAYERS'][$recipient['to_id']] ,
'viewed' => ( ! is_null($recipient['view_date']))
);
$result[$key] = $row;
}
}
// now convert the recipients for each message to a string
$recip_string = '';
if (is_array($row['recipient_data'])) {
foreach ($row['recipient_data'] as $recipient) {
if (empty($recipient['name'])) {
continue;
}
$recip_string .= ( ! $recipient['viewed']) ? '<span class="highlight">'.$recipient['name'].'</span>, ' : $recipient['name'].', ';
}
}
$result[$key]['recipients'] = substr($recip_string, 0, -2);
}
}
return $result;
}
/** public function get_admin_list
* Retrieves the list of messages that were
* neither sent from or to the current admin
*
* @param void
* @return array message box data
*/
public function get_admin_list( )
{
call(__METHOD__);
// NOTE: DO NOT LOOK FOR SEND DATE
// grab all entries that were neither sent nor received by the current admin
$query = "
SELECT G.*
, IF('' <> M.subject, M.subject, '<No Subject>') AS subject
, ((G.send_date < NOW( )) || G.send_date IS NULL) AS sent
, P.username AS sender
FROM ".self::GLUE_TABLE." AS G
LEFT JOIN ".self::MESSAGE_TABLE." AS M
USING (message_id)
LEFT JOIN ".Player::PLAYER_TABLE." AS P
ON (P.player_id = G.from_id)
WHERE G.message_id IN (
SELECT DISTINCT(message_id)
FROM ".self::GLUE_TABLE."
WHERE message_id NOT IN (
SELECT DISTINCT(message_id)
FROM ".self::GLUE_TABLE."
WHERE from_id = {$this->_user_id}
OR to_id = {$this->_user_id}
)
)
AND G.to_id = G.from_id
ORDER BY M.create_date DESC
, M.message_id DESC
";
$result = $this->_mysql->fetch_array($query);
if ($result) {
foreach ($result as $key => $row) {
// if it's an invitation message, don't show it
if (preg_match('/^Invitation to ("|").+?\1$/i', $row['subject'])) {
unset($result[$key]);
continue;
}
// grab all the recipients of this message
$query = "
SELECT *
FROM ".self::GLUE_TABLE."
WHERE message_id = '{$row['message_id']}'
AND to_id <> {$row['from_id']}
ORDER BY to_id ASC
";
$recipients = $this->_mysql->fetch_array($query);
// add the recipients to the message
if ($recipients) {
foreach ($recipients as $recipient) {
if (0 == $recipient['to_id']) {
$row['recipient_data'][] = array(
'id' => $recipient['to_id'] ,
'name' => 'GLOBAL' ,
'viewed' => true
);
break;
}
$row['recipient_data'][] = array(
'id' => $recipient['to_id'] ,
'name' => $GLOBALS['_PLAYERS'][$recipient['to_id']] ,
'viewed' => ( ! is_null($recipient['view_date']))
);
$result[$key] = $row;
}
}
// now convert the recipients for each message to a string
$recip_string = '';
if (is_array($row['recipient_data'])) {
foreach ($row['recipient_data'] as $recipient) {
if (empty($recipient['name'])) {
continue;
}
$recip_string .= ( ! $recipient['viewed']) ? '<span class="highlight">'.$recipient['name'].'</span>, ' : $recipient['name'].', ';
}
}
$result[$key]['recipients'] = substr($recip_string, 0, -2);
}
}
return $result;
}
/** public function get_message
* Retrieves the message from the database
* but makes sure this user can see this message first
*
* @param int message id
* @param bool is admin
* @action tests to make sure this user can see this message
* @return array message data
*/
public function get_message($message_id, $admin = false)
{
call(__METHOD__);
$message_id = (int) $message_id;
$admin = (bool) $admin;
if (empty($message_id)) {
throw new MyException(__METHOD__.': No message id given');
}
$query = "
SELECT M.*
FROM ".self::MESSAGE_TABLE." AS M
WHERE M.message_id = {$message_id}
";
$message = $this->_mysql->fetch_assoc($query);
if ( ! $message) {
throw new MyException(__METHOD__.': Message not found');
}
// find out who this message was sent by
$query = "
SELECT G.*
, P.username AS recipient
, S.username AS sender
FROM ".self::GLUE_TABLE." AS G
LEFT JOIN ".GamePlayer::EXTEND_TABLE." AS R
ON (R.player_id = G.to_id)
LEFT JOIN ".Player::PLAYER_TABLE." AS P
ON (P.player_id = R.player_id)
LEFT JOIN ".Player::PLAYER_TABLE." AS S
ON (S.player_id = G.from_id)
WHERE G.message_id = '{$message['message_id']}'
ORDER BY recipient
";
$message['recipients'] = $this->_mysql->fetch_array($query);
// parse through the recipients and find out
// if we are allowed to view this message
// and set some various message flags
$message['allowed'] = false;
$message['inbox'] = false;
$message['global'] = false;
foreach ($message['recipients'] as $recipient) {
if ($recipient['from_id'] == $this->_user_id) {
$message['allowed'] = true;
$message['inbox'] = true;
}
if ($recipient['to_id'] == $this->_user_id) {
$message['allowed'] = true;
}
if (0 == $recipient['to_id']) {
$message['global'] = true;
}
}
if ( ! $message['allowed'] && ! $admin) {
throw new MyException(__METHOD__.': Not allowed to view this message');
}
else {
$this->set_message_read($message_id);
}
if ('' == $message['subject']) {
$message['subject'] = '<No Subject>';
}
return $message;
}
/** public function get_message_reply
* Retrieves the message from the database
* but makes sure this user can see this message first
* and then appends data to the message so it can be replied to
*
* @param int message id
* @action tests to make sure this user can see this message
* @action appends data to the subject and message so it can be replied to
* @return array [subject, message, to]
*/
public function get_message_reply($message_id)
{
call(__METHOD__);
try {
$message = $this->_get_message_data($message_id, true);
- $data['subject'] = (0 === strpos($message['subject'], 'RE')) ? $message['subject'] : 'RE: '.$message['subject'];
+ $message['subject'] = (0 === strpos($message['subject'], 'RE')) ? $message['subject'] : 'RE: '.$message['subject'];
}
catch (MyExeption $e) {
throw $e;
}
return $message;
}
/** public function get_message_forward
* Retrieves the message from the database
* but makes sure this user can see this message first
* and then appends data to the message so it can be forwarded
*
* @param int message id
* @action tests to make sure this user can see this message
* @action appends data to the subject and message so it can be forwarded
* @return array [subject, message, to]
*/
public function get_message_forward($message_id)
{
call(__METHOD__);
try {
$message = $this->_get_message_data($message_id, false);
- $data['subject'] = (0 === strpos($message['subject'], 'FW')) ? $message['subject'] : 'FW: '.$message['subject'];
+ $message['subject'] = (0 === strpos($message['subject'], 'FW')) ? $message['subject'] : 'FW: '.$message['subject'];
}
catch (MyExeption $e) {
throw $e;
}
return $message;
}
/** public function set_message_read
* Sets the given messages as read by this user
*
* @param array or csv string message id(s)
* @action sets read date for these messages
* @return void
*/
public function set_message_read($message_ids)
{
call(__METHOD__);
// if we are admin logged in as another player
// don't mark it as read if we view the message
if ( ! empty($_SESSION['admin_id'])) {
return;
}
array_trim($message_ids, 'int');
if (0 != count($message_ids)) {
$WHERE = "
WHERE to_id = '{$this->_user_id}'
AND message_id IN (".implode(',', $message_ids).")
";
$this->_mysql->insert(self::GLUE_TABLE, array('view_date ' => 'NOW( )'), $WHERE);
}
}
/** public function set_message_unread
* Sets the given messages as unread by this user
*
* @param array or csv string message id(s)
* @action removes read date for these messages
* @return void
*/
public function set_message_unread($message_ids)
{
call(__METHOD__);
array_trim($message_ids, 'int');
if (0 != count($message_ids)) {
$WHERE = "
WHERE to_id = '{$this->_user_id}'
AND message_id IN (".implode(',', $message_ids).")
";
$this->_mysql->insert(self::GLUE_TABLE, array('view_date' => NULL), $WHERE);
}
}
/** public function delete_message
* Deletes the glue table entry for these messages for this user
*
* @param array or csv string message id(s)
* @action deletes the glue table entries
* @return void
*/
public function delete_message($message_ids)
{
call(__METHOD__);
array_trim($message_ids, 'int');
if (0 != count($message_ids)) {
foreach ($message_ids as $message_id) {
$query = "
SELECT *
FROM ".self::GLUE_TABLE."
WHERE to_id = '{$this->_user_id}'
AND message_id = '{$message_id}'
";
$result = $this->_mysql->fetch_assoc($query);
// test and see if the message is from this user
if ($result['from_id'] == $this->_user_id) {
if (strtotime($result['send_date']) > time( )) {
// the message has not been sent yet, delete them all
// (use actual deletions here)
$this->_mysql->multi_delete(array(self::GLUE_TABLE, self::MESSAGE_TABLE), " WHERE message_id = '{$message_id}' ");
}
// check for global message and delete if found
// (use actual deletion here)
if ($this->_can_send_global) {
$WHERE = "
WHERE to_id = 0
AND message_id = '{$message_id}'
";
$this->_mysql->delete(self::GLUE_TABLE, $WHERE);
}
}
// delete our own entry
$WHERE = "
WHERE to_id = '{$this->_user_id}'
AND message_id = '{$message_id}'
";
$this->_mysql->insert(self::GLUE_TABLE, array('deleted' => 1), $WHERE);
}
}
}
/** static public function player_deleted
* Deletes the given players messages
*
* @param mixed array or csv of player ids
* @action deletes the players messages
* @return void
*/
static public function player_deleted($player_ids)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
array_trim($player_ids, 'int');
if ( ! $player_ids) {
throw new MyException(__METHOD__.': No player IDs given');
}
$player_ids = implode(',', $player_ids);
$Mysql->delete(Message::GLUE_TABLE, " WHERE from_id IN ({$player_ids}) OR to_id IN ({$player_ids}) ");
}
/** public function send_message
* Deletes the glue table entry for this message for this user
*
* @param string message subject
* @param string message body
* @param array (or csv string) message recipient user ids
* @param int optional message send date as unix timestamp (default: now)
* @param int optional message expire date as unix timestamp (default: never)
* @action saves all relevant data to database
* @return void
*/
public function send_message($subject, $message, $user_ids, $send_date = false, $expire_date = false)
{
call(__METHOD__);
array_trim($user_ids, 'int');
// check for a global message
if ($this->_can_send_global) {
// just replace the user_ids, everybody's gonna get it anyway
if (in_array(0, $user_ids)) {
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
";
$user_ids = $this->_mysql->fetch_value_array($query);
$user_ids[] = 0;
}
}
else { // this is not an admin
// remove all instances of 0 from the id list
$user_ids = array_diff(array_unique($user_ids), array(0));
}
if ( ! is_array($user_ids) || (0 == count($user_ids))) {
throw new MyException(__METHOD__.': Trying to send a message to nobody');
}
// clean the message bits
$subject = htmlentities($subject, ENT_QUOTES, 'ISO-8859-1', false);
$message = htmlentities($message, ENT_QUOTES, 'ISO-8859-1', false);
// save the message so we can grab the id
$message_id = $this->_mysql->insert(self::MESSAGE_TABLE, array('subject' => $subject, 'message' => $message));
// add ourselves to the recipient list and clean it up
$user_ids[] = $this->_user_id;
$user_ids = array_unique($user_ids);
// convert 04/24/2008 -> 2008-04-24
$send_date = ( ! preg_match('%^(\\d+)/(\\d+)/(\\d+)$%', $send_date)) ? NULL : preg_replace('%^(\\d+)/(\\d+)/(\\d+)$%', '$3-$1-$2', $send_date);
$expire_date = ( ! preg_match('%^(\\d+)/(\\d+)/(\\d+)$%', $expire_date)) ? NULL : preg_replace('%^(\\d+)/(\\d+)/(\\d+)$%', '$3-$1-$2', $expire_date);
foreach($user_ids as $user_id) {
$data = array(
'message_id' => $message_id,
'from_id' => $this->_user_id,
'to_id' => $user_id,
'send_date' => $send_date,
'expire_date' => $expire_date,
);
$this->_mysql->insert(self::GLUE_TABLE, $data);
}
}
/** public function grab_global_messages
* Searches the glue table for global messages and copies
* those entries to this user
*
* @param void
* @action copies global messages to this users inbox
* @return void
*/
public function grab_global_messages( )
{
call(__METHOD__);
$query = "
SELECT *
FROM ".self::GLUE_TABLE."
WHERE to_id = 0
AND deleted = 0
";
$result = $this->_mysql->fetch_array($query);
if ($result) {
foreach ($result as $row) {
unset($row['message_glue_id']);
unset($row['view_date']);
unset($row['create_date']);
unset($row['deleted']);
$row['to_id'] = $this->_user_id;
$this->_mysql->insert(self::GLUE_TABLE, $row);
}
}
}
/** protected function _get_message_data
* Retrieves the message from the database for sending
* but makes sure this user can see this message first
* and then appends data to the message so it can be sent
*
* @param int message id
* @action tests to make sure this user can see this message
* @action appends data to the subject and message so it can be sent
* @return array [subject, message, to]
*/
protected function _get_message_data($message_id)
{
call(__METHOD__);
try {
$message = $this->get_message($message_id);
}
catch (MyExeption $e) {
throw $e;
}
$message['from'] = Player::get_username($message['recipients'][0]['from_id']);
$message['date'] = (empty($message['send_date']) ? $message['create_date'] : $message['send_date']);
$message['date'] = date(Settings::read('long_date'), strtotime($message['date']));
$message['subject'] = ('' == $message['subject']) ? '<No Subject>' : $message['subject'];
$message['message'] = "\n\n\n".str_repeat('=', 50)."\n\n{$message['from']} said: ({$message['date']})\n".str_repeat('-', 50)."\n{$message['message']}";
return $message;
}
/** static public function get_count
* Grab the inbox count of new and total messages
* for the given player
*
* @param int player id
* @return array (int total messages, int new messages)
*/
static public function get_count($player_id)
{
call(__METHOD__);
$player_id = (int) $player_id;
$Mysql = Mysql::get_instance( );
$query = "
SELECT COUNT(*)
FROM ".self::GLUE_TABLE."
WHERE to_id = '{$player_id}'
AND from_id <> '{$player_id}'
AND (send_date <= NOW( )
OR send_date IS NULL)
AND deleted = 0
";
$msgs = $Mysql->fetch_value($query);
$query .= "
AND view_date IS NULL
";
$new_msgs = $Mysql->fetch_value($query);
return array($msgs, $new_msgs);
}
/** static public function check_new
* Checks if the given player has any new messages
*
* @param int player id
* @return number of new messages
*/
static public function check_new($player_id)
{
call(__METHOD__);
$player_id = (int) $player_id;
if ( ! $player_id) {
return false;
}
$Mysql = Mysql::get_instance( );
$query = "
SELECT COUNT(*)
FROM ".self::GLUE_TABLE."
WHERE to_id = '{$player_id}'
AND from_id <> '{$player_id}'
AND (send_date <= NOW( )
OR send_date IS NULL)
AND deleted = 0
AND view_date IS NULL
";
$new = $Mysql->fetch_value($query);
return $new;
}
} // end of Message class
/* schemas
// ===================================
--
-- Table structure for table `wr_message`
--
DROP TABLE IF EXISTS `wr_message`;
CREATE TABLE IF NOT EXISTS `wr_message` (
`message_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`subject` varchar(255) NOT NULL DEFAULT '',
`message` text NOT NULL,
`create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`message_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
-- --------------------------------------------------------
--
-- Table structure for table `wr_message_glue`
--
DROP TABLE IF EXISTS `wr_message_glue`;
CREATE TABLE IF NOT EXISTS `wr_message_glue` (
`message_glue_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`message_id` int(10) unsigned NOT NULL DEFAULT '0',
`from_id` int(10) unsigned NOT NULL DEFAULT '0',
`to_id` int(10) unsigned NOT NULL DEFAULT '0',
`send_date` datetime DEFAULT NULL,
`expire_date` datetime DEFAULT NULL,
`view_date` datetime DEFAULT NULL,
`create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`message_glue_id`),
KEY `outbox` (`from_id`,`message_id`),
KEY `inbox` (`to_id`,`message_id`),
KEY `created` (`create_date`),
KEY `expire_date` (`expire_date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
*/
|
benjamw/pharaoh | f5784aaf58afbc435ba99fdaf7f3baa09f21ef04 | nudge only marked as complete if email was sent | diff --git a/classes/game.class.php b/classes/game.class.php
index 10e015f..58530ff 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1090,1028 +1090,1032 @@ class Game
/** public function is_player
* Tests if the given ID is a player in the game
*
* @param int player id
* @return bool player is in game
*/
public function is_player($player_id)
{
$player_id = (int) $player_id;
return ((isset($this->_players['white']['player_id']) && ($player_id == $this->_players['white']['player_id']))
|| (isset($this->_players['black']['player_id']) && ($player_id == $this->_players['black']['player_id'])));
}
/** public function get_color
* Returns the requested player's color
*
* @param bool current player is requested player
* @return string requested player's color (or false on failure)
*/
public function get_color($player = true)
{
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['color'])) ? $this->_players[$request]['color'] : false);
}
/** public function is_turn
* Returns the requested player's turn
*
* @param bool current player is requested player
* @return bool is the requested player's turn
*/
public function is_turn($player = true)
{
if ('Playing' != $this->state) {
return false;
}
if ($this->_extra_info['draw_offered']) {
return false;
}
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['turn'])) ? (bool) $this->_players[$request]['turn'] : false);
}
/** public function get_turn
* Returns the name of the player who's turn it is
*
* @param void
* @return string current player's name
*/
public function get_turn( )
{
return ((isset($this->turn) && isset($this->_players[$this->turn]['object'])) ? $this->_players[$this->turn]['object']->username : false);
}
/** public function get_extra
* Returns details of the extra_info var
*
* @param void
* @return string extra info details
*/
public function get_extra( )
{
call(__METHOD__);
$return = array( );
if ($this->_extra_info['battle_dead']) {
$front_abbr = $front_text = '';
if ($this->_pharaoh->has_sphynx) {
$front_abbr = ', Front Only';
$front_text = ($this->_extra_info['battle_front_only'] ? ', Yes' : ', No');
}
$return[] = '<span>Laser Battle (<abbr title="Dead, Immune'.$front_abbr.'">'.$this->_extra_info['battle_dead'].', '.$this->_extra_info['battle_immune'].$front_text.'</abbr>)</span>';
}
if ($this->_pharaoh->has_sphynx && $this->_extra_info['move_sphynx']) {
$return[] = '<span>Movable Sphynx</span>';
}
return implode(' | ', $return);
}
/** public function get_extra_info
* Returns the extra_info var
*
* @param void
* @return array extra info
*/
public function get_extra_info( )
{
return $this->_extra_info;
}
/** public function get_board
* Returns the current board
*
* @param bool optional return expanded FEN
* @param int optional history index
* @return string board FEN (or xFEN)
*/
public function get_board($index = null, $expanded = false)
{
call(__METHOD__);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$expanded = (bool) $expanded;
if (isset($this->_history[$index])) {
$board = $this->_history[$index]['board'];
}
else {
return false;
}
if ($expanded) {
return expandFEN($board);
}
return $board;
}
/** public function get_move_history
* Returns the game move history
*
* @param void
* @return array game history
*/
public function get_move_history( )
{
call(__METHOD__);
$history = $this->_history;
array_shift($history); // remove the empty first move
$return = array( );
foreach ($history as $i => $ply) {
if (false !== strpos($ply['move'], '-')) {
$ply['move'] = str_replace(array('-0','-1'), array('-L','-R'), $ply['move']);
}
$return[floor($i / 2)][$i % 2] = $ply['move'];
}
if (isset($i) && (0 == ($i % 2))) {
++$i;
$return[floor($i / 2)][$i % 2] = '';
}
return $return;
}
/** public function get_history
* Returns the game history
*
* @param bool optional return as JSON string
* @return array or string game history
*/
public function get_history($json = false)
{
call(__METHOD__);
call($json);
$json = (bool) $json;
if ( ! $json) {
return $this->_history;
}
$history = array( );
foreach ($this->_history as $i => $node) {
$move = $this->get_move($i);
if ($move) {
$move = array_unique(array_values($move));
}
$history[] = array(
expandFEN($node['board']),
$move,
(($this->_history[$i]['laser_fired']) ? $this->get_laser_path($i) : array( )),
$this->get_hit_data($i),
$this->get_battle_data($i, true),
);
}
return json_encode($history);
}
/** public function get_move
* Returns the data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string previous turn
*/
public function get_move($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$turn = $this->_history[$index];
$board = expandFEN($turn['board']);
if ( ! empty($this->_history[$index - 1])) {
$board = expandFEN($this->_history[$index - 1]['board']);
}
if ( ! $turn['move']) {
if ($json) {
return 'false';
}
return false;
}
$move = array( );
$move[0] = Pharaoh::target_to_index(substr($turn['move'], 0, 2));
if ('-' == $turn['move'][2]) {
$move[1] = $move[0][0];
$move[2] = $turn['move'][3];
}
else {
$move[1] = Pharaoh::target_to_index(substr($turn['move'], 3, 2));
$move[2] = (int) (':' == $turn['move'][2]);
}
$move[3] = Pharaoh::get_piece_color($board[$move[0]]);
if ($json) {
return json_encode($move);
}
$move['from'] = $move[0];
$move['to'] = $move[1];
$move['extra'] = $move[2];
$move['color'] = $move[3];
return $move;
}
/** public function get_laser_path
* Returns the laser path for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or JSON string laser path
*/
public function get_laser_path($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$count = count($this->_history);
call($count);
call($this->_history[$index]);
if ((1 > $index) || ($index > ($count - 1))) {
if ($json) {
return '[]';
}
return false;
}
$color = ((0 != ($index % 2)) ? 'silver' : 'red');
call($color);
// here we need to do the move, store the board as is
// and then fire the laser.
// the reason being: if we just fire the laser at the previous board,
// if the piece hit was rotated into the beam, it will not display correctly
// and if we try and fire the laser at the current board, it will pass through
// any hit piece because it's no longer there (unless it's a stacked obelisk, of course)
// create a dummy pharaoh class and set the board as it was prior to the laser (-1)
$PH = new Pharaoh( );
$PH->set_board(expandFEN($this->_history[$index - 1]['board']));
$PH->set_extra_info($this->_extra_info);
// do the move, but do not fire the laser, and store the board
$pre_board = $PH->do_move($this->_history[$index]['move'], false);
// now fire the laser at that board
$return = Pharaoh::fire_laser($color, $pre_board, $this->_pharaoh->get_extra_info( ));
if ($json) {
return json_encode($return['laser_path']);
}
return $return['laser_path'];
}
/** public function get_hit_data
* Returns the turn data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string previous turn
*/
public function get_hit_data($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$move_data = array( );
// because we may have only hit the piece at A8 (idx: 0), this will
// return false unless we test for that location specifically
if ($this->_history[$index]['hits'] || ('0' === $this->_history[$index]['hits'])) {
// we need to grab the previous board here, and perform the move
// without firing the laser so we get the proper orientation
// of the pieces as they were hit in case any pieces were rotated
// into the beam
// create a dummy pharaoh class and set the board as it was prior to the laser (-1)
$PH = new Pharaoh( );
$PH->set_board(expandFEN($this->_history[$index - 1]['board']));
$PH->set_extra_info($this->_extra_info);
// do the move and store that board
$prev_board = $PH->do_move($this->_history[$index]['move'], false);
$pieces = array( );
$hits = array_trim($this->_history[$index]['hits'], 'int');
foreach ($hits as $hit) {
$pieces[] = $prev_board[$hit];
}
$move_data = compact('hits', 'pieces');
}
if ($json) {
return json_encode($move_data);
}
return $move_data;
}
/** public function get_battle_data
* Returns the battle data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string battle data
*/
public function get_battle_data($index = null, $simple = false, $json = false)
{
call(__METHOD__);
call($index);
call($simple);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$simple = (bool) $simple;
$json = (bool) $json;
$battle_data = array(
'silver' => array(
'dead' => 0,
'immune' => 0,
),
'red' => array(
'dead' => 0,
'immune' => 0,
),
);
$color = ((0 != ($index % 2)) ? 'silver' : 'red');
$other = (('silver' == $color) ? 'red' : 'silver');
call($color);
if (isset($this->_history[$index])) {
// grab the current data
$battle_data[$color]['dead'] = $this->_history[$index]['dead_for'];
$battle_data[$color]['immune'] = $this->_history[$index]['immune_for'];
// for the game display, we want to decrease the value here
$dead = false;
if ($battle_data[$color]['dead']) {
$dead = true;
--$battle_data[$color]['dead'];
}
if ($battle_data[$color]['immune']) {
--$battle_data[$color]['immune'];
}
// if we recently came back to life, show that
if ($dead && ! $battle_data[$color]['dead']) {
$battle_data[$color]['immune'] = $this->_extra_info['battle_immune'];
}
// grab the future data for the other player
if (isset($this->_history[$index + 1])) {
$battle_data[$other]['dead'] = $this->_history[$index + 1]['dead_for'];
$battle_data[$other]['immune'] = $this->_history[$index + 1]['immune_for'];
}
else {
// there is no next move, we need to calculate it based on the previous one
// if there is no previous move data, the values will stay as defaults
if (isset($this->_history[$index - 1])) {
$m_extra_info = $this->_gen_move_extra_info($this->_history[$index], $this->_history[$index - 1]);
$battle_data[$other]['dead'] = $m_extra_info['dead_for'];
$battle_data[$other]['immune'] = $m_extra_info['immune_for'];
}
}
}
if ($simple) {
$battle_data = array(
array($battle_data['silver']['dead'], $battle_data['silver']['immune']),
array($battle_data['red']['dead'], $battle_data['red']['immune']),
);
}
if ($json) {
return json_encode($battle_data);
}
return $battle_data;
}
/** public function get_setup_name
* Returns the name of the initial setup
* used for this game
*
* @param void
* @return string initial setup name
*/
public function get_setup_name( )
{
return $this->_setup['name'];
}
/** public function get_setup
* Returns the board of the initial setup
* used for this game
*
* @param void
* @return string initial setup name
*/
public function get_setup( )
{
return $this->_history[0]['board'];
}
/** public function nudge
* Nudges the given player to take their turn
*
* @param void
* @return bool success
*/
public function nudge( )
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
if ($this->test_nudge( )) {
- Email::send('nudge', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
- $this->_mysql->delete(self::GAME_NUDGE_TABLE, " WHERE game_id = '{$this->id}' ");
- $this->_mysql->insert(self::GAME_NUDGE_TABLE, array('game_id' => $this->id, 'player_id' => $this->_players['opponent']['player_id']));
- return true;
+ $sent = Email::send('nudge', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
+
+ if ($sent) {
+ $this->_mysql->delete(self::GAME_NUDGE_TABLE, " WHERE game_id = '{$this->id}' ");
+ $this->_mysql->insert(self::GAME_NUDGE_TABLE, array('game_id' => $this->id, 'player_id' => $this->_players['opponent']['player_id']));
+ }
+
+ return $sent;
}
return false;
}
/** public function test_nudge
* Tests if the current player can nudge or not
*
* @param void
* @return bool player can be nudged
*/
public function test_nudge( )
{
call(__METHOD__);
$player_id = (int) $this->_players['opponent']['player_id'];
if ( ! $this->is_player($player_id) || $this->is_turn( ) || ('Playing' != $this->state) || $this->paused) {
return false;
}
if ( ! $this->_players['opponent']['object']->allow_email || ('' == $this->_players['opponent']['object']->email)) {
return false;
}
try {
$nudge_time = Settings::read('nudge_flood_control');
}
catch (MyException $e) {
return false;
}
if (-1 == $nudge_time) {
return false;
}
elseif (0 == $nudge_time) {
return true;
}
// check the nudge status for this game/player
// 'now' is taken from the DB because it may
// have a different time from the PHP server
$query = "
SELECT NOW( ) AS now
, G.modify_date AS move_date
, GN.nudged
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_NUDGE_TABLE." AS GN
ON (GN.game_id = G.game_id
AND GN.player_id = '{$player_id}')
WHERE G.game_id = '{$this->id}'
AND G.state = 'Playing'
";
$dates = $this->_mysql->fetch_assoc($query);
if ( ! $dates) {
return false;
}
// check the dates
// if the move date is far enough in the past
// AND the player has not been nudged
// OR the nudge date is far enough in the past
if ((strtotime($dates['move_date']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now'])))
&& ((empty($dates['nudged']))
|| (strtotime($dates['nudged']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now'])))))
{
return true;
}
return false;
}
/** public function get_players
* Grabs the player array
*
* @param void
* @return array player data
*/
public function get_players( )
{
$players = array( );
foreach (array('white','black') as $color) {
$player_id = $this->_players[$color]['player_id'];
$players[$player_id] = $this->_players[$color];
$players[$player_id]['username'] = $this->_players[$color]['object']->username;
unset($players[$player_id]['object']);
}
return $players;
}
/** public function get_outcome
* Returns the outcome string and outcome
*
* @param int id of observing player
* @return array (outcome text, outcome string)
*/
public function get_outcome($player_id)
{
call(__METHOD__);
$player_id = (int) $player_id;
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
return false;
}
if ('Draw' == $this->state) {
return array('Draw Game', 'lost');
}
if ( ! empty($this->_pharaoh->winner) && isset($this->_players[$this->_pharaoh->winner]['player_id'])) {
$winner = $this->_players[$this->_pharaoh->winner]['player_id'];
}
else {
$query = "
SELECT G.winner_id
FROM ".self::GAME_TABLE." AS G
WHERE G.game_id = '{$this->id}'
";
$winner = $this->_mysql->fetch_value($query);
}
if ( ! $winner) {
return false;
}
if ($player_id == $winner) {
return array('You Won !', 'won');
}
else {
return array($GLOBALS['_PLAYERS'][$winner].' Won', 'lost');
}
}
/** static public function write_game_file
* Writes the game to a text file for storage
*
* @param int game id
* @action writes the game PGN file
* @return string PGN
*/
static public function write_game_file($game_id)
{
// the PGN export format is very exact when it comes to what is allowed
// and what is not allowed when creating a PGN file.
// first, the only new line character that is allowed is a single line feed character
// output in PHP as \n, this means that \r is not allowed, nor is \r\n
// second, no tab characters are allowed, neither vertical, nor horizontal (\t)
// third, comments do NOT nest, thus { { } } will be in error, as will { ; }
// fourth, { } denotes an inline comment, where ; denotes a 'rest of line' comment
// fifth, a percent sign (%) at the beginning of a line denotes a whole line comment
// sixth, comments may not be included in the meta tags ( [Meta "data"] )
$Mysql = Mysql::get_instance( );
if (empty($game_id)) {
throw new MyException(__METHOD__.': No game id given');
}
try {
$Game = new Game($game_id);
}
catch (MyException $e) {
throw $e;
}
if ( ! isset($Game->_history[1])) {
return false;
}
$start_date = date('Y-m-d', strtotime($Game->_history[1]['move_date']));
$white_name = $Game->_players['white']['object']->lastname.', '.$Game->_players['white']['object']->firstname.' ('.$Game->_players['white']['object']->username.')';
$black_name = $Game->_players['black']['object']->lastname.', '.$Game->_players['black']['object']->firstname.' ('.$Game->_players['black']['object']->username.')';
$extra_info = $Game->_extra_info;
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
unset($extra_info['white_color']);
unset($extra_info['draw_offered']);
unset($extra_info['undo_requested']);
$xheadxtra = '';
$xheader = "[Event \"Pharaoh (Khet) Casual Game #{$Game->id}\"]\n"
. "[Site \"{$GLOBALS['_ROOT_URI']}\"]\n"
. "[Date \"{$start_date}\"]\n"
. "[Round \"-\"]\n"
. "[White \"{$white_name}\"]\n"
. "[Black \"{$black_name}\"]\n"
. "[Setup \"{$Game->_history[0]['board']}\"]\n";
if ($extra_info) {
$options = serialize($extra_info);
$xheadxtra .= "[Options \"{$options}\"]\n";
}
$xheadxtra .= "[Mode \"ICS\"]\n";
$body = '';
$line = '';
$token = '';
foreach ($Game->_history as $key => $move) {
// skip the first entry
if ( ! $key) {
continue;
}
if (0 != ($key % 2)) {
$token = floor(($key + 1) / 2) . '. ' . $move['move'];
}
else {
$token .= ' ' . $move['move'];
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
}
if ($token) {
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
// finish up the PGN with the game result
$result = '*';
if ('Finished' == $Game->state) {
if ('white' == $Game->turn) {
$result = '1-0';
}
else {
$result = '0-1';
}
}
elseif ('Draw' == $Game->state) {
$result = '1/2-1/2';
}
$body .= $line;
if ((strlen($line) + strlen($result)) > 79) {
$body .= "\n";
}
elseif (strlen($line) > 0) {
$body .= ' ';
}
$body .= $result . "\n";
$xheader .= "[Result \"$result\"]\n";
$data = $xheader . $xheadxtra . "\n" . $body;
$filename = GAMES_DIR."/Pharoah_Game_{$Game->id}_".str_replace(array(' ','-',':'), '', $Game->_history[count($Game->_history) - 1]['move_date']).'.pgn';
file_put_contents($filename, $data);
return $data;
}
protected function _gen_move_extra_info($curr_move, $prev_move = null)
{
call(__METHOD__);
$m_extra_info = self::$_HISTORY_EXTRA_INFO_DEFAULTS;
if ( ! $this->_extra_info['battle_dead']) {
return $m_extra_info;
}
if ( ! $curr_move) {
throw new MyException(__METHOD__.': Move data not present for calculation');
}
// set our current move extra info
if ($prev_move) {
$m_extra_info['dead_for'] = $prev_move['dead_for'];
$m_extra_info['immune_for'] = $prev_move['immune_for'];
}
$dead = false;
if ($m_extra_info['dead_for']) {
$dead = true;
}
if (0 < $m_extra_info['dead_for']) {
--$m_extra_info['dead_for'];
}
// we are allowed to shoot now, set our immunity
if ($dead && ! $m_extra_info['dead_for']) {
$m_extra_info['immune_for'] = $this->_extra_info['battle_immune'];
}
if ( ! $dead && (0 < $m_extra_info['immune_for'])) {
--$m_extra_info['immune_for'];
}
if ( ! $m_extra_info['dead_for'] && ! $m_extra_info['immune_for'] && $curr_move['laser_hit']) {
$m_extra_info['dead_for'] = $this->_extra_info['battle_dead'];
}
return $m_extra_info;
}
/** protected function _pull
* Pulls the data from the database
* and sets up the objects
*
* @param void
* @action pulls the game data
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return false;
}
if ( ! $_SESSION['player_id']) {
throw new MyException(__METHOD__.': Player id is not in session when pulling game data');
}
// grab the game data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
call($result);
if ( ! $result) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
if ('Waiting' == $result['state']) {
throw new MyException(__METHOD__.': Game (#'.$this->id.') is still only an invite');
}
// set the properties
$this->state = $result['state'];
$this->paused = (bool) $result['paused'];
$this->create_date = strtotime($result['create_date']);
$this->modify_date = strtotime($result['modify_date']);
$this->_extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($result['extra_info']));
// just empty this out, we don't need it anymore
$this->_extra_info['invite_setup'] = '';
// grab the initial setup
// TODO: convert to the setup object
// (need to build more in the setup object)
$query = "
SELECT *
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$result['setup_id']}'
";
$setup = $this->_mysql->fetch_assoc($query);
call($setup);
// the setup may have been deleted
if ( ! $setup) {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => '[DELETED]',
);
}
else {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => $setup['name'],
);
}
// set up the players
$this->_players['white']['player_id'] = $result['white_id'];
$this->_players['white']['object'] = new GamePlayer($result['white_id']);
$this->_players['silver'] = & $this->_players['white'];
$this->_players['black']['player_id'] = $result['black_id'];
if (0 != $result['black_id']) { // we may have an open game
$this->_players['black']['object'] = new GamePlayer($result['black_id']);
$this->_players['red'] = & $this->_players['black'];
}
// we test this first one against the black id, so if it fails because
// the person viewing the game is not playing in the game (viewing it
// after it's finished) we want "player" to be equal to "white"
if ($_SESSION['player_id'] == $result['black_id']) {
$this->_players['player'] = & $this->_players['black'];
$this->_players['player']['color'] = 'black';
$this->_players['player']['opp_color'] = 'white';
$this->_players['opponent'] = & $this->_players['white'];
$this->_players['opponent']['color'] = 'white';
$this->_players['opponent']['opp_color'] = 'black';
}
else {
$this->_players['player'] = & $this->_players['white'];
$this->_players['player']['color'] = 'white';
$this->_players['player']['opp_color'] = 'black';
$this->_players['opponent'] = & $this->_players['black'];
$this->_players['opponent']['color'] = 'black';
$this->_players['opponent']['opp_color'] = 'white';
}
// set up the board
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date ASC
";
$result = $this->_mysql->fetch_array($query);
call($result);
if ($result) {
$count = count($result);
// integrate the extra info into the history array
foreach ($result as & $move) {
$m_extra = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, unserialize($move['extra_info']));
$move = array_merge($move, $m_extra);
}
unset($move); // kill the reference
$this->_history = $result;
$this->turn = ((0 == ($count % 2)) ? 'black' : 'white');
$this->last_move = strtotime($result[$count - 1]['move_date']);
try {
$this->_pharaoh = new Pharaoh( );
$this->_pharaoh->set_board(expandFEN($this->_history[$count - 1]['board']));
$this->_pharaoh->set_extra_info($this->_extra_info);
}
catch (MyException $e) {
throw $e;
}
$m_extra_info = $this->_gen_move_extra_info($this->_history[$count - 1], (isset($this->_history[$count - 2]) ? $this->_history[$count - 2] : null));
$this->_current_move_extra_info = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, $m_extra_info);
}
else {
$this->last_move = $this->create_date;
}
$this->_players[$this->turn]['turn'] = true;
}
/** public function save
* Saves all changed data to the database
*
* @param void
* @action saves the game data
* @return void
*/
public function save( )
{
call(__METHOD__);
// grab the base game data
$query = "
SELECT state
, extra_info
, modify_date
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
AND state <> 'Waiting'
";
$game = $this->_mysql->fetch_assoc($query);
call($game);
$update_modified = false;
if ( ! $game) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
$this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date']));
// test the modified date and make sure we still have valid data
call($this->modify_date);
call(strtotime($game['modify_date']));
if ($this->modify_date != strtotime($game['modify_date'])) {
$this->_log('== FAILED ==');
throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data');
}
|
benjamw/pharaoh | 1d6a7b7b0a715f854a46f4098b464b1771d7b246 | made ajax refresh calls wait for previous ajax call to finish | diff --git a/scripts/game.js b/scripts/game.js
index 85749c8..dba861d 100644
--- a/scripts/game.js
+++ b/scripts/game.js
@@ -264,544 +264,549 @@ function show_new_board(cont) {
$('div#idx_'+game_history[move_index][3]['hits'][i]).append(create_piece(piece, true));
}
}
if ((move_count - 1) == move_index) {
enable_moves( );
}
if (cont) {
timer = setTimeout('fire_laser(game_history[move_index][2]);', 1000);
}
else {
// hide the hit piece
$('img.hit').hide( );
}
return true;
}
function clear_laser( ) {
if (old_board) {
show_new_board( );
}
clearTimeout(timer);
timer = false;
$('img.laser').remove( );
$('img.hit').hide( );
}
function do_full_move(idx) {
// stop any previous moves and/or animations
show_old_board( );
show_new_board( );
clear_laser( );
if (idx > (move_count - 1)) {
return false;
}
// set the global move index
move_index = parseInt(move_index) || (move_count - 1);
// and do the move
show_old_board(true);
}
function review( ) {
var type = $(this).attr('id');
switch (type) {
case 'first' : move_index = 1; break;
case 'prev5' : move_index -= 5; break;
case 'prev' : move_index -= 1; break;
case 'next' : move_index += 1; break;
case 'next5' : move_index += 5; break;
case 'last' : move_index = (move_count - 1); break;
}
if (move_index < 1) {
move_index = 1;
}
else if (move_index > (move_count - 1)) {
move_index = (move_count - 1);
}
update_history( );
do_full_move(move_index);
}
function update_history( ) {
// update our active move history item
$('#history table td.active').removeClass('active');
$('td#mv_'+move_index).addClass('active');
// update our disabled review buttons as needed
$('#history div .disabled').removeClass('disabled');
if (1 >= move_index) {
$('#prev, #prev5, #first').addClass('disabled');
}
if (move_index >= (move_count - 1)) {
$('#next, #next5, #last').addClass('disabled');
}
}
function enable_moves( ) {
move_index = parseInt(move_index) || (move_count - 1);
if ( ! my_turn || draw_offered || undo_requested || ('finished' == state) || ('draw' == state) || ((move_count - 1) != move_index)) {
return;
}
if (old_board) {
show_new_board( );
return false;
}
// make all our pieces clickable
$('div#board div.piece.p_'+color)
.click(set_square)
.css('cursor', 'pointer');
}
function highlight_valid_moves(elem) {
var $elem = $(elem);
clear_highlights( );
// highlight all adjacent non-occupied squares
var adj = get_adjacent($elem.attr('id').slice(4));
$.each(adj, function(i, val) {
var $idx = $('#idx_'+val);
var to_class = $idx.prop('class');
var to_color = to_class.match(/p_[^\s]+/ig);
var fr_class = $elem.prop('class');
var fr_color = fr_class.match(/p_[^\s]+/ig);
// check the ability to move the sphynx
if ((-1 != fr_class.indexOf('sphynx')) && ! move_sphynx) {
return;
}
// if the class is an empty string, just set the class and exit here
if ('' == to_class) {
add_highlight($idx);
return;
}
// now run some tests to see if we should be highlighting this square
// if it's a color square, make sure it's the same color
var to_square_color = to_class.match(/c_[^\s]+/ig);
var fr_square_color = fr_class.replace(/c_[^\s]+/ig, '').replace(/p_([^\s]+)/ig, 'c_$1').match(/c_[^\s]+/ig);
if ((null != to_square_color) && (to_square_color[0] != fr_square_color[0])) {
return;
}
// remove all squares with pieces that are not obelisks or pyramids
// (they may get allowed in the next step)
if (-1 != to_class.indexOf('piece')) {
if (-1 != to_class.indexOf('pyramid')) {
// do nothing
}
else if (-1 != to_class.indexOf('obelisk')) {
// do nothing
}
else if (-1 != to_class.indexOf('anubis')) {
// do nothing
}
else {
return;
}
// test for djed and eye of horus
// if it's not one of those, remove all pieces
// we also want to allow a same colored single stack obelisk
// if the piece we are moving is an obelisk
if (-1 != fr_class.indexOf('djed')) {
// do nothing
}
else if (-1 != fr_class.indexOf('horus')) {
// do nothing
}
else if (-1 != fr_class.indexOf('obelisk')) {
// make sure it's moving onto a single stack obelisk of the same color
if ((-1 != to_class.indexOf('obelisk')) && (-1 == to_class.indexOf('obelisk_stack')) && (fr_color[0] == to_color[0])) {
// do nothing
}
else {
return;
}
}
else {
return;
}
// make sure if we're swapping pieces that the swapped piece
// doesn't end up on a color square where they shouldn't be
var fr_sqr_color = fr_class.match(/c_[^\s]+/ig);
var to_sqr_color = to_class.replace(/c_[^\s]+/ig, '').replace(/p_([^\s]+)/ig, 'c_$1').match(/c_[^\s]+/ig);
if ((null != fr_sqr_color) && (to_sqr_color[0] != fr_sqr_color[0])) {
return;
}
}
// we made it through the gauntlet, set the highlight
add_highlight($idx);
});
}
function add_highlight($elem) {
$elem
.addClass('highlight');
if ( ! $elem.is('div.piece.p_'+color)) {
$elem
.click(set_square)
.css('cursor', 'pointer');
}
}
function clear_highlights( ) {
$('div.highlight')
.removeClass('highlight')
.each( function( ) {
var $elem = $(this);
if ( ! $elem.is('div.piece.p_'+color)) {
$elem
.unbind('click', set_square)
.css('cursor', 'default');
}
});
}
var stage_1 = false;
var from_index = -1;
var time = [];
function set_square(event) {
// don't allow the event to bubble up the DOM tree
event.stopPropagation( );
// set the time of the click
time.push(new Date( ).getTime( ));
clear_laser( );
var $elem = $(event.currentTarget);
var board_index = $elem.attr('id').slice(4).toLowerCase( );
if ( ! stage_1) {
stage_1 = true;
from_index = board_index;
highlight_valid_moves($elem);
// create our two images
// if the piece is not an obelisk or pharaoh
var piece_code = $elem.prop('class').match(/i_[^\s]+/ig)[0].slice(2).toLowerCase( );
if (('v' != piece_code) && ('w' != piece_code) && ('p' != piece_code)) {
var allow_right = true;
var allow_left = true;
// make sure the sphynx doesn't get rotated toward a wall
if (piece_code.match(/[efjk]/i)) {
var up_right = (piece_code.match(/[e]/i) && (9 == (board_index % 10))); // pointing up against right wall
var down_right = (piece_code.match(/[j]/i) && (9 == (board_index % 10))); // pointing down against right wall
var up_left = (piece_code.match(/[e]/i) && (0 == (board_index % 10))); // pointing up against left wall
var down_left = (piece_code.match(/[j]/i) && (0 == (board_index % 10))); // pointing down against left wall
var right_top = (piece_code.match(/[f]/i) && (board_index < 10)); // pointing right against top wall
var left_top = (piece_code.match(/[k]/i) && (board_index < 10)); // pointing left against top wall
var right_bottom = (piece_code.match(/[f]/i) && (board_index >= 70)); // pointing right against bottom wall
var left_bottom = (piece_code.match(/[k]/i) && (board_index >= 70)); // pointing left against bottom wall
if (( ! invert && (up_right || down_left || left_top || right_bottom))
|| (invert && (up_left || down_right || left_bottom || right_top))) {
allow_right = false;
}
if (( ! invert && (up_left || down_right || left_bottom || right_top))
|| (invert && (up_right || down_left || left_top || right_bottom))) {
allow_left = false;
}
}
if (allow_right) {
$('div#idx_'+board_index)
.append($('<img/>', {
'id' : 'rot_r',
'class' : 'rotate cw',
'src' : 'images/rotate_cw.png',
'alt' : '->',
'click' : set_square
}));
}
if (allow_left) {
$('div#idx_'+board_index)
.append($('<img/>', {
'id' : 'rot_l',
'class' : 'rotate ccw',
'src' : 'images/rotate_ccw.png',
'alt' : '<-',
'click' : set_square
}));
}
}
$('input#from').val(board_index);
}
else {
// grab some info about the piece
var $fr_elem = $('div#idx_'+from_index);
var fr_class = $fr_elem.prop('class');
var fr_color = fr_class.match(/p_[^\s]+/ig);
// if we are not rotating the piece, we need
// to grab some more info about where the piece
// is going
if ( ! isNaN(parseInt(board_index))) {
var $to_elem = $('div#idx_'+board_index);
var to_class = $to_elem.prop('class');
var to_color = to_class.match(/p_[^\s]+/ig);
}
var rotating = false;
if (('r' == board_index) || ('l' == board_index)) {
// check the time between clicks and make sure this wasn't a mistake
if (1000 > (time[1] - time[0])) {
if ( ! confirm('You clicked that rotate button awfully fast... ('+(time[1] - time[0])+' ms)\nWas that what you meant to do? (Rotating '+board_index.toUpperCase( )+')')) {
// reset
stage_1 = false;
from_index = -1;
time = []
clear_highlights( );
$('img.rotate').remove( );
// perform the original click again
$fr_elem.click( );
return;
}
}
rotating = true;
}
else if (board_index == from_index) {
// reset
stage_1 = false;
from_index = -1;
time = []
clear_highlights( );
$('img.rotate').remove( );
return;
}
else if (-1 == $elem.prop('class').indexOf('highlight')) {
// reset
stage_1 = false;
from_index = -1;
time = [];
clear_highlights( );
$('img.rotate').remove( );
// perform the click again
$to_elem.click( );
return;
}
else {
// if the FROM piece is a djed,
// or eye of horus, or obelisk
// moving onto another single stack obelisk...
var moveable_piece = (fr_color && to_color && (fr_color[0] == to_color[0]));
// set this piece as the TO index
// as long as it's okay with the player
if (moveable_piece) {
var piece_code = $elem.prop('class').match(/i_[^\s]+/ig)[0].slice(2).toLowerCase( );
var swap = 'swap';
if (('v' == piece_code.toLowerCase( )) && ('v' == fr_class.match(/i_[^\s]+/ig)[0].slice(2).toLowerCase( ))) {
swap = 'stack';
}
if ( ! confirm('Do you want to '+swap+' this piece?\n\nOK- '+swap.capitalize( )+' these two pieces | Cancel- Move this new piece')) {
// reset
stage_1 = false;
from_index = -1;
time = []
clear_highlights( );
$('img.rotate').remove( );
// perform the click again
$to_elem.click( );
return;
}
}
}
// set the TO value and send the form
$('input#to').val(board_index);
// if FROM piece is a stacked obelisk and the TO space is empty
// test for splitting an obelisk and confirm with player
if ( ! rotating) {
var stacked_obelisk = (-1 != fr_class.indexOf('obelisk_stack'));
var empty_to = (-1 == to_class.indexOf('piece'));
if (stacked_obelisk && empty_to && confirm('Do you want to split this obelisk stack?\n\nOK- Split obelisk stack | Cancel- Move stack as whole')) {
$('input#to').val(board_index+'-split');
}
}
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+$('form#game').serialize( )+'&turn=1';
return false;
}
// ajax the form
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: $('form#game').serialize( )+'&turn=1',
success: function(msg) {
// if something happened, just reload
if ('{' != msg[0]) {
alert('ERROR: AJAX Failed');
if (reload) { window.location.reload( ); }
return;
}
var reply = JSON.parse(msg);
if (reply.error) {
alert(reply.error);
if (reload) { window.location.reload( ); }
return;
}
if (reload) { window.location.reload( ); }
}
});
}
}
// TOWER: this is going to get _complicated_
function get_adjacent(board_index) {
board_index = parseInt(board_index);
var val;
var test;
var adj = [];
var diff = [
[-11, -10, -9],
[ -1, +1],
[ +9, +10, +11]
];
for (var i in diff) {
for (var j in diff[i]) {
val = diff[i][j];
// make sure we are not going off the edge of the board
test = true; // innocent until proven guilty
test = (test && (0 <= (board_index + val))); // top edge
test = (test && (80 > (board_index + val))); // bottom edge
test = (test && (2 > Math.abs(((board_index + val) % 10) - (board_index % 10)))); // side edges
if (test) {
adj.push(board_index + val);
}
}
}
return adj;
}
function show_battle_data(show_old_data) {
if ( ! laser_battle) {
return false;
}
var idx = move_index;
if ( !! show_old_data) {
--idx;
}
var data = game_history[idx][4];
var clss, value;
if (data[0][0]) {
clss = 'dead';
value = data[0][0];
}
else if (data[0][1]) {
clss = 'immune';
value = data[0][1];
}
else {
clss = 'alive';
value = '';
}
$('div#the_board div.silver_laser').empty( ).append('<div class="'+clss+'">'+value+'</div>');
if (data[1][0]) {
clss = 'dead';
value = data[1][0];
}
else if (data[1][1]) {
clss = 'immune';
value = data[1][1];
}
else {
clss = 'alive';
value = '';
}
$('div#the_board div.red_laser').empty( ).append('<div class="'+clss+'">'+value+'</div>');
}
-
+var jqXHR = false;
function ajax_refresh( ) {
// no debug redirect, just do it
- $.ajax({
- type: 'POST',
- url: 'ajax_helper.php',
- data: 'refresh=1',
- success: function(msg) {
- if (msg != last_move) {
- // don't just reload( ), it tries to submit the POST again
- if (reload) { window.location = window.location.href; }
+ // only run this if the previous ajax call has completed
+ if (false == jqXHR) {
+ jqXHR = $.ajax({
+ type: 'POST',
+ url: 'ajax_helper.php',
+ data: 'refresh=1',
+ success: function(msg) {
+ if (msg != last_move) {
+ // don't just reload( ), it tries to submit the POST again
+ if (reload) { window.location = window.location.href; }
+ }
}
- }
- });
+ }).always( function( ) {
+ jqXHR = false;
+ });
+ }
// successively increase the timeout time in case someone
// leaves their window open, don't poll the server every
// two seconds for the rest of time
if (0 == (refresh_timeout % 5)) {
refresh_timeout += Math.floor(refresh_timeout * 0.001) * 1000;
}
++refresh_timeout;
refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout);
}
String.prototype.capitalize = function( ) {
return this.charAt(0).toUpperCase( ) + this.slice(1);
}
diff --git a/scripts/index.js b/scripts/index.js
index 36376e6..e86b0a1 100644
--- a/scripts/index.js
+++ b/scripts/index.js
@@ -1,126 +1,133 @@
// index javascript
var reload = true; // do not change this
var refresh_timer = false;
var refresh_timeout = 30001; // 30 seconds
$(document).ready( function( ) {
// make the table row clicks work
$('.datatable tbody tr').css('cursor', 'pointer').click( function( ) {
var id = $(this).attr('id').substr(1);
var state = $($(this).children( )[2]).text( );
//* -- SWITCH --
if (state == 'Waiting') {
window.location = 'join.php?id='+id+debug_query_;
}
else {
window.location = 'game.php?id='+id+debug_query_;
}
//*/
});
// blinky menu items
$('.blink').fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( );
// chat box functions
$('#chatbox form').submit( function( ) {
if ('' == $.trim($('#chatbox input#chat').val( ))) {
return false;
}
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+$('#chatbox form').serialize( );
return false;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: $('#chatbox form').serialize( ),
success: function(msg) {
var reply = JSON.parse(msg);
if (reply.error) {
alert(reply.error);
}
else {
var entry = '<dt>'+reply.username+'</dt>'+
'<dd>'+reply.message+'</dd>';
$('#chats').prepend(entry);
$('#chatbox input#chat').val('');
}
}
});
return false;
});
// run the sounds
if (('#refresh' == document.location.hash) && turn_msg_count) {
$('#sounds').jPlayer({
ready: function ( ) {
$(this).jPlayer('setMedia', {
mp3: 'sounds/message.mp3',
oga: 'sounds/message.ogg'
}).jPlayer('play');
},
volume: 1,
swfPath: 'scripts'
});
}
// run the ajax refresher
ajax_refresh( );
// set some things that will halt the timer
$('#chatbox form input').focus( function( ) {
clearTimeout(refresh_timer);
});
$('#chatbox form input').blur( function( ) {
if ('' != $(this).val( )) {
refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout);
}
});
});
+var jqXHR = false;
function ajax_refresh( ) {
// no debug redirect, just do it
- $.ajax({
- type: 'POST',
- url: 'ajax_helper.php',
- data: 'timer=1',
- success: function(msg) {
- if (('' != msg) && (msg != turn_msg_count)) {
- // we don't want to play sounds when they hit the page manually
- // so set a hash on the URL that we can test when we embed the sounds
- // we don't care what the hash is, just refresh if there is a hash
- // (the user may have silenced the sounds with #silent)
- if ('' != window.location.hash) {
- if (reload) { window.location.reload( ); }
- }
- else {
- // stick the hash on the end of the URL
- window.location = window.location.href+'#refresh'
- if (reload) { window.location.reload( ); }
+
+ // only run this if the previous ajax call has completed
+ if (false == jqXHR) {
+ jqXHR = $.ajax({
+ type: 'POST',
+ url: 'ajax_helper.php',
+ data: 'timer=1',
+ success: function(msg) {
+ if (('' != msg) && (msg != turn_msg_count)) {
+ // we don't want to play sounds when they hit the page manually
+ // so set a hash on the URL that we can test when we embed the sounds
+ // we don't care what the hash is, just refresh if there is a hash
+ // (the user may have silenced the sounds with #silent)
+ if ('' != window.location.hash) {
+ if (reload) { window.location.reload( ); }
+ }
+ else {
+ // stick the hash on the end of the URL
+ window.location = window.location.href+'#refresh'
+ if (reload) { window.location.reload( ); }
+ }
}
}
- }
- });
+ }).always( function( ) {
+ jqXHR = false;
+ });
+ }
// successively increase the timeout time in case someone
// leaves their window open, don't poll the server every
// 30 seconds for the rest of time
if (0 == (refresh_timeout % 5)) {
refresh_timeout += Math.floor(refresh_timeout * 0.001) * 1000;
}
++refresh_timeout;
refresh_timer = setTimeout('ajax_refresh( )', refresh_timeout);
}
|
benjamw/pharaoh | 8de9658004b71b90da25bf762bbc188f975fbb79 | removed __destruct and moved _save where it was needed | diff --git a/ajax_helper.php b/ajax_helper.php
index c115f84..dc5cc91 100644
--- a/ajax_helper.php
+++ b/ajax_helper.php
@@ -1,294 +1,295 @@
<?php
$GLOBALS['NODEBUG'] = true;
$GLOBALS['AJAX'] = true;
// don't require log in when testing for used usernames and emails
if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) {
define('LOGIN', false);
}
require_once 'includes/inc.global.php';
// if we are debugging, change some things for us
// (although REQUEST_METHOD may not always be valid)
if (('GET' == $_SERVER['REQUEST_METHOD']) && test_debug( )) {
$GLOBALS['NODEBUG'] = false;
$GLOBALS['AJAX'] = false;
$_GET['token'] = $_SESSION['token'];
$_GET['keep_token'] = true;
$_POST = $_GET;
$DEBUG = true;
call('AJAX HELPER');
call($_POST);
}
// run the index page refresh checks
if (isset($_POST['timer'])) {
$message_count = (int) Message::check_new($_SESSION['player_id']);
$turn_count = (int) Game::check_turns($_SESSION['player_id']);
echo $message_count + $turn_count;
exit;
}
// run registration checks
if (isset($_POST['validity_test'])) {
# if (('email' == $_POST['type']) && ('' == $_POST['value'])) {
# echo 'OK';
# exit;
# }
$player_id = 0;
if ( ! empty($_POST['profile'])) {
$player_id = (int) $_SESSION['player_id'];
}
switch ($_POST['validity_test']) {
case 'username' :
case 'email' :
$username = '';
$email = '';
${$_POST['validity_test']} = sani($_POST['value']);
$player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0);
try {
Player::check_database($username, $email, $player_id);
}
catch (MyException $e) {
echo $e->getCode( );
exit;
}
break;
default :
break;
}
echo 'OK';
exit;
}
// run the in game chat
if (isset($_POST['chat'])) {
try {
if ( ! isset($_SESSION['game_id'])) {
$_SESSION['game_id'] = 0;
}
$Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']);
$Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby']));
$return = $Chat->get_box_list(1);
$return = $return[0];
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup validation
if (isset($_POST['test_setup'])) {
try {
Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']);
$return['valid'] = true;
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup laser test fire
if (isset($_POST['test_fire'])) {
try {
// returns laser_path and hits arrays
$return = Pharaoh::fire_laser($_POST['color'], $_POST['board']);
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run the invites stuff
if (isset($_POST['invite'])) {
if ('delete' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
if (Game::delete_invite($_POST['game_id'])) {
echo 'Invite Deleted';
}
else {
echo 'ERROR: Invite not deleted';
}
}
else {
echo 'ERROR: Not your invite';
}
}
else if ('resend' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
try {
if (Game::resend_invite($_POST['game_id'])) {
echo 'Invite Resent';
}
else {
echo 'ERROR: Could not resend invite';
}
}
catch (MyException $e) {
echo 'ERROR: '.$e->outputMessage( );
}
}
else {
echo 'ERROR: Not your invite';
}
}
else {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) {
if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended
echo $game_id;
}
else {
echo 'ERROR: Could not create game';
}
}
else {
echo 'ERROR: Not your invite';
}
}
exit;
}
// we'll need a game id from here forward, so make sure we have one
if (empty($_SESSION['game_id'])) {
echo 'ERROR: Game not found';
exit;
}
// init our game
if ( ! isset($Game)) {
$Game = new Game((int) $_SESSION['game_id']);
}
// run the game refresh check
if (isset($_POST['refresh'])) {
echo $Game->last_move;
exit;
}
// do some validity checking
if (empty($DEBUG) && empty($_POST['notoken'])) {
test_token( ! empty($_POST['keep_token']));
}
if ($_POST['game_id'] != $_SESSION['game_id']) {
throw new MyException('ERROR: Incorrect game id given. Was #'.$_POST['game_id'].', should be #'.$_SESSION['game_id'].'.');
}
// make sure we are the player we say we are
// unless we're an admin, then it's ok
$player_id = (int) $_POST['player_id'];
if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) {
throw new MyException('ERROR: Incorrect player id given');
}
// run the simple button actions
$actions = array(
'nudge',
'resign',
'offer_draw',
'accept_draw',
'reject_draw',
'request_undo',
'accept_undo',
'reject_undo',
);
foreach ($actions as $action) {
if (isset($_POST[$action])) {
try {
if ($Game->{$action}($player_id)) {
echo 'OK';
}
else {
echo 'ERROR';
}
}
catch (MyException $e) {
echo $e;
}
exit;
}
}
// run the game actions
if (isset($_POST['turn'])) {
$return = array( );
try {
if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk
$to = substr($_POST['to'], 0, 2);
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.'.'.$to);
$Game->do_move($from.'.'.$to);
}
elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving
$to = $_POST['to'];
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.':'.$to);
$Game->do_move($from.':'.$to);
}
else { // rotating
$target = Pharaoh::index_to_target($_POST['from']);
$dir = (int) ('r' == strtolower($_POST['to']));
call($target.'-'.$dir);
$Game->do_move($target.'-'.$dir);
}
+ $Game->save( );
$return['action'] = 'RELOAD';
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
diff --git a/classes/game.class.php b/classes/game.class.php
index 16d3b31..10e015f 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1,1554 +1,1556 @@
<?php
/*
+---------------------------------------------------------------------------
|
| game.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| This module is built to facilitate the game Pharaoh, it doesn't really
| care about how to play, or the deep goings on of the game, only about
| database structure and how to allow players to interact with the game.
|
+---------------------------------------------------------------------------
|
| > Pharaoh (Khet) Game module
| > Date started: 2008-02-28
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
if (defined('INCLUDE_DIR')) {
require_once INCLUDE_DIR.'func.array.php';
}
class Game
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property GAME_TABLE
* Holds the game table name
*
* @var string
*/
const GAME_TABLE = T_GAME;
/** const property GAME_HISTORY_TABLE
* Holds the game board table name
*
* @var string
*/
const GAME_HISTORY_TABLE = T_GAME_HISTORY;
/** const property GAME_NUDGE_TABLE
* Holds the game nudge table name
*
* @var string
*/
const GAME_NUDGE_TABLE = T_GAME_NUDGE;
/** const property GAME_STATS_TABLE
* Holds the game stats table name
*
* @var string
*/
const GAME_STATS_TABLE = T_STATS;
/** static protected property _EXTRA_INFO_DEFAULTS
* Holds the default extra info data
*
* @var array
*/
static protected $_EXTRA_INFO_DEFAULTS = array(
'white_color' => 'random',
'battle_dead' => false,
'battle_immune' => false,
'battle_front_only' => true,
'battle_hit_self' => false,
'move_sphynx' => false,
'draw_offered' => false,
'undo_requested' => false,
'custom_rules' => '',
'invite_setup' => '', // this is to hold the setup for invites only
);
/** static protected property _HISTORY_EXTRA_INFO_DEFAULTS
* Holds the default extra info data for the move history
*
* @var array
*/
static protected $_HISTORY_EXTRA_INFO_DEFAULTS = array(
'laser_hit' => false,
'laser_fired' => true,
'dead_for' => 0,
'immune_for' => 0,
);
/** public property id
* Holds the game's id
*
* @var int
*/
public $id;
/** public property state
* Holds the game's current state
* can be one of 'Waiting', 'Playing', 'Finished', 'Draw'
*
* @var string (enum)
*/
public $state;
/** public property turn
* Holds the game's current turn
* can be one of 'white', 'black'
*
* @var string
*/
public $turn;
/** public property paused
* Holds the game's current pause state
*
* @var bool
*/
public $paused;
/** public property create_date
* Holds the game's create date
*
* @var int (unix timestamp)
*/
public $create_date;
/** public property modify_date
* Holds the game's modified date
*
* @var int (unix timestamp)
*/
public $modify_date;
/** public property last_move
* Holds the game's last move date
*
* @var int (unix timestamp)
*/
public $last_move;
/** public property watch_mode
* Lets us know if we are just visiting this game
*
* @var bool
*/
public $watch_mode = false;
/** protected property _setup
* Holds the game's initial setup
* as an associative array
* array(
* 'id' => [setup_id],
* 'name' => [setup_name],
* );
*
* @var array
*/
protected $_setup;
/** protected property _laser_fired
* Holds the laser fired flag
*
* @var bool did we fire the laser?
*/
protected $_laser_fired = false;
/** protected property _extra_info
* Holds the extra game info
*
* @var array
*/
protected $_extra_info;
/** protected property _current_move_extra_info
* Holds the extra current move info
*
* @var array
*/
protected $_current_move_extra_info;
/** protected property _players
* Holds our player's object references
* along with other game data
*
* @var array of player data
*/
protected $_players;
/** protected property _pharaoh
* Holds the pharaoh object reference
*
* @var Pharaoh object reference
*/
protected $_pharaoh;
/** protected property _history
* Holds the board history
*
* @var array of pharaoh boards
*/
protected $_history;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional game id
* @param Mysql optional object reference
* @action instantiates object
* @return void
*/
public function __construct($id = 0, Mysql $Mysql = null)
{
call(__METHOD__);
$this->id = (int) $id;
call($this->id);
$this->_pharaoh = new Pharaoh($this->id);
if (is_null($Mysql)) {
$Mysql = Mysql::get_instance( );
}
$this->_mysql = $Mysql;
try {
$this->_pull( );
}
catch (MyException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action saves changed data
* @action destroys object
* @return void
*/
+/*
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if ($this->id && (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type']))) {
try {
- $this->_save( );
+ $this->save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
+*/
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
switch ($property) {
case 'name' :
return $this->_players['white']['object']->username.' vs '.$this->_players['black']['object']->username;
break;
case 'first_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return 'Your';
}
else {
return $this->_players['white']['object']->username.'\'s';
}
break;
case 'second_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return $this->_players['opponent']['object']->username.'\'s';
}
else {
return $this->_players['black']['object']->username.'\'s';
}
break;
default :
// go to next step
break;
}
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
$this->$property = $value;
}
/** static public function invite
* Creates the game from _POST data
*
* @param void
* @action creates an invite
* @return int game id
*/
static public function invite( )
{
call(__METHOD__);
call($_POST);
$Mysql = Mysql::get_instance( );
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
$_P = $_POST;
// translate (filter/sanitize) the data
$_P['white_id'] = (int) $_SESSION['player_id'];
$_P['black_id'] = (int) $_P['opponent'];
$_P['setup_id'] = (int) $_P['setup'];
$_P['laser_battle'] = is_checked($_P['laser_battle_box']);
$_P['battle_front_only'] = is_checked($_P['battle_front_only']);
$_P['battle_hit_self'] = is_checked($_P['battle_hit_self']);
$_P['move_sphynx'] = is_checked($_P['move_sphynx']);
call($_P);
// grab the setup
$query = "
SELECT setup_id
FROM ".Setup::SETUP_TABLE."
";
$setup_ids = $Mysql->fetch_value_array($query);
call($setup_ids);
// check for random setup
if (0 == $_P['setup_id']) {
shuffle($setup_ids);
shuffle($setup_ids);
$_P['setup_id'] = (int) reset($setup_ids);
sort($setup_ids);
}
// make sure the setup id is valid
if ( ! in_array($_P['setup_id'], $setup_ids)) {
throw new MyException(__METHOD__.': Setup is not valid');
}
$query = "
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$_P['setup_id']}'
";
$setup = $Mysql->fetch_value($query);
// laser battle cleanup
// only run this if the laser battle box was open
if ($_P['laser_battle']) {
ifer($_P['battle_dead'], 1, false);
ifer($_P['battle_immune'], 1);
// we can only hit ourselves in the sides or back, never front
if ($_P['battle_front_only']) {
$_P['battle_hit_self'] = false;
}
$extra_info = array(
'battle_dead' => (int) max((int) $_P['battle_dead'], 1),
'battle_immune' => (int) max((int) $_P['battle_immune'], 0),
'battle_front_only' => (bool) $_P['battle_front_only'],
'battle_hit_self' => (bool) $_P['battle_hit_self'],
);
}
$extra_info['white_color'] = $_P['color'];
$extra_info['move_sphynx'] = $_P['move_sphynx'];
$setup = expandFEN($setup);
try {
if (is_checked($_P['convert_to_1']) || is_checked($_P['rand_convert_to_1'])) {
$setup = Setup::convert_to_1($setup);
}
elseif (is_checked($_P['convert_to_2']) || is_checked($_P['rand_convert_to_2'])) {
$setup = Setup::convert_to_2($setup);
}
}
catch (MyException $e) {
throw $e;
}
$extra_info['invite_setup'] = packFEN($setup);
call($extra_info);
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
if ( ! empty($extra_info)) {
$_P['extra_info'] = serialize($extra_info);
}
// create the game
$required = array(
'white_id' ,
'setup_id' ,
);
$key_list = array_merge($required, array(
'black_id' ,
'extra_info' ,
));
try {
$_DATA = array_clean($_P, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['state'] = 'Waiting';
$_DATA['create_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$insert_id = $Mysql->insert(self::GAME_TABLE, $_DATA);
if (empty($insert_id)) {
throw new MyException(__METHOD__.': Invite could not be created');
}
// send the email
if ($_DATA['black_id']) {
Email::send('invite', $_DATA['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$_DATA['white_id']], 'page' => 'invite.php'));
}
return $insert_id;
}
/** static public function resend_invite
* Resends the invite email (if allowed)
*
* @param int game id
* @action resends an invite email
* @return bool invite email sent
*/
static public function resend_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$white_id = (int) $_SESSION['player_id'];
$Mysql = Mysql::get_instance( );
// grab the invite from the database
$query = "
SELECT *
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$invite = $Mysql->fetch_assoc($query);
if ( ! $invite) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend a non-existant invite (#'.$game_id.')');
}
if ((int) $invite['white_id'] !== (int) $white_id) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is not theirs');
}
if ( ! (int) $invite['black_id']) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is open');
}
if (strtotime($invite['modify_date']) >= strtotime($invite['resend_limit'])) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is too new');
}
// if we get here, all is good...
$sent = Email::send('invite', $invite['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$invite['white_id']], 'page' => 'invite.php'));
if ($sent) {
// update the modify_date to prevent invite resend flooding
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$Mysql->insert(self::GAME_TABLE, $_DATA, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
return $sent;
}
/** static public function accept_invite
* Creates the game from invite data
*
* @param int game id
* @action creates a game
* @return int game id
*/
static public function accept_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
// basically all we do, is set the state to Playing
// and set the player order based on the invite data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$game = $Mysql->fetch_assoc($query);
$invitor_id = $game['white_id']; // for use later
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($game['extra_info']));
if ((('random' == $extra_info['white_color']) && mt_rand(0, 1)) || ('white' == $extra_info['white_color'])) {
$game['white_id'] = $game['white_id'];
$game['black_id'] = $_SESSION['player_id'];
}
else {
$game['black_id'] = $game['white_id'];
$game['white_id'] = $_SESSION['player_id'];
}
call($extra_info);
unset($extra_info['white_color']);
$board = false;
if ( ! empty($extra_info['invite_setup'])) {
$board = $extra_info['invite_setup'];
}
$extra_info['invite_setup'] = '';
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
unset($game['extra_info']);
if ( ! empty($extra_info)) {
$game['extra_info'] = serialize($extra_info);
}
$game['state'] = 'Playing';
$Mysql->insert(self::GAME_TABLE, $game, " WHERE game_id = '{$game_id}' ");
// add the first entry in the history table
if (empty($board)) {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', (
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$game['setup_id']}'
))
";
$Mysql->query($query);
}
else {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', '{$board}')
";
$Mysql->query($query);
}
// add a used count to the setup table
Setup::add_used($game['setup_id']);
// send the email
Email::send('start', $invitor_id, array('opponent' => $GLOBALS['_PLAYERS'][$_SESSION['player_id']], 'game_id' => $game_id));
return $game_id;
}
/** static public function delete_invite
* Deletes the given invite
*
* @param int game id
* @action deletes the invite
* @return void
*/
static public function delete_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
return $Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
/** static public function has_invite
* Tests if the given player has the given invite
*
* @param int game id
* @param int player id
* @param bool optional player can accept invite
* @return bool player has invite
*/
static public function has_invite($game_id, $player_id, $accept = false)
{
call(__METHOD__);
$game_id = (int) $game_id;
$player_id = (int) $player_id;
$accept = (bool) $accept;
$Mysql = Mysql::get_instance( );
$open = "";
if ($accept) {
$open = " OR black_id IS NULL
OR black_id = FALSE ";
}
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
{$open}
)
";
$has_invite = (bool) $Mysql->fetch_value($query);
return $has_invite;
}
public function can_fire_laser( )
{
call(__METHOD__);
if ( ! $this->_extra_info['battle_dead']) {
return true;
}
return ! $this->_current_move_extra_info['dead_for'];
}
public function prev_laser_fired( )
{
$last = end($this->_history);
return (bool) $last['laser_fired'];
}
/** public function do_move
* Do the given move and send out emails
*
* @param string move code
* @action performs the move
* @return array indexes hit
*/
public function do_move($move)
{
call(__METHOD__);
try {
$this->_laser_fired = $this->can_fire_laser( );
$hits = $this->_pharaoh->do_move($move, $this->_laser_fired);
$winner = $this->_pharaoh->winner;
}
catch (MyException $e) {
throw $e;
}
if ($winner) {
if ('draw' == $winner) {
$this->state = 'Draw';
$this->_players['silver']['object']->add_draw( );
$this->_players['red']['object']->add_draw( );
// send the email
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
else {
$this->state = 'Finished';
$this->_players[$winner]['object']->add_win( );
$this->_players[$this->_players[$winner]['opp_color']]['object']->add_loss( );
// send the email
$type = (($this->_players[$winner]['player_id'] == $_SESSION['player_id']) ? 'defeated' : 'won');
Email::send($type, $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
}
else {
// send the email
Email::send('turn', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
return $hits;
}
/** public function resign
* Resigns the given player from the game
*
* @param int player id
* @return void
*/
public function resign($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign from a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign opponent from a game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_win( );
$this->_players['player']['object']->add_loss( );
$this->state = 'Finished';
$this->_pharaoh->winner = 'opponent';
Email::send('resigned', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function offer_draw
* Offers a draw to the given player's apponent
*
* @param int player id
* @return void
*/
public function offer_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = $player_id;
Email::send('draw_offered', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function draw_offered
* Returns the state of the game draw for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function draw_offered($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the draw was offered AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['draw_offered']) && ( ! $player_id || ($player_id != $this->_extra_info['draw_offered']))) {
return true;
}
return false;
}
/** public function accept_draw
* Accepts a draw offered to the given player
*
* @param int player id
* @return void
*/
public function accept_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw for an opponent in game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_draw( );
$this->_players['player']['object']->add_draw( );
$this->state = 'Draw';
$this->_extra_info['draw_offered'] = false;
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_draw
* Rejects a draw offered to the given player
*
* @param int player id
* @return void
*/
public function reject_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = false;
}
/** public function request_undo
* Requests an undo from the given player's apponent
*
* @param int player id
* @return void
*/
public function request_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo from an opponent in game (#'.$this->id.')');
}
$this->_extra_info['undo_requested'] = $player_id;
Email::send('undo_requested', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function undo_requested
* Returns the state of the game undo for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function undo_requested($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the undo was requested AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['undo_requested']) && ( ! $player_id || ($player_id != $this->_extra_info['undo_requested']))) {
return true;
}
return false;
}
/** public function accept_undo
* Accepts an undo requested to the given player
*
* @param int player id
* @return void
*/
public function accept_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept undo in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept undo for an opponent in game (#'.$this->id.')');
}
// we need to adjust the database here
- // it's not really possible via the _save function
+ // it's not really possible via the save function
$this->_mysql->delete(self::GAME_HISTORY_TABLE, "
WHERE `game_id` = '{$this->id}'
ORDER BY `move_date` DESC
LIMIT 1
");
// and fix up the game data
$this->_pull( );
$this->_extra_info['undo_requested'] = false;
Email::send('undo_accepted', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_undo
* Rejects an undo requested to the given player
*
* @param int player id
* @return void
*/
public function reject_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject undo in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject undo for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['undo_requested'] = false;
}
/** public function is_player
* Tests if the given ID is a player in the game
*
* @param int player id
* @return bool player is in game
*/
public function is_player($player_id)
{
$player_id = (int) $player_id;
return ((isset($this->_players['white']['player_id']) && ($player_id == $this->_players['white']['player_id']))
|| (isset($this->_players['black']['player_id']) && ($player_id == $this->_players['black']['player_id'])));
}
/** public function get_color
* Returns the requested player's color
*
* @param bool current player is requested player
* @return string requested player's color (or false on failure)
*/
public function get_color($player = true)
{
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['color'])) ? $this->_players[$request]['color'] : false);
}
/** public function is_turn
* Returns the requested player's turn
*
* @param bool current player is requested player
* @return bool is the requested player's turn
*/
public function is_turn($player = true)
{
if ('Playing' != $this->state) {
return false;
}
if ($this->_extra_info['draw_offered']) {
return false;
}
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['turn'])) ? (bool) $this->_players[$request]['turn'] : false);
}
/** public function get_turn
* Returns the name of the player who's turn it is
*
* @param void
* @return string current player's name
*/
public function get_turn( )
{
return ((isset($this->turn) && isset($this->_players[$this->turn]['object'])) ? $this->_players[$this->turn]['object']->username : false);
}
/** public function get_extra
* Returns details of the extra_info var
*
* @param void
* @return string extra info details
*/
public function get_extra( )
{
call(__METHOD__);
$return = array( );
if ($this->_extra_info['battle_dead']) {
$front_abbr = $front_text = '';
if ($this->_pharaoh->has_sphynx) {
$front_abbr = ', Front Only';
$front_text = ($this->_extra_info['battle_front_only'] ? ', Yes' : ', No');
}
$return[] = '<span>Laser Battle (<abbr title="Dead, Immune'.$front_abbr.'">'.$this->_extra_info['battle_dead'].', '.$this->_extra_info['battle_immune'].$front_text.'</abbr>)</span>';
}
if ($this->_pharaoh->has_sphynx && $this->_extra_info['move_sphynx']) {
$return[] = '<span>Movable Sphynx</span>';
}
return implode(' | ', $return);
}
/** public function get_extra_info
* Returns the extra_info var
*
* @param void
* @return array extra info
*/
public function get_extra_info( )
{
return $this->_extra_info;
}
/** public function get_board
* Returns the current board
*
* @param bool optional return expanded FEN
* @param int optional history index
* @return string board FEN (or xFEN)
*/
public function get_board($index = null, $expanded = false)
{
call(__METHOD__);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$expanded = (bool) $expanded;
if (isset($this->_history[$index])) {
$board = $this->_history[$index]['board'];
}
else {
return false;
}
if ($expanded) {
return expandFEN($board);
}
return $board;
}
/** public function get_move_history
* Returns the game move history
*
* @param void
* @return array game history
*/
public function get_move_history( )
{
call(__METHOD__);
$history = $this->_history;
array_shift($history); // remove the empty first move
$return = array( );
foreach ($history as $i => $ply) {
if (false !== strpos($ply['move'], '-')) {
$ply['move'] = str_replace(array('-0','-1'), array('-L','-R'), $ply['move']);
}
$return[floor($i / 2)][$i % 2] = $ply['move'];
}
if (isset($i) && (0 == ($i % 2))) {
++$i;
$return[floor($i / 2)][$i % 2] = '';
}
return $return;
}
/** public function get_history
* Returns the game history
*
* @param bool optional return as JSON string
* @return array or string game history
*/
public function get_history($json = false)
{
call(__METHOD__);
call($json);
$json = (bool) $json;
if ( ! $json) {
return $this->_history;
}
$history = array( );
foreach ($this->_history as $i => $node) {
$move = $this->get_move($i);
if ($move) {
$move = array_unique(array_values($move));
}
$history[] = array(
expandFEN($node['board']),
$move,
(($this->_history[$i]['laser_fired']) ? $this->get_laser_path($i) : array( )),
$this->get_hit_data($i),
$this->get_battle_data($i, true),
);
}
return json_encode($history);
}
/** public function get_move
* Returns the data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string previous turn
*/
public function get_move($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$turn = $this->_history[$index];
$board = expandFEN($turn['board']);
if ( ! empty($this->_history[$index - 1])) {
$board = expandFEN($this->_history[$index - 1]['board']);
}
if ( ! $turn['move']) {
if ($json) {
return 'false';
}
return false;
}
$move = array( );
$move[0] = Pharaoh::target_to_index(substr($turn['move'], 0, 2));
if ('-' == $turn['move'][2]) {
$move[1] = $move[0][0];
$move[2] = $turn['move'][3];
}
else {
$move[1] = Pharaoh::target_to_index(substr($turn['move'], 3, 2));
$move[2] = (int) (':' == $turn['move'][2]);
}
$move[3] = Pharaoh::get_piece_color($board[$move[0]]);
if ($json) {
return json_encode($move);
}
$move['from'] = $move[0];
$move['to'] = $move[1];
$move['extra'] = $move[2];
$move['color'] = $move[3];
return $move;
}
/** public function get_laser_path
* Returns the laser path for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or JSON string laser path
*/
public function get_laser_path($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$count = count($this->_history);
call($count);
call($this->_history[$index]);
if ((1 > $index) || ($index > ($count - 1))) {
if ($json) {
return '[]';
}
return false;
}
$color = ((0 != ($index % 2)) ? 'silver' : 'red');
call($color);
// here we need to do the move, store the board as is
// and then fire the laser.
// the reason being: if we just fire the laser at the previous board,
// if the piece hit was rotated into the beam, it will not display correctly
// and if we try and fire the laser at the current board, it will pass through
// any hit piece because it's no longer there (unless it's a stacked obelisk, of course)
// create a dummy pharaoh class and set the board as it was prior to the laser (-1)
$PH = new Pharaoh( );
$PH->set_board(expandFEN($this->_history[$index - 1]['board']));
$PH->set_extra_info($this->_extra_info);
// do the move, but do not fire the laser, and store the board
$pre_board = $PH->do_move($this->_history[$index]['move'], false);
// now fire the laser at that board
$return = Pharaoh::fire_laser($color, $pre_board, $this->_pharaoh->get_extra_info( ));
if ($json) {
return json_encode($return['laser_path']);
}
return $return['laser_path'];
}
/** public function get_hit_data
* Returns the turn data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string previous turn
*/
public function get_hit_data($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$move_data = array( );
// because we may have only hit the piece at A8 (idx: 0), this will
// return false unless we test for that location specifically
if ($this->_history[$index]['hits'] || ('0' === $this->_history[$index]['hits'])) {
// we need to grab the previous board here, and perform the move
// without firing the laser so we get the proper orientation
// of the pieces as they were hit in case any pieces were rotated
// into the beam
// create a dummy pharaoh class and set the board as it was prior to the laser (-1)
$PH = new Pharaoh( );
$PH->set_board(expandFEN($this->_history[$index - 1]['board']));
$PH->set_extra_info($this->_extra_info);
// do the move and store that board
$prev_board = $PH->do_move($this->_history[$index]['move'], false);
$pieces = array( );
$hits = array_trim($this->_history[$index]['hits'], 'int');
foreach ($hits as $hit) {
$pieces[] = $prev_board[$hit];
}
$move_data = compact('hits', 'pieces');
}
if ($json) {
return json_encode($move_data);
}
return $move_data;
}
/** public function get_battle_data
* Returns the battle data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string battle data
*/
public function get_battle_data($index = null, $simple = false, $json = false)
{
call(__METHOD__);
call($index);
call($simple);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$simple = (bool) $simple;
$json = (bool) $json;
$battle_data = array(
'silver' => array(
'dead' => 0,
'immune' => 0,
),
'red' => array(
'dead' => 0,
'immune' => 0,
),
);
$color = ((0 != ($index % 2)) ? 'silver' : 'red');
$other = (('silver' == $color) ? 'red' : 'silver');
call($color);
if (isset($this->_history[$index])) {
// grab the current data
$battle_data[$color]['dead'] = $this->_history[$index]['dead_for'];
$battle_data[$color]['immune'] = $this->_history[$index]['immune_for'];
// for the game display, we want to decrease the value here
$dead = false;
if ($battle_data[$color]['dead']) {
$dead = true;
--$battle_data[$color]['dead'];
}
if ($battle_data[$color]['immune']) {
--$battle_data[$color]['immune'];
}
// if we recently came back to life, show that
if ($dead && ! $battle_data[$color]['dead']) {
$battle_data[$color]['immune'] = $this->_extra_info['battle_immune'];
}
// grab the future data for the other player
if (isset($this->_history[$index + 1])) {
$battle_data[$other]['dead'] = $this->_history[$index + 1]['dead_for'];
$battle_data[$other]['immune'] = $this->_history[$index + 1]['immune_for'];
}
else {
// there is no next move, we need to calculate it based on the previous one
// if there is no previous move data, the values will stay as defaults
if (isset($this->_history[$index - 1])) {
$m_extra_info = $this->_gen_move_extra_info($this->_history[$index], $this->_history[$index - 1]);
$battle_data[$other]['dead'] = $m_extra_info['dead_for'];
$battle_data[$other]['immune'] = $m_extra_info['immune_for'];
}
}
}
if ($simple) {
$battle_data = array(
array($battle_data['silver']['dead'], $battle_data['silver']['immune']),
array($battle_data['red']['dead'], $battle_data['red']['immune']),
);
}
if ($json) {
return json_encode($battle_data);
}
@@ -1566,1032 +1568,1032 @@ class Game
public function get_setup_name( )
{
return $this->_setup['name'];
}
/** public function get_setup
* Returns the board of the initial setup
* used for this game
*
* @param void
* @return string initial setup name
*/
public function get_setup( )
{
return $this->_history[0]['board'];
}
/** public function nudge
* Nudges the given player to take their turn
*
* @param void
* @return bool success
*/
public function nudge( )
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
if ($this->test_nudge( )) {
Email::send('nudge', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
$this->_mysql->delete(self::GAME_NUDGE_TABLE, " WHERE game_id = '{$this->id}' ");
$this->_mysql->insert(self::GAME_NUDGE_TABLE, array('game_id' => $this->id, 'player_id' => $this->_players['opponent']['player_id']));
return true;
}
return false;
}
/** public function test_nudge
* Tests if the current player can nudge or not
*
* @param void
* @return bool player can be nudged
*/
public function test_nudge( )
{
call(__METHOD__);
$player_id = (int) $this->_players['opponent']['player_id'];
if ( ! $this->is_player($player_id) || $this->is_turn( ) || ('Playing' != $this->state) || $this->paused) {
return false;
}
if ( ! $this->_players['opponent']['object']->allow_email || ('' == $this->_players['opponent']['object']->email)) {
return false;
}
try {
$nudge_time = Settings::read('nudge_flood_control');
}
catch (MyException $e) {
return false;
}
if (-1 == $nudge_time) {
return false;
}
elseif (0 == $nudge_time) {
return true;
}
// check the nudge status for this game/player
// 'now' is taken from the DB because it may
// have a different time from the PHP server
$query = "
SELECT NOW( ) AS now
, G.modify_date AS move_date
, GN.nudged
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_NUDGE_TABLE." AS GN
ON (GN.game_id = G.game_id
AND GN.player_id = '{$player_id}')
WHERE G.game_id = '{$this->id}'
AND G.state = 'Playing'
";
$dates = $this->_mysql->fetch_assoc($query);
if ( ! $dates) {
return false;
}
// check the dates
// if the move date is far enough in the past
// AND the player has not been nudged
// OR the nudge date is far enough in the past
if ((strtotime($dates['move_date']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now'])))
&& ((empty($dates['nudged']))
|| (strtotime($dates['nudged']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now'])))))
{
return true;
}
return false;
}
/** public function get_players
* Grabs the player array
*
* @param void
* @return array player data
*/
public function get_players( )
{
$players = array( );
foreach (array('white','black') as $color) {
$player_id = $this->_players[$color]['player_id'];
$players[$player_id] = $this->_players[$color];
$players[$player_id]['username'] = $this->_players[$color]['object']->username;
unset($players[$player_id]['object']);
}
return $players;
}
/** public function get_outcome
* Returns the outcome string and outcome
*
* @param int id of observing player
* @return array (outcome text, outcome string)
*/
public function get_outcome($player_id)
{
call(__METHOD__);
$player_id = (int) $player_id;
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
return false;
}
if ('Draw' == $this->state) {
return array('Draw Game', 'lost');
}
if ( ! empty($this->_pharaoh->winner) && isset($this->_players[$this->_pharaoh->winner]['player_id'])) {
$winner = $this->_players[$this->_pharaoh->winner]['player_id'];
}
else {
$query = "
SELECT G.winner_id
FROM ".self::GAME_TABLE." AS G
WHERE G.game_id = '{$this->id}'
";
$winner = $this->_mysql->fetch_value($query);
}
if ( ! $winner) {
return false;
}
if ($player_id == $winner) {
return array('You Won !', 'won');
}
else {
return array($GLOBALS['_PLAYERS'][$winner].' Won', 'lost');
}
}
/** static public function write_game_file
* Writes the game to a text file for storage
*
* @param int game id
* @action writes the game PGN file
* @return string PGN
*/
static public function write_game_file($game_id)
{
// the PGN export format is very exact when it comes to what is allowed
// and what is not allowed when creating a PGN file.
// first, the only new line character that is allowed is a single line feed character
// output in PHP as \n, this means that \r is not allowed, nor is \r\n
// second, no tab characters are allowed, neither vertical, nor horizontal (\t)
// third, comments do NOT nest, thus { { } } will be in error, as will { ; }
// fourth, { } denotes an inline comment, where ; denotes a 'rest of line' comment
// fifth, a percent sign (%) at the beginning of a line denotes a whole line comment
// sixth, comments may not be included in the meta tags ( [Meta "data"] )
$Mysql = Mysql::get_instance( );
if (empty($game_id)) {
throw new MyException(__METHOD__.': No game id given');
}
try {
$Game = new Game($game_id);
}
catch (MyException $e) {
throw $e;
}
if ( ! isset($Game->_history[1])) {
return false;
}
$start_date = date('Y-m-d', strtotime($Game->_history[1]['move_date']));
$white_name = $Game->_players['white']['object']->lastname.', '.$Game->_players['white']['object']->firstname.' ('.$Game->_players['white']['object']->username.')';
$black_name = $Game->_players['black']['object']->lastname.', '.$Game->_players['black']['object']->firstname.' ('.$Game->_players['black']['object']->username.')';
$extra_info = $Game->_extra_info;
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
unset($extra_info['white_color']);
unset($extra_info['draw_offered']);
unset($extra_info['undo_requested']);
$xheadxtra = '';
$xheader = "[Event \"Pharaoh (Khet) Casual Game #{$Game->id}\"]\n"
. "[Site \"{$GLOBALS['_ROOT_URI']}\"]\n"
. "[Date \"{$start_date}\"]\n"
. "[Round \"-\"]\n"
. "[White \"{$white_name}\"]\n"
. "[Black \"{$black_name}\"]\n"
. "[Setup \"{$Game->_history[0]['board']}\"]\n";
if ($extra_info) {
$options = serialize($extra_info);
$xheadxtra .= "[Options \"{$options}\"]\n";
}
$xheadxtra .= "[Mode \"ICS\"]\n";
$body = '';
$line = '';
$token = '';
foreach ($Game->_history as $key => $move) {
// skip the first entry
if ( ! $key) {
continue;
}
if (0 != ($key % 2)) {
$token = floor(($key + 1) / 2) . '. ' . $move['move'];
}
else {
$token .= ' ' . $move['move'];
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
}
if ($token) {
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
// finish up the PGN with the game result
$result = '*';
if ('Finished' == $Game->state) {
if ('white' == $Game->turn) {
$result = '1-0';
}
else {
$result = '0-1';
}
}
elseif ('Draw' == $Game->state) {
$result = '1/2-1/2';
}
$body .= $line;
if ((strlen($line) + strlen($result)) > 79) {
$body .= "\n";
}
elseif (strlen($line) > 0) {
$body .= ' ';
}
$body .= $result . "\n";
$xheader .= "[Result \"$result\"]\n";
$data = $xheader . $xheadxtra . "\n" . $body;
$filename = GAMES_DIR."/Pharoah_Game_{$Game->id}_".str_replace(array(' ','-',':'), '', $Game->_history[count($Game->_history) - 1]['move_date']).'.pgn';
file_put_contents($filename, $data);
return $data;
}
protected function _gen_move_extra_info($curr_move, $prev_move = null)
{
call(__METHOD__);
$m_extra_info = self::$_HISTORY_EXTRA_INFO_DEFAULTS;
if ( ! $this->_extra_info['battle_dead']) {
return $m_extra_info;
}
if ( ! $curr_move) {
throw new MyException(__METHOD__.': Move data not present for calculation');
}
// set our current move extra info
if ($prev_move) {
$m_extra_info['dead_for'] = $prev_move['dead_for'];
$m_extra_info['immune_for'] = $prev_move['immune_for'];
}
$dead = false;
if ($m_extra_info['dead_for']) {
$dead = true;
}
if (0 < $m_extra_info['dead_for']) {
--$m_extra_info['dead_for'];
}
// we are allowed to shoot now, set our immunity
if ($dead && ! $m_extra_info['dead_for']) {
$m_extra_info['immune_for'] = $this->_extra_info['battle_immune'];
}
if ( ! $dead && (0 < $m_extra_info['immune_for'])) {
--$m_extra_info['immune_for'];
}
if ( ! $m_extra_info['dead_for'] && ! $m_extra_info['immune_for'] && $curr_move['laser_hit']) {
$m_extra_info['dead_for'] = $this->_extra_info['battle_dead'];
}
return $m_extra_info;
}
/** protected function _pull
* Pulls the data from the database
* and sets up the objects
*
* @param void
* @action pulls the game data
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return false;
}
if ( ! $_SESSION['player_id']) {
throw new MyException(__METHOD__.': Player id is not in session when pulling game data');
}
// grab the game data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
call($result);
if ( ! $result) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
if ('Waiting' == $result['state']) {
throw new MyException(__METHOD__.': Game (#'.$this->id.') is still only an invite');
}
// set the properties
$this->state = $result['state'];
$this->paused = (bool) $result['paused'];
$this->create_date = strtotime($result['create_date']);
$this->modify_date = strtotime($result['modify_date']);
$this->_extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($result['extra_info']));
// just empty this out, we don't need it anymore
$this->_extra_info['invite_setup'] = '';
// grab the initial setup
// TODO: convert to the setup object
// (need to build more in the setup object)
$query = "
SELECT *
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$result['setup_id']}'
";
$setup = $this->_mysql->fetch_assoc($query);
call($setup);
// the setup may have been deleted
if ( ! $setup) {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => '[DELETED]',
);
}
else {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => $setup['name'],
);
}
// set up the players
$this->_players['white']['player_id'] = $result['white_id'];
$this->_players['white']['object'] = new GamePlayer($result['white_id']);
$this->_players['silver'] = & $this->_players['white'];
$this->_players['black']['player_id'] = $result['black_id'];
if (0 != $result['black_id']) { // we may have an open game
$this->_players['black']['object'] = new GamePlayer($result['black_id']);
$this->_players['red'] = & $this->_players['black'];
}
// we test this first one against the black id, so if it fails because
// the person viewing the game is not playing in the game (viewing it
// after it's finished) we want "player" to be equal to "white"
if ($_SESSION['player_id'] == $result['black_id']) {
$this->_players['player'] = & $this->_players['black'];
$this->_players['player']['color'] = 'black';
$this->_players['player']['opp_color'] = 'white';
$this->_players['opponent'] = & $this->_players['white'];
$this->_players['opponent']['color'] = 'white';
$this->_players['opponent']['opp_color'] = 'black';
}
else {
$this->_players['player'] = & $this->_players['white'];
$this->_players['player']['color'] = 'white';
$this->_players['player']['opp_color'] = 'black';
$this->_players['opponent'] = & $this->_players['black'];
$this->_players['opponent']['color'] = 'black';
$this->_players['opponent']['opp_color'] = 'white';
}
// set up the board
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date ASC
";
$result = $this->_mysql->fetch_array($query);
call($result);
if ($result) {
$count = count($result);
// integrate the extra info into the history array
foreach ($result as & $move) {
$m_extra = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, unserialize($move['extra_info']));
$move = array_merge($move, $m_extra);
}
unset($move); // kill the reference
$this->_history = $result;
$this->turn = ((0 == ($count % 2)) ? 'black' : 'white');
$this->last_move = strtotime($result[$count - 1]['move_date']);
try {
$this->_pharaoh = new Pharaoh( );
$this->_pharaoh->set_board(expandFEN($this->_history[$count - 1]['board']));
$this->_pharaoh->set_extra_info($this->_extra_info);
}
catch (MyException $e) {
throw $e;
}
$m_extra_info = $this->_gen_move_extra_info($this->_history[$count - 1], (isset($this->_history[$count - 2]) ? $this->_history[$count - 2] : null));
$this->_current_move_extra_info = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, $m_extra_info);
}
else {
$this->last_move = $this->create_date;
}
$this->_players[$this->turn]['turn'] = true;
}
- /** protected function _save
+ /** public function save
* Saves all changed data to the database
*
* @param void
* @action saves the game data
* @return void
*/
- protected function _save( )
+ public function save( )
{
call(__METHOD__);
// grab the base game data
$query = "
SELECT state
, extra_info
, modify_date
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
AND state <> 'Waiting'
";
$game = $this->_mysql->fetch_assoc($query);
call($game);
$update_modified = false;
if ( ! $game) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
$this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date']));
// test the modified date and make sure we still have valid data
call($this->modify_date);
call(strtotime($game['modify_date']));
if ($this->modify_date != strtotime($game['modify_date'])) {
$this->_log('== FAILED ==');
throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data');
}
$update_game = false;
call($game['state']);
call($this->state);
if ($game['state'] != $this->state) {
$update_game['state'] = $this->state;
if ('Finished' == $this->state) {
$update_game['winner_id'] = $this->_players[$this->_pharaoh->winner]['player_id'];
}
if (in_array($this->state, array('Finished', 'Draw'))) {
try {
$this->_add_stats( );
}
catch (MyException $e) {
// do nothing, it gets logged
}
}
}
$diff = array_compare($this->_extra_info, self::$_EXTRA_INFO_DEFAULTS);
$update_game['extra_info'] = $diff[0];
ksort($update_game['extra_info']);
$update_game['extra_info'] = serialize($update_game['extra_info']);
if ('a:0:{}' == $update_game['extra_info']) {
$update_game['extra_info'] = null;
}
if (0 === strcmp($game['extra_info'], $update_game['extra_info'])) {
unset($update_game['extra_info']);
}
if ($update_game) {
$update_modified = true;
$this->_mysql->insert(self::GAME_TABLE, $update_game, " WHERE game_id = '{$this->id}' ");
}
// update the board
$color = $this->_players['player']['color'];
call($color);
call('IN-GAME SAVE');
// grab the current board from the database
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date DESC
LIMIT 1
";
$move = $this->_mysql->fetch_assoc($query);
$board = $move['board'];
call($board);
$new_board = packFEN($this->_pharaoh->get_board( ));
call($new_board);
list($new_move, $new_hits) = $this->_pharaoh->get_move( );
call($new_move);
call($new_hits);
if (is_array($new_hits)) {
$new_hits = implode(',', $new_hits);
}
if ($new_board != $board) {
call('UPDATED BOARD');
$update_modified = true;
$this->_current_move_extra_info['laser_fired'] = (bool) $this->can_fire_laser( );
$this->_current_move_extra_info['laser_hit'] = (bool) $this->_pharaoh->laser_hit;
$diff = array_compare($this->_current_move_extra_info, self::$_HISTORY_EXTRA_INFO_DEFAULTS);
$m_extra_info = $diff[0];
ksort($m_extra_info);
$m_extra_info = serialize($m_extra_info);
if ('a:0:{}' == $m_extra_info) {
$m_extra_info = null;
}
$this->_mysql->insert(self::GAME_HISTORY_TABLE, array('board' => $new_board, 'move' => $new_move, 'hits' => $new_hits, 'extra_info' => $m_extra_info, 'game_id' => $this->id));
}
// update the game modified date
if ($update_modified) {
$this->_mysql->insert(self::GAME_TABLE, array('modify_date' => NULL), " WHERE game_id = '{$this->id}' ");
}
}
/** protected function _add_stats
* Adds data to the stats table
*
* @param void
* @action adds stats to stats table
* @return void
*/
protected function _add_stats( )
{
call(__METHOD__);
call($this);
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
throw new MyException (__METHOD__.': Game (#'.$this->id.') is not finished ('.$this->state.')');
}
$count = count($this->_history) - 1;
$start = $end = $this->_history[0]['move_date'];
if ($count) {
$start = $this->_history[1]['move_date'];
$end = $this->_history[$count]['move_date'];
}
$start_unix = strtotime($start);
$end_unix = strtotime($end);
$hours = round(($end_unix - $start_unix) / (60 * 60), 3);
$stat = array(
'game_id' => $this->id,
'setup_id' => $this->_setup['id'],
'move_count' => $count,
'start_date' => $start,
'end_date' => $end,
'hour_count' => $hours,
);
$white_outcome = $black_outcome = 0;
if ('Finished' == $this->state) {
$white_outcome = 1;
$black_outcome = -1;
if ('red' == $this->_pharaoh->winner) {
$white_outcome = -1;
$black_outcome = 1;
}
}
$white = array_merge($stat, array(
'player_id' => $this->_players['white']['player_id'],
'color' => 'white',
'win' => $white_outcome,
));
call($white);
$this->_mysql->insert(self::GAME_STATS_TABLE, $white);
$black = array_merge($stat, array(
'player_id' => $this->_players['black']['player_id'],
'color' => 'black',
'win' => $black_outcome,
));
call($black);
$this->_mysql->insert(self::GAME_STATS_TABLE, $black);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
// log the error
if (false && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** protected function _diff
* Compares two boards are returns the
* indexes of any differences
*
* @param string board
* @param string board
* @return array of difference indexes
*/
protected function _diff($board1, $board2)
{
$diff = array( );
for ($i = 0, $length = strlen($board1); $i < $length; ++$i) {
if ($board1[$i] != $board2[$i]) {
$diff[] = $i;
}
}
call($diff);
return $diff;
}
/**
* STATIC METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static public function get_list
* Returns a list array of all the games in the database
* with games which need the users attention highlighted
*
* NOTE: $player_id is required when not pulling all games
* (when $all is false)
*
* @param int optional player's id
* @param bool optional pull all games (vs only given player's games)
* @return array game list (or bool false on failure)
*/
static public function get_list($player_id = 0, $all = true)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
if ( ! $all && ! $player_id) {
throw new MyException(__METHOD__.': Player ID required when not pulling all games');
}
$WHERE = " WHERE state <> 'Waiting' ";
if ( ! $all) {
$WHERE .= "
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id})
";
}
$query = "
SELECT G.*
, MAX(GH.move_date) AS last_move
, COUNT(GH.move_date) AS count
, 0 AS my_turn
, 0 AS in_game
, W.username AS white
, B.username AS black
, S.name AS setup_name
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_HISTORY_TABLE." AS GH
ON GH.game_id = G.game_id
LEFT JOIN ".Player::PLAYER_TABLE." AS W
ON W.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS B
ON B.player_id = G.black_id
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
{$WHERE}
GROUP BY G.game_id
ORDER BY G.state ASC
, last_move DESC
";
$list = $Mysql->fetch_array($query);
if (0 != $player_id) {
// run though the list and find games the user needs action on
foreach ($list as & $game) {
$game['turn'] = (0 == ($game['count'] % 2)) ? 'black' : 'white';
$game['in_game'] = (int) (($player_id == $game['white_id']) || ($player_id == $game['black_id']));
$game['my_turn'] = (int) ( ! empty($game['turn']) && ($player_id == $game[$game['turn'].'_id']));
if (in_array($game['state'], array('Finished', 'Draw'))) {
$game['my_turn'] = 0;
}
$game['my_color'] = ($player_id == $game['white_id']) ? 'white' : 'black';
$game['opp_color'] = ($player_id == $game['white_id']) ? 'black' : 'white';
$game['opponent'] = ($player_id == $game['white_id']) ? $game['black'] : $game['white'];
}
unset($game); // kill the reference
}
// run through the games, and set the current player to the winner if the game is finished
// and fix the setup name if it was deleted
foreach ($list as & $game) {
if ('Finished' == $game['state']) {
if ($game['winner_id']) {
$game['turn'] = ($game['winner_id'] == $game['white_id']) ? 'white' : 'black';
}
else {
$game['turn'] = 'draw';
}
}
if ( ! $game['setup_name']) {
$game['setup_name'] = '[DELETED]';
}
}
unset($game); // kill the reference
return $list;
}
/** static public function get_player_stats_list
* Returns a list array of all game players
* in the database with additional stats added
*
* @param void
* @return array game player list (or bool false on failure)
*/
static public function get_player_stats_list( )
{
$Mysql = Mysql::get_instance( );
$players = GamePlayer::get_list(true);
if ($players) {
// add some more stats
$query = "
SELECT o.player_id
, COUNT(ww.win) AS white_wins
, COUNT(wl.win) AS white_losses
, COUNT(wd.win) AS white_draws
, COUNT(bw.win) AS black_wins
, COUNT(bl.win) AS black_losses
, COUNT(bd.win) AS black_draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.player_id = ww.player_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wl
ON (o.player_id = wl.player_id
AND o.game_id = wl.game_id
AND wl.win = -1
AND wl.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wd
ON (o.player_id = wd.player_id
AND o.game_id = wd.game_id
AND wd.win = 0
AND wd.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.player_id = bw.player_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bl
ON (o.player_id = bl.player_id
AND o.game_id = bl.game_id
AND bl.win = -1
AND bl.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bd
ON (o.player_id = bd.player_id
AND o.game_id = bd.game_id
AND bd.win = 0
AND bd.color = 'black')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['player_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'white_losses' => 0,
'white_draws' => 0,
'black_wins' => 0,
'black_losses' => 0,
'black_draws' => 0,
);
foreach ($players as & $player) { // be careful with the reference
if (isset($stats[$player['player_id']])) {
$player = array_merge($player, $stats[$player['player_id']]);
}
else {
$player = array_merge($player, $empty);
}
}
unset($player); // kill the reference
}
return $players;
}
/** static public function get_setup_stats_list
* Gets the list of all the setups with
* additional stats included in the list
*
* @param void
* @return array setups
*/
static public function get_setup_stats_list( )
{
$Mysql = Mysql::get_instance( );
$setups = Setup::get_list(true);
if ($setups) {
// add some more stats
$query = "
SELECT o.setup_id
, COUNT(ww.win) AS white_wins
, COUNT(bw.win) AS black_wins
, COUNT(d.win) AS draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.setup_id = ww.setup_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.setup_id = bw.setup_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS d
ON (o.setup_id = d.setup_id
AND o.game_id = d.game_id
AND d.win = 0
AND d.color = 'white')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['setup_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'black_wins' => 0,
'draws' => 0,
);
foreach ($setups as & $setup) { // be careful with the reference
if (isset($stats[$setup['setup_id']])) {
$setup = array_merge($setup, $stats[$setup['setup_id']]);
}
else {
$setup = array_merge($setup, $empty);
}
}
unset($setup); // kill the reference
}
return $setups;
}
/** static public function get_invites
* Returns a list array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite list
*/
static public function get_invites($player_id)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT G.*
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
, R.username AS invitor
, E.username AS invitee
, S.name AS setup
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
LEFT JOIN ".Player::PLAYER_TABLE." AS R
ON R.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS E
ON E.player_id = G.black_id
WHERE G.state = 'Waiting'
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id}
OR G.black_id IS NULL
OR G.black_id = FALSE
)
diff --git a/classes/gameplayer.class.php b/classes/gameplayer.class.php
index e2b397b..29820c8 100644
--- a/classes/gameplayer.class.php
+++ b/classes/gameplayer.class.php
@@ -1,673 +1,675 @@
<?php
/*
+---------------------------------------------------------------------------
|
| gameplayer.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Game Player Extension module for Pharaoh (Khet)
| > Date started: 2008-02-28
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
class GamePlayer
extends Player
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property EXTEND_TABLE
* Holds the player extend table name
*
* @var string
*/
const EXTEND_TABLE = T_PHARAOH;
/** protected property allow_email
* Flag shows whether or not to send emails to this player
*
* @var bool
*/
protected $allow_email;
/** protected property max_games
* Number of games player can be in at one time
*
* @var int
*/
protected $max_games;
/** protected property current_games
* Number of games player is currently playing in
*
* @var int
*/
protected $current_games;
/** protected property color
* Holds the players skin color preference
*
* @var string
*/
protected $color;
/** protected property wins
* Holds the players win count
*
* @var int
*/
protected $wins;
/** protected property draws
* Holds the players draw count
*
* @var int
*/
protected $draws;
/** protected property losses
* Holds the players loss count
*
* @var int
*/
protected $losses;
/** protected property last_online
* Holds the date the player was last online
*
* @var int (unix timestamp)
*/
protected $last_online;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional player id
* @action instantiates object
* @return void
*/
public function __construct($id = null)
{
$this->_mysql = Mysql::get_instance( );
// check and make sure we have logged into this game before
if (0 != (int) $id) {
$query = "
SELECT COUNT(*)
FROM ".self::EXTEND_TABLE."
WHERE player_id = '{$id}'
";
$count = (int) $this->_mysql->fetch_value($query);
if (0 == $count) {
throw new MyException(__METHOD__.': '.GAME_NAME.' Player (#'.$id.') not found in database');
}
}
parent::__construct($id);
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action destroys object
* @return void
*/
+/*
public function __destruct( )
{
return; // until i can figure out WTF?
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) {
try {
- $this->_save( );
+ $this->save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
+*/
/** public function log_in
* Runs the parent's log_in function
* then, if success, tests game player
* database to see if this player has been
* here before, if not, it adds then to the
* database, and if so, refreshes the last_online value
*
* @param void
* @action logs the player in
* @action optionally adds new game player data to the database
* @return bool success
*/
public function log_in( )
{
// this will redirect and exit upon failure
parent::log_in( );
// test an arbitrary property for existence, so we don't _pull twice unnecessarily
if (is_null($this->color)) {
$this->_mysql->insert(self::EXTEND_TABLE, array('player_id' => $this->id));
$this->_pull( );
}
// don't update the last online time if we logged in as an admin
if ( ! isset($_SESSION['admin_id'])) {
$this->_mysql->insert(self::EXTEND_TABLE, array('last_online' => NULL), " WHERE player_id = '{$this->id}' ");
}
return true;
}
/** public function register
* Registers a new player in the extend table
* also calls the parent register function
* which performs some validity checks
*
* @param void
* @action creates a new player in the database
* @return bool success
*/
public function register( )
{
call(__METHOD__);
try {
parent::register( );
}
catch (MyException $e) {
call('Exception Thrown: '.$e->getMessage( ));
throw $e;
}
if ($this->id) {
// add the user to the table
$this->_mysql->insert(self::EXTEND_TABLE, array('player_id' => $this->id));
// update the last_online time so we don't break things later
$this->_mysql->insert(self::EXTEND_TABLE, array('last_online' => NULL), " WHERE player_id = '{$this->id}' ");
}
}
/** public function add_win
* Adds a win to this player's stats
* both here, and in the database
*
* @param void
* @action adds a win in the database
* @return void
*/
public function add_win( )
{
$this->wins++;
// note the trailing space on the field name, it's not a typo
$this->_mysql->insert(self::EXTEND_TABLE, array('wins ' => 'wins + 1'), " WHERE player_id = '{$this->id}' ");
}
/** public function add_draw
* Adds a draw to this player's stats
* both here, and in the database
*
* @param void
* @action adds a draw in the database
* @return void
*/
public function add_draw( )
{
$this->draws++;
// note the trailing space on the field name, it's not a typo
$this->_mysql->insert(self::EXTEND_TABLE, array('draws ' => 'draws + 1'), " WHERE player_id = '{$this->id}' ");
}
/** public function add_loss
* Adds a loss to this player's stats
* both here, and in the database
*
* @param void
* @action adds a loss in the database
* @return void
*/
public function add_loss( )
{
$this->losses++;
// note the trailing space on the field name, it's not a typo
$this->_mysql->insert(self::EXTEND_TABLE, array('losses ' => 'losses + 1'), " WHERE player_id = '{$this->id}' ");
}
/** public function admin_delete
* Deletes the given players from the players database
*
* @param mixed csv or array of player ids
* @action deletes the players from the database
* @return void
*/
public function admin_delete($player_ids)
{
call(__METHOD__);
// make sure the user doing this is an admin
if ( ! $this->is_admin) {
throw new MyException(__METHOD__.': Player is not an admin');
}
array_trim($player_ids, 'int');
$player_ids = Player::clean_deleted($player_ids);
if ( ! $player_ids) {
throw new MyException(__METHOD__.': No player IDs given');
}
$this->_mysql->delete(self::EXTEND_TABLE, " WHERE player_id IN (".implode(',', $player_ids).") ");
}
/** public function admin_add_admin
* Gives the given players admin status
*
* @param mixed csv or array of player ids
* @action gives the given players admin status
* @return void
*/
public function admin_add_admin($player_ids)
{
// make sure the user doing this is an admin
if ( ! $this->is_admin) {
throw new MyException(__METHOD__.': Player is not an admin');
}
array_trim($player_ids, 'int');
$player_ids[] = 0; // make sure we have at least one entry
if (isset($GLOBALS['_ROOT_ADMIN'])) {
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
WHERE username = '{$GLOBALS['_ROOT_ADMIN']}'
";
$player_ids[] = (int) $this->_mysql->fetch_value($query);
}
$this->_mysql->insert(self::EXTEND_TABLE, array('is_admin' => 1), " WHERE player_id IN (".implode(',', $player_ids).") ");
}
/** public function admin_remove_admin
* Removes admin status from the given players
*
* @param mixed csv or array of player ids
* @action removes the given players admin status
* @return void
*/
public function admin_remove_admin($player_ids)
{
// make sure the user doing this is an admin
if ( ! $this->is_admin) {
throw new MyException(__METHOD__.': Player is not an admin');
}
array_trim($player_ids, 'int');
$player_ids[] = 0; // make sure we have at least one entry
if (isset($GLOBALS['_ROOT_ADMIN'])) {
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
WHERE username = '{$GLOBALS['_ROOT_ADMIN']}'
";
$root_admin = (int) $this->_mysql->fetch_value($query);
if (in_array($root_admin, $player_ids)) {
unset($player_ids[array_search($root_admin, $player_ids)]);
}
}
// remove the player doing the removing
unset($player_ids[array_search($_SESSION['player_id'], $player_ids)]);
// remove the admin doing the removing
unset($player_ids[array_search($_SESSION['admin_id'], $player_ids)]);
$this->_mysql->insert(self::EXTEND_TABLE, array('is_admin' => 0), " WHERE player_id IN (".implode(',', $player_ids).") ");
}
/** public function save
* Saves all changed data to the database
*
* @param void
* @action saves the player data
* @return void
*/
public function save( )
{
// update the player data
$query = "
SELECT allow_email
, max_games
, color
FROM ".self::EXTEND_TABLE."
WHERE player_id = '{$this->id}'
";
$player = $this->_mysql->fetch_assoc($query);
if ( ! $player) {
throw new MyException(__METHOD__.': Player data not found for player #'.$this->id);
}
// TODO: test the last online date and make sure we still have valid data
$update_player = false;
if ((bool) $player['allow_email'] != $this->allow_email) {
$update_player['allow_email'] = (int) $this->allow_email;
}
if ($player['max_games'] != $this->max_games) {
$update_player['max_games'] = (int) $this->max_games;
}
if ($player['color'] != $this->color) {
$update_player['color'] = $this->color;
}
if ($update_player) {
$this->_mysql->insert(self::EXTEND_TABLE, $update_player, " WHERE player_id = '{$this->id}' ");
}
}
/** protected function _pull
* Pulls all game player data from the database
* as well as the parent's data
*
* @param void
* @action pulls the player data
* @action pulls the game player data
* @return void
*/
protected function _pull( )
{
parent::_pull( );
$query = "
SELECT *
FROM ".self::EXTEND_TABLE."
WHERE player_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
if ( ! $result) {
// TODO: find out what is going on here and fix.
# throw new MyException(__METHOD__.': Data not found in database (#'.$this->id.')');
return false;
}
$this->is_admin = ( ! $this->is_admin) ? (bool) $result['is_admin'] : true;
$this->allow_email = (bool) $result['allow_email'];
$this->max_games = (int) $result['max_games'];
$this->color = $result['color'];
$this->wins = (int) $result['wins'];
$this->draws = (int) $result['draws'];
$this->losses = (int) $result['losses'];
$this->last_online = strtotime($result['last_online']);
// grab the player's current game count
$query = "
SELECT COUNT(*)
FROM ".Game::GAME_TABLE." AS G
LEFT JOIN ".Game::GAME_HISTORY_TABLE." AS GH
USING (game_id)
WHERE ((G.white_id = '{$this->id}'
OR G.black_id = '{$this->id}')
AND GH.board IS NOT NULL)
AND G.state = 'Playing'
";
$this->current_games = $this->_mysql->fetch_value($query);
}
/**
* STATIC METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static public function get_list
* Returns a list array of all game players
* in the database
* This function supersedes the parent's function and
* just grabs the whole lot in one query
*
* @param bool restrict to approved players
* @return array game player list (or bool false on failure)
*/
static public function get_list($only_approved = false)
{
$Mysql = Mysql::get_instance( );
$WHERE = ($only_approved) ? " WHERE P.is_approved = 1 " : '';
$query = "
SELECT *
, P.is_admin AS full_admin
, E.is_admin AS half_admin
FROM ".Player::PLAYER_TABLE." AS P
INNER JOIN ".self::EXTEND_TABLE." AS E
USING (player_id)
{$WHERE}
ORDER BY P.username
";
$list = $Mysql->fetch_array($query);
return $list;
}
/** static public function get_count
* Returns a count of all game players
* in the database
*
* @param void
* @return int game player count
*/
static public function get_count( )
{
$Mysql = Mysql::get_instance( );
$query = "
SELECT COUNT(*)
FROM ".self::EXTEND_TABLE." AS E
JOIN ".Player::PLAYER_TABLE." AS P
USING (player_id)
WHERE P.is_approved = 1
-- TODO: AND E.is_approved = 1
";
$count = $Mysql->fetch_value($query);
return $count;
}
/** static public function get_maxed
* Returns an array of all player ids
* who have reached their max games count
*
* @param void
* @return array of int player ids
*/
static public function get_maxed( )
{
$Mysql = Mysql::get_instance( );
// run through the maxed invites and set the key
// to the player id and the value to the invite count
// for ease of use later
$invites = array( );
// TODO: set a setting for this
if (true || $invites_count_toward_max_games) {
$query = "
SELECT COUNT(G.game_id) AS invite_count
, PE.player_id
FROM ".Game::GAME_TABLE." AS G
LEFT JOIN ".self::EXTEND_TABLE." AS PE
ON (PE.player_id = G.white_id
OR PE.player_id = G.black_id)
WHERE G.state = 'Waiting'
AND PE.max_games > 0
GROUP BY PE.player_id
";
$maxed_invites = $Mysql->fetch_array($query);
foreach ($maxed_invites as $invite) {
$invites[$invite['player_id']] = $invite['invite_count'];
}
}
$query = "
SELECT COUNT(G.game_id) AS game_count
, PE.player_id
, PE.max_games
FROM ".Game::GAME_TABLE." AS G
LEFT JOIN ".self::EXTEND_TABLE." AS PE
ON (PE.player_id = G.white_id
OR PE.player_id = G.black_id)
WHERE G.state = 'Playing'
AND PE.max_games > 0
GROUP BY PE.player_id
";
$maxed_players = $Mysql->fetch_array($query);
$player_ids = array( );
foreach ($maxed_players as $data) {
if ( ! isset($invites[$data['player_id']])) {
$invites[$data['player_id']] = 0;
}
if (($data['game_count'] + $invites[$data['player_id']]) >= $data['max_games']) {
$player_ids[] = $data['player_id'];
}
}
return $player_ids;
}
/** static public function delete_inactive
* Deletes the inactive users from the database
*
* @param int age in days
* @return void
*/
static public function delete_inactive($age)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$age = (int) abs($age);
if (0 == $age) {
return false;
}
$exception_ids = array( );
// make sure the 'unused' player is not an admin
$query = "
SELECT EP.player_id
FROM ".self::EXTEND_TABLE." AS EP
JOIN ".Player::PLAYER_TABLE." AS P
USING (player_id)
WHERE P.is_admin = 1
OR EP.is_admin = 1
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
// make sure the 'unused' player is not currently in a game
$query = "
SELECT DISTINCT white_id
FROM ".Game::GAME_TABLE."
WHERE state = 'Playing'
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
$query = "
SELECT DISTINCT black_id
FROM ".Game::GAME_TABLE."
WHERE state = 'Playing'
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
// make sure the 'unused' player isn't awaiting approval
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
WHERE is_approved = 0
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
$exception_ids[] = 0;
$exception_id_list = implode(',', $exception_ids);
// select unused accounts
$query = "
SELECT player_id
FROM ".self::EXTEND_TABLE."
WHERE wins + losses <= 2
AND player_id NOT IN ({$exception_id_list})
AND last_online < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
";
$player_ids = $Mysql->fetch_value_array($query);
call($player_ids);
if ($player_ids) {
Game::player_deleted($player_ids);
$Mysql->delete(self::EXTEND_TABLE, " WHERE player_id IN (".implode(',', $player_ids).") ");
}
}
diff --git a/classes/mysql.class.php b/classes/mysql.class.php
index c5e8274..261b978 100644
--- a/classes/mysql.class.php
+++ b/classes/mysql.class.php
@@ -1,645 +1,647 @@
<?php
/*
+---------------------------------------------------------------------------
|
| mysql.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
| based on works by W. Jason Gilmore
| http://www.wjgilmore.com; http://www.apress.com
|
+---------------------------------------------------------------------------
|
| > MySQL DB Queries module
| > Date started: 2005-09-02
|
| > Module Version Number: 0.9.2
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
class Mysql
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
protected $link_id; // MySQL Resource ID
protected $query; // MySQL query
protected $result; // Query result
protected $query_time; // Time it took to run the query
protected $query_count; // Total number of queries executed since class inception
protected $error; // Any error message encountered while running
protected $_host; // MySQL Host name
protected $_user; // MySQL Username
protected $_pswd; // MySQL password
protected $_db; // MySQL Database
protected $_page_query; // MySQL query for pagination
protected $_page_result; // MySQL result for pagination
protected $_num_results; // Number of total results found
protected $_page; // Current pagination page
protected $_num_per_page; // Number of records per page
protected $_num_pages; // number of total pages
protected $_error_debug = false; // Allows for error debug output
protected $_query_debug = false; // Allows for output of all queries all the time
protected $_log_errors = false; // write to log file when an error is encountered
protected $_log_path = './'; // Path to the MySQL error log file
protected $_email_errors = false; // send an email when an error is encountered
protected $_email_subject = 'Query Error'; // the email subject for the email message
protected $_email_from = '[email protected]'; // the email address to send error reports from
protected $_email_to = '[email protected]'; // the email address to send error reports to
static private $_instance; // Instance of the MySQL Object
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** protected function __construct
* Class constructor.
* Initializes the host, user, pswd, and db vars.
*
* @param array optional configuration array
* @return void
*/
protected function __construct($config = null)
{
if (empty($config) && isset($GLOBALS['_DEFAULT_DATABASE'])) {
$config = $GLOBALS['_DEFAULT_DATABASE'];
}
// each of these can be set independently as needed
$this->_error_debug = false; // set to true for output of errors
$this->_query_debug = false; // set to true for output of every query
if (empty($config)) {
throw new MySQLException(__METHOD__.': Missing MySQL configuration data');
}
$this->_host = $config['hostname'];
$this->_user = $config['username'];
$this->_pswd = $config['password'];
$this->_db = $config['database'];
$this->_log_path = (isset($config['log_path'])) ? $config['log_path'] : './';
$this->query_time = 0;
$this->query_count = 0;
try {
$this->_log(__METHOD__);
$this->_log('===============================');
$this->connect_select( );
}
catch (MySQLException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor.
* Closes the mysql connection.
*
* @param void
* @action close the mysql connection
* @return void
*/
+/*
public function __destruct( )
{
$this->_log(__METHOD__.': '.$this->link_id);
$this->_log('===============================');
return; // just stop doing this
@mysql_close($this->link_id);
$this->link_id = null;
self::$_instance = null;
}
+*/
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! property_exists($this, $property)) {
throw new MySQLException(__METHOD__.': Trying to access non-existent property ('.$property.')');
}
if ('_' === $property[0]) {
throw new MySQLException(__METHOD__.': Trying to access _private property ('.$property.')');
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MySQLException(__METHOD__.': Trying to access non-existent property ('.$property.')');
}
if ('_' === $property[0]) {
throw new MySQLException(__METHOD__.': Trying to access _private property ('.$property.')');
}
$this->$property = $value;
}
/** public function set_settings
* Sets the given settings for the object
*
* @param array settings array
* @action updates the settings
* @return void
*/
public function set_settings($settings)
{
$valid = array(
'log_errors',
'log_path',
'email_errors',
'email_subject',
'email_from',
'email_to',
);
foreach ($valid as $key) {
if (isset($settings[$key])) {
$var = '_'.$key;
$this->$var = $settings[$key];
}
}
}
/** public function test_connection
* Tests the connection to the MySQL
* server, and reconnects if needed
*
* @param void
* @action reconnects to the server
* @return void
*/
public function test_connection( )
{
if ( ! mysql_ping( )) {
mysql_close($this->link_id);
$this->connect_select( );
$this->_log('RECONNECT ++++++++++++++++++++++++++++++++++++++ '.$this->link_id);
}
}
/** public function connect
* Connect to the MySQL server.
*
* @param void
* @action connect to the mysql server
* @return void
*/
public function connect( )
{
$this->link_id = @mysql_connect($this->_host, $this->_user, $this->_pswd);
if ( ! $this->link_id) {
$this->error = mysql_errno( ).': '.mysql_error( );
throw new MySQLException(__METHOD__.': There was an error connecting to the server');
}
}
/** public function select
* Select the MySQL database.
*
* @param string [optional] database name
* @action select the mysql database
* @return void
*/
public function select($database = null)
{
if ( ! is_null($database)) {
$this->_db = $database;
}
if ( ! @mysql_select_db($this->_db, $this->link_id)) {
$this->error = mysql_errno($this->link_id).': '.mysql_error($this->link_id);
throw new MySQLException(__METHOD__.': There was an error selecting the database');
}
}
/** public function connect_select
* Connects to the server AND selects the default database in one function.
*
* @param string [optional] database name
* @action connect to the mysql server
* @action select the mysql database
* @return void
*/
public function connect_select($database = null)
{
if ( ! is_null($database)) {
$this->_db = $database;
}
try {
$this->connect( );
$this->select( );
}
catch (MySQLException $e) {
throw $e;
}
$this->_log(__METHOD__.': '.$this->link_id);
$this->_log('-------------------------------');
}
/** public function set_error
* Set the error level based on a bitwise value.
*
* @param int value (0 = none, 3 = all)
* @action set the error level
* @return void
*/
public function set_error($val)
{
$this->_error_debug = (0 != (1 & $val));
$this->_query_debug = (0 != (2 & $val));
}
/** public function query
* Execute a database query
* If no query is passed, it executes the last saved query.
*
* @param string [optional] SQL query string
* @param int [optional] number of tries
* @action execute a mysql query
* @return mysql result resource
*/
public function query($query = null, $tries = 0)
{
if ( ! is_null($query)) {
$this->query = $query;
}
if (is_null($this->query)) {
throw new MySQLException(__METHOD__.': No query found');
}
$backtrace_file = $this->_get_backtrace( );
$this->_log(__METHOD__.' in '.basename($backtrace_file['file']).' on '.$backtrace_file['line'].' : '.$this->query);
if (empty($this->link_id)) {
$this->connect_select( );
}
$done = true; // innocent until proven guilty
// start time logging
$time = microtime_float( );
$this->result = @mysql_query($this->query, $this->link_id);
$this->query_time = microtime_float( ) - $time;
if ($this->_query_debug && empty($GLOBALS['AJAX'])) {
$this->query = trim(preg_replace('/\\s+/', ' ', $this->query));
if (('cli' == php_sapi_name( )) && empty($_SERVER['REMOTE_ADDR'])) {
echo "\n\nMYSQL - ".basename($backtrace_file['file']).' on '.$backtrace_file['line']."- {$this->query} - Aff(".$this->affected_rows( ).") (".number_format($this->query_time, 5)." s)\n\n";
}
else {
echo "<div style='background:#FFF;color:#009;'><br /><strong>".basename($backtrace_file['file']).' on '.$backtrace_file['line']."</strong>- {$this->query} - <strong>Aff(".$this->affected_rows( ).") (".number_format($this->query_time, 5)." s)</strong></div>";
}
}
if ( ! $this->result) {
if ((5 >= $tries) && ((2013 == mysql_errno($this->link_id)) || (2006 == mysql_errno($this->link_id)))) {
// try reconnecting a couple of times
$this->_log('RETRYING #'.$tries.': '.mysql_errno($this->link_id));
$this->test_connection( );
return $this->query(null, ++$tries);
}
$extra = '';
if ($backtrace_file) {
$line = $backtrace_file['line'];
$file = $backtrace_file['file'];
$file = substr($file, strlen(realpath($file.'../../../')));
$extra = ' on line <strong>'.$line.'</strong> of <strong>'.$file.'</strong>';
}
$this->error = mysql_errno($this->link_id).': '.mysql_error($this->link_id);
$this->_error_report( );
if ($this->_error_debug) {
if (('cli' == php_sapi_name( )) && empty($_SERVER['REMOTE_ADDR'])) {
$extra = strip_tags($extra);
echo "\n\nMYSQL ERROR - There was an error in your query{$extra}:\nERROR: {$this->error}\nQUERY: {$this->query}\n\n";
}
else {
echo "<div style='background:#900;color:#FFF;'>There was an error in your query{$extra}:<br />ERROR: {$this->error}<br />QUERY: {$this->query}</div>";
}
}
else {
$this->error = 'There was a database error.';
}
$done = false;
}
if ($done) {
// if we just performed an insert, grab the insert_id and return it
if (preg_match('/^\s*(INSERT|REPLACE)/i', $this->query)) {
$this->result = $this->fetch_insert_id( );
}
$this->query_count++;
return $this->result;
}
// no result found
return false;
}
/** public function affected_rows
* Return the number of affected rows from the latest query.
*
* @param void
* @return int number of affected rows
*/
public function affected_rows( )
{
$count = @mysql_affected_rows($this->link_id);
return $count;
}
/** public function num_rows
* Return the number of returned rows from the latest query.
*
* @param void
* @return int number of returned rows
*/
public function num_rows( )
{
$count = @mysql_num_rows($this->result);
if ( ! $count) {
return 0;
}
return $count;
}
/** public function insert
* Insert the associative data array into the table.
* $data['field_name'] = value
* $data['field_name2'] = value2
* If the field name has a trailing space: $data['field_name ']
* then the query will insert the data with no sanitation
* or wrapping quotes (good for function calls, like NOW( )).
*
* @param string table name
* @param array associative data array
* @param string [optional] where clause (for updates)
* @param bool [optional] whether or not we should replace values (true / false)
* @action execute a mysql query
* @return int insert id for row
*/
public function insert($table, $data_array, $where = '', $replace = false)
{
$where = trim($where);
$replace = (bool) $replace;
if ('' == $where) {
$query = (false == $replace) ? ' INSERT ' : ' REPLACE ';
$query .= ' INTO ';
}
else {
$query = ' UPDATE ';
}
$query .= '`'.$table.'`';
if ( ! is_array($data_array)) {
throw new MySQLException(__METHOD__.': Trying to insert non-array data');
}
else {
$query .= ' SET ';
foreach ($data_array as $field => $value) {
if (is_null($value)) {
$query .= " `{$field}` = NULL , ";
}
elseif (' ' == substr($field, -1, 1)) { // i picked a trailing space because it's an illegal field name in MySQL
$field = trim($field);
$query .= " `{$field}` = {$value} , ";
}
else {
$query .= " `{$field}` = '".sani($value)."' , ";
}
}
$query = substr($query, 0, -2).' '; // remove the last comma (but preserve those spaces)
}
$query .= ' '.$where.' ';
$this->query = $query;
$return = $this->query( );
if ('' == $where) {
return $this->fetch_insert_id( );
}
else {
return $return;
}
}
/** public function multi_insert
* Insert the array of associative data arrays into the table.
* $data[0]['field_name'] = value
* $data[0]['field_name2'] = value2
* $data[0]['DBWHERE'] = where clause [optional]
* $data[1]['field_name'] = value
* $data[1]['field_name2'] = value2
* $data[1]['DBWHERE'] = where clause [optional]
*
* @param string table name
* @param array associative data array
* @param bool [optional] whether or not we should replace values (true / false)
* @action execute multiple mysql queries
* @return array insert ids for rows (with original keys preserved)
*/
public function multi_insert($table, $data_array, $replace = false)
{
if ( ! is_array($data_array)) {
throw new MySQLException(__METHOD__.': Trying to multi-insert non-array data');
}
else {
$result = array( );
foreach ($data_array as $key => $row) {
$where = (isset($row['DBWHERE'])) ? $row['DBWHERE'] : '';
unset($row['DBWHERE']);
$result[$key] = $this->insert($table, $row, $where, $replace);
}
}
return $result;
}
/** public function delete
* Delete the row from the table
*
* @param string table name
* @param string where clause
* @action execute a mysql query
* @return result
*/
public function delete($table, $where)
{
$query = "
DELETE
FROM `{$table}`
{$where}
";
$this->query = $query;
try {
return $this->query( );
}
catch (MySQLException $e) {
throw $e;
}
}
/** public function multi_delete
* Delete the array of data from the table.
* $table[0] = table name
* $table[1] = table name
*
* $where[0] = where clause
* $where[1] = where clause
*
* If recursive is true, all combinations of table name
* and where clauses will be executed.
*
* If only one table name is set, that table will
* be used for all of the queries, looping through
* the where array
*
* If only one where clause is set, that where clause
* will be used for all of the queries, looping through
* the table array
*
* @param mixed table name array or single string
* @param mixed where clause array or single string
* @param bool optional recursive (default false)
* @action execute multiple mysql queries
* @return array results
*/
public function multi_delete($table_array, $where_array, $recursive = false)
{
if ( ! is_array($table_array)) {
$recursive = false;
$table_array = (array) $table_array;
}
if ( ! is_array($where_array)) {
$recursive = false;
$where_array = (array) $where_array;
}
if ($recursive) {
foreach ($table_array as $table) {
foreach ($where_array as $where) {
$result[] = $this->delete($table, $where);
}
}
}
else {
if (count($table_array) == count($where_array)) {
for ($i = 0, $count = count($table_array); $i < $count; ++$i) {
$result[] = $this->delete($table_array[$i], $where_array[$i]);
}
}
elseif (1 == count($table_array)) {
$table = $table_array[0];
foreach ($where_array as $where) {
$result[] = $this->delete($table, $where);
}
}
elseif (1 == count($where_array)) {
$where = $where_array[0];
foreach ($table_array as $table) {
$result[] = $this->delete($table, $where);
}
}
else {
throw new MySQLException(__METHOD__.': Trying to multi-delete with incompatible array sizes');
}
}
return $result;
}
/** public function fetch_object
* Execute a database query and return the next result row as object.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return mysql next result object row
*/
public function fetch_object($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_object($this->result);
return $row;
}
diff --git a/classes/settings.class.php b/classes/settings.class.php
index 7439054..1055389 100644
--- a/classes/settings.class.php
+++ b/classes/settings.class.php
@@ -1,471 +1,476 @@
<?php
/*
+---------------------------------------------------------------------------
|
| settings.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Settings module
| > Date started: 2009-04-15
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
class Settings
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property SETTINGS_TABLE
* Holds the settings table name
*
* @var string
*/
const SETTINGS_TABLE = T_SETTINGS;
/** protected property _settings
* Stores the site settings in an
* associative array
*
* @param array
*/
protected $_settings = array( );
/** protected property _notes
* Stores the site settings notes in an
* associative array
*
* @param array
*/
protected $_notes = array( );
/** protected property _delete_missing
* Deletes missing settings from the database
* when saving settings
*
* @param bool
*/
protected $_delete_missing = false;
/** protected property _save_new
* Saves new (previously unsaved) settings
* to the database when saving settings
*
* @param bool
*/
protected $_save_new = false;
/** static private property _instance
* Holds the instance of this object
*
* @var Settings object
*/
static private $_instance;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** protected function __construct
* Class constructor
*
* @param void
* @action instantiates object
* @action pulls settings from settings table
* @return void
*/
protected function __construct( )
{
$this->_mysql = Mysql::get_instance( );
if ($this->test( )) {
$this->_pull( );
}
}
/** public function __destruct
* Class destructor
*
* @param void
* @action saves settings to DB
* @action destroys object
* @return void
*/
+/*
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) {
try {
- $this->_save( );
+ $this->save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
+*/
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! isset($this->_settings[$property]) && ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
if (isset($this->_settings[$property])) {
return $this->_settings[$property];
}
else {
return $this->$property;
}
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return void
*/
public function __set($property, $value)
{
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
if (property_exists($this, $property)) {
$this->$property = $value;
}
else {
$this->_settings[$property] = $value;
}
}
/** protected function _pull
* Pulls all settings data from the database
*
* @param void
* @action pulls the settings data
* @return void
*/
protected function _pull( )
{
$query = "
SELECT *
FROM ".self::SETTINGS_TABLE."
ORDER BY sort
";
$results = $this->_mysql->fetch_array($query);
if ( ! $results) {
die('Settings were not pulled properly');
}
$this->_settings = array( );
foreach ((array) $results as $result) {
$this->_settings[$result['setting']] = $result['value'];
$this->_notes[$result['setting']] = $result['notes'];
}
}
- /** protected function _save
+ /** public function save
* Saves all settings data to the database
* if the settings are different
*
* @param void
* @action saves the settings data
* @return void
*/
- protected function _save( )
+ public function save( )
{
call(__METHOD__);
$query = "
SELECT *
FROM ".self::SETTINGS_TABLE."
ORDER BY sort
";
$results = $this->_mysql->fetch_array($query);
$data = array( );
$settings = $this->_settings;
foreach ($results as $result) {
if (isset($settings[$result['setting']])) {
if ($result['value'] != $settings[$result['setting']]) {
$result['value'] = $settings[$result['setting']];
$data[] = $result;
}
unset($settings[$result['setting']]);
}
elseif ($this->_delete_missing) {
$this->_mysql->delete(self::SETTINGS_TABLE, " WHERE setting = {$result['setting']} ");
}
}
if ($this->_save_new) {
foreach ($settings as $setting => $value) {
$addition['setting'] = $setting;
$addition['value'] = $value;
$data[] = $addition;
}
}
$this->_mysql->multi_insert(self::SETTINGS_TABLE, $data, true);
}
/** protected function get_settings
* Grabs the whole settings array and returns it
*
* @param void
* @return array settings
*/
protected function get_settings( )
{
return $this->_settings;
}
/** protected function put_settings
* Merges the submitted settings into
* the settings array
*
* @param array settings
* @return void
*/
protected function put_settings($settings)
{
if (is_array($settings)) {
$this->_settings = array_merge($this->_settings, $settings);
}
}
/** static public function get_instance
* Returns the singleton instance
* of the Settings Object as a reference
*
* @param void
* @action optionally creates the instance
* @return Settings Object reference
*/
static public function get_instance( )
{
if (is_null(self::$_instance) && self::test( )) {
self::$_instance = new Settings( );
}
return self::$_instance;
}
/** static public function read
* Gets the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
* @see __get
*/
static public function read($property)
{
if (self::get_instance( )) {
return self::get_instance( )->$property;
}
else {
return false;
}
}
/** static public function read_all
* Gets all the properties
*
* @param void
* @return array property => value pairs
*/
static public function read_all( )
{
if (self::get_instance( )) {
return self::get_instance( )->get_settings( );
}
else {
return false;
}
}
/** static public function write
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @return void
* @see __set
*/
static public function write($property, $value)
{
if (self::get_instance( )) {
self::get_instance( )->$property = $value;
+ self::get_instance( )->save( );
}
}
/** static public function write_all
* Sets all the properties
*
* @param array property => value pairs
* @return void
* @see __set
*/
static public function write_all($settings)
{
if (self::get_instance( )) {
- return self::get_instance( )->put_settings($settings);
+ self::get_instance( )->put_settings($settings);
+ self::get_instance( )->save( );
+ return self::get_instance( )->get_settings( );
}
else {
return false;
}
}
/** static public function read_setting_notes
* Reads the notes associated with the settings
*
* @param void
* @return array settings notes
*/
static public function read_setting_notes( )
{
if ($_this = self::get_instance( )) { // single equals intended
return $_this->_notes;
}
else {
return false;
}
}
/** static public function test
* Test the MySQL connection
*
* @param void
* @return bool connection OK
*/
static public function test( )
{
if ( ! is_null(self::$_instance)) {
return true;
}
if ( ! Mysql::test( )) {
return false;
}
// look for anything in the settings table
$query = "
SELECT *
FROM ".self::SETTINGS_TABLE."
";
$return = Mysql::get_instance( )->query($query);
return (bool) $return;
}
} // end of Settings class
/* schemas
// ===================================
--
-- Table structure for table `ph_settings`
--
DROP TABLE IF EXISTS `ph_settings`;
CREATE TABLE IF NOT EXISTS `ph_settings` (
`setting` varchar(255) NOT NULL DEFAULT '',
`value` text NOT NULL,
`notes` text,
`sort` smallint(5) unsigned NOT NULL DEFAULT '0',
UNIQUE KEY `setting` (`setting`),
KEY `sort` (`sort`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
--
-- Dumping data for table `ph_settings`
--
INSERT INTO `ph_settings` (`setting`, `value`, `notes`, `sort`) VALUES
('site_name', 'Your Site Name', 'The name of your site', 10),
('default_color', 'c_green_white.css', 'The default theme color for the script pages', 20),
('nav_links', '<!-- your nav links here -->', 'HTML code for your site''s navigation links to display on the script pages', 30),
('from_email', '[email protected]', 'The email address used to send game emails', 40),
('to_email', '[email protected]', 'The email address to send admin notices to (comma separated)', 50),
('new_users', '1', '(1/0) Allow new users to register (0 = off)', 60),
('approve_users', '0', '(1/0) Require admin approval for new users (0 = off)', 70),
('confirm_email', '0', '(1/0) Require email confirmation for new users (0 = off)', 80),
('max_users', '0', 'Max users allowed to register (0 = off)', 90),
('default_pass', 'change!me', 'The password to use when resetting a user''s password', 100),
('expire_users', '45', 'Number of days until untouched games are deleted (0 = off)', 110),
('save_games', '1', '(1/0) Save games in the ''games'' directory on the server (0 = off)', 120),
('expire_games', '30', 'Number of days until untouched user accounts are deleted (0 = off)', 130),
('nudge_flood_control', '24', 'Number of hours between nudges. (-1 = no nudging, 0 = no flood control)', 135),
('timezone', 'UTC', 'The timezone to use for dates (<a href="http://www.php.net/manual/en/timezones.php">List of Timezones</a>)', 140),
('long_date', 'M j, Y g:i a', 'The long format for dates (<a href="http://www.php.net/manual/en/function.date.php">Date Format Codes</a>)', 150),
('short_date', 'Y.m.d H:i', 'The short format for dates (<a href="http://www.php.net/manual/en/function.date.php">Date Format Codes</a>)', 160),
('debug_pass', '', 'The DEBUG password to use to set temporary DEBUG status for the script', 170),
('DB_error_log', '1', '(1/0) Log database errors to the ''logs'' directory on the server (0 = off)', 180),
('DB_error_email', '1', '(1/0) Email database errors to the admin email addresses given (0 = off)', 190);
*/
diff --git a/classes/setup.class.php b/classes/setup.class.php
index 74dfc91..4668097 100644
--- a/classes/setup.class.php
+++ b/classes/setup.class.php
@@ -1,628 +1,630 @@
<?php
/*
+---------------------------------------------------------------------------
|
| setup.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Pharaoh Setup module
| > Date started: 2009-12-22
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
class Setup {
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property SETUP_TABLE
* Holds the game setup table name
*
* @var string
*/
const SETUP_TABLE = T_SETUP;
/** protected property id
* Holds the setup id
*
* @var int
*/
protected $id;
/** protected property board
* Holds the game board as expanded FEN
*
* @var string
*/
protected $board;
/** protected property name
* Holds the name of the setup
*
* @var string
*/
protected $name = '';
/** protected property creator
* Holds the id of the creator (player)
*
* @var int
*/
protected $creator = 0;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param void
* @action instantiates object
* @return void
*/
public function __construct($id = null)
{
$id = (int) $id;
call(__METHOD__);
$this->_init_board( );
if ($id) {
$this->id = $id;
}
$this->_pull( );
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action destroys object
* @return void
*/
+/*
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
+*/
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
switch ($property) {
case 'name' :
// make sure this name isn't in use
$test_value = sani($value);
$query = "
SELECT COUNT(*)
FROM ".self::SETUP_TABLE."
WHERE name = '{$test_value}'
AND setup_id <> '{$this->id}'
";
$count = Mysql::get_instance( )->fetch_value($query);
if ($count) {
throw new MyException(__METHOD__.': That setup name ('.$value.') is already in use');
}
break;
case 'board' :
try {
self::is_valid_setup($value);
}
catch (MyExecption $e) {
throw $e;
}
$value = expandFEN($value);
break;
case 'id' :
$value = (int) $value;
break;
default :
// do nothing
break;
}
$this->$property = $value;
}
/** public function __toString
* Returns the ascii version of the board
* when asked to output the object
*
* @param void
* @return string ascii version of the board
*/
public function __toString( )
{
return $this->_get_board_ascii( );
}
/** static public function get_board_ascii
* Returns the board in an ASCII format
*
* A B C D E F G H I J
* +---+---+---+---+---+---+---+---+---+---+
* 8 | R | S | | | | | | | R | S | 8
* +---+---+---+---+---+---+---+---+---+---+
* 7 | R | | | | | | | | | S | 7
* +---+---+---+---+---+---+---+---+---+---+
* 6 | R | | | | | | | | | S | 6
* +---+---+---+---+---+---+---+---+---+---+
* 5 | R | | | | | | | | | S | 5
* +---+---+---+---+---o---+---+---+---+---+
* 4 | R | | | | | | | | | S | 4
* +---+---+---+---+---+---+---+---+---+---+
* 3 | R | | | | | | | | | S | 3
* +---+---+---+---+---+---+---+---+---+---+
* 2 | R | | | | | | | | | S | 2
* +---+---+---+---+---+---+---+---+---+---+
* 1 | R | S | | | | | | | R | S | 1
* +---+---+---+---+---+---+---+---+---+---+
* A B C D E F G H I J
*
* @param string expanded board FEN
* @return string ascii board
*/
static public function get_board_ascii($board)
{
$ascii = '
A B C D E F G H I J
+---+---+---+---+---+---+---+---+---+---+';
for ($length = strlen($board), $i = 0; $i < $length; ++$i) {
$char = $board[$i];
if (0 == ($i % 10)) {
$ascii .= "\n ".(8 - floor($i / 10)).' |';
}
if ('0' == $char) {
$char = ' ';
}
$ascii .= ' '.$char.' |';
if (9 == ($i % 10)) {
$ascii .= ' '.(8 - floor($i / 10)).'
+---+---+---+---+---+---+---+---+---+---+';
}
}
$ascii .= '
A B C D E F G H I J
';
return $ascii;
}
/** protected function _get_board_ascii
* Returns the board in an ASCII format
*
* @see get_board_ascii
* @param string optional expanded board FEN
* @return string ascii board
*/
protected function _get_board_ascii($board = null)
{
if ( ! $board) {
$board = $this->_board;
}
return self::get_board_ascii($board);
}
/** protected function _pull
* Pulls the setup data from the database
*
* @param void
* @action pulls the setup data and sets the class properties
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return;
}
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE setup_id = '{$this->id}'
";
$setup = Mysql::get_instance( )->fetch_assoc($query);
$this->board = expandFEN($setup['board']);
$this->creator = $setup['created_by'];
$this->name = $setup['name'];
}
/** protected function _init_board
* Initializes an empty board
*
* @param void
* @action initializes an empty board
* @return void
*/
protected function _init_board( )
{
$this->board = expandFEN('10/10/10/10/10/10/10/10');
}
/** public function validate
* Validates the current setup
*
* @param string [optional] reflection type (Origin, Long, Short)
* @return bool if the setup is valid
*/
public function validate($reflection = 'Origin')
{
call(__METHOD__);
call($this->board);
$Mysql = Mysql::get_instance( );
try {
// will run is_valid_setup as well
self::is_valid_reflection($this->board, $reflection);
}
catch (MyExecption $e) {
throw $e;
}
// test for pre-existing setup
$FEN = packFEN($this->board);
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE board = '{$FEN}'
AND setup_id <> '{$this->id}'
";
$result = $Mysql->fetch_assoc($query);
if ($result) {
throw new MyException(__METHOD__.': Setup already exists as "'.$result['name'].'" (#'.$result['setup_id'].')');
}
// test for pre-existing setup name
$name = sani($this->name);
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE name = '{$name}'
AND setup_id <> '{$this->id}'
";
$result = $Mysql->fetch_assoc($query);
if ($result) {
throw new MyException(__METHOD__.': Setup name ('.$name.') already used (#'.$result['setup_id'].')');
}
return true;
}
/** protected function _save
* Saves the setup data to the database
*
* @param string [optional] reflection type (Origin, Long, Short)
* @action saves the setup data
* @return void
*/
protected function _save($reflection = 'Origin')
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
try {
$this->validate($reflection);
}
catch (MyException $e) {
throw $e;
}
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
// translate (filter/sanitize) the data
$data['name'] = $this->name;
$data['board'] = packFEN($this->board);
$data['reflection'] = self::_get_reflection($this->board);
$data['has_horus'] = self::has_horus($this->board);
$data['has_sphynx'] = self::has_sphynx($this->board);
$data['has_tower'] = self::has_tower($this->board);
$data['created_by'] = (int) $this->creator;
call($data);
// create the setup
$required = array(
'name',
'board',
);
$key_list = array_merge($required, array(
'reflection',
'has_horus',
'has_sphynx',
'has_tower',
'created_by',
));
try {
$_DATA = array_clean($data, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['created '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
// grab the original setup data
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE setup_id = '{$this->id}'
";
$setup = $Mysql->fetch_assoc($query);
call($setup);
if ( ! empty($this->id) && ! $setup) {
// we must have deleted the setup, just stop
return false;
}
if ( ! $setup) {
$this->id = $Mysql->insert(self::SETUP_TABLE, $_DATA);
if (empty($this->id)) {
throw new MyException(__METHOD__.': Setup could not be created');
}
return $this->id;
}
$update_setup = false;
// don't change the creator
// in case of admin edits
unset($_DATA['created_by']);
foreach ($setup as $key => $value) {
if (empty($_DATA[$key])) {
continue;
}
if ($_DATA[$key] != $value) {
$update_setup[$key] = $_DATA[$key];
}
}
call($update_setup);
if ($update_setup) {
$Mysql->insert(self::SETUP_TABLE, $update_setup, " WHERE setup_id = '{$this->id}' ");
return true;
}
return false;
}
public function save( )
{
call(__METHOD__);
call($_POST);
// set the post stuff into the object
try {
$this->name = $_POST['name'];
$this->board = $_POST['setup'];
$this->creator = $_SESSION['player_id'];
}
catch (MyException $e) {
throw $e;
}
return $this->_save($_POST['reflection']);
}
/** static public function is_valid_setup
* Tests the validity of the given setup
*
* @param string setup
* @return bool valid setup
*/
static public function is_valid_setup($setup)
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
if (80 != strlen($xFEN)) {
throw new MyException(__METHOD__.': Incorrect board size');
}
// test for a pharaoh on both sides
if ( ! preg_match('/P/', $xFEN, $s_match) || ! preg_match('/p/', $xFEN, $r_match)) {
throw new MyException(__METHOD__.': Missing one or both Pharaohs');
}
// make sure there's only one of each pharaoh
if ((1 != count($s_match)) || (1 != count($r_match))) {
throw new MyException(__METHOD__.': Too many of one or both Pharaohs');
}
// test for a sphynx on both sides (if any)
if (preg_match('/[EFJK]/i', $xFEN) && ( ! preg_match('/[EFJK]/', $xFEN, $s_match) || ! preg_match('/[efjk]/', $xFEN, $r_match))) {
throw new MyException(__METHOD__.': Missing one or both Sphynxes');
}
// make sure there's only one of each sphynx
if ((1 != count($s_match)) || (1 != count($r_match))) {
throw new MyException(__METHOD__.': Too many of one or both Sphynxes');
}
// look for invalid characters
if (preg_match('/[^abcdefhijklmnoptvwxy0]/i', $xFEN)) {
throw new MyException(__METHOD__.': Invalid characters found in setup');
}
// test for pieces on incorrect colors
$not_silver = array(0, 10, 20, 30, 40, 50, 60, 70, 8, 78);
foreach ($not_silver as $i) {
if (('0' != $xFEN[$i]) && ('silver' == Pharaoh::get_piece_color($xFEN[$i]))) {
throw new MyException(__METHOD__.': Silver piece on red square at '.$i);
}
}
$not_red = array(9, 19, 29, 39, 49, 59, 69, 79, 1, 71);
foreach ($not_red as $i) {
if (('0' != $xFEN[$i]) && ('red' == Pharaoh::get_piece_color($xFEN[$i]))) {
throw new MyException(__METHOD__.': Red piece on silver square at '.$i);
}
}
return true;
}
/** static public function test_reflection
* Tests the validity of the given reflection
* for the given setup
*
* @param string setup
* @param string [optional] reflection type (Origin, Long, Short)
* @return bool if the reflection is valid
*/
static public function is_valid_reflection($setup, $type = 'Origin')
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
// validate the setup
try {
self::is_valid_setup($xFEN);
}
catch (MyException $e) {
throw $e;
}
// make sure the given xFEN has all the pieces reflected properly
switch ($type) {
case 'Origin' :
$reflect = array(
// pyramids
'A' => 'c', 'C' => 'a',
'B' => 'd', 'D' => 'b',
// djeds
'X' => 'x', 'Y' => 'y',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'h', 'I' => 'i',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$return = 79 - $i;
';
break;
case 'Long' :
$reflect = array(
// pyramids
'A' => 'b', 'B' => 'a',
diff --git a/invite.php b/invite.php
index f946c54..960b66d 100644
--- a/invite.php
+++ b/invite.php
@@ -1,273 +1,274 @@
<?php
require_once 'includes/inc.global.php';
// this has nothing to do with creating a game
// but I'm running it here to prevent long load
// times on other pages where it would be run more often
GamePlayer::delete_inactive(Settings::read('expire_users'));
Game::delete_inactive(Settings::read('expire_games'));
Game::delete_finished(Settings::read('expire_finished_games'));
-$Game = new Game( );
-
if (isset($_POST['invite'])) {
+ $Game = new Game( );
+
// make sure this user is not full
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
Flash::store('You have reached your maximum allowed games !', false);
}
test_token( );
try {
$game_id = $Game->invite( );
+ $Game->save( );
Flash::store('Invitation Sent Successfully', true);
}
catch (MyException $e) {
Flash::store('Invitation FAILED !', false);
}
}
// grab the full list of players
$players_full = GamePlayer::get_list(true);
$invite_players = array_shrink($players_full, 'player_id');
// grab the players who's max game count has been reached
$players_maxed = GamePlayer::get_maxed( );
$players_maxed[] = $_SESSION['player_id'];
// remove the maxed players from the invite list
$players = array_diff($invite_players, $players_maxed);
$opponent_selection = '';
$opponent_selection .= '<option value="">-- Open --</option>';
foreach ($players_full as $player) {
if ($_SESSION['player_id'] == $player['player_id']) {
continue;
}
if (in_array($player['player_id'], $players)) {
$opponent_selection .= '
<option value="'.$player['player_id'].'">'.$player['username'].'</option>';
}
}
$groups = array(
'Normal' => array(0, 0),
'Eye of Horus' => array(0, 1),
'Sphynx' => array(1, 0),
'Sphynx & Horus' => array(1, 1),
);
$group_names = array_keys($groups);
$group_markers = array_values($groups);
$setups = Setup::get_list( );
$setup_selection = '<option value="0">Random</option>';
$setup_javascript = '';
$cur_group = false;
$group_open = false;
foreach ($setups as $setup) {
$marker = array((int) $setup['has_sphynx'], (int) $setup['has_horus']);
$group_index = array_search($marker, $group_markers, true);
if ($cur_group !== $group_names[$group_index]) {
if ($group_open) {
$setup_selection .= '</optgroup>';
$group_open = false;
}
$cur_group = $group_names[$group_index];
$setup_selection .= '<optgroup label="'.$cur_group.'">';
$group_open = true;
}
$setup_selection .= '
<option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>';
$setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n";
}
$setup_javascript = substr(trim($setup_javascript), 0, -1);
if ($group_open) {
$setup_selection .= '</optgroup>';
}
$meta['title'] = 'Send Game Invitation';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">//<![CDATA[
var setups = {
'.$setup_javascript.'
};
/*]]>*/</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/invite.js"></script>
';
$hints = array(
'Invite a player to a game by filling out your desired game options.' ,
'<span class="highlight">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' ,
);
// make sure this user is not full
$submit_button = '<div><input type="submit" name="invite" value="Send Invitation" /></div>';
$warning = '';
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
$submit_button = $warning = '<p class="warning">You have reached your maximum allowed games, you can not create this game !</p>';
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="send"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="player_id" value="{$_SESSION['player_id']}" />
{$warning}
<div><label for="opponent">Opponent</label><select id="opponent" name="opponent">{$opponent_selection}</select></div>
<div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup" class="options">Show Setup</a></div>
<div><label for="color">Your Color</label><select id="color" name="color"><option value="random">Random</option><option value="white">Silver</option><option value="black">Red</option></select></div>
<div class="random_convert options">
<fieldset>
<legend>Conversion</legend>
<p>
If your random game is a v1.0 game, you can convert it to play v2.0 Pharaoh.<br />
Or, if your random game is a v2.0 game, you can convert it to play v1.0 Pharaoh.<br />
</p>
<p>
When you select to convert, more options may be shown below.
</p>
<div><label class="inline"><input type="checkbox" id="rand_convert_to_1" name="rand_convert_to_1" /> Convert to 1.0</label></div>
<div><label class="inline"><input type="checkbox" id="rand_convert_to_2" name="rand_convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .random_convert -->
<div class="pharaoh_1 options">
<fieldset>
<legend>v1.0 Options</legend>
<p class="conversion">
Here you can convert v1.0 setups to play v2.0 Pharaoh.<br />
The conversion places a Sphynx in your lower-right corner facing upwards (and opposite for your opponent)
and converts any double-stacked Obelisks to Anubises which face forward.
</p>
<p class="conversion">
When you select to convert, more options will be shown below, as well as the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_2" name="convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .pharaoh_1 -->
<div class="pharaoh_2 p2_box options">
<fieldset>
<legend>v2.0 Options</legend>
<p class="conversion">
Here you can convert the v2.0 setups to play v1.0 Pharaoh.<br />
The conversion removes any Sphynxes from the board and converts any Anubises to double-stacked Obelisks.
</p>
<p class="conversion">
When you select to convert, the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_1" name="convert_to_1" /> Convert to 1.0</label></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="move_sphynx" name="move_sphynx" /> Sphynx is movable</label></div>
</fieldset>
</div> <!-- .pharaoh_2 -->
<fieldset>
<legend><label class="inline"><input type="checkbox" name="laser_battle_box" id="laser_battle_box" class="fieldset_box" /> Laser Battle</label></legend>
<div id="laser_battle" class="options">
<p>
When a laser gets shot by the opponents laser, it will be disabled for a set number of turns, making that laser unable to shoot until those turns have passed.<br />
After those turns have passed, and the laser has recovered, it will be immune from further shots for a set number of turns.<br />
After the immunity turns have passed, whether or not the laser was shot again, it will now be susceptible to being shot again.
<span class="pharaoh_2"><br />You can also select if the Sphynx is hittable only in the front, or on all four sides.</span>
</p>
<div><label for="battle_dead">Dead for:</label><input type="text" id="battle_dead" name="battle_dead" size="4" /> <span class="info">(Default: 1; Minimum: 1)</span></div>
<div><label for="battle_immune">Immune for:</label><input type="text" id="battle_immune" name="battle_immune" size="4" /> <span class="info">(Default: 1; Minimum: 0)</span></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_front_only" name="battle_front_only" checked="checked" /> Only front hits on Sphynx count</label></div>
<!-- <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_hit_self" name="battle_hit_self" /> Hit Self</label></div> -->
<p>You can set the "Immune for" value to 0 to allow a laser to be shot continuously, but the minimum value for the "Dead for" value is 1, as it makes no sense otherwise.</p>
</div> <!-- #laser_battle -->
</fieldset>
{$submit_button}
<div class="clr"></div>
</div></form>
<div id="setup_display"></div>
EOF;
// create our invitation tables
list($in_vites, $out_vites, $open_vites) = Game::get_invites($_SESSION['player_id']);
$contents .= <<< EOT
<form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv" id="invites">
EOT;
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no received invites to show</p>' ,
'caption' => 'Invitations Received' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" /><input type="button" id="decline-[[[game_id]]]" value="Decline" />', false) ,
);
$contents .= get_table($table_format, $in_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no sent invites to show</p>' ,
'caption' => 'Invitations Sent' ,
);
$table_format = array(
array('Invitee', '###ifenr(\'[[[invitee]]]\', \'-- OPEN --\')') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '###\'<input type="button" id="withdraw-[[[game_id]]]" value="Withdraw" />\'.((strtotime(\'[[[create_date]]]\') >= strtotime(\'[[[resend_limit]]]\')) ? \'\' : \'<input type="button" id="resend-[[[game_id]]]" value="Resend" />\')', false) ,
);
$contents .= get_table($table_format, $out_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no open invites to show</p>' ,
'caption' => 'Open Invitations' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" />', false) ,
);
$contents .= get_table($table_format, $open_vites, $table_meta);
$contents .= <<< EOT
</div></form>
EOT;
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer( );
|
benjamw/pharaoh | e54e940c52a4c9174047cc2b9854fd1a41998d18 | made error messages more useful | diff --git a/ajax_helper.php b/ajax_helper.php
index e5030c8..c115f84 100644
--- a/ajax_helper.php
+++ b/ajax_helper.php
@@ -1,290 +1,294 @@
<?php
$GLOBALS['NODEBUG'] = true;
$GLOBALS['AJAX'] = true;
// don't require log in when testing for used usernames and emails
if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) {
define('LOGIN', false);
}
require_once 'includes/inc.global.php';
// if we are debugging, change some things for us
// (although REQUEST_METHOD may not always be valid)
if (('GET' == $_SERVER['REQUEST_METHOD']) && test_debug( )) {
$GLOBALS['NODEBUG'] = false;
$GLOBALS['AJAX'] = false;
$_GET['token'] = $_SESSION['token'];
$_GET['keep_token'] = true;
$_POST = $_GET;
$DEBUG = true;
call('AJAX HELPER');
call($_POST);
}
// run the index page refresh checks
if (isset($_POST['timer'])) {
$message_count = (int) Message::check_new($_SESSION['player_id']);
$turn_count = (int) Game::check_turns($_SESSION['player_id']);
echo $message_count + $turn_count;
exit;
}
// run registration checks
if (isset($_POST['validity_test'])) {
# if (('email' == $_POST['type']) && ('' == $_POST['value'])) {
# echo 'OK';
# exit;
# }
$player_id = 0;
if ( ! empty($_POST['profile'])) {
$player_id = (int) $_SESSION['player_id'];
}
switch ($_POST['validity_test']) {
case 'username' :
case 'email' :
$username = '';
$email = '';
${$_POST['validity_test']} = sani($_POST['value']);
$player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0);
try {
Player::check_database($username, $email, $player_id);
}
catch (MyException $e) {
echo $e->getCode( );
exit;
}
break;
default :
break;
}
echo 'OK';
exit;
}
// run the in game chat
if (isset($_POST['chat'])) {
try {
if ( ! isset($_SESSION['game_id'])) {
$_SESSION['game_id'] = 0;
}
$Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']);
$Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby']));
$return = $Chat->get_box_list(1);
$return = $return[0];
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup validation
if (isset($_POST['test_setup'])) {
try {
Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']);
$return['valid'] = true;
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup laser test fire
if (isset($_POST['test_fire'])) {
try {
// returns laser_path and hits arrays
$return = Pharaoh::fire_laser($_POST['color'], $_POST['board']);
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run the invites stuff
if (isset($_POST['invite'])) {
if ('delete' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
if (Game::delete_invite($_POST['game_id'])) {
echo 'Invite Deleted';
}
else {
echo 'ERROR: Invite not deleted';
}
}
else {
echo 'ERROR: Not your invite';
}
}
else if ('resend' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
try {
if (Game::resend_invite($_POST['game_id'])) {
echo 'Invite Resent';
}
else {
echo 'ERROR: Could not resend invite';
}
}
catch (MyException $e) {
echo 'ERROR: '.$e->outputMessage( );
}
}
else {
echo 'ERROR: Not your invite';
}
}
else {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) {
if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended
echo $game_id;
}
else {
echo 'ERROR: Could not create game';
}
}
else {
echo 'ERROR: Not your invite';
}
}
exit;
}
// we'll need a game id from here forward, so make sure we have one
if (empty($_SESSION['game_id'])) {
echo 'ERROR: Game not found';
exit;
}
// init our game
if ( ! isset($Game)) {
$Game = new Game((int) $_SESSION['game_id']);
}
// run the game refresh check
if (isset($_POST['refresh'])) {
echo $Game->last_move;
exit;
}
// do some validity checking
if (empty($DEBUG) && empty($_POST['notoken'])) {
test_token( ! empty($_POST['keep_token']));
}
if ($_POST['game_id'] != $_SESSION['game_id']) {
- throw new MyException('ERROR: Incorrect game id given');
+ throw new MyException('ERROR: Incorrect game id given. Was #'.$_POST['game_id'].', should be #'.$_SESSION['game_id'].'.');
}
// make sure we are the player we say we are
// unless we're an admin, then it's ok
$player_id = (int) $_POST['player_id'];
if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) {
throw new MyException('ERROR: Incorrect player id given');
}
// run the simple button actions
$actions = array(
'nudge',
'resign',
'offer_draw',
'accept_draw',
'reject_draw',
'request_undo',
'accept_undo',
'reject_undo',
);
foreach ($actions as $action) {
if (isset($_POST[$action])) {
try {
- $Game->{$action}($player_id);
- echo 'OK';
+ if ($Game->{$action}($player_id)) {
+ echo 'OK';
+ }
+ else {
+ echo 'ERROR';
+ }
}
catch (MyException $e) {
echo $e;
}
exit;
}
}
// run the game actions
if (isset($_POST['turn'])) {
$return = array( );
try {
if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk
$to = substr($_POST['to'], 0, 2);
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.'.'.$to);
$Game->do_move($from.'.'.$to);
}
elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving
$to = $_POST['to'];
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.':'.$to);
$Game->do_move($from.':'.$to);
}
else { // rotating
$target = Pharaoh::index_to_target($_POST['from']);
$dir = (int) ('r' == strtolower($_POST['to']));
call($target.'-'.$dir);
$Game->do_move($target.'-'.$dir);
}
$return['action'] = 'RELOAD';
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
diff --git a/todo.txt b/todo.txt
index fe69ee0..25cc6d3 100644
--- a/todo.txt
+++ b/todo.txt
@@ -1,32 +1,39 @@
+- update scripts
+ - use yepnope and cdn
+
- there are errors when trying to re-send invites
- make sure everything is working with the invites
+ - i didn't find any errors =(
+ - it may be something to do with the resend button being shown
+ before it should be, or that the resnd time checker is off
+ somehow. it's basically failing due to being too new
- make hover tooltips better
- add ability to hit own laser from side as option
- for revisions for setups, allow the same name for the setup and when
a user creates a revision or edits their setup, it creates a new
setup and inactivates the previous setup, and then either sort by
create date, or add a field in the table called revision and
increment that and when we pull the setup, order by created or
revision number, and use the most recent.
- add more stats:
player's most played setup
player's favorite setup
player's worst setup
player's favorite opponent
win-loss per opponent
etc...
- build game reader for saved games
- don't show success messages if email is not sent for things like
nudge, that are only email dependent
- fully convert times to UTC in MySQL and back to user's timezone
everywhere dates are output
- add showdown to messages (JS port of Markdown, in zz_scripts_js)
\ No newline at end of file
|
benjamw/pharaoh | 7783555670d5a5da1cc8e7031a5cf23f7bd0d610 | hide nudge button if nudge not possible | diff --git a/classes/game.class.php b/classes/game.class.php
index b9d0f37..16d3b31 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1114,1024 +1114,1028 @@ class Game
}
/** public function is_turn
* Returns the requested player's turn
*
* @param bool current player is requested player
* @return bool is the requested player's turn
*/
public function is_turn($player = true)
{
if ('Playing' != $this->state) {
return false;
}
if ($this->_extra_info['draw_offered']) {
return false;
}
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['turn'])) ? (bool) $this->_players[$request]['turn'] : false);
}
/** public function get_turn
* Returns the name of the player who's turn it is
*
* @param void
* @return string current player's name
*/
public function get_turn( )
{
return ((isset($this->turn) && isset($this->_players[$this->turn]['object'])) ? $this->_players[$this->turn]['object']->username : false);
}
/** public function get_extra
* Returns details of the extra_info var
*
* @param void
* @return string extra info details
*/
public function get_extra( )
{
call(__METHOD__);
$return = array( );
if ($this->_extra_info['battle_dead']) {
$front_abbr = $front_text = '';
if ($this->_pharaoh->has_sphynx) {
$front_abbr = ', Front Only';
$front_text = ($this->_extra_info['battle_front_only'] ? ', Yes' : ', No');
}
$return[] = '<span>Laser Battle (<abbr title="Dead, Immune'.$front_abbr.'">'.$this->_extra_info['battle_dead'].', '.$this->_extra_info['battle_immune'].$front_text.'</abbr>)</span>';
}
if ($this->_pharaoh->has_sphynx && $this->_extra_info['move_sphynx']) {
$return[] = '<span>Movable Sphynx</span>';
}
return implode(' | ', $return);
}
/** public function get_extra_info
* Returns the extra_info var
*
* @param void
* @return array extra info
*/
public function get_extra_info( )
{
return $this->_extra_info;
}
/** public function get_board
* Returns the current board
*
* @param bool optional return expanded FEN
* @param int optional history index
* @return string board FEN (or xFEN)
*/
public function get_board($index = null, $expanded = false)
{
call(__METHOD__);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$expanded = (bool) $expanded;
if (isset($this->_history[$index])) {
$board = $this->_history[$index]['board'];
}
else {
return false;
}
if ($expanded) {
return expandFEN($board);
}
return $board;
}
/** public function get_move_history
* Returns the game move history
*
* @param void
* @return array game history
*/
public function get_move_history( )
{
call(__METHOD__);
$history = $this->_history;
array_shift($history); // remove the empty first move
$return = array( );
foreach ($history as $i => $ply) {
if (false !== strpos($ply['move'], '-')) {
$ply['move'] = str_replace(array('-0','-1'), array('-L','-R'), $ply['move']);
}
$return[floor($i / 2)][$i % 2] = $ply['move'];
}
if (isset($i) && (0 == ($i % 2))) {
++$i;
$return[floor($i / 2)][$i % 2] = '';
}
return $return;
}
/** public function get_history
* Returns the game history
*
* @param bool optional return as JSON string
* @return array or string game history
*/
public function get_history($json = false)
{
call(__METHOD__);
call($json);
$json = (bool) $json;
if ( ! $json) {
return $this->_history;
}
$history = array( );
foreach ($this->_history as $i => $node) {
$move = $this->get_move($i);
if ($move) {
$move = array_unique(array_values($move));
}
$history[] = array(
expandFEN($node['board']),
$move,
(($this->_history[$i]['laser_fired']) ? $this->get_laser_path($i) : array( )),
$this->get_hit_data($i),
$this->get_battle_data($i, true),
);
}
return json_encode($history);
}
/** public function get_move
* Returns the data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string previous turn
*/
public function get_move($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$turn = $this->_history[$index];
$board = expandFEN($turn['board']);
if ( ! empty($this->_history[$index - 1])) {
$board = expandFEN($this->_history[$index - 1]['board']);
}
if ( ! $turn['move']) {
if ($json) {
return 'false';
}
return false;
}
$move = array( );
$move[0] = Pharaoh::target_to_index(substr($turn['move'], 0, 2));
if ('-' == $turn['move'][2]) {
$move[1] = $move[0][0];
$move[2] = $turn['move'][3];
}
else {
$move[1] = Pharaoh::target_to_index(substr($turn['move'], 3, 2));
$move[2] = (int) (':' == $turn['move'][2]);
}
$move[3] = Pharaoh::get_piece_color($board[$move[0]]);
if ($json) {
return json_encode($move);
}
$move['from'] = $move[0];
$move['to'] = $move[1];
$move['extra'] = $move[2];
$move['color'] = $move[3];
return $move;
}
/** public function get_laser_path
* Returns the laser path for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or JSON string laser path
*/
public function get_laser_path($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$count = count($this->_history);
call($count);
call($this->_history[$index]);
if ((1 > $index) || ($index > ($count - 1))) {
if ($json) {
return '[]';
}
return false;
}
$color = ((0 != ($index % 2)) ? 'silver' : 'red');
call($color);
// here we need to do the move, store the board as is
// and then fire the laser.
// the reason being: if we just fire the laser at the previous board,
// if the piece hit was rotated into the beam, it will not display correctly
// and if we try and fire the laser at the current board, it will pass through
// any hit piece because it's no longer there (unless it's a stacked obelisk, of course)
// create a dummy pharaoh class and set the board as it was prior to the laser (-1)
$PH = new Pharaoh( );
$PH->set_board(expandFEN($this->_history[$index - 1]['board']));
$PH->set_extra_info($this->_extra_info);
// do the move, but do not fire the laser, and store the board
$pre_board = $PH->do_move($this->_history[$index]['move'], false);
// now fire the laser at that board
$return = Pharaoh::fire_laser($color, $pre_board, $this->_pharaoh->get_extra_info( ));
if ($json) {
return json_encode($return['laser_path']);
}
return $return['laser_path'];
}
/** public function get_hit_data
* Returns the turn data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string previous turn
*/
public function get_hit_data($index = null, $json = false)
{
call(__METHOD__);
call($index);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$json = (bool) $json;
$move_data = array( );
// because we may have only hit the piece at A8 (idx: 0), this will
// return false unless we test for that location specifically
if ($this->_history[$index]['hits'] || ('0' === $this->_history[$index]['hits'])) {
// we need to grab the previous board here, and perform the move
// without firing the laser so we get the proper orientation
// of the pieces as they were hit in case any pieces were rotated
// into the beam
// create a dummy pharaoh class and set the board as it was prior to the laser (-1)
$PH = new Pharaoh( );
$PH->set_board(expandFEN($this->_history[$index - 1]['board']));
$PH->set_extra_info($this->_extra_info);
// do the move and store that board
$prev_board = $PH->do_move($this->_history[$index]['move'], false);
$pieces = array( );
$hits = array_trim($this->_history[$index]['hits'], 'int');
foreach ($hits as $hit) {
$pieces[] = $prev_board[$hit];
}
$move_data = compact('hits', 'pieces');
}
if ($json) {
return json_encode($move_data);
}
return $move_data;
}
/** public function get_battle_data
* Returns the battle data for the given move index
*
* @param int optional move history index
* @param bool optional return as JSON string
* @return array or string battle data
*/
public function get_battle_data($index = null, $simple = false, $json = false)
{
call(__METHOD__);
call($index);
call($simple);
call($json);
if (is_null($index)) {
$index = count($this->_history) - 1;
}
$index = (int) $index;
$simple = (bool) $simple;
$json = (bool) $json;
$battle_data = array(
'silver' => array(
'dead' => 0,
'immune' => 0,
),
'red' => array(
'dead' => 0,
'immune' => 0,
),
);
$color = ((0 != ($index % 2)) ? 'silver' : 'red');
$other = (('silver' == $color) ? 'red' : 'silver');
call($color);
if (isset($this->_history[$index])) {
// grab the current data
$battle_data[$color]['dead'] = $this->_history[$index]['dead_for'];
$battle_data[$color]['immune'] = $this->_history[$index]['immune_for'];
// for the game display, we want to decrease the value here
$dead = false;
if ($battle_data[$color]['dead']) {
$dead = true;
--$battle_data[$color]['dead'];
}
if ($battle_data[$color]['immune']) {
--$battle_data[$color]['immune'];
}
// if we recently came back to life, show that
if ($dead && ! $battle_data[$color]['dead']) {
$battle_data[$color]['immune'] = $this->_extra_info['battle_immune'];
}
// grab the future data for the other player
if (isset($this->_history[$index + 1])) {
$battle_data[$other]['dead'] = $this->_history[$index + 1]['dead_for'];
$battle_data[$other]['immune'] = $this->_history[$index + 1]['immune_for'];
}
else {
// there is no next move, we need to calculate it based on the previous one
// if there is no previous move data, the values will stay as defaults
if (isset($this->_history[$index - 1])) {
$m_extra_info = $this->_gen_move_extra_info($this->_history[$index], $this->_history[$index - 1]);
$battle_data[$other]['dead'] = $m_extra_info['dead_for'];
$battle_data[$other]['immune'] = $m_extra_info['immune_for'];
}
}
}
if ($simple) {
$battle_data = array(
array($battle_data['silver']['dead'], $battle_data['silver']['immune']),
array($battle_data['red']['dead'], $battle_data['red']['immune']),
);
}
if ($json) {
return json_encode($battle_data);
}
return $battle_data;
}
/** public function get_setup_name
* Returns the name of the initial setup
* used for this game
*
* @param void
* @return string initial setup name
*/
public function get_setup_name( )
{
return $this->_setup['name'];
}
/** public function get_setup
* Returns the board of the initial setup
* used for this game
*
* @param void
* @return string initial setup name
*/
public function get_setup( )
{
return $this->_history[0]['board'];
}
/** public function nudge
* Nudges the given player to take their turn
*
* @param void
* @return bool success
*/
public function nudge( )
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
if ($this->test_nudge( )) {
Email::send('nudge', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
$this->_mysql->delete(self::GAME_NUDGE_TABLE, " WHERE game_id = '{$this->id}' ");
$this->_mysql->insert(self::GAME_NUDGE_TABLE, array('game_id' => $this->id, 'player_id' => $this->_players['opponent']['player_id']));
return true;
}
return false;
}
/** public function test_nudge
* Tests if the current player can nudge or not
*
* @param void
* @return bool player can be nudged
*/
public function test_nudge( )
{
call(__METHOD__);
$player_id = (int) $this->_players['opponent']['player_id'];
if ( ! $this->is_player($player_id) || $this->is_turn( ) || ('Playing' != $this->state) || $this->paused) {
return false;
}
+ if ( ! $this->_players['opponent']['object']->allow_email || ('' == $this->_players['opponent']['object']->email)) {
+ return false;
+ }
+
try {
$nudge_time = Settings::read('nudge_flood_control');
}
catch (MyException $e) {
return false;
}
if (-1 == $nudge_time) {
return false;
}
elseif (0 == $nudge_time) {
return true;
}
// check the nudge status for this game/player
// 'now' is taken from the DB because it may
// have a different time from the PHP server
$query = "
SELECT NOW( ) AS now
, G.modify_date AS move_date
, GN.nudged
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_NUDGE_TABLE." AS GN
ON (GN.game_id = G.game_id
AND GN.player_id = '{$player_id}')
WHERE G.game_id = '{$this->id}'
AND G.state = 'Playing'
";
$dates = $this->_mysql->fetch_assoc($query);
if ( ! $dates) {
return false;
}
// check the dates
// if the move date is far enough in the past
// AND the player has not been nudged
// OR the nudge date is far enough in the past
if ((strtotime($dates['move_date']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now'])))
&& ((empty($dates['nudged']))
|| (strtotime($dates['nudged']) <= strtotime('-'.$nudge_time.' hour', strtotime($dates['now'])))))
{
return true;
}
return false;
}
/** public function get_players
* Grabs the player array
*
* @param void
* @return array player data
*/
public function get_players( )
{
$players = array( );
foreach (array('white','black') as $color) {
$player_id = $this->_players[$color]['player_id'];
$players[$player_id] = $this->_players[$color];
$players[$player_id]['username'] = $this->_players[$color]['object']->username;
unset($players[$player_id]['object']);
}
return $players;
}
/** public function get_outcome
* Returns the outcome string and outcome
*
* @param int id of observing player
* @return array (outcome text, outcome string)
*/
public function get_outcome($player_id)
{
call(__METHOD__);
$player_id = (int) $player_id;
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
return false;
}
if ('Draw' == $this->state) {
return array('Draw Game', 'lost');
}
if ( ! empty($this->_pharaoh->winner) && isset($this->_players[$this->_pharaoh->winner]['player_id'])) {
$winner = $this->_players[$this->_pharaoh->winner]['player_id'];
}
else {
$query = "
SELECT G.winner_id
FROM ".self::GAME_TABLE." AS G
WHERE G.game_id = '{$this->id}'
";
$winner = $this->_mysql->fetch_value($query);
}
if ( ! $winner) {
return false;
}
if ($player_id == $winner) {
return array('You Won !', 'won');
}
else {
return array($GLOBALS['_PLAYERS'][$winner].' Won', 'lost');
}
}
/** static public function write_game_file
* Writes the game to a text file for storage
*
* @param int game id
* @action writes the game PGN file
* @return string PGN
*/
static public function write_game_file($game_id)
{
// the PGN export format is very exact when it comes to what is allowed
// and what is not allowed when creating a PGN file.
// first, the only new line character that is allowed is a single line feed character
// output in PHP as \n, this means that \r is not allowed, nor is \r\n
// second, no tab characters are allowed, neither vertical, nor horizontal (\t)
// third, comments do NOT nest, thus { { } } will be in error, as will { ; }
// fourth, { } denotes an inline comment, where ; denotes a 'rest of line' comment
// fifth, a percent sign (%) at the beginning of a line denotes a whole line comment
// sixth, comments may not be included in the meta tags ( [Meta "data"] )
$Mysql = Mysql::get_instance( );
if (empty($game_id)) {
throw new MyException(__METHOD__.': No game id given');
}
try {
$Game = new Game($game_id);
}
catch (MyException $e) {
throw $e;
}
if ( ! isset($Game->_history[1])) {
return false;
}
$start_date = date('Y-m-d', strtotime($Game->_history[1]['move_date']));
$white_name = $Game->_players['white']['object']->lastname.', '.$Game->_players['white']['object']->firstname.' ('.$Game->_players['white']['object']->username.')';
$black_name = $Game->_players['black']['object']->lastname.', '.$Game->_players['black']['object']->firstname.' ('.$Game->_players['black']['object']->username.')';
$extra_info = $Game->_extra_info;
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
unset($extra_info['white_color']);
unset($extra_info['draw_offered']);
unset($extra_info['undo_requested']);
$xheadxtra = '';
$xheader = "[Event \"Pharaoh (Khet) Casual Game #{$Game->id}\"]\n"
. "[Site \"{$GLOBALS['_ROOT_URI']}\"]\n"
. "[Date \"{$start_date}\"]\n"
. "[Round \"-\"]\n"
. "[White \"{$white_name}\"]\n"
. "[Black \"{$black_name}\"]\n"
. "[Setup \"{$Game->_history[0]['board']}\"]\n";
if ($extra_info) {
$options = serialize($extra_info);
$xheadxtra .= "[Options \"{$options}\"]\n";
}
$xheadxtra .= "[Mode \"ICS\"]\n";
$body = '';
$line = '';
$token = '';
foreach ($Game->_history as $key => $move) {
// skip the first entry
if ( ! $key) {
continue;
}
if (0 != ($key % 2)) {
$token = floor(($key + 1) / 2) . '. ' . $move['move'];
}
else {
$token .= ' ' . $move['move'];
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
}
if ($token) {
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
// finish up the PGN with the game result
$result = '*';
if ('Finished' == $Game->state) {
if ('white' == $Game->turn) {
$result = '1-0';
}
else {
$result = '0-1';
}
}
elseif ('Draw' == $Game->state) {
$result = '1/2-1/2';
}
$body .= $line;
if ((strlen($line) + strlen($result)) > 79) {
$body .= "\n";
}
elseif (strlen($line) > 0) {
$body .= ' ';
}
$body .= $result . "\n";
$xheader .= "[Result \"$result\"]\n";
$data = $xheader . $xheadxtra . "\n" . $body;
$filename = GAMES_DIR."/Pharoah_Game_{$Game->id}_".str_replace(array(' ','-',':'), '', $Game->_history[count($Game->_history) - 1]['move_date']).'.pgn';
file_put_contents($filename, $data);
return $data;
}
protected function _gen_move_extra_info($curr_move, $prev_move = null)
{
call(__METHOD__);
$m_extra_info = self::$_HISTORY_EXTRA_INFO_DEFAULTS;
if ( ! $this->_extra_info['battle_dead']) {
return $m_extra_info;
}
if ( ! $curr_move) {
throw new MyException(__METHOD__.': Move data not present for calculation');
}
// set our current move extra info
if ($prev_move) {
$m_extra_info['dead_for'] = $prev_move['dead_for'];
$m_extra_info['immune_for'] = $prev_move['immune_for'];
}
$dead = false;
if ($m_extra_info['dead_for']) {
$dead = true;
}
if (0 < $m_extra_info['dead_for']) {
--$m_extra_info['dead_for'];
}
// we are allowed to shoot now, set our immunity
if ($dead && ! $m_extra_info['dead_for']) {
$m_extra_info['immune_for'] = $this->_extra_info['battle_immune'];
}
if ( ! $dead && (0 < $m_extra_info['immune_for'])) {
--$m_extra_info['immune_for'];
}
if ( ! $m_extra_info['dead_for'] && ! $m_extra_info['immune_for'] && $curr_move['laser_hit']) {
$m_extra_info['dead_for'] = $this->_extra_info['battle_dead'];
}
return $m_extra_info;
}
/** protected function _pull
* Pulls the data from the database
* and sets up the objects
*
* @param void
* @action pulls the game data
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return false;
}
if ( ! $_SESSION['player_id']) {
throw new MyException(__METHOD__.': Player id is not in session when pulling game data');
}
// grab the game data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
call($result);
if ( ! $result) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
if ('Waiting' == $result['state']) {
throw new MyException(__METHOD__.': Game (#'.$this->id.') is still only an invite');
}
// set the properties
$this->state = $result['state'];
$this->paused = (bool) $result['paused'];
$this->create_date = strtotime($result['create_date']);
$this->modify_date = strtotime($result['modify_date']);
$this->_extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($result['extra_info']));
// just empty this out, we don't need it anymore
$this->_extra_info['invite_setup'] = '';
// grab the initial setup
// TODO: convert to the setup object
// (need to build more in the setup object)
$query = "
SELECT *
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$result['setup_id']}'
";
$setup = $this->_mysql->fetch_assoc($query);
call($setup);
// the setup may have been deleted
if ( ! $setup) {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => '[DELETED]',
);
}
else {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => $setup['name'],
);
}
// set up the players
$this->_players['white']['player_id'] = $result['white_id'];
$this->_players['white']['object'] = new GamePlayer($result['white_id']);
$this->_players['silver'] = & $this->_players['white'];
$this->_players['black']['player_id'] = $result['black_id'];
if (0 != $result['black_id']) { // we may have an open game
$this->_players['black']['object'] = new GamePlayer($result['black_id']);
$this->_players['red'] = & $this->_players['black'];
}
// we test this first one against the black id, so if it fails because
// the person viewing the game is not playing in the game (viewing it
// after it's finished) we want "player" to be equal to "white"
if ($_SESSION['player_id'] == $result['black_id']) {
$this->_players['player'] = & $this->_players['black'];
$this->_players['player']['color'] = 'black';
$this->_players['player']['opp_color'] = 'white';
$this->_players['opponent'] = & $this->_players['white'];
$this->_players['opponent']['color'] = 'white';
$this->_players['opponent']['opp_color'] = 'black';
}
else {
$this->_players['player'] = & $this->_players['white'];
$this->_players['player']['color'] = 'white';
$this->_players['player']['opp_color'] = 'black';
$this->_players['opponent'] = & $this->_players['black'];
$this->_players['opponent']['color'] = 'black';
$this->_players['opponent']['opp_color'] = 'white';
}
// set up the board
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date ASC
";
$result = $this->_mysql->fetch_array($query);
call($result);
if ($result) {
$count = count($result);
// integrate the extra info into the history array
foreach ($result as & $move) {
$m_extra = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, unserialize($move['extra_info']));
$move = array_merge($move, $m_extra);
}
unset($move); // kill the reference
$this->_history = $result;
$this->turn = ((0 == ($count % 2)) ? 'black' : 'white');
$this->last_move = strtotime($result[$count - 1]['move_date']);
try {
$this->_pharaoh = new Pharaoh( );
$this->_pharaoh->set_board(expandFEN($this->_history[$count - 1]['board']));
$this->_pharaoh->set_extra_info($this->_extra_info);
}
catch (MyException $e) {
throw $e;
}
$m_extra_info = $this->_gen_move_extra_info($this->_history[$count - 1], (isset($this->_history[$count - 2]) ? $this->_history[$count - 2] : null));
$this->_current_move_extra_info = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, $m_extra_info);
}
else {
$this->last_move = $this->create_date;
}
$this->_players[$this->turn]['turn'] = true;
}
/** protected function _save
* Saves all changed data to the database
*
* @param void
* @action saves the game data
* @return void
*/
protected function _save( )
{
call(__METHOD__);
// grab the base game data
$query = "
SELECT state
, extra_info
, modify_date
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
AND state <> 'Waiting'
";
$game = $this->_mysql->fetch_assoc($query);
call($game);
$update_modified = false;
if ( ! $game) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
$this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date']));
// test the modified date and make sure we still have valid data
call($this->modify_date);
call(strtotime($game['modify_date']));
if ($this->modify_date != strtotime($game['modify_date'])) {
$this->_log('== FAILED ==');
throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data');
}
$update_game = false;
call($game['state']);
call($this->state);
if ($game['state'] != $this->state) {
$update_game['state'] = $this->state;
if ('Finished' == $this->state) {
$update_game['winner_id'] = $this->_players[$this->_pharaoh->winner]['player_id'];
}
if (in_array($this->state, array('Finished', 'Draw'))) {
try {
$this->_add_stats( );
}
catch (MyException $e) {
// do nothing, it gets logged
}
}
}
$diff = array_compare($this->_extra_info, self::$_EXTRA_INFO_DEFAULTS);
$update_game['extra_info'] = $diff[0];
ksort($update_game['extra_info']);
$update_game['extra_info'] = serialize($update_game['extra_info']);
diff --git a/todo.txt b/todo.txt
index 6947571..fe69ee0 100644
--- a/todo.txt
+++ b/todo.txt
@@ -1,35 +1,32 @@
- there are errors when trying to re-send invites
- make sure everything is working with the invites
- make hover tooltips better
- add ability to hit own laser from side as option
- for revisions for setups, allow the same name for the setup and when
- a user creates a revision or edits their setup, it creates a new setup
- and inactivates the previous setup, and then either sort by create
- date, or add a field in the table called revision and increment that
- and when we pull the setup, order by created or revision number, and
- use the most recent.
+ a user creates a revision or edits their setup, it creates a new
+ setup and inactivates the previous setup, and then either sort by
+ create date, or add a field in the table called revision and
+ increment that and when we pull the setup, order by created or
+ revision number, and use the most recent.
- add more stats:
player's most played setup
player's favorite setup
player's worst setup
player's favorite opponent
win-loss per opponent
etc...
- build game reader for saved games
-- don't refresh page if an email success message is sent for things
- like resend invites, nudges, etc. just make changes to html if needed
-
- don't show success messages if email is not sent for things like
nudge, that are only email dependent
-- fully convert times to UTC in MySQL and back to user's timezone everywhere
- dates are output
+- fully convert times to UTC in MySQL and back to user's timezone
+ everywhere dates are output
- add showdown to messages (JS port of Markdown, in zz_scripts_js)
\ No newline at end of file
|
benjamw/pharaoh | 53d67b327a8322935eb2534c069c400733326211 | ajax and javascript for simple invite actions | diff --git a/ajax_helper.php b/ajax_helper.php
index 15e8bc7..e5030c8 100644
--- a/ajax_helper.php
+++ b/ajax_helper.php
@@ -1,281 +1,290 @@
<?php
$GLOBALS['NODEBUG'] = true;
$GLOBALS['AJAX'] = true;
// don't require log in when testing for used usernames and emails
if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) {
define('LOGIN', false);
}
require_once 'includes/inc.global.php';
// if we are debugging, change some things for us
// (although REQUEST_METHOD may not always be valid)
if (('GET' == $_SERVER['REQUEST_METHOD']) && test_debug( )) {
$GLOBALS['NODEBUG'] = false;
$GLOBALS['AJAX'] = false;
$_GET['token'] = $_SESSION['token'];
$_GET['keep_token'] = true;
$_POST = $_GET;
$DEBUG = true;
call('AJAX HELPER');
call($_POST);
}
// run the index page refresh checks
if (isset($_POST['timer'])) {
$message_count = (int) Message::check_new($_SESSION['player_id']);
$turn_count = (int) Game::check_turns($_SESSION['player_id']);
echo $message_count + $turn_count;
exit;
}
// run registration checks
if (isset($_POST['validity_test'])) {
# if (('email' == $_POST['type']) && ('' == $_POST['value'])) {
# echo 'OK';
# exit;
# }
$player_id = 0;
if ( ! empty($_POST['profile'])) {
$player_id = (int) $_SESSION['player_id'];
}
switch ($_POST['validity_test']) {
case 'username' :
case 'email' :
$username = '';
$email = '';
${$_POST['validity_test']} = sani($_POST['value']);
$player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0);
try {
Player::check_database($username, $email, $player_id);
}
catch (MyException $e) {
echo $e->getCode( );
exit;
}
break;
default :
break;
}
echo 'OK';
exit;
}
// run the in game chat
if (isset($_POST['chat'])) {
try {
if ( ! isset($_SESSION['game_id'])) {
$_SESSION['game_id'] = 0;
}
$Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']);
$Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby']));
$return = $Chat->get_box_list(1);
$return = $return[0];
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup validation
if (isset($_POST['test_setup'])) {
try {
Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']);
$return['valid'] = true;
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup laser test fire
if (isset($_POST['test_fire'])) {
try {
// returns laser_path and hits arrays
$return = Pharaoh::fire_laser($_POST['color'], $_POST['board']);
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run the invites stuff
if (isset($_POST['invite'])) {
if ('delete' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
- Game::delete_invite($_POST['game_id']);
- echo 'Invite Deleted';
+ if (Game::delete_invite($_POST['game_id'])) {
+ echo 'Invite Deleted';
+ }
+ else {
+ echo 'ERROR: Invite not deleted';
+ }
}
else {
echo 'ERROR: Not your invite';
}
}
else if ('resend' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
- if (Game::resend_invite($_POST['game_id'])) {
- echo 'Invite Resent';
+ try {
+ if (Game::resend_invite($_POST['game_id'])) {
+ echo 'Invite Resent';
+ }
+ else {
+ echo 'ERROR: Could not resend invite';
+ }
}
- else {
- echo 'Could not resend invite';
+ catch (MyException $e) {
+ echo 'ERROR: '.$e->outputMessage( );
}
}
else {
echo 'ERROR: Not your invite';
}
}
else {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) {
if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended
echo $game_id;
}
else {
echo 'ERROR: Could not create game';
}
}
else {
echo 'ERROR: Not your invite';
}
}
exit;
}
// we'll need a game id from here forward, so make sure we have one
if (empty($_SESSION['game_id'])) {
echo 'ERROR: Game not found';
exit;
}
// init our game
if ( ! isset($Game)) {
$Game = new Game((int) $_SESSION['game_id']);
}
// run the game refresh check
if (isset($_POST['refresh'])) {
echo $Game->last_move;
exit;
}
// do some validity checking
if (empty($DEBUG) && empty($_POST['notoken'])) {
test_token( ! empty($_POST['keep_token']));
}
if ($_POST['game_id'] != $_SESSION['game_id']) {
throw new MyException('ERROR: Incorrect game id given');
}
// make sure we are the player we say we are
// unless we're an admin, then it's ok
$player_id = (int) $_POST['player_id'];
if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) {
throw new MyException('ERROR: Incorrect player id given');
}
// run the simple button actions
$actions = array(
'nudge',
'resign',
'offer_draw',
'accept_draw',
'reject_draw',
'request_undo',
'accept_undo',
'reject_undo',
);
foreach ($actions as $action) {
if (isset($_POST[$action])) {
try {
$Game->{$action}($player_id);
echo 'OK';
}
catch (MyException $e) {
echo $e;
}
exit;
}
}
// run the game actions
if (isset($_POST['turn'])) {
$return = array( );
try {
if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk
$to = substr($_POST['to'], 0, 2);
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.'.'.$to);
$Game->do_move($from.'.'.$to);
}
elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving
$to = $_POST['to'];
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.':'.$to);
$Game->do_move($from.':'.$to);
}
else { // rotating
$target = Pharaoh::index_to_target($_POST['from']);
$dir = (int) ('r' == strtolower($_POST['to']));
call($target.'-'.$dir);
$Game->do_move($target.'-'.$dir);
}
$return['action'] = 'RELOAD';
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
diff --git a/classes/game.class.php b/classes/game.class.php
index a2a3737..b9d0f37 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -173,1025 +173,1025 @@ class Game
* 'id' => [setup_id],
* 'name' => [setup_name],
* );
*
* @var array
*/
protected $_setup;
/** protected property _laser_fired
* Holds the laser fired flag
*
* @var bool did we fire the laser?
*/
protected $_laser_fired = false;
/** protected property _extra_info
* Holds the extra game info
*
* @var array
*/
protected $_extra_info;
/** protected property _current_move_extra_info
* Holds the extra current move info
*
* @var array
*/
protected $_current_move_extra_info;
/** protected property _players
* Holds our player's object references
* along with other game data
*
* @var array of player data
*/
protected $_players;
/** protected property _pharaoh
* Holds the pharaoh object reference
*
* @var Pharaoh object reference
*/
protected $_pharaoh;
/** protected property _history
* Holds the board history
*
* @var array of pharaoh boards
*/
protected $_history;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional game id
* @param Mysql optional object reference
* @action instantiates object
* @return void
*/
public function __construct($id = 0, Mysql $Mysql = null)
{
call(__METHOD__);
$this->id = (int) $id;
call($this->id);
$this->_pharaoh = new Pharaoh($this->id);
if (is_null($Mysql)) {
$Mysql = Mysql::get_instance( );
}
$this->_mysql = $Mysql;
try {
$this->_pull( );
}
catch (MyException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action saves changed data
* @action destroys object
* @return void
*/
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if ($this->id && (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type']))) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
switch ($property) {
case 'name' :
return $this->_players['white']['object']->username.' vs '.$this->_players['black']['object']->username;
break;
case 'first_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return 'Your';
}
else {
return $this->_players['white']['object']->username.'\'s';
}
break;
case 'second_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return $this->_players['opponent']['object']->username.'\'s';
}
else {
return $this->_players['black']['object']->username.'\'s';
}
break;
default :
// go to next step
break;
}
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
$this->$property = $value;
}
/** static public function invite
* Creates the game from _POST data
*
* @param void
* @action creates an invite
* @return int game id
*/
static public function invite( )
{
call(__METHOD__);
call($_POST);
$Mysql = Mysql::get_instance( );
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
$_P = $_POST;
// translate (filter/sanitize) the data
$_P['white_id'] = (int) $_SESSION['player_id'];
$_P['black_id'] = (int) $_P['opponent'];
$_P['setup_id'] = (int) $_P['setup'];
$_P['laser_battle'] = is_checked($_P['laser_battle_box']);
$_P['battle_front_only'] = is_checked($_P['battle_front_only']);
$_P['battle_hit_self'] = is_checked($_P['battle_hit_self']);
$_P['move_sphynx'] = is_checked($_P['move_sphynx']);
call($_P);
// grab the setup
$query = "
SELECT setup_id
FROM ".Setup::SETUP_TABLE."
";
$setup_ids = $Mysql->fetch_value_array($query);
call($setup_ids);
// check for random setup
if (0 == $_P['setup_id']) {
shuffle($setup_ids);
shuffle($setup_ids);
$_P['setup_id'] = (int) reset($setup_ids);
sort($setup_ids);
}
// make sure the setup id is valid
if ( ! in_array($_P['setup_id'], $setup_ids)) {
throw new MyException(__METHOD__.': Setup is not valid');
}
$query = "
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$_P['setup_id']}'
";
$setup = $Mysql->fetch_value($query);
// laser battle cleanup
// only run this if the laser battle box was open
if ($_P['laser_battle']) {
ifer($_P['battle_dead'], 1, false);
ifer($_P['battle_immune'], 1);
// we can only hit ourselves in the sides or back, never front
if ($_P['battle_front_only']) {
$_P['battle_hit_self'] = false;
}
$extra_info = array(
'battle_dead' => (int) max((int) $_P['battle_dead'], 1),
'battle_immune' => (int) max((int) $_P['battle_immune'], 0),
'battle_front_only' => (bool) $_P['battle_front_only'],
'battle_hit_self' => (bool) $_P['battle_hit_self'],
);
}
$extra_info['white_color'] = $_P['color'];
$extra_info['move_sphynx'] = $_P['move_sphynx'];
$setup = expandFEN($setup);
try {
if (is_checked($_P['convert_to_1']) || is_checked($_P['rand_convert_to_1'])) {
$setup = Setup::convert_to_1($setup);
}
elseif (is_checked($_P['convert_to_2']) || is_checked($_P['rand_convert_to_2'])) {
$setup = Setup::convert_to_2($setup);
}
}
catch (MyException $e) {
throw $e;
}
$extra_info['invite_setup'] = packFEN($setup);
call($extra_info);
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
if ( ! empty($extra_info)) {
$_P['extra_info'] = serialize($extra_info);
}
// create the game
$required = array(
'white_id' ,
'setup_id' ,
);
$key_list = array_merge($required, array(
'black_id' ,
'extra_info' ,
));
try {
$_DATA = array_clean($_P, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['state'] = 'Waiting';
$_DATA['create_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$insert_id = $Mysql->insert(self::GAME_TABLE, $_DATA);
if (empty($insert_id)) {
throw new MyException(__METHOD__.': Invite could not be created');
}
// send the email
if ($_DATA['black_id']) {
Email::send('invite', $_DATA['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$_DATA['white_id']], 'page' => 'invite.php'));
}
return $insert_id;
}
/** static public function resend_invite
* Resends the invite email (if allowed)
*
* @param int game id
* @action resends an invite email
* @return bool invite email sent
*/
static public function resend_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$white_id = (int) $_SESSION['player_id'];
$Mysql = Mysql::get_instance( );
// grab the invite from the database
$query = "
SELECT *
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$invite = $Mysql->fetch_assoc($query);
if ( ! $invite) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend a non-existant invite (#'.$game_id.')');
}
if ((int) $invite['white_id'] !== (int) $white_id) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is not theirs');
}
if ( ! (int) $invite['black_id']) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is open');
}
if (strtotime($invite['modify_date']) >= strtotime($invite['resend_limit'])) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is too new');
}
// if we get here, all is good...
$sent = Email::send('invite', $invite['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$invite['white_id']], 'page' => 'invite.php'));
if ($sent) {
// update the modify_date to prevent invite resend flooding
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$Mysql->insert(self::GAME_TABLE, $_DATA, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
return $sent;
}
/** static public function accept_invite
* Creates the game from invite data
*
* @param int game id
* @action creates a game
* @return int game id
*/
static public function accept_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
// basically all we do, is set the state to Playing
// and set the player order based on the invite data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$game = $Mysql->fetch_assoc($query);
$invitor_id = $game['white_id']; // for use later
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($game['extra_info']));
if ((('random' == $extra_info['white_color']) && mt_rand(0, 1)) || ('white' == $extra_info['white_color'])) {
$game['white_id'] = $game['white_id'];
$game['black_id'] = $_SESSION['player_id'];
}
else {
$game['black_id'] = $game['white_id'];
$game['white_id'] = $_SESSION['player_id'];
}
call($extra_info);
unset($extra_info['white_color']);
$board = false;
if ( ! empty($extra_info['invite_setup'])) {
$board = $extra_info['invite_setup'];
}
$extra_info['invite_setup'] = '';
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
unset($game['extra_info']);
if ( ! empty($extra_info)) {
$game['extra_info'] = serialize($extra_info);
}
$game['state'] = 'Playing';
$Mysql->insert(self::GAME_TABLE, $game, " WHERE game_id = '{$game_id}' ");
// add the first entry in the history table
if (empty($board)) {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', (
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$game['setup_id']}'
))
";
$Mysql->query($query);
}
else {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', '{$board}')
";
$Mysql->query($query);
}
// add a used count to the setup table
Setup::add_used($game['setup_id']);
// send the email
Email::send('start', $invitor_id, array('opponent' => $GLOBALS['_PLAYERS'][$_SESSION['player_id']], 'game_id' => $game_id));
return $game_id;
}
/** static public function delete_invite
* Deletes the given invite
*
* @param int game id
* @action deletes the invite
* @return void
*/
static public function delete_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
- $Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
+ return $Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
/** static public function has_invite
* Tests if the given player has the given invite
*
* @param int game id
* @param int player id
* @param bool optional player can accept invite
* @return bool player has invite
*/
static public function has_invite($game_id, $player_id, $accept = false)
{
call(__METHOD__);
$game_id = (int) $game_id;
$player_id = (int) $player_id;
$accept = (bool) $accept;
$Mysql = Mysql::get_instance( );
$open = "";
if ($accept) {
$open = " OR black_id IS NULL
OR black_id = FALSE ";
}
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
{$open}
)
";
$has_invite = (bool) $Mysql->fetch_value($query);
return $has_invite;
}
public function can_fire_laser( )
{
call(__METHOD__);
if ( ! $this->_extra_info['battle_dead']) {
return true;
}
return ! $this->_current_move_extra_info['dead_for'];
}
public function prev_laser_fired( )
{
$last = end($this->_history);
return (bool) $last['laser_fired'];
}
/** public function do_move
* Do the given move and send out emails
*
* @param string move code
* @action performs the move
* @return array indexes hit
*/
public function do_move($move)
{
call(__METHOD__);
try {
$this->_laser_fired = $this->can_fire_laser( );
$hits = $this->_pharaoh->do_move($move, $this->_laser_fired);
$winner = $this->_pharaoh->winner;
}
catch (MyException $e) {
throw $e;
}
if ($winner) {
if ('draw' == $winner) {
$this->state = 'Draw';
$this->_players['silver']['object']->add_draw( );
$this->_players['red']['object']->add_draw( );
// send the email
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
else {
$this->state = 'Finished';
$this->_players[$winner]['object']->add_win( );
$this->_players[$this->_players[$winner]['opp_color']]['object']->add_loss( );
// send the email
$type = (($this->_players[$winner]['player_id'] == $_SESSION['player_id']) ? 'defeated' : 'won');
Email::send($type, $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
}
else {
// send the email
Email::send('turn', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
return $hits;
}
/** public function resign
* Resigns the given player from the game
*
* @param int player id
* @return void
*/
public function resign($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign from a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign opponent from a game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_win( );
$this->_players['player']['object']->add_loss( );
$this->state = 'Finished';
$this->_pharaoh->winner = 'opponent';
Email::send('resigned', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function offer_draw
* Offers a draw to the given player's apponent
*
* @param int player id
* @return void
*/
public function offer_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = $player_id;
Email::send('draw_offered', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function draw_offered
* Returns the state of the game draw for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function draw_offered($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the draw was offered AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['draw_offered']) && ( ! $player_id || ($player_id != $this->_extra_info['draw_offered']))) {
return true;
}
return false;
}
/** public function accept_draw
* Accepts a draw offered to the given player
*
* @param int player id
* @return void
*/
public function accept_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw for an opponent in game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_draw( );
$this->_players['player']['object']->add_draw( );
$this->state = 'Draw';
$this->_extra_info['draw_offered'] = false;
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_draw
* Rejects a draw offered to the given player
*
* @param int player id
* @return void
*/
public function reject_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = false;
}
/** public function request_undo
* Requests an undo from the given player's apponent
*
* @param int player id
* @return void
*/
public function request_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo from an opponent in game (#'.$this->id.')');
}
$this->_extra_info['undo_requested'] = $player_id;
Email::send('undo_requested', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function undo_requested
* Returns the state of the game undo for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function undo_requested($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the undo was requested AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['undo_requested']) && ( ! $player_id || ($player_id != $this->_extra_info['undo_requested']))) {
return true;
}
return false;
}
/** public function accept_undo
* Accepts an undo requested to the given player
*
* @param int player id
* @return void
*/
public function accept_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept undo in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept undo for an opponent in game (#'.$this->id.')');
}
// we need to adjust the database here
// it's not really possible via the _save function
$this->_mysql->delete(self::GAME_HISTORY_TABLE, "
WHERE `game_id` = '{$this->id}'
ORDER BY `move_date` DESC
LIMIT 1
");
// and fix up the game data
$this->_pull( );
$this->_extra_info['undo_requested'] = false;
Email::send('undo_accepted', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_undo
* Rejects an undo requested to the given player
*
* @param int player id
* @return void
*/
public function reject_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject undo in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject undo for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['undo_requested'] = false;
}
/** public function is_player
* Tests if the given ID is a player in the game
*
* @param int player id
* @return bool player is in game
*/
public function is_player($player_id)
{
$player_id = (int) $player_id;
return ((isset($this->_players['white']['player_id']) && ($player_id == $this->_players['white']['player_id']))
|| (isset($this->_players['black']['player_id']) && ($player_id == $this->_players['black']['player_id'])));
}
/** public function get_color
* Returns the requested player's color
*
* @param bool current player is requested player
* @return string requested player's color (or false on failure)
*/
public function get_color($player = true)
{
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['color'])) ? $this->_players[$request]['color'] : false);
}
/** public function is_turn
* Returns the requested player's turn
*
* @param bool current player is requested player
* @return bool is the requested player's turn
*/
public function is_turn($player = true)
{
if ('Playing' != $this->state) {
return false;
}
if ($this->_extra_info['draw_offered']) {
return false;
}
$request = (((bool) $player) ? 'player' : 'opponent');
return ((isset($this->_players[$request]['turn'])) ? (bool) $this->_players[$request]['turn'] : false);
}
/** public function get_turn
* Returns the name of the player who's turn it is
*
* @param void
* @return string current player's name
*/
public function get_turn( )
{
return ((isset($this->turn) && isset($this->_players[$this->turn]['object'])) ? $this->_players[$this->turn]['object']->username : false);
}
/** public function get_extra
* Returns details of the extra_info var
*
* @param void
* @return string extra info details
*/
public function get_extra( )
{
call(__METHOD__);
$return = array( );
if ($this->_extra_info['battle_dead']) {
$front_abbr = $front_text = '';
if ($this->_pharaoh->has_sphynx) {
$front_abbr = ', Front Only';
$front_text = ($this->_extra_info['battle_front_only'] ? ', Yes' : ', No');
}
$return[] = '<span>Laser Battle (<abbr title="Dead, Immune'.$front_abbr.'">'.$this->_extra_info['battle_dead'].', '.$this->_extra_info['battle_immune'].$front_text.'</abbr>)</span>';
}
if ($this->_pharaoh->has_sphynx && $this->_extra_info['move_sphynx']) {
$return[] = '<span>Movable Sphynx</span>';
}
return implode(' | ', $return);
}
/** public function get_extra_info
* Returns the extra_info var
*
* @param void
* @return array extra info
*/
public function get_extra_info( )
{
return $this->_extra_info;
}
/** public function get_board
* Returns the current board
*
* @param bool optional return expanded FEN
* @param int optional history index
* @return string board FEN (or xFEN)
*/
diff --git a/classes/mysql.class.php b/classes/mysql.class.php
index 9820188..c5e8274 100644
--- a/classes/mysql.class.php
+++ b/classes/mysql.class.php
@@ -35,1025 +35,1030 @@ class Mysql
protected $query_time; // Time it took to run the query
protected $query_count; // Total number of queries executed since class inception
protected $error; // Any error message encountered while running
protected $_host; // MySQL Host name
protected $_user; // MySQL Username
protected $_pswd; // MySQL password
protected $_db; // MySQL Database
protected $_page_query; // MySQL query for pagination
protected $_page_result; // MySQL result for pagination
protected $_num_results; // Number of total results found
protected $_page; // Current pagination page
protected $_num_per_page; // Number of records per page
protected $_num_pages; // number of total pages
protected $_error_debug = false; // Allows for error debug output
protected $_query_debug = false; // Allows for output of all queries all the time
protected $_log_errors = false; // write to log file when an error is encountered
protected $_log_path = './'; // Path to the MySQL error log file
protected $_email_errors = false; // send an email when an error is encountered
protected $_email_subject = 'Query Error'; // the email subject for the email message
protected $_email_from = '[email protected]'; // the email address to send error reports from
protected $_email_to = '[email protected]'; // the email address to send error reports to
static private $_instance; // Instance of the MySQL Object
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** protected function __construct
* Class constructor.
* Initializes the host, user, pswd, and db vars.
*
* @param array optional configuration array
* @return void
*/
protected function __construct($config = null)
{
if (empty($config) && isset($GLOBALS['_DEFAULT_DATABASE'])) {
$config = $GLOBALS['_DEFAULT_DATABASE'];
}
// each of these can be set independently as needed
$this->_error_debug = false; // set to true for output of errors
$this->_query_debug = false; // set to true for output of every query
if (empty($config)) {
throw new MySQLException(__METHOD__.': Missing MySQL configuration data');
}
$this->_host = $config['hostname'];
$this->_user = $config['username'];
$this->_pswd = $config['password'];
$this->_db = $config['database'];
$this->_log_path = (isset($config['log_path'])) ? $config['log_path'] : './';
$this->query_time = 0;
$this->query_count = 0;
try {
$this->_log(__METHOD__);
$this->_log('===============================');
$this->connect_select( );
}
catch (MySQLException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor.
* Closes the mysql connection.
*
* @param void
* @action close the mysql connection
* @return void
*/
public function __destruct( )
{
$this->_log(__METHOD__.': '.$this->link_id);
$this->_log('===============================');
return; // just stop doing this
@mysql_close($this->link_id);
$this->link_id = null;
self::$_instance = null;
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! property_exists($this, $property)) {
throw new MySQLException(__METHOD__.': Trying to access non-existent property ('.$property.')');
}
if ('_' === $property[0]) {
throw new MySQLException(__METHOD__.': Trying to access _private property ('.$property.')');
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MySQLException(__METHOD__.': Trying to access non-existent property ('.$property.')');
}
if ('_' === $property[0]) {
throw new MySQLException(__METHOD__.': Trying to access _private property ('.$property.')');
}
$this->$property = $value;
}
/** public function set_settings
* Sets the given settings for the object
*
* @param array settings array
* @action updates the settings
* @return void
*/
public function set_settings($settings)
{
$valid = array(
'log_errors',
'log_path',
'email_errors',
'email_subject',
'email_from',
'email_to',
);
foreach ($valid as $key) {
if (isset($settings[$key])) {
$var = '_'.$key;
$this->$var = $settings[$key];
}
}
}
/** public function test_connection
* Tests the connection to the MySQL
* server, and reconnects if needed
*
* @param void
* @action reconnects to the server
* @return void
*/
public function test_connection( )
{
if ( ! mysql_ping( )) {
mysql_close($this->link_id);
$this->connect_select( );
$this->_log('RECONNECT ++++++++++++++++++++++++++++++++++++++ '.$this->link_id);
}
}
/** public function connect
* Connect to the MySQL server.
*
* @param void
* @action connect to the mysql server
* @return void
*/
public function connect( )
{
$this->link_id = @mysql_connect($this->_host, $this->_user, $this->_pswd);
if ( ! $this->link_id) {
$this->error = mysql_errno( ).': '.mysql_error( );
throw new MySQLException(__METHOD__.': There was an error connecting to the server');
}
}
/** public function select
* Select the MySQL database.
*
* @param string [optional] database name
* @action select the mysql database
* @return void
*/
public function select($database = null)
{
if ( ! is_null($database)) {
$this->_db = $database;
}
if ( ! @mysql_select_db($this->_db, $this->link_id)) {
$this->error = mysql_errno($this->link_id).': '.mysql_error($this->link_id);
throw new MySQLException(__METHOD__.': There was an error selecting the database');
}
}
/** public function connect_select
* Connects to the server AND selects the default database in one function.
*
* @param string [optional] database name
* @action connect to the mysql server
* @action select the mysql database
* @return void
*/
public function connect_select($database = null)
{
if ( ! is_null($database)) {
$this->_db = $database;
}
try {
$this->connect( );
$this->select( );
}
catch (MySQLException $e) {
throw $e;
}
$this->_log(__METHOD__.': '.$this->link_id);
$this->_log('-------------------------------');
}
/** public function set_error
* Set the error level based on a bitwise value.
*
* @param int value (0 = none, 3 = all)
* @action set the error level
* @return void
*/
public function set_error($val)
{
$this->_error_debug = (0 != (1 & $val));
$this->_query_debug = (0 != (2 & $val));
}
/** public function query
* Execute a database query
* If no query is passed, it executes the last saved query.
*
* @param string [optional] SQL query string
* @param int [optional] number of tries
* @action execute a mysql query
* @return mysql result resource
*/
public function query($query = null, $tries = 0)
{
if ( ! is_null($query)) {
$this->query = $query;
}
if (is_null($this->query)) {
throw new MySQLException(__METHOD__.': No query found');
}
$backtrace_file = $this->_get_backtrace( );
$this->_log(__METHOD__.' in '.basename($backtrace_file['file']).' on '.$backtrace_file['line'].' : '.$this->query);
if (empty($this->link_id)) {
$this->connect_select( );
}
$done = true; // innocent until proven guilty
// start time logging
$time = microtime_float( );
$this->result = @mysql_query($this->query, $this->link_id);
$this->query_time = microtime_float( ) - $time;
if ($this->_query_debug && empty($GLOBALS['AJAX'])) {
$this->query = trim(preg_replace('/\\s+/', ' ', $this->query));
if (('cli' == php_sapi_name( )) && empty($_SERVER['REMOTE_ADDR'])) {
echo "\n\nMYSQL - ".basename($backtrace_file['file']).' on '.$backtrace_file['line']."- {$this->query} - Aff(".$this->affected_rows( ).") (".number_format($this->query_time, 5)." s)\n\n";
}
else {
echo "<div style='background:#FFF;color:#009;'><br /><strong>".basename($backtrace_file['file']).' on '.$backtrace_file['line']."</strong>- {$this->query} - <strong>Aff(".$this->affected_rows( ).") (".number_format($this->query_time, 5)." s)</strong></div>";
}
}
if ( ! $this->result) {
if ((5 >= $tries) && ((2013 == mysql_errno($this->link_id)) || (2006 == mysql_errno($this->link_id)))) {
// try reconnecting a couple of times
$this->_log('RETRYING #'.$tries.': '.mysql_errno($this->link_id));
$this->test_connection( );
return $this->query(null, ++$tries);
}
$extra = '';
if ($backtrace_file) {
$line = $backtrace_file['line'];
$file = $backtrace_file['file'];
$file = substr($file, strlen(realpath($file.'../../../')));
$extra = ' on line <strong>'.$line.'</strong> of <strong>'.$file.'</strong>';
}
$this->error = mysql_errno($this->link_id).': '.mysql_error($this->link_id);
$this->_error_report( );
if ($this->_error_debug) {
if (('cli' == php_sapi_name( )) && empty($_SERVER['REMOTE_ADDR'])) {
$extra = strip_tags($extra);
echo "\n\nMYSQL ERROR - There was an error in your query{$extra}:\nERROR: {$this->error}\nQUERY: {$this->query}\n\n";
}
else {
echo "<div style='background:#900;color:#FFF;'>There was an error in your query{$extra}:<br />ERROR: {$this->error}<br />QUERY: {$this->query}</div>";
}
}
else {
$this->error = 'There was a database error.';
}
$done = false;
}
if ($done) {
// if we just performed an insert, grab the insert_id and return it
if (preg_match('/^\s*(INSERT|REPLACE)/i', $this->query)) {
$this->result = $this->fetch_insert_id( );
}
$this->query_count++;
return $this->result;
}
// no result found
return false;
}
/** public function affected_rows
* Return the number of affected rows from the latest query.
*
* @param void
* @return int number of affected rows
*/
public function affected_rows( )
{
$count = @mysql_affected_rows($this->link_id);
return $count;
}
/** public function num_rows
* Return the number of returned rows from the latest query.
*
* @param void
* @return int number of returned rows
*/
public function num_rows( )
{
$count = @mysql_num_rows($this->result);
if ( ! $count) {
return 0;
}
return $count;
}
/** public function insert
* Insert the associative data array into the table.
* $data['field_name'] = value
* $data['field_name2'] = value2
* If the field name has a trailing space: $data['field_name ']
* then the query will insert the data with no sanitation
* or wrapping quotes (good for function calls, like NOW( )).
*
* @param string table name
* @param array associative data array
* @param string [optional] where clause (for updates)
* @param bool [optional] whether or not we should replace values (true / false)
* @action execute a mysql query
* @return int insert id for row
*/
public function insert($table, $data_array, $where = '', $replace = false)
{
$where = trim($where);
$replace = (bool) $replace;
if ('' == $where) {
$query = (false == $replace) ? ' INSERT ' : ' REPLACE ';
$query .= ' INTO ';
}
else {
$query = ' UPDATE ';
}
$query .= '`'.$table.'`';
if ( ! is_array($data_array)) {
throw new MySQLException(__METHOD__.': Trying to insert non-array data');
}
else {
$query .= ' SET ';
foreach ($data_array as $field => $value) {
if (is_null($value)) {
$query .= " `{$field}` = NULL , ";
}
elseif (' ' == substr($field, -1, 1)) { // i picked a trailing space because it's an illegal field name in MySQL
$field = trim($field);
$query .= " `{$field}` = {$value} , ";
}
else {
$query .= " `{$field}` = '".sani($value)."' , ";
}
}
$query = substr($query, 0, -2).' '; // remove the last comma (but preserve those spaces)
}
$query .= ' '.$where.' ';
$this->query = $query;
$return = $this->query( );
if ('' == $where) {
return $this->fetch_insert_id( );
}
else {
return $return;
}
}
/** public function multi_insert
* Insert the array of associative data arrays into the table.
* $data[0]['field_name'] = value
* $data[0]['field_name2'] = value2
* $data[0]['DBWHERE'] = where clause [optional]
* $data[1]['field_name'] = value
* $data[1]['field_name2'] = value2
* $data[1]['DBWHERE'] = where clause [optional]
*
* @param string table name
* @param array associative data array
* @param bool [optional] whether or not we should replace values (true / false)
* @action execute multiple mysql queries
* @return array insert ids for rows (with original keys preserved)
*/
public function multi_insert($table, $data_array, $replace = false)
{
if ( ! is_array($data_array)) {
throw new MySQLException(__METHOD__.': Trying to multi-insert non-array data');
}
else {
$result = array( );
foreach ($data_array as $key => $row) {
$where = (isset($row['DBWHERE'])) ? $row['DBWHERE'] : '';
unset($row['DBWHERE']);
$result[$key] = $this->insert($table, $row, $where, $replace);
}
}
return $result;
}
/** public function delete
* Delete the row from the table
*
* @param string table name
* @param string where clause
* @action execute a mysql query
* @return result
*/
public function delete($table, $where)
{
$query = "
DELETE
FROM `{$table}`
{$where}
";
$this->query = $query;
- return $this->query( );
+ try {
+ return $this->query( );
+ }
+ catch (MySQLException $e) {
+ throw $e;
+ }
}
/** public function multi_delete
* Delete the array of data from the table.
* $table[0] = table name
* $table[1] = table name
*
* $where[0] = where clause
* $where[1] = where clause
*
* If recursive is true, all combinations of table name
* and where clauses will be executed.
*
* If only one table name is set, that table will
* be used for all of the queries, looping through
* the where array
*
* If only one where clause is set, that where clause
* will be used for all of the queries, looping through
* the table array
*
* @param mixed table name array or single string
* @param mixed where clause array or single string
* @param bool optional recursive (default false)
* @action execute multiple mysql queries
* @return array results
*/
public function multi_delete($table_array, $where_array, $recursive = false)
{
if ( ! is_array($table_array)) {
$recursive = false;
$table_array = (array) $table_array;
}
if ( ! is_array($where_array)) {
$recursive = false;
$where_array = (array) $where_array;
}
if ($recursive) {
foreach ($table_array as $table) {
foreach ($where_array as $where) {
$result[] = $this->delete($table, $where);
}
}
}
else {
if (count($table_array) == count($where_array)) {
for ($i = 0, $count = count($table_array); $i < $count; ++$i) {
$result[] = $this->delete($table_array[$i], $where_array[$i]);
}
}
elseif (1 == count($table_array)) {
$table = $table_array[0];
foreach ($where_array as $where) {
$result[] = $this->delete($table, $where);
}
}
elseif (1 == count($where_array)) {
$where = $where_array[0];
foreach ($table_array as $table) {
$result[] = $this->delete($table, $where);
}
}
else {
throw new MySQLException(__METHOD__.': Trying to multi-delete with incompatible array sizes');
}
}
return $result;
}
/** public function fetch_object
* Execute a database query and return the next result row as object.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return mysql next result object row
*/
public function fetch_object($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_object($this->result);
return $row;
}
/** public function fetch_row
* Execute a database query and return result as an indexed array.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array indexed mysql result array
*/
public function fetch_row($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_row($this->result);
if ( ! $row) {
$row = array( );
}
return $row;
}
/** public function fetch_assoc
* Execute a database query and return result as an associative array.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array associative mysql result array
*/
public function fetch_assoc($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_assoc($this->result);
if ( ! $row) {
$row = array( );
}
return $row;
}
/** public function fetch_both
* Execute a database query and return result as both
* an associative array and indexed array.
* Each subsequent call to this method returns the next result row.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array associative and indexed mysql result array
*/
public function fetch_both($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_array($this->result, MYSQL_BOTH);
if ( ! $row) {
$row = array( );
}
return $row;
}
/** public function fetch_array
* Execute a database query and return result as
* an indexed array of both indexed and associative arrays.
* This method returns the entire result set in a single call.
*
* @param string [optional] SQL query string
* @param int [optional] SQL result type ( One of: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH )
* @action [optional] execute a mysql query
* @return array indexed array of mysql result arrays of type $result_type
*/
public function fetch_array($query = null, $result_type = MYSQL_ASSOC)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$arr = array( );
while ($row = @mysql_fetch_array($this->result, $result_type)) {
$arr[] = $row;
}
return $arr;
}
/** public function fetch_value
* Execute a database query and return result as
* a single result value.
* This method only returns the single value at index 0.
* Each subsequent call to this method returns the next value.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return mixed single mysql result value
*/
public function fetch_value($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$row = @mysql_fetch_row($this->result);
if (false !== $row) {
return $row[0];
}
else {
// no data found
return null;
}
}
/** public function fetch_value_array
* Execute a database query and return result as
* an indexed array of single result values.
* This method returns the entire result set in a single call.
*
* @param string [optional] SQL query string
* @action [optional] execute a mysql query
* @return array indexed array of single mysql result values
*/
public function fetch_value_array($query = null)
{
if ( ! is_null($query)) {
$this->query = $query;
$this->query( );
}
$arr = array( );
while ($row = @mysql_fetch_row($this->result)) {
$arr[] = $row[0];
}
return $arr;
}
/** public function paginate NOT TESTED
* Paginates a query result set based on supplied information
* NOTE: It is not necessary to include the SQL_CALC_FOUND_ROWS
* nor the LIMIT clause in the query, in fact, including the
* LIMIT clause in the query will probably break MySQL.
*
* @param int [optional] current page number
* @param int [optional] number of records per page
* @param string [optional] SQL query string
* @return array pagination result and data
*/
public function paginate($page = null, $num_per_page = null, $query = null)
{
if ( ! is_null($page)) {
$this->_page = $page;
}
else { // we don't have a page, either increment, or set equal to 1
$this->_page = (isset($this->_page)) ? ($this->_page + 1) : 1;
}
if ( ! is_null($num_per_page)) {
$this->_num_per_page = $num_per_page;
}
else {
$this->_num_per_page = (isset($this->_num_per_page)) ? $this->_num_per_page : 50;
}
if ( ! $this->_page || ! $this->_num_per_page) {
throw new MySQLException(__METHOD__.': No pagination data given');
}
if ( ! is_null($query)) {
$this->_page_query = $query;
// add the SQL_CALC_FOUND_ROWS keyword to the query
if (false === strpos($query, 'SQL_CALC_FOUND_ROWS')) {
$query = preg_replace('/SELECT\\s+(?!SQL_)/i', 'SELECT SQL_CALC_FOUND_ROWS ', $query);
}
$start = ($this->_num_per_page * ($this->_page - 1));
// add the LIMIT clause to the query
$query .= "
LIMIT {$start}, {$this->_num_per_page}
";
$this->_page_result = $this->fetch_array($query);
if ( ! $this->_page_result) {
// no data found
return array( );
}
$query = "
SELECT FOUND_ROWS( ) AS count
";
$this->_num_results = $this->fetch_value($query);
$this->_num_pages = (int) ceil($this->_num_results / $this->_num_per_page);
}
else { // we are using the previous data
if ($this->_num_results < ($this->_num_per_page * ($this->_page - 1))) {
return array( );
}
$query = $this->_page_query;
$start = $this->_num_per_page * ($this->_page - 1);
// add the LIMIT clause to the query
$query .= "
LIMIT {$start}, {$this->_num_per_page}
";
$this->_page_result = $this->fetch_array($query);
if ( ! $this->_page_result) {
// no data found
return array( );
}
}
// clean up the data and output to user
$output = array( );
$output['num_rows'] = $this->_num_results;
$output['num_per_page'] = $this->_num_per_page;
$output['num_pages'] = $this->_num_pages;
$output['cur_page'] = $this->_page;
$output['data'] = $this->_page_result;
return $output;
}
/** public function fetch_insert_id
* Return the insert id for the most recent query.
*
* @param void
* @return int previous insert id
*/
public function fetch_insert_id( )
{
return @mysql_insert_id($this->link_id);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
if (false && $this->_log_errors && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** protected function _error_report
* Report the errors
*
* @param void
* @action log errors
* @return void
*/
protected function _error_report( )
{
$this->_log($this->error);
// generate an error report and then act according to configuration
$error_report = date('Y-m-d H:i:s')."\n\tAn error has been generated by the server.\n\tFollowing is the debug information:\n\n";
// we don't need this function in the error report, just delete it
$debug_array = debug_backtrace( );
unset($debug_array[0]);
// if a database query caused the error, show the query
if ('' != $this->query) {
$error_report .= "\t* Query: {$this->query}\n";
}
$error_report .= "\t* Error: {$this->error}\n";
$error_report .= "\t* Backtrace: ".print_r($debug_array, true)."\n\n";
// send the error as email if set
if ($this->_email_errors && ('' != $this->_email_to) && ('' != $this->_email_from)) {
mail($this->_email_to, trim($this->_email_subject), $error_report, 'From: '.$this->_email_from."\r\n");
}
// log the error
if ($this->_log_errors) {
$log = $this->_log_path.'mysql.err';
$fp = fopen($log, 'a+');
fwrite($fp, $error_report);
@chmod($log, 0777);
fclose($fp);
}
}
/** protected function _get_backtrace
* Grab the data for the file that called the mysql function
*
* @param void
* @return mixed array backtrace data, or bool false on failure
*/
protected function _get_backtrace( )
{
// grab the debug_backtrace
$debug = debug_backtrace(false);
// parse through it, and find the first instance that isn't from this file
$file = false;
foreach ($debug as $file) {
if (__FILE__ == $file['file']) {
continue;
}
else {
// $file will be the file that called the mysql function
break;
}
}
return $file;
}
/** static public function get_instance
* Returns the singleton instance
* of the MySQL Object as a reference
*
* @param array optional configuration array
* @action optionally creates the instance
* @return MySQL Object reference
*/
static public function get_instance($config = null)
{
try {
if (is_null(self::$_instance)) {
self::$_instance = new Mysql($config);
}
self::$_instance->test_connection( );
self::$_instance->_log(__METHOD__.' --------------------------------------');
}
catch (MySQLException $e) {
throw $e;
}
return self::$_instance;
}
/** static public function test
* Test the MySQL connection
*
* @param void
* @return bool connection OK
*/
static public function test( )
{
try {
self::get_instance( );
return true;
}
catch (MySQLException $e) {
return false;
}
}
} // end of Mysql class
class MySQLException
extends Exception {
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param string error message
* @param int optional error code
* @action instantiates object
* @action writes the exception to the log
* @return void
*/
public function __construct($message, $code = 1)
{
parent::__construct($message, $code);
// our own exception handling stuff
if ( ! empty($GLOBALS['_LOGGING'])) {
$this->_write_error( );
}
diff --git a/scripts/invite.js b/scripts/invite.js
index 1cf9c31..c1ebddc 100644
--- a/scripts/invite.js
+++ b/scripts/invite.js
@@ -1,281 +1,300 @@
var reload = true; // do not change this
var new_setup = false;
function check_fieldset_box( ) {
$('input.fieldset_box').each( function(i, elem) {
var $this = $(this);
var id = $this.attr('id').slice(0,-4);
if ($this.prop('checked')) {
$('div#'+id).show( );
}
else {
$('div#'+id).hide( );
}
});
}
$(document).ready( function( ) {
// hide the setup div
$('div#setup_display').hide( );
check_fieldset_box( );
show_link( );
show_version( );
// show the setup div in a fancybox
$('a#show_setup').fancybox({
padding : 10,
onStart : function( ) {
var setup = setups[$('select#setup').val( )];
if (new_setup) {
setup = new_setup;
}
$('div#setup_display')
.empty( )
.append(create_board(setup))
.show( );
},
onClosed :function( ) {
$('div#setup_display').hide( );
}
});
// only show the setup link when a setup is selected
$('select#setup').change( function( ) {
show_link( );
show_version( );
});
$('input#convert_to_1, input#convert_to_2, input#rand_convert_to_1, input#rand_convert_to_2').change( function( ) {
show_version( );
});
// show the setup div for the invites
$('a.setup').fancybox({
type : 'inline',
href : '#setup_display',
padding : 10,
onStart : function(arr, idx, opts) {
var $elem = $(arr[idx]);
var setup = setups[$(arr[idx]).attr('id').slice(2)];
if ('#setup_display' != $elem.attr('href')) {
setup = $elem.attr('href').slice(1);
}
$('div#setup_display')
.empty( )
.append(create_board(setup))
.show( );
},
onClosed :function( ) {
$('div#setup_display').hide( );
}
});
$('form#send').submit( function( ) {
if ( ! $('select#setup').val( )) {
alert('You must select a setup');
return false;
}
return true;
});
// hide the collapsable fieldsets
$('input.fieldset_box').change( function( ) {
check_fieldset_box( );
});
// this runs all the ...vites
$('div#invites input').click( function( ) {
- var id = $(this).attr('id').split('-');
+ var $this = $(this);
+ var id = $this.attr('id').split('-');
if ('accept' == id[0]) { // invites and openvites
// accept the invite
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'invite=accept&game_id='+id[1];
return;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'invite=accept&game_id='+id[1],
success: function(msg) {
- window.location = 'game.php?id='+msg+debug_query_;
+ if ('ERROR' == msg.slice(0, 5)) {
+ alert(msg);
+ if (reload) { window.location.reload( ); }
+ }
+ else {
+ window.location = 'game.php?id='+msg+debug_query_;
+ }
return;
}
});
}
else if ('resend' == id[0]) { // resends outvites
// resend the invite
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'invite=resend&game_id='+id[1];
return;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'invite=resend&game_id='+id[1],
success: function(msg) {
alert(msg);
- if (reload) { window.location.reload( ); }
+ if ('ERROR' == msg.slice(0, 5)) {
+ if (reload) { window.location.reload( ); }
+ }
+ else {
+ // remove the resend button
+ $this.remove( );
+ }
return;
}
});
}
else { // invites decline and outvites withdraw
// delete the invite
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'invite=delete&game_id='+id[1];
return;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'invite=delete&game_id='+id[1],
success: function(msg) {
alert(msg);
- if (reload) { window.location.reload( ); }
+ if ('ERROR' == msg.slice(0, 5)) {
+ if (reload) { window.location.reload( ); }
+ }
+ else {
+ // remove the parent TR
+ $this.parent( ).parent( ).remove( );
+ }
return;
}
});
}
});
});
function show_link( ) {
if (0 != $('select#setup').val( )) {
$('a#show_setup').show( );
}
else {
$('a#show_setup').hide( );
}
}
function show_version( ) {
if (0 != $('select#setup').val( )) {
if (setups[$('select#setup').val( )].match(/[efjk]/i)) {
$('.random_convert').hide( );
$('.pharaoh_1').hide( );
$('.pharaoh_2').show( );
$('.pharaoh_2 .conversion').show( );
if ($('input#convert_to_1').prop('checked')) {
$('.pharaoh_2').hide( );
$('.p2_box').show( );
convert_setup(1);
}
else {
new_setup = false;
}
}
else {
$('.random_convert').hide( );
$('.pharaoh_2').hide( );
$('.pharaoh_1').show( );
if ($('input#convert_to_2').prop('checked')) {
$('.pharaoh_2').show( );
$('.pharaoh_2 .conversion').hide( );
convert_setup(2);
}
else {
new_setup = false;
}
}
}
else {
$('.pharaoh_1, .pharaoh_2').hide( );
$('.random_convert').show( );
if ($('input#rand_convert_to_2').prop('checked')) {
$('.pharaoh_2').show( );
$('.pharaoh_2 .conversion').hide( );
}
}
}
function convert_setup(to) {
to = parseInt(to || 1);
var setup = setups[$('select#setup').val( )];
// the p1 pieces are repeated here for the TO v1 conversion
// just make sure that the TO v2 conversion pieces are listed first
// that way they will get converted and be correct
var p1 = ['w','w','w','w','W','W','W','W'];
var p2 = ['n','l','m','o','L','M','N','O'];
switch (to) {
case 1 :
// swap out the anubises with obelisks
new_setup = str_replace(p2, p1, setup);
// remove the sphynxes
new_setup = new_setup.replace(/[efjk]/ig, '0');
break;
case 2 :
// swap out the obelisks with anubises
new_setup = str_replace(p1, p2, setup);
// replace anything on the laser corners with a sphynx
new_setup = new_setup.replaceAt(0, 'j').replaceAt(79, 'E');
break;
}
return new_setup;
}
// http://phpjs.org/functions/str_replace:527
function str_replace(search, replace, subject, count) {
var i = 0,
j = 0,
temp = '',
repl = '',
sl = 0,
fl = 0,
f = [].concat(search),
r = [].concat(replace),
s = subject,
ra = Object.prototype.toString.call(r) === '[object Array]',
sa = Object.prototype.toString.call(s) === '[object Array]';
s = [].concat(s);
if (count) {
this.window[count] = 0;
}
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue;
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + '';
repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
s[i] = (temp).split(f[j]).join(repl);
if (count && s[i] !== temp) {
this.window[count] += (temp.length - s[i].length) / f[j].length;
}
}
}
return sa ? s : s[0];
}
String.prototype.replaceAt = function(index, str) {
index = parseInt(index);
return this.slice(0, index) + str + this.slice(index + str.length);
}
diff --git a/todo.txt b/todo.txt
index cea583d..6947571 100644
--- a/todo.txt
+++ b/todo.txt
@@ -1,38 +1,35 @@
+- there are errors when trying to re-send invites
+ - make sure everything is working with the invites
+
- make hover tooltips better
- add ability to hit own laser from side as option
- for revisions for setups, allow the same name for the setup and when
a user creates a revision or edits their setup, it creates a new setup
and inactivates the previous setup, and then either sort by create
date, or add a field in the table called revision and increment that
and when we pull the setup, order by created or revision number, and
use the most recent.
- add more stats:
player's most played setup
player's favorite setup
player's worst setup
player's favorite opponent
win-loss per opponent
etc...
- build game reader for saved games
- don't refresh page if an email success message is sent for things
like resend invites, nudges, etc. just make changes to html if needed
-- add a different method for removing the click on the piece, because
- clicking the piece again doesn't work for rotatable pieces
-
- don't show success messages if email is not sent for things like
- nudge, that are only emails possibly for other things like invite,
- etc. that are largely email dependent
- - make accept invite and withdraw invite pages ajax powered and
- just remove the item from the table (and other places as well)
+ nudge, that are only email dependent
- fully convert times to UTC in MySQL and back to user's timezone everywhere
dates are output
- add showdown to messages (JS port of Markdown, in zz_scripts_js)
\ No newline at end of file
|
benjamw/pharaoh | b5df2d7f3ffac333620fbf044ea262abca387419 | Fixed issue with admin deleting setups | diff --git a/setups.php b/setups.php
index a3bca6e..13a07ab 100644
--- a/setups.php
+++ b/setups.php
@@ -1,290 +1,291 @@
<?php
require_once 'includes/inc.global.php';
$act = (isset($_REQUEST['act']) ? $_REQUEST['act'] : '');
switch ($act) {
case 'create' :
case 'edit' :
case 'clone' :
if (isset($_POST['setup'])) {
test_token( );
$edit = false;
try {
if (isset($_POST['id'])) {
$edit = true;
// make sure this user can edit this setup
$Setup = new Setup((int) $_POST['id']);
if (((string) $_SESSION['player_id'] !== (string) $Setup->creator) && ! $GLOBALS['Player']->is_admin) {
Flash::store('You are not allowed to perform this action', 'setups.php');
}
}
else {
$Setup = new Setup( );
}
$setup_id = $Setup->save( );
Flash::store('Setup '.(($edit) ? 'Edited' : 'Created').' Successfully');
}
catch (MyException $e) {
Flash::store('Setup '.(($edit) ? 'Edit' : 'Creation').' FAILED !\n'.$e->outputMessage( ), false);
// it will just continue on here...
}
}
$hints = array(
'Click on a piece to select it, and then click anywhere on the board to place that piece.' ,
'Click on the Cancel button to cancel piece selection.' ,
'Click on the Delete button, and then click on the piece to delete an existing piece.' ,
'The reflection setting will also place the reflected pieces along with the pieces you place, making board creation faster and less prone to errors.' ,
'The reflections setting will also validate, so if you have a few non-reflected pieces in your layout, set reflection to "None" before submitting.' ,
'Setups will be immediately available for use after successful creation.' ,
);
$edit = false;
if ( ! empty($_REQUEST['id'])) {
$hints[] = 'Only unique names and layouts will be accepted.';
$Setup = new Setup((int) $_REQUEST['id']);
// make sure this user can edit this setup
if ('edit' == $act) {
if (((string) $_SESSION['player_id'] !== (string) $Setup->creator) && ! $GLOBALS['Player']->is_admin) {
Flash::store('You are not allowed to perform this action', 'setups.php');
}
$edit = true;
}
}
else {
$Setup = new Setup( );
}
if ( ! $edit) {
$id_field = '';
$create = 'Create';
}
else {
$id_field = "<input type=\"hidden\" name=\"id\" value=\"{$Setup->id}\" />";
$create = 'Edit';
}
$suffix = '';
if ('clone' == $act) {
$suffix = ' Clone';
}
$meta['title'] = $create.' Game Setup';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">
var invert = false;
var board = "'.expandFEN($Setup->board).'";
</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/setups.js"></script>
';
$reflection = $Setup->get_reflection( );
foreach (array('Origin', 'Long', 'Short', 'None') as $type) {
${$type} = '';
if ($reflection == $type) {
${$type} = ' selected="selected"';
}
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="setup_form"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="act" value="{$act}" />
<input type="hidden" name="setup" id="setup" value="" />
{$id_field}
<div><label for="name">Setup Name</label><input id="name" name="name" value="{$Setup->name}{$suffix}" /></div>
<div><label for="reflection">Piece Reflection</label><select id="reflection" name="reflection">
<option{$None}>None</option>
<option{$Origin}>Origin</option>
<option{$Long}>Long</option>
<option{$Short}>Short</option>
</select></div>
<div id="pieces_display">
<div id="cancel_delete">
<img src="images/cancel.png" alt="Cancel" title="Cancel Selection" class="cancel" />
<img src="images/delete.png" alt="Delete" title="Delete Piece" class="delete" />
</div>
<div id="silver_pieces"></div>
<div id="red_pieces"></div>
</div> <!-- #pieces_display -->
<div id="setup_display">
<!-- the board will go here -->
<div class="buttons" style="text-align:center;">
<a href="javascript:;" id="red_laser" style="float:left;">Test Fire Red Laser</a>
<a href="javascript:;" id="invert">Invert Board</a> |
<a href="javascript:;" id="clear_laser">Clear Laser</a>
<a href="javascript:;" id="silver_laser" style="float:right;">Test Fire Silver Laser</a>
</div> <!-- .buttons -->
</div>
<div><input type="submit" value="{$create} Setup" /></div>
</div></form>
EOF;
break;
case 'delete' :
if (isset($_POST['id'])) {
test_token( );
// make sure this user can delete this setup
$Setup = new Setup((int) $_POST['id']);
- if ( ! $Setup->creator || (((string) $_SESSION['player_id'] !== (string) $Setup->creator) && ! $GLOBALS['Player']->is_admin)) {
+ if ( ! $GLOBALS['Player']->is_admin && ( ! $Setup->creator || ((string) $_SESSION['player_id'] !== (string) $Setup->creator))) {
Flash::store('You are not allowed to perform this action', 'setups.php');
}
Setup::delete($Setup->id);
Flash::store('Setup deleted successfully', 'setups.php');
}
elseif (isset($_GET['id'])) {
// make sure this user can edit / delete this setup
$Setup = new Setup((int) $_GET['id']);
- if ( ! $Setup->creator || (((string) $_SESSION['player_id'] !== (string) $Setup->creator) && ! $GLOBALS['Player']->is_admin)) {
+ if ( ! $GLOBALS['Player']->is_admin && ( ! $Setup->creator || ((string) $_SESSION['player_id'] !== (string) $Setup->creator))) {
Flash::store('You are not allowed to perform this action', 'setups.php');
}
// we need to confirm the delete request via a safer method (no XSRF here)
$meta['title'] = 'Delete Game Setup';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">
var invert = false;
var board = "'.expandFEN($Setup->board).'";
</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/setups.js"></script>
';
$hints = array(
'Delete your game setup by clicking the button.' ,
'If you do not wish to delete your setup, simply go to another section of the site. Or click here to return to the <a href="setups.php">Setup Page</a>' ,
);
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="delete_form"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="act" value="delete" />
<input type="hidden" name="id" value="{$Setup->id}" />
- <div>Are you sure you wish to delete your setup, {$Setup->name}? This cannot be undone.</div>
+ <div>Are you sure you wish to delete your setup, {$Setup->name}?<br />
+ <strong>THIS CANNOT BE UNDONE.</strong> <a href="setups.php">Cancel Delete</a></div>
<div><input type="submit" value="Delete Setup" /></div>
</div></form>
<div id="setup_display">
<!-- the board will go here -->
<div class="buttons" style="text-align:center;">
<a href="javascript:;" id="red_laser" style="float:left;">Test Fire Red Laser</a>
<a href="javascript:;" id="invert">Invert Board</a> |
<a href="javascript:;" id="clear_laser">Clear Laser</a>
<a href="javascript:;" id="silver_laser" style="float:right;">Test Fire Silver Laser</a>
</div> <!-- .buttons -->
</div>
EOF;
}
break;
default : // setup list
$setups = Setup::get_list( );
$setup_selection = '<option value="0">Random</option>';
$setup_javascript = '';
foreach ($setups as $setup) {
$setup_selection .= '
<option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>';
$setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n";
}
$setup_javascript = substr(trim($setup_javascript), 0, -1); // remove trailing comma
$meta['title'] = 'Game Setups';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">//<![CDATA[
var setups = {
'.$setup_javascript.'
};
/*]]>*/</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/setups.js"></script>
<script type="text/javascript" src="scripts/stats.js"></script>
';
$hints = array(
'Click on Setup table row to view setup.' ,
'Clone will take you to the create setup page with that setup pre-filled out.' ,
);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no setups to show</p>' ,
'caption' => 'Setups' ,
);
$table_format = array(
array('SPECIAL_CLASS', 'true', 'setup') ,
array('SPECIAL_HTML', 'true', ' id="s_[[[setup_id]]]"') ,
array('Setup', 'name') ,
array('Used', 'used') ,
array('Horus', '###(([[[has_horus]]]) ? \'Yes\' : \'No\')') ,
array('Sphynx', '###(([[[has_sphynx]]]) ? \'Yes\' : \'No\')') ,
// array('Tower', '###(([[[has_tower]]]) ? \'Yes\' : \'No\')') , // TOWER
array('Reflection', 'reflection') ,
array('Created', '###date(Settings::read(\'long_date\'), strtotime(\'[[[created]]]\'))', null, ' class="date"') ,
array('Creator', '###((0 == [[[created_by]]]) ? \'Admin\' : $GLOBALS[\'_PLAYERS\'][[[[created_by]]]])') ,
array('Action', '###((('.$_SESSION['player_id'].' == [[[created_by]]]) || '.(int) $GLOBALS['Player']->is_admin.') ? ((('.$_SESSION['player_id'].' != [[[created_by]]]) && '.(int) $GLOBALS['Player']->is_admin.') ? "<a href=\"setups.php?act=clone&id=[[[setup_id]]]'.$GLOBALS['_&_DEBUG_QUERY'].'\">Clone</a> | " : "") . "<a href=\"setups.php?act=edit&id=[[[setup_id]]]'.$GLOBALS['_&_DEBUG_QUERY'].'\">Edit</a> | <a href=\"setups.php?act=delete&id=[[[setup_id]]]'.$GLOBALS['_&_DEBUG_QUERY'].'\">Delete</a>" : "<a href=\"setups.php?act=clone&id=[[[setup_id]]]'.$GLOBALS['_&_DEBUG_QUERY'].'\">Clone</a>")', null, ' class="action"') ,
);
$contents = <<< EOF
<form method="get" action="{$_SERVER['REQUEST_URI']}" id="create_form"><div class="formdiv">
<input type="hidden" name="act" value="create" />
<div><input type="submit" value="Create Setup" /></div>
</div></form>
EOF;
$contents .= get_table($table_format, $setups, $table_meta);
$contents .= <<< EOF
<div id="setup_display"></div>
EOF;
break;
}
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer( );
|
benjamw/pharaoh | 4923c4d83cfbf0282aaba3a2f52357c6cd13c1fb | allow for conversion of randomly selected setups | diff --git a/classes/game.class.php b/classes/game.class.php
index aff1c1e..a2a3737 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1,985 +1,979 @@
<?php
/*
+---------------------------------------------------------------------------
|
| game.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| This module is built to facilitate the game Pharaoh, it doesn't really
| care about how to play, or the deep goings on of the game, only about
| database structure and how to allow players to interact with the game.
|
+---------------------------------------------------------------------------
|
| > Pharaoh (Khet) Game module
| > Date started: 2008-02-28
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
if (defined('INCLUDE_DIR')) {
require_once INCLUDE_DIR.'func.array.php';
}
class Game
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property GAME_TABLE
* Holds the game table name
*
* @var string
*/
const GAME_TABLE = T_GAME;
/** const property GAME_HISTORY_TABLE
* Holds the game board table name
*
* @var string
*/
const GAME_HISTORY_TABLE = T_GAME_HISTORY;
/** const property GAME_NUDGE_TABLE
* Holds the game nudge table name
*
* @var string
*/
const GAME_NUDGE_TABLE = T_GAME_NUDGE;
/** const property GAME_STATS_TABLE
* Holds the game stats table name
*
* @var string
*/
const GAME_STATS_TABLE = T_STATS;
/** static protected property _EXTRA_INFO_DEFAULTS
* Holds the default extra info data
*
* @var array
*/
static protected $_EXTRA_INFO_DEFAULTS = array(
'white_color' => 'random',
'battle_dead' => false,
'battle_immune' => false,
'battle_front_only' => true,
'battle_hit_self' => false,
'move_sphynx' => false,
'draw_offered' => false,
'undo_requested' => false,
'custom_rules' => '',
'invite_setup' => '', // this is to hold the setup for invites only
);
/** static protected property _HISTORY_EXTRA_INFO_DEFAULTS
* Holds the default extra info data for the move history
*
* @var array
*/
static protected $_HISTORY_EXTRA_INFO_DEFAULTS = array(
'laser_hit' => false,
'laser_fired' => true,
'dead_for' => 0,
'immune_for' => 0,
);
/** public property id
* Holds the game's id
*
* @var int
*/
public $id;
/** public property state
* Holds the game's current state
* can be one of 'Waiting', 'Playing', 'Finished', 'Draw'
*
* @var string (enum)
*/
public $state;
/** public property turn
* Holds the game's current turn
* can be one of 'white', 'black'
*
* @var string
*/
public $turn;
/** public property paused
* Holds the game's current pause state
*
* @var bool
*/
public $paused;
/** public property create_date
* Holds the game's create date
*
* @var int (unix timestamp)
*/
public $create_date;
/** public property modify_date
* Holds the game's modified date
*
* @var int (unix timestamp)
*/
public $modify_date;
/** public property last_move
* Holds the game's last move date
*
* @var int (unix timestamp)
*/
public $last_move;
/** public property watch_mode
* Lets us know if we are just visiting this game
*
* @var bool
*/
public $watch_mode = false;
/** protected property _setup
* Holds the game's initial setup
* as an associative array
* array(
* 'id' => [setup_id],
* 'name' => [setup_name],
* );
*
* @var array
*/
protected $_setup;
/** protected property _laser_fired
* Holds the laser fired flag
*
* @var bool did we fire the laser?
*/
protected $_laser_fired = false;
/** protected property _extra_info
* Holds the extra game info
*
* @var array
*/
protected $_extra_info;
/** protected property _current_move_extra_info
* Holds the extra current move info
*
* @var array
*/
protected $_current_move_extra_info;
/** protected property _players
* Holds our player's object references
* along with other game data
*
* @var array of player data
*/
protected $_players;
/** protected property _pharaoh
* Holds the pharaoh object reference
*
* @var Pharaoh object reference
*/
protected $_pharaoh;
/** protected property _history
* Holds the board history
*
* @var array of pharaoh boards
*/
protected $_history;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional game id
* @param Mysql optional object reference
* @action instantiates object
* @return void
*/
public function __construct($id = 0, Mysql $Mysql = null)
{
call(__METHOD__);
$this->id = (int) $id;
call($this->id);
$this->_pharaoh = new Pharaoh($this->id);
if (is_null($Mysql)) {
$Mysql = Mysql::get_instance( );
}
$this->_mysql = $Mysql;
try {
$this->_pull( );
}
catch (MyException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action saves changed data
* @action destroys object
* @return void
*/
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if ($this->id && (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type']))) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
switch ($property) {
case 'name' :
return $this->_players['white']['object']->username.' vs '.$this->_players['black']['object']->username;
break;
case 'first_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return 'Your';
}
else {
return $this->_players['white']['object']->username.'\'s';
}
break;
case 'second_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return $this->_players['opponent']['object']->username.'\'s';
}
else {
return $this->_players['black']['object']->username.'\'s';
}
break;
default :
// go to next step
break;
}
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
$this->$property = $value;
}
/** static public function invite
* Creates the game from _POST data
*
* @param void
* @action creates an invite
* @return int game id
*/
static public function invite( )
{
call(__METHOD__);
call($_POST);
$Mysql = Mysql::get_instance( );
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
$_P = $_POST;
// translate (filter/sanitize) the data
$_P['white_id'] = (int) $_SESSION['player_id'];
$_P['black_id'] = (int) $_P['opponent'];
$_P['setup_id'] = (int) $_P['setup'];
$_P['laser_battle'] = is_checked($_P['laser_battle_box']);
$_P['battle_front_only'] = is_checked($_P['battle_front_only']);
$_P['battle_hit_self'] = is_checked($_P['battle_hit_self']);
$_P['move_sphynx'] = is_checked($_P['move_sphynx']);
call($_P);
// grab the setup
$query = "
SELECT setup_id
FROM ".Setup::SETUP_TABLE."
";
$setup_ids = $Mysql->fetch_value_array($query);
call($setup_ids);
// check for random setup
if (0 == $_P['setup_id']) {
shuffle($setup_ids);
shuffle($setup_ids);
$_P['setup_id'] = (int) reset($setup_ids);
sort($setup_ids);
}
// make sure the setup id is valid
if ( ! in_array($_P['setup_id'], $setup_ids)) {
throw new MyException(__METHOD__.': Setup is not valid');
}
$query = "
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$_P['setup_id']}'
";
$setup = $Mysql->fetch_value($query);
// laser battle cleanup
// only run this if the laser battle box was open
if ($_P['laser_battle']) {
ifer($_P['battle_dead'], 1, false);
ifer($_P['battle_immune'], 1);
// we can only hit ourselves in the sides or back, never front
if ($_P['battle_front_only']) {
$_P['battle_hit_self'] = false;
}
$extra_info = array(
'battle_dead' => (int) max((int) $_P['battle_dead'], 1),
'battle_immune' => (int) max((int) $_P['battle_immune'], 0),
'battle_front_only' => (bool) $_P['battle_front_only'],
'battle_hit_self' => (bool) $_P['battle_hit_self'],
);
}
$extra_info['white_color'] = $_P['color'];
$extra_info['move_sphynx'] = $_P['move_sphynx'];
$setup = expandFEN($setup);
- if (is_checked($_P['convert_to_1'])) {
- // add the sphynxes
- $setup = preg_replace('/[efjk]/i', '0', $setup);
-
- // replace the obelisks with anubises
- $setup = preg_replace('/[lmno]/', 'w', $setup);
- $setup = preg_replace('/[LMNO]/', 'W', $setup);
- }
- elseif (is_checked($_P['convert_to_2'])) {
- // add the sphynxes
- $setup = substr_replace($setup, 'j', 0, 1);
- $setup = substr_replace($setup, 'E', -1, 1);
-
- // replace the obelisks with anubises
- $setup = str_replace('w', 'n', $setup);
- $setup = str_replace('W', 'L', $setup);
+ try {
+ if (is_checked($_P['convert_to_1']) || is_checked($_P['rand_convert_to_1'])) {
+ $setup = Setup::convert_to_1($setup);
+ }
+ elseif (is_checked($_P['convert_to_2']) || is_checked($_P['rand_convert_to_2'])) {
+ $setup = Setup::convert_to_2($setup);
+ }
+ }
+ catch (MyException $e) {
+ throw $e;
}
$extra_info['invite_setup'] = packFEN($setup);
call($extra_info);
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
if ( ! empty($extra_info)) {
$_P['extra_info'] = serialize($extra_info);
}
// create the game
$required = array(
'white_id' ,
'setup_id' ,
);
$key_list = array_merge($required, array(
'black_id' ,
'extra_info' ,
));
try {
$_DATA = array_clean($_P, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['state'] = 'Waiting';
$_DATA['create_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$insert_id = $Mysql->insert(self::GAME_TABLE, $_DATA);
if (empty($insert_id)) {
throw new MyException(__METHOD__.': Invite could not be created');
}
// send the email
if ($_DATA['black_id']) {
Email::send('invite', $_DATA['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$_DATA['white_id']], 'page' => 'invite.php'));
}
return $insert_id;
}
/** static public function resend_invite
* Resends the invite email (if allowed)
*
* @param int game id
* @action resends an invite email
* @return bool invite email sent
*/
static public function resend_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$white_id = (int) $_SESSION['player_id'];
$Mysql = Mysql::get_instance( );
// grab the invite from the database
$query = "
SELECT *
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$invite = $Mysql->fetch_assoc($query);
if ( ! $invite) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend a non-existant invite (#'.$game_id.')');
}
if ((int) $invite['white_id'] !== (int) $white_id) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is not theirs');
}
if ( ! (int) $invite['black_id']) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is open');
}
if (strtotime($invite['modify_date']) >= strtotime($invite['resend_limit'])) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is too new');
}
// if we get here, all is good...
$sent = Email::send('invite', $invite['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$invite['white_id']], 'page' => 'invite.php'));
if ($sent) {
// update the modify_date to prevent invite resend flooding
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$Mysql->insert(self::GAME_TABLE, $_DATA, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
return $sent;
}
/** static public function accept_invite
* Creates the game from invite data
*
* @param int game id
* @action creates a game
* @return int game id
*/
static public function accept_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
// basically all we do, is set the state to Playing
// and set the player order based on the invite data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$game = $Mysql->fetch_assoc($query);
$invitor_id = $game['white_id']; // for use later
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($game['extra_info']));
if ((('random' == $extra_info['white_color']) && mt_rand(0, 1)) || ('white' == $extra_info['white_color'])) {
$game['white_id'] = $game['white_id'];
$game['black_id'] = $_SESSION['player_id'];
}
else {
$game['black_id'] = $game['white_id'];
$game['white_id'] = $_SESSION['player_id'];
}
call($extra_info);
unset($extra_info['white_color']);
$board = false;
if ( ! empty($extra_info['invite_setup'])) {
$board = $extra_info['invite_setup'];
}
$extra_info['invite_setup'] = '';
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
unset($game['extra_info']);
if ( ! empty($extra_info)) {
$game['extra_info'] = serialize($extra_info);
}
$game['state'] = 'Playing';
$Mysql->insert(self::GAME_TABLE, $game, " WHERE game_id = '{$game_id}' ");
// add the first entry in the history table
if (empty($board)) {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', (
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$game['setup_id']}'
))
";
$Mysql->query($query);
}
else {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', '{$board}')
";
$Mysql->query($query);
}
// add a used count to the setup table
Setup::add_used($game['setup_id']);
// send the email
Email::send('start', $invitor_id, array('opponent' => $GLOBALS['_PLAYERS'][$_SESSION['player_id']], 'game_id' => $game_id));
return $game_id;
}
/** static public function delete_invite
* Deletes the given invite
*
* @param int game id
* @action deletes the invite
* @return void
*/
static public function delete_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
$Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
/** static public function has_invite
* Tests if the given player has the given invite
*
* @param int game id
* @param int player id
* @param bool optional player can accept invite
* @return bool player has invite
*/
static public function has_invite($game_id, $player_id, $accept = false)
{
call(__METHOD__);
$game_id = (int) $game_id;
$player_id = (int) $player_id;
$accept = (bool) $accept;
$Mysql = Mysql::get_instance( );
$open = "";
if ($accept) {
$open = " OR black_id IS NULL
OR black_id = FALSE ";
}
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
{$open}
)
";
$has_invite = (bool) $Mysql->fetch_value($query);
return $has_invite;
}
public function can_fire_laser( )
{
call(__METHOD__);
if ( ! $this->_extra_info['battle_dead']) {
return true;
}
return ! $this->_current_move_extra_info['dead_for'];
}
public function prev_laser_fired( )
{
$last = end($this->_history);
return (bool) $last['laser_fired'];
}
/** public function do_move
* Do the given move and send out emails
*
* @param string move code
* @action performs the move
* @return array indexes hit
*/
public function do_move($move)
{
call(__METHOD__);
try {
$this->_laser_fired = $this->can_fire_laser( );
$hits = $this->_pharaoh->do_move($move, $this->_laser_fired);
$winner = $this->_pharaoh->winner;
}
catch (MyException $e) {
throw $e;
}
if ($winner) {
if ('draw' == $winner) {
$this->state = 'Draw';
$this->_players['silver']['object']->add_draw( );
$this->_players['red']['object']->add_draw( );
// send the email
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
else {
$this->state = 'Finished';
$this->_players[$winner]['object']->add_win( );
$this->_players[$this->_players[$winner]['opp_color']]['object']->add_loss( );
// send the email
$type = (($this->_players[$winner]['player_id'] == $_SESSION['player_id']) ? 'defeated' : 'won');
Email::send($type, $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
}
else {
// send the email
Email::send('turn', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
return $hits;
}
/** public function resign
* Resigns the given player from the game
*
* @param int player id
* @return void
*/
public function resign($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign from a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign opponent from a game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_win( );
$this->_players['player']['object']->add_loss( );
$this->state = 'Finished';
$this->_pharaoh->winner = 'opponent';
Email::send('resigned', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function offer_draw
* Offers a draw to the given player's apponent
*
* @param int player id
* @return void
*/
public function offer_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = $player_id;
Email::send('draw_offered', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function draw_offered
* Returns the state of the game draw for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function draw_offered($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the draw was offered AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['draw_offered']) && ( ! $player_id || ($player_id != $this->_extra_info['draw_offered']))) {
return true;
}
return false;
}
/** public function accept_draw
* Accepts a draw offered to the given player
*
* @param int player id
* @return void
*/
public function accept_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw for an opponent in game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_draw( );
$this->_players['player']['object']->add_draw( );
$this->state = 'Draw';
$this->_extra_info['draw_offered'] = false;
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_draw
* Rejects a draw offered to the given player
*
* @param int player id
* @return void
*/
public function reject_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = false;
}
/** public function request_undo
* Requests an undo from the given player's apponent
*
* @param int player id
* @return void
*/
public function request_undo($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to request undo in a game (#'.$this->id.') they are not playing in');
}
diff --git a/classes/setup.class.php b/classes/setup.class.php
index c12c67e..74dfc91 100644
--- a/classes/setup.class.php
+++ b/classes/setup.class.php
@@ -279,693 +279,756 @@ class Setup {
* @return string ascii board
*/
protected function _get_board_ascii($board = null)
{
if ( ! $board) {
$board = $this->_board;
}
return self::get_board_ascii($board);
}
/** protected function _pull
* Pulls the setup data from the database
*
* @param void
* @action pulls the setup data and sets the class properties
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return;
}
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE setup_id = '{$this->id}'
";
$setup = Mysql::get_instance( )->fetch_assoc($query);
$this->board = expandFEN($setup['board']);
$this->creator = $setup['created_by'];
$this->name = $setup['name'];
}
/** protected function _init_board
* Initializes an empty board
*
* @param void
* @action initializes an empty board
* @return void
*/
protected function _init_board( )
{
$this->board = expandFEN('10/10/10/10/10/10/10/10');
}
/** public function validate
* Validates the current setup
*
* @param string [optional] reflection type (Origin, Long, Short)
* @return bool if the setup is valid
*/
public function validate($reflection = 'Origin')
{
call(__METHOD__);
call($this->board);
$Mysql = Mysql::get_instance( );
try {
// will run is_valid_setup as well
self::is_valid_reflection($this->board, $reflection);
}
catch (MyExecption $e) {
throw $e;
}
// test for pre-existing setup
$FEN = packFEN($this->board);
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE board = '{$FEN}'
AND setup_id <> '{$this->id}'
";
$result = $Mysql->fetch_assoc($query);
if ($result) {
throw new MyException(__METHOD__.': Setup already exists as "'.$result['name'].'" (#'.$result['setup_id'].')');
}
// test for pre-existing setup name
$name = sani($this->name);
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE name = '{$name}'
AND setup_id <> '{$this->id}'
";
$result = $Mysql->fetch_assoc($query);
if ($result) {
throw new MyException(__METHOD__.': Setup name ('.$name.') already used (#'.$result['setup_id'].')');
}
return true;
}
/** protected function _save
* Saves the setup data to the database
*
* @param string [optional] reflection type (Origin, Long, Short)
* @action saves the setup data
* @return void
*/
protected function _save($reflection = 'Origin')
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
try {
$this->validate($reflection);
}
catch (MyException $e) {
throw $e;
}
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
// translate (filter/sanitize) the data
$data['name'] = $this->name;
$data['board'] = packFEN($this->board);
$data['reflection'] = self::_get_reflection($this->board);
$data['has_horus'] = self::has_horus($this->board);
$data['has_sphynx'] = self::has_sphynx($this->board);
$data['has_tower'] = self::has_tower($this->board);
$data['created_by'] = (int) $this->creator;
call($data);
// create the setup
$required = array(
'name',
'board',
);
$key_list = array_merge($required, array(
'reflection',
'has_horus',
'has_sphynx',
'has_tower',
'created_by',
));
try {
$_DATA = array_clean($data, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['created '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
// grab the original setup data
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE setup_id = '{$this->id}'
";
$setup = $Mysql->fetch_assoc($query);
call($setup);
if ( ! empty($this->id) && ! $setup) {
// we must have deleted the setup, just stop
return false;
}
if ( ! $setup) {
$this->id = $Mysql->insert(self::SETUP_TABLE, $_DATA);
if (empty($this->id)) {
throw new MyException(__METHOD__.': Setup could not be created');
}
return $this->id;
}
$update_setup = false;
// don't change the creator
// in case of admin edits
unset($_DATA['created_by']);
foreach ($setup as $key => $value) {
if (empty($_DATA[$key])) {
continue;
}
if ($_DATA[$key] != $value) {
$update_setup[$key] = $_DATA[$key];
}
}
call($update_setup);
if ($update_setup) {
$Mysql->insert(self::SETUP_TABLE, $update_setup, " WHERE setup_id = '{$this->id}' ");
return true;
}
return false;
}
public function save( )
{
call(__METHOD__);
call($_POST);
// set the post stuff into the object
try {
$this->name = $_POST['name'];
$this->board = $_POST['setup'];
$this->creator = $_SESSION['player_id'];
}
catch (MyException $e) {
throw $e;
}
return $this->_save($_POST['reflection']);
}
/** static public function is_valid_setup
* Tests the validity of the given setup
*
* @param string setup
* @return bool valid setup
*/
static public function is_valid_setup($setup)
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
if (80 != strlen($xFEN)) {
throw new MyException(__METHOD__.': Incorrect board size');
}
// test for a pharaoh on both sides
if ( ! preg_match('/P/', $xFEN, $s_match) || ! preg_match('/p/', $xFEN, $r_match)) {
throw new MyException(__METHOD__.': Missing one or both Pharaohs');
}
// make sure there's only one of each pharaoh
if ((1 != count($s_match)) || (1 != count($r_match))) {
throw new MyException(__METHOD__.': Too many of one or both Pharaohs');
}
// test for a sphynx on both sides (if any)
if (preg_match('/[EFJK]/i', $xFEN) && ( ! preg_match('/[EFJK]/', $xFEN, $s_match) || ! preg_match('/[efjk]/', $xFEN, $r_match))) {
throw new MyException(__METHOD__.': Missing one or both Sphynxes');
}
// make sure there's only one of each sphynx
if ((1 != count($s_match)) || (1 != count($r_match))) {
throw new MyException(__METHOD__.': Too many of one or both Sphynxes');
}
// look for invalid characters
if (preg_match('/[^abcdefhijklmnoptvwxy0]/i', $xFEN)) {
throw new MyException(__METHOD__.': Invalid characters found in setup');
}
// test for pieces on incorrect colors
$not_silver = array(0, 10, 20, 30, 40, 50, 60, 70, 8, 78);
foreach ($not_silver as $i) {
if (('0' != $xFEN[$i]) && ('silver' == Pharaoh::get_piece_color($xFEN[$i]))) {
throw new MyException(__METHOD__.': Silver piece on red square at '.$i);
}
}
$not_red = array(9, 19, 29, 39, 49, 59, 69, 79, 1, 71);
foreach ($not_red as $i) {
if (('0' != $xFEN[$i]) && ('red' == Pharaoh::get_piece_color($xFEN[$i]))) {
throw new MyException(__METHOD__.': Red piece on silver square at '.$i);
}
}
return true;
}
/** static public function test_reflection
* Tests the validity of the given reflection
* for the given setup
*
* @param string setup
* @param string [optional] reflection type (Origin, Long, Short)
* @return bool if the reflection is valid
*/
static public function is_valid_reflection($setup, $type = 'Origin')
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
// validate the setup
try {
self::is_valid_setup($xFEN);
}
catch (MyException $e) {
throw $e;
}
// make sure the given xFEN has all the pieces reflected properly
switch ($type) {
case 'Origin' :
$reflect = array(
// pyramids
'A' => 'c', 'C' => 'a',
'B' => 'd', 'D' => 'b',
// djeds
'X' => 'x', 'Y' => 'y',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'h', 'I' => 'i',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$return = 79 - $i;
';
break;
case 'Long' :
$reflect = array(
// pyramids
'A' => 'b', 'B' => 'a',
'C' => 'd', 'D' => 'c',
// djeds
'X' => 'y', 'Y' => 'x',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'i', 'I' => 'h',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$tens = (int) floor($i / 10);
$return = ((7 - $tens) * 10) + ($i % 10);
';
break;
case 'Short' :
$reflect = array(
// pyramids
'A' => 'd', 'D' => 'a',
'B' => 'c', 'C' => 'b',
// djeds
'X' => 'y', 'Y' => 'x',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'i', 'I' => 'h',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$tens = (int) floor($i / 10);
$return = ($tens * 10) + (9 - ($i % 10));
';
break;
default :
return true;
break;
}
// TOWER: may need to change limits
for ($i = 0; $i < 80; ++$i) {
$c = $xFEN[$i];
if (('0' !== $c) && (strtoupper($c) === $c) && in_array($c, $reflect_keys)) {
eval($_reflect); // creates $return
if ($reflect[$c] !== $xFEN[$return]) {
throw new MyException(__METHOD__.': Invalid reflected character found at index '.$i.' ('.Pharaoh::index_to_target($i).') = '.$c.'->'.$xFEN[$return].' should be '.$reflect[$c]);
}
// remove the tested chars
$xFEN[$i] = '.';
$xFEN[$return] = '.';
}
}
// we tested all silver -> red
// and matching pairs were removed
// now look for any remaining red
if (preg_match('/[a-dhipvwxy]/', $xFEN, $matches, PREG_OFFSET_CAPTURE)) {
// TODO: get index for faulty red pieces
throw new MyException(__METHOD__.': Red piece found without matching Silver piece');
}
return true;
}
/** static public function _get_reflection
* Gets the reflection type for the given setup
*
* @param string board
* @return string reflection type
*/
static public function _get_reflection($setup)
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
foreach (array('Origin', 'Long', 'Short', 'None') as $type) {
try {
self::is_valid_reflection($xFEN, $type);
}
catch (MyException $e) {
continue;
}
break;
}
return $type;
}
/** public function get_reflection
* Gets the reflection type for the current setup
*
* @param void
* @return string reflection type
*/
public function get_reflection( )
{
return self::_get_reflection($this->board);
}
/** static public function has_tower
* Does the given setup use the tower?
*
* @param void
* @return bool setup has tower
*/
static public function has_tower($setup)
{
return preg_match('/[t]/i', $setup);
}
/** static public function has_horus
* Does the given setup use the Eye of Horus?
*
* @param void
* @return bool setup has eye of horus
*/
static public function has_horus($setup)
{
return preg_match('/[hi]/i', $setup);
}
/** static public function has_sphynx
* Does the given setup use the Sphynx?
*
* @param void
* @return bool setup has sphynx
*/
static public function has_sphynx($setup)
{
return preg_match('/[efjk]/i', $setup);
}
+ /** static public function convert_to_1
+ * Convert the given setup to a v1.0 layout
+ * Will not perform conversion on already v1.0 setups
+ *
+ * @param string setup
+ * @return string converted setup
+ */
+ static public function convert_to_1($setup)
+ {
+ try {
+ self::is_valid_setup($setup);
+ }
+ catch (MyException $e) {
+ throw $e;
+ }
+
+ if ( ! self::has_sphynx($setup)) {
+ return $setup;
+ }
+
+ // add the sphynxes
+ $setup = preg_replace('/[efjk]/i', '0', $setup);
+
+ // replace the obelisks with anubises
+ $setup = preg_replace('/[lmno]/', 'w', $setup);
+ $setup = preg_replace('/[LMNO]/', 'W', $setup);
+
+ return $setup;
+ }
+
+
+ /** static public function convert_to_2
+ * Convert the given setup to a v2.0 layout
+ * Will not perform conversion on already v2.0 setups
+ *
+ * @param string setup
+ * @return string converted setup
+ */
+ static public function convert_to_2($setup)
+ {
+ try {
+ self::is_valid_setup($setup);
+ }
+ catch (MyException $e) {
+ throw $e;
+ }
+
+ if (self::has_sphynx($setup)) {
+ return $setup;
+ }
+
+ // add the sphynxes
+ $setup = substr_replace($setup, 'j', 0, 1);
+ $setup = substr_replace($setup, 'E', -1, 1);
+
+ // replace the obelisks with anubises
+ $setup = str_replace('w', 'n', $setup);
+ $setup = str_replace('W', 'L', $setup);
+
+ return $setup;
+ }
+
+
/** static public function delete
* Deletes the given setup and all related data
*
* @param mixed array or csv of setup ids
* @action deletes the setup and all related data from the database
* @return void
*/
static public function delete($ids)
{
$Mysql = Mysql::get_instance( );
array_trim($ids, 'int');
if (empty($ids)) {
throw new MyException(__METHOD__.': No game ids given');
}
$tables = array(
self::SETUP_TABLE ,
);
$Mysql->multi_delete($tables, " WHERE setup_id IN (".implode(',', $ids).") ");
$query = "
OPTIMIZE TABLE ".self::SETUP_TABLE."
";
$Mysql->query($query);
}
/** static public function get_list
* Gets the list of all the setups
*
* @param void
* @return array setups
*/
static public function get_list( )
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$query = "
SELECT S.*
, COUNT(G.game_id) AS current_games
FROM ".self::SETUP_TABLE." AS S
LEFT JOIN ".Game::GAME_TABLE." AS G
ON (G.setup_id = S.setup_id)
GROUP BY S.setup_id
ORDER BY S.has_tower ASC
, S.has_sphynx ASC
, S.has_horus ASC
, S.name ASC
";
$setups = $Mysql->fetch_array($query);
return $setups;
}
/** static public function get_count
* Gets the count of all the setups
* optionally filters by creator
*
* @param int [optipnal] player id
* @return array (total, owned by player)
*/
static public function get_count($player_id = 0)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT COUNT(*)
FROM ".self::SETUP_TABLE."
";
$total = $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::SETUP_TABLE."
WHERE created_by = '{$player_id}'
";
$mine = $Mysql->fetch_value($query);
return array($total, $mine);
}
/** static public function add_used
* Increments the 'used' count for the given setup
*
* @param int setup id
* @action increments the 'used' count
* @return void
*/
static public function add_used($setup_id)
{
call(__METHOD__);
$setup_id = (int) $setup_id;
$query = "
UPDATE ".self::SETUP_TABLE."
SET used = used + 1
WHERE setup_id = '{$setup_id}'
";
Mysql::get_instance( )->query($query);
}
} // end Setup
/*
--
-- Table structure for table `ph_setup`
--
DROP TABLE IF EXISTS `ph_setup`;
CREATE TABLE IF NOT EXISTS `ph_setup` (
`setup_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE latin1_general_ci NOT NULL,
`board` varchar(87) COLLATE latin1_general_ci NOT NULL,
`reflection` enum('Origin','Short','Long','None') COLLATE latin1_general_ci NOT NULL DEFAULT 'Origin',
`has_horus` tinyint(1) NOT NULL DEFAULT '0',
`has_sphynx` tinyint(1) NOT NULL DEFAULT '0',
`has_tower` tinyint(1) NOT NULL DEFAULT '0',
`used` int(11) NOT NULL DEFAULT '0',
`silver_wins` int(10) unsigned NOT NULL DEFAULT '0',
`draws` int(10) unsigned NOT NULL DEFAULT '0',
`red_wins` int(10) unsigned NOT NULL DEFAULT '0',
`shortest_game` int(10) unsigned DEFAULT NULL,
`longest_game` int(10) unsigned DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1',
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'the player id of the player that created the setup',
PRIMARY KEY (`setup_id`),
KEY `has_horus` (`has_horus`),
KEY `has_tower` (`has_tower`),
KEY `active` (`active`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
--
-- Dumping data for table `ph_setup`
--
INSERT INTO `ph_setup` (`setup_id`, `name`, `board`, `reflection`, `has_horus`, `has_tower`, `used`, `created`, `created_by`) VALUES
(NULL, 'Classic', '4wpwb2/2c7/3D6/a1C1xy1b1D/b1D1YX1a1C/6b3/7A2/2DWPW4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Dynasty', '4cwb3/5p4/a3cwy3/b1x1D1B3/3d1b1X1D/3YWA3C/4P5/3DWA4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Imhotep', '4wpwy2/10/3D2a3/aC2By2bD/bD2Yd2aC/3C2b3/10/2YWPW4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Osiris', '1Y3cp1bC/2w3wb2/6D3/a3ix3D/b3XI3C/3b6/2DW3W2/aD1PA3y1', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Isis', '6wpb1/a1x3cw2/1X8/a1a1DI2c1/1A2ib1C1C/8x1/2WA3X1C/1DPW6', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Classic 2', '4wpwb2/2c7/3D6/a1C1xi1b1D/b1D1IX1a1C/6b3/7A2/2DWPW4', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Dynasty 2', '4cwb3/5p4/a3cwy3/b1h1D1B3/3d1b1H1D/3YWA3C/4P5/3DWA4', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Imhotep 2', '4wpwy2/10/3D2a3/aC2Bi2bD/bD2Id2aC/3C2b3/10/2YWPW4', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Khufu', '4wpwb2/5cb3/a5D3/4yX1a1D/b1C1Xy4/3b5C/3DA5/2DWPW4', 'None', 0, 0, 0, NOW( ), 0),
(NULL, 'Imseti', '1B1wpb4/2Xbcw4/10/a3xc3D/b3AX3C/10/4WADx2/4DPW1d1', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Nefertiti', '4w1w3/3c1pb3/2C1cy1c2/a1Y6D/b6y1C/2A1YA1a2/3DP1A3/3W1W4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Rameses', '3w1pwb2/4bc4/2Cb2x3/a4X3D/b3x4C/3X2Da2/4AD4/2DWP1W3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Amarna', '1CBcwpw3/4bcb3/10/a2x2x3/3X2X2C/10/3DAD4/3WPWAda1', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Saqqara', '3cwp1wb1/4bxb3/a2D6/4X4D/b4x4/6b2C/3DXD4/1DW1PWA3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Djoser''s Step', '3cw1w1b1/5p1b2/4bxb3/a4y3D/b3Y4C/3DXD4/2D1P5/1D1W1WA3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Horemheb', '3c3b2/4wpw3/3x1x1b2/a3c1b2D/b2D1A3C/2D1X1X3/3WPW4/2D3A3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Senet', '4cwb3/a2c1p1b2/4xwy3/5b3C/a3D5/3YWX4/2D1P1A2C/3DWA4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Tutankhamun', '3w4b1/a1cpb5/3w1b4/b1x1y1b3/3D1Y1X1D/4D1W3/5DPA1C/1D4W3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Offla', '3c1pwb2/4cwb3/2X2x4/a4D3D/b3b4C/4X2x2/3DWA4/2DWP1A3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Ebana', '3xwpwb2/5x4/2DA6/a1CB5D/b5da1C/6cb2/4X5/2DWPWX3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Qa''a', '3xwpwb2/4cy4/8bD/3c2b2C/a2D2A3/bD8/4YA4/2DWPWX3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Qa''a 2', '3xwpwb2/4cy4/8bD/3c2b1hC/aH1D2A3/bD8/4YA4/2DWPWX3', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Seti I', '1XB1cw1pb1/a4cwy1D/6b3/5i4/4I5/3D6/b1YWA4C/1DP1WA1dx1', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Seti II', '1XB1cw1pb1/a4cwy1D/6b3/10/10/3D6/b1YWA4C/1DP1WA1dx1', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Ay', '4cw1wbC/3CB5/5x4/a3Ypb3/3DPy3C/4X5/5da3/aDW1WA4', 'Origin', 0, 0, 0, NOW( ), 0);
*/
diff --git a/invite.php b/invite.php
index e3ab6fb..f946c54 100644
--- a/invite.php
+++ b/invite.php
@@ -1,255 +1,273 @@
<?php
require_once 'includes/inc.global.php';
// this has nothing to do with creating a game
// but I'm running it here to prevent long load
// times on other pages where it would be run more often
GamePlayer::delete_inactive(Settings::read('expire_users'));
Game::delete_inactive(Settings::read('expire_games'));
Game::delete_finished(Settings::read('expire_finished_games'));
$Game = new Game( );
if (isset($_POST['invite'])) {
// make sure this user is not full
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
Flash::store('You have reached your maximum allowed games !', false);
}
test_token( );
try {
$game_id = $Game->invite( );
Flash::store('Invitation Sent Successfully', true);
}
catch (MyException $e) {
Flash::store('Invitation FAILED !', false);
}
}
// grab the full list of players
$players_full = GamePlayer::get_list(true);
$invite_players = array_shrink($players_full, 'player_id');
// grab the players who's max game count has been reached
$players_maxed = GamePlayer::get_maxed( );
$players_maxed[] = $_SESSION['player_id'];
// remove the maxed players from the invite list
$players = array_diff($invite_players, $players_maxed);
$opponent_selection = '';
$opponent_selection .= '<option value="">-- Open --</option>';
foreach ($players_full as $player) {
if ($_SESSION['player_id'] == $player['player_id']) {
continue;
}
if (in_array($player['player_id'], $players)) {
$opponent_selection .= '
<option value="'.$player['player_id'].'">'.$player['username'].'</option>';
}
}
$groups = array(
'Normal' => array(0, 0),
'Eye of Horus' => array(0, 1),
'Sphynx' => array(1, 0),
'Sphynx & Horus' => array(1, 1),
);
$group_names = array_keys($groups);
$group_markers = array_values($groups);
$setups = Setup::get_list( );
$setup_selection = '<option value="0">Random</option>';
$setup_javascript = '';
$cur_group = false;
$group_open = false;
foreach ($setups as $setup) {
$marker = array((int) $setup['has_sphynx'], (int) $setup['has_horus']);
$group_index = array_search($marker, $group_markers, true);
if ($cur_group !== $group_names[$group_index]) {
if ($group_open) {
$setup_selection .= '</optgroup>';
$group_open = false;
}
$cur_group = $group_names[$group_index];
$setup_selection .= '<optgroup label="'.$cur_group.'">';
$group_open = true;
}
$setup_selection .= '
<option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>';
$setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n";
}
$setup_javascript = substr(trim($setup_javascript), 0, -1);
if ($group_open) {
$setup_selection .= '</optgroup>';
}
$meta['title'] = 'Send Game Invitation';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">//<![CDATA[
var setups = {
'.$setup_javascript.'
};
/*]]>*/</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/invite.js"></script>
';
$hints = array(
'Invite a player to a game by filling out your desired game options.' ,
'<span class="highlight">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' ,
);
// make sure this user is not full
$submit_button = '<div><input type="submit" name="invite" value="Send Invitation" /></div>';
$warning = '';
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
$submit_button = $warning = '<p class="warning">You have reached your maximum allowed games, you can not create this game !</p>';
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="send"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="player_id" value="{$_SESSION['player_id']}" />
{$warning}
<div><label for="opponent">Opponent</label><select id="opponent" name="opponent">{$opponent_selection}</select></div>
- <div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup">Show Setup</a></div>
+ <div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup" class="options">Show Setup</a></div>
<div><label for="color">Your Color</label><select id="color" name="color"><option value="random">Random</option><option value="white">Silver</option><option value="black">Red</option></select></div>
- <div class="pharaoh_1">
+ <div class="random_convert options">
+ <fieldset>
+ <legend>Conversion</legend>
+
+ <p>
+ If your random game is a v1.0 game, you can convert it to play v2.0 Pharaoh.<br />
+ Or, if your random game is a v2.0 game, you can convert it to play v1.0 Pharaoh.<br />
+ </p>
+ <p>
+ When you select to convert, more options may be shown below.
+ </p>
+
+ <div><label class="inline"><input type="checkbox" id="rand_convert_to_1" name="rand_convert_to_1" /> Convert to 1.0</label></div>
+ <div><label class="inline"><input type="checkbox" id="rand_convert_to_2" name="rand_convert_to_2" /> Convert to 2.0</label></div>
+
+ </fieldset>
+ </div> <!-- .random_convert -->
+
+ <div class="pharaoh_1 options">
<fieldset>
<legend>v1.0 Options</legend>
<p class="conversion">
- Here you can convert old v1.0 setups to play v2.0 Pharaoh.<br />
+ Here you can convert v1.0 setups to play v2.0 Pharaoh.<br />
The conversion places a Sphynx in your lower-right corner facing upwards (and opposite for your opponent)
and converts any double-stacked Obelisks to Anubises which face forward.
</p>
<p class="conversion">
When you select to convert, more options will be shown below, as well as the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_2" name="convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .pharaoh_1 -->
- <div class="pharaoh_2 p2_box">
+ <div class="pharaoh_2 p2_box options">
<fieldset>
<legend>v2.0 Options</legend>
<p class="conversion">
- Here you can convert the new v2.0 setups to play v1.0 Pharaoh.<br />
+ Here you can convert the v2.0 setups to play v1.0 Pharaoh.<br />
The conversion removes any Sphynxes from the board and converts any Anubises to double-stacked Obelisks.
</p>
<p class="conversion">
When you select to convert, the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_1" name="convert_to_1" /> Convert to 1.0</label></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="move_sphynx" name="move_sphynx" /> Sphynx is movable</label></div>
</fieldset>
</div> <!-- .pharaoh_2 -->
<fieldset>
<legend><label class="inline"><input type="checkbox" name="laser_battle_box" id="laser_battle_box" class="fieldset_box" /> Laser Battle</label></legend>
- <div id="laser_battle">
+ <div id="laser_battle" class="options">
<p>
When a laser gets shot by the opponents laser, it will be disabled for a set number of turns, making that laser unable to shoot until those turns have passed.<br />
After those turns have passed, and the laser has recovered, it will be immune from further shots for a set number of turns.<br />
After the immunity turns have passed, whether or not the laser was shot again, it will now be susceptible to being shot again.
<span class="pharaoh_2"><br />You can also select if the Sphynx is hittable only in the front, or on all four sides.</span>
</p>
<div><label for="battle_dead">Dead for:</label><input type="text" id="battle_dead" name="battle_dead" size="4" /> <span class="info">(Default: 1; Minimum: 1)</span></div>
<div><label for="battle_immune">Immune for:</label><input type="text" id="battle_immune" name="battle_immune" size="4" /> <span class="info">(Default: 1; Minimum: 0)</span></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_front_only" name="battle_front_only" checked="checked" /> Only front hits on Sphynx count</label></div>
<!-- <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_hit_self" name="battle_hit_self" /> Hit Self</label></div> -->
<p>You can set the "Immune for" value to 0 to allow a laser to be shot continuously, but the minimum value for the "Dead for" value is 1, as it makes no sense otherwise.</p>
</div> <!-- #laser_battle -->
</fieldset>
{$submit_button}
<div class="clr"></div>
</div></form>
<div id="setup_display"></div>
EOF;
// create our invitation tables
list($in_vites, $out_vites, $open_vites) = Game::get_invites($_SESSION['player_id']);
$contents .= <<< EOT
<form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv" id="invites">
EOT;
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no received invites to show</p>' ,
'caption' => 'Invitations Received' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" /><input type="button" id="decline-[[[game_id]]]" value="Decline" />', false) ,
);
$contents .= get_table($table_format, $in_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no sent invites to show</p>' ,
'caption' => 'Invitations Sent' ,
);
$table_format = array(
array('Invitee', '###ifenr(\'[[[invitee]]]\', \'-- OPEN --\')') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '###\'<input type="button" id="withdraw-[[[game_id]]]" value="Withdraw" />\'.((strtotime(\'[[[create_date]]]\') >= strtotime(\'[[[resend_limit]]]\')) ? \'\' : \'<input type="button" id="resend-[[[game_id]]]" value="Resend" />\')', false) ,
);
$contents .= get_table($table_format, $out_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no open invites to show</p>' ,
'caption' => 'Open Invitations' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" />', false) ,
);
$contents .= get_table($table_format, $open_vites, $table_meta);
$contents .= <<< EOT
</div></form>
EOT;
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer( );
diff --git a/scripts/invite.js b/scripts/invite.js
index 227d185..1cf9c31 100644
--- a/scripts/invite.js
+++ b/scripts/invite.js
@@ -1,273 +1,281 @@
var reload = true; // do not change this
var new_setup = false;
function check_fieldset_box( ) {
$('input.fieldset_box').each( function(i, elem) {
var $this = $(this);
var id = $this.attr('id').slice(0,-4);
if ($this.prop('checked')) {
$('div#'+id).show( );
}
else {
$('div#'+id).hide( );
}
});
}
$(document).ready( function( ) {
// hide the setup div
$('div#setup_display').hide( );
check_fieldset_box( );
show_link( );
show_version( );
// show the setup div in a fancybox
$('a#show_setup').fancybox({
padding : 10,
onStart : function( ) {
var setup = setups[$('select#setup').val( )];
if (new_setup) {
setup = new_setup;
}
$('div#setup_display')
.empty( )
.append(create_board(setup))
.show( );
},
onClosed :function( ) {
$('div#setup_display').hide( );
}
});
// only show the setup link when a setup is selected
$('select#setup').change( function( ) {
show_link( );
show_version( );
});
- $('input#convert_to_2, input#convert_to_1').change( function( ) {
+ $('input#convert_to_1, input#convert_to_2, input#rand_convert_to_1, input#rand_convert_to_2').change( function( ) {
show_version( );
});
// show the setup div for the invites
$('a.setup').fancybox({
type : 'inline',
href : '#setup_display',
padding : 10,
onStart : function(arr, idx, opts) {
var $elem = $(arr[idx]);
var setup = setups[$(arr[idx]).attr('id').slice(2)];
if ('#setup_display' != $elem.attr('href')) {
setup = $elem.attr('href').slice(1);
}
$('div#setup_display')
.empty( )
.append(create_board(setup))
.show( );
},
onClosed :function( ) {
$('div#setup_display').hide( );
}
});
$('form#send').submit( function( ) {
if ( ! $('select#setup').val( )) {
alert('You must select a setup');
return false;
}
return true;
});
// hide the collapsable fieldsets
$('input.fieldset_box').change( function( ) {
check_fieldset_box( );
});
// this runs all the ...vites
$('div#invites input').click( function( ) {
var id = $(this).attr('id').split('-');
if ('accept' == id[0]) { // invites and openvites
// accept the invite
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'invite=accept&game_id='+id[1];
return;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'invite=accept&game_id='+id[1],
success: function(msg) {
window.location = 'game.php?id='+msg+debug_query_;
return;
}
});
}
else if ('resend' == id[0]) { // resends outvites
// resend the invite
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'invite=resend&game_id='+id[1];
return;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'invite=resend&game_id='+id[1],
success: function(msg) {
alert(msg);
if (reload) { window.location.reload( ); }
return;
}
});
}
else { // invites decline and outvites withdraw
// delete the invite
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'invite=delete&game_id='+id[1];
return;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'invite=delete&game_id='+id[1],
success: function(msg) {
alert(msg);
if (reload) { window.location.reload( ); }
return;
}
});
}
});
});
function show_link( ) {
if (0 != $('select#setup').val( )) {
$('a#show_setup').show( );
}
else {
$('a#show_setup').hide( );
}
}
function show_version( ) {
if (0 != $('select#setup').val( )) {
if (setups[$('select#setup').val( )].match(/[efjk]/i)) {
+ $('.random_convert').hide( );
$('.pharaoh_1').hide( );
$('.pharaoh_2').show( );
$('.pharaoh_2 .conversion').show( );
if ($('input#convert_to_1').prop('checked')) {
$('.pharaoh_2').hide( );
$('.p2_box').show( );
convert_setup(1);
}
else {
new_setup = false;
}
}
else {
+ $('.random_convert').hide( );
$('.pharaoh_2').hide( );
$('.pharaoh_1').show( );
if ($('input#convert_to_2').prop('checked')) {
$('.pharaoh_2').show( );
$('.pharaoh_2 .conversion').hide( );
convert_setup(2);
}
else {
new_setup = false;
}
}
}
else {
$('.pharaoh_1, .pharaoh_2').hide( );
+ $('.random_convert').show( );
+
+ if ($('input#rand_convert_to_2').prop('checked')) {
+ $('.pharaoh_2').show( );
+ $('.pharaoh_2 .conversion').hide( );
+ }
}
}
function convert_setup(to) {
to = parseInt(to || 1);
var setup = setups[$('select#setup').val( )];
// the p1 pieces are repeated here for the TO v1 conversion
// just make sure that the TO v2 conversion pieces are listed first
// that way they will get converted and be correct
var p1 = ['w','w','w','w','W','W','W','W'];
var p2 = ['n','l','m','o','L','M','N','O'];
switch (to) {
case 1 :
// swap out the anubises with obelisks
new_setup = str_replace(p2, p1, setup);
// remove the sphynxes
new_setup = new_setup.replace(/[efjk]/ig, '0');
break;
case 2 :
// swap out the obelisks with anubises
new_setup = str_replace(p1, p2, setup);
// replace anything on the laser corners with a sphynx
new_setup = new_setup.replaceAt(0, 'j').replaceAt(79, 'E');
break;
}
return new_setup;
}
// http://phpjs.org/functions/str_replace:527
function str_replace(search, replace, subject, count) {
var i = 0,
j = 0,
temp = '',
repl = '',
sl = 0,
fl = 0,
f = [].concat(search),
r = [].concat(replace),
s = subject,
ra = Object.prototype.toString.call(r) === '[object Array]',
sa = Object.prototype.toString.call(s) === '[object Array]';
s = [].concat(s);
if (count) {
this.window[count] = 0;
}
for (i = 0, sl = s.length; i < sl; i++) {
if (s[i] === '') {
continue;
}
for (j = 0, fl = f.length; j < fl; j++) {
temp = s[i] + '';
repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
s[i] = (temp).split(f[j]).join(repl);
if (count && s[i] !== temp) {
this.window[count] += (temp.length - s[i].length) / f[j].length;
}
}
}
return sa ? s : s[0];
}
String.prototype.replaceAt = function(index, str) {
index = parseInt(index);
return this.slice(0, index) + str + this.slice(index + str.length);
}
|
benjamw/pharaoh | 5f527f309a656260157f9ed26051e779248b0c57 | added instruction for invites | diff --git a/index.php b/index.php
index 8e5776b..8956271 100644
--- a/index.php
+++ b/index.php
@@ -1,116 +1,117 @@
<?php
require_once 'includes/inc.global.php';
// remove any previous game sessions
unset($_SESSION['game_id']);
// grab the message and game counts
$message_count = (int) Message::check_new($_SESSION['player_id']);
$turn_count = (int) Game::check_turns($_SESSION['player_id']);
$turn_msg_count = $message_count + $turn_count;
$meta['title'] = 'Game List';
$meta['head_data'] = '
<script type="text/javascript" src="scripts/jquery.jplayer.min.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
<script type="text/javascript">//<![CDATA[
var turn_msg_count = '.$turn_msg_count.';
//]]></script>
';
$meta['foot_data'] = '
<div id="sounds"></div>
';
// grab the list of games
$list = Game::get_list($_SESSION['player_id']);
$contents = '';
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no games to show</p>' ,
'caption' => 'Current Games' ,
);
$table_format = array(
array('SPECIAL_HTML', 'true', 'id="g[[[game_id]]]"') ,
array('SPECIAL_CLASS', '(1 == \'[[[my_turn]]]\')', 'highlight') ,
array('SPECIAL_CLASS', '(in_array(\'[[[state]]]\', array(\'Finished\',\'Draw\')))', 'lowlight') ,
array('ID', 'game_id') ,
array('State', '###(([[[paused]]]) ? \'Paused\' : \'[[[state]]]\')') ,
array('Silver', '###(('.$_SESSION['player_id'].' == [[[white_id]]]) ? \'<span class="highlight">[[[white]]]</span>\' : \'[[[white]]]\')') ,
array('Red', '###(('.$_SESSION['player_id'].' == [[[black_id]]]) ? \'<span class="highlight">[[[black]]]</span>\' : \'[[[black]]]\')') ,
array('Turn', '###((\'draw\' == \'[[[turn]]]\') ? \'Draw\' : ((\'white\' == \'[[[turn]]]\') ? \'[[[white]]]\' : \'[[[black]]]\'))') ,
array('Moves', '###([[[count]]] - 1)') ,
array('Setup', 'setup_name') ,
array('Last Move', '###date(Settings::read(\'long_date\'), strtotime(\'[[[last_move]]]\'))', null, ' class="date"') ,
);
$contents .= '
<div class="tableholder">
'.get_table($table_format, $list, $table_meta).'
</div>';
// create the lobby
$Chat = new Chat($_SESSION['player_id'], 0);
$chat_data = $Chat->get_box_list( );
// temp storage for gravatar imgs
$gravatars = array( );
$lobby = '
<div id="lobby">
<div class="caption">Lobby</div>
<div id="chatbox">
<form action="'.$_SERVER['REQUEST_URI'].'" method="post"><div>
<input type="hidden" name="lobby" value="1" />
<input id="chat" type="text" name="chat" />
</div></form>';
if (is_array($chat_data)) {
$lobby .= '
<dl id="chats">';
foreach ($chat_data as $chat) {
// preserve spaces in the chat text
$chat['message'] = str_replace("\t", ' ', $chat['message']);
$chat['message'] = str_replace(' ', ' ', $chat['message']);
if ( ! isset($gravatars[$chat['email']])) {
$gravatars[$chat['email']] = Gravatar::src($chat['email']);
}
$grav_img = '<img src="'.$gravatars[$chat['email']].'" alt="" /> ';
if ('' == $chat['username']) {
$chat['username'] = '[deleted]';
}
$lobby .= '
<dt>'.$grav_img.'<span>'.$chat['create_date'].'</span> '.$chat['username'].'</dt>
<dd>'.htmlentities($chat['message'], ENT_QUOTES, 'ISO-8859-1', false).'</dd>';
}
$lobby .= '
</dl> <!-- #chats -->';
}
$lobby .= '
</div> <!-- #chatbox -->
</div> <!-- #lobby -->';
$contents .= $lobby;
$hints = array(
'Select a game from the list and resume play by clicking anywhere on the row.' ,
+ 'Invite another player to a game by clicking on the Invitations menu item.' ,
'<span class="highlight">Colored entries</span> indicate that it is your turn.' ,
'<span class="warning">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' ,
'Finished games will be deleted after '.Settings::read('expire_finished_games').' days.' ,
);
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer($meta);
|
benjamw/pharaoh | 072abb50ffe3b9bad7eeb075144e96bb4bb5f717 | added default value for email | diff --git a/classes/email.class.php b/classes/email.class.php
index 1336591..ef62767 100644
--- a/classes/email.class.php
+++ b/classes/email.class.php
@@ -1,269 +1,269 @@
<?php
/*
+---------------------------------------------------------------------------
|
| email.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Email module
| > Date started: 2009-04-27
|
| > Module Version Number: 0.9.0
|
+---------------------------------------------------------------------------
*/
/*
Requires
----------------------------------------------------------------------------
Settings class:
Settings::read('site_name')
Settings::read('from_email')
Log class:
Log::write(
Mysql class:
Mysql::get_instance( )->fetch_row(
MyException class
*/
class Email
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static private property _instance
* Holds the instance of this object
*
* @var Email object
*/
static private $_instance;
/** protected property email_data
* Holds the message data
*
* @var array
*/
protected $email_data = array( );
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** protected function __construct
* Class constructor
*
* @param void
* @action instantiates object
* @return void
*/
protected function __construct( )
{
if ( ! $this->email_data && defined('INCLUDE_DIR')) {
require INCLUDE_DIR.'inc.email.php';
$this->email_data = $GLOBALS['__EMAIL_DATA'];
unset($GLOBALS['__EMAIL_DATA']);
}
}
/** protected function _send
* Sends email messages of various types [optional data contents]
*
* @param string message type
* @param mixed player id OR email address OR mixed array of both
* @param array optional message data
* @action send emails
* @return bool success
*/
protected function _send($type, $to, $data = array( ))
{
call(__METHOD__);
call($type);
call($to);
call($data);
if (is_array($to)) {
$return = true;
foreach ($to as $player) {
$return = ($this->_send($type, trim($player), $data) && $return);
}
return $return;
}
// $to is an email address (or comma separated email addresses)
elseif (preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $to)) {
$email = $to;
}
else { // $to is a single player id
$player_id = (int) $to;
// test if this user accepts emails
$query = "
SELECT P.email
, PE.allow_email
FROM ".Player::PLAYER_TABLE." AS P
LEFT JOIN ".GamePlayer::EXTEND_TABLE." AS PE
ON P.player_id = PE.player_id
WHERE P.player_id = '{$player_id}'
";
list($email, $allow) = Mysql::get_instance( )->fetch_row($query);
call($email);call($allow);
if (empty($allow) || empty($email)) {
// no exception, just quit
return false;
}
}
call($email);
$site_name = Settings::read('site_name');
if ( ! in_array($type, array_keys($this->email_data))) {
throw new MyException(__METHOD__.': Trying to send email with unsupported type ('.$type.')');
}
$subject = $this->email_data[$type]['subject'];
$message = $this->email_data[$type]['message'];
// replace the meta vars
$replace = array(
'/\[\[\[GAME_NAME\]\]\]/' => GAME_NAME,
'/\[\[\[site_name\]\]\]/' => $site_name,
- '/\[\[\[opponent\]\]\]/' => @$data['opponent'],
+ '/\[\[\[opponent\]\]\]/' => ife($data['opponent'], 'opponent'),
'/\[\[\[export_data\]\]\]/' => var_export($data, true),
);
$message = preg_replace(array_keys($replace), $replace, $message);
$subject = GAME_NAME.' - '.$subject;
if ( ! empty($data['game_id'])) {
$message .= "\n\n".'Game Link: '.$GLOBALS['_ROOT_URI'].'game.php?id='.(int) $data['game_id'];
}
elseif ( ! empty($data['page'])) {
$message .= "\n\n".'Direct Link: '.$GLOBALS['_ROOT_URI'].$data['page'];
}
$message .= '
=============================================
This message was automatically sent by
'.$site_name.'
and should not be replied to.
=============================================
'.$GLOBALS['_ROOT_URI'];
$from_email = Settings::read('from_email');
// send the email
$headers = "From: ".GAME_NAME." <{$from_email}>\r\n";
$message = html_entity_decode($message);
$this->_log($email."\n".$headers."\n".$subject."\n".$message);
call($subject);call($message);call($headers);
if ($GLOBALS['_USEEMAIL']) {
return mail($email, $subject, $message, $headers);
}
return false;
}
/** protected function _strip
* Strips out the bad stuff from the email
*
* @param string the string to clean
* @param bool optional this is a message string
* @return string clean string
*/
protected function _strip($value, $message = false) {
$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
$search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*';
if ( ! (bool) $message) {
$search .= '|\r|\n';
}
$search = '#(?:' . $search . ')#i';
while (preg_match($search, $value)) {
$value = preg_replace($search, '', $value);
}
return htmlentities($value, ENT_QUOTES, 'ISO-8859-1', false);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
// log the error
if (false && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** static public function get_instance
* Returns the singleton instance
* of the Email Object as a reference
*
* @param void
* @action optionally creates the instance
* @return Email Object reference
*/
static public function get_instance( )
{
if (is_null(self::$_instance)) {
self::$_instance = new Email( );
}
return self::$_instance;
}
/** static public function send
* Static access for _send
*
* @param string message type
* @param mixed player id OR email address OR mixed array of both
* @param array optional message data
* @action send emails
* @return bool success
* @see _send
*/
static public function send($type, $to, $data = array( ))
{
call(__METHOD__);
call($type);
$_this = self::get_instance( );
return $_this->_send($type, $to, $data);
}
} // end of Email class
|
benjamw/pharaoh | 9a4e3e69d5cb9a8d7f336e4fbc7f8f69170e53dd | made class autoloader a bit more bulletproof | diff --git a/includes/func.global.php b/includes/func.global.php
index 1650f2a..f1ca927 100644
--- a/includes/func.global.php
+++ b/includes/func.global.php
@@ -1,293 +1,296 @@
<?php
/** function call [dump] [debug]
* This function is for debugging only
* Outputs given var to screen
* or, if no var given, outputs stars to note position
*
* @param mixed optional var to output
* @param bool optional bypass debug value and output anyway
* @action outputs var to screen
* @return void
*/
function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false)
{
if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) {
return false;
}
if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) {
$contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>';
}
else {
// begin output buffering so we can escape any html
// and print_r is better at catching recursion than var_export
ob_start( );
if ( ! function_exists('xdebug_disable')) {
if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings
print_r($var);
}
else {
if (is_array($var) || is_object($var)) {
print_r($var);
}
else {
var_dump($var);
}
}
}
else {
var_dump($var);
}
// end output buffering and output the result
if ( ! function_exists('xdebug_disable')) {
$contents = htmlentities(ob_get_contents( ));
}
else {
$contents = ob_get_contents( );
}
ob_end_clean( );
}
$j = 0;
$html = '';
$debug_funcs = array('dump', 'debug');
if ((bool) $show_from) {
$called_from = debug_backtrace( );
if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) {
++$j;
}
$file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT']));
$line0 = $called_from[$j]['line'];
$called = '';
if (isset($called_from[$j + 1]['file'])) {
$file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT']));
$line1 = $called_from[$j + 1]['line'];
$called = "{$file1} : {$line1} called ";
}
elseif (isset($called_from[$j + 1]['class'])) {
$called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called ';
}
$html = "<strong>{$called}{$file0} : {$line0}</strong>\n";
}
if ( ! $new_window) {
$color = '#000';
if ($error) {
$color = '#F00';
}
echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n";
}
else { ?>
<script language="javascript">
myRef = window.open('','debugWindow');
myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">');
myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>');
myRef.document.write('\n<hr /></pre>\n\n');
</script>
<?php }
}
function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); }
function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); }
/** function load_class
* This function automagically loads the class
* via the spl_autoload_register function above
* as it is instantiated (jit).
*
* @param string class name
* @action loads given class name if found
* @return bool success
*/
function load_class($class_name) {
$class_file = CLASSES_DIR.strtolower($class_name).'.class.php';
- if (file_exists($class_file)) {
+ if (class_exists($class_name)) {
+ return true;
+ }
+ elseif (file_exists($class_file) && is_readable($class_file)) {
require_once $class_file;
return true;
}
else {
throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found');
}
}
/** function test_token
* This function tests the token given by the
* form and checks it against the session token
* and if they do not match, dies
*
* @param bool optional keep original token flag
* @action tests tokens and dies if bad
* @action optionally renews the session token
* @return void
*/
function test_token($keep = false) {
call($_SESSION['token']);
call($_POST['token']);
if (DEBUG || ('games' == $_SERVER['HTTP_HOST'])) {
return;
}
if ( ! isset($_SESSION['token']) || ! isset($_POST['token'])
|| (0 !== strcmp($_SESSION['token'], $_POST['token'])))
{
die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.');
}
// renew the token
if ( ! $keep) {
$_SESSION['token'] = md5(uniqid(rand( ), true));
}
}
/** function test_debug
* This function tests the debug given by the
* URL and checks it against the globals debug password
* and if they do not match, doesn't debug
*
* @param void
* @action tests debug pass
* @return bool success
*/
function test_debug( ) {
if ( ! isset($_GET['DEBUG'])) {
return false;
}
if ( ! class_exists('Settings') || ! Settings::test( )) {
return false;
}
if ('' == trim(Settings::read('debug_pass'))) {
return false;
}
if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) {
return false;
}
$GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG'];
$GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG'];
return true;
}
/** function expandFEN
* This function expands a packed FEN into a
* string where each index is a valid location
*
* @param string packed FEN
* @return string expanded FEN
*/
function expandFEN($FEN)
{
$FEN = preg_replace('/\s+/', '', $FEN); // remove spaces
$FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s
$xFEN = str_replace('/', '', $FEN); // remove the row separators
return $xFEN;
}
function replace_callback($match) {
return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]);
}
/** function packFEN
* This function packs an expanded FEN into a
* string that takes up less space
*
* @param string expanded FEN
* @param int [optional] length of rows
* @return string packed FEN
*/
function packFEN($xFEN, $row_length = 10)
{
$xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces
$xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators
$xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators
$FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s
return $FEN;
}
/** function ife
* if-else
* This function returns the value if it exists (or is optionally not empty)
* or a default value if it does not exist (or is empty)
*
* @param mixed var to test
* @param mixed optional default value
* @param bool optional allow empty value
* @param bool optional change the passed reference var
* @return mixed $var if exists (and not empty) or default otherwise
*/
function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) {
if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) {
if ((bool) $change_reference) {
$var = $default; // so it can also be used by reference
}
return $default;
}
return $var;
}
/** function ifer
* if-else reference
* This function returns the value if it exists (or is optionally not empty)
* or a default value if it does not exist (or is empty)
* It also changes the reference var
*
* @param mixed var to test
* @param mixed optional default value
* @param bool optional allow empty value
* @action updates/sets the reference var if needed
* @return mixed $var if exists (and not empty) or default otherwise
*/
function ifer( & $var, $default = null, $allow_empty = true) {
return ife($var, $default, $allow_empty, true);
}
/** function ifenr
* if-else non-reference
* This function returns the value if it is not empty
* or a default value if it is empty
*
* @param mixed var to test
* @param mixed optional default value
* @return mixed $var if not empty or default otherwise
*/
function ifenr($var, $default = null) {
if (empty($var)) {
return $default;
}
return $var;
}
|
benjamw/pharaoh | 99a1bab3a8c8112e4daa0de33404caf632e10846 | fixed issue with pharaohs and sphynxes on setups | diff --git a/scripts/setups.js b/scripts/setups.js
index 4fc8f1d..9bf95ce 100644
--- a/scripts/setups.js
+++ b/scripts/setups.js
@@ -1,279 +1,292 @@
var reload = true;
var selected = false;
var board_changed = false;
if ('undefined' == typeof board) {
var board = false;
}
$(document).ready( function($) {
// invert board button
$('a#invert').click( function( ) {
do_clear_laser( );
invert = ! invert;
$('#setup_display').find('#the_board').remove( ).end( ).prepend(create_board(board));
return false;
});
// fire silver laser button
$('a#silver_laser').click( function( ) {
do_clear_laser( );
do_fire_laser('silver');
return false;
});
// fire red laser button
$('a#red_laser').click( function( ) {
do_clear_laser( );
do_fire_laser('red');
return false;
});
// clear laser button
$('a#clear_laser').click( function( ) {
do_clear_laser( );
return false;
});
// show the pieces
var piece;
var $silver_pieces_div = $('#silver_pieces');
var $red_pieces_div = $('#red_pieces');
for (piece in pieces) {
$silver_pieces_div.append(create_piece(piece, false, true));
$red_pieces_div.append(create_piece(piece.toLowerCase( ), false, true));
}
// make the pieces clickable
var $pieces_div = $('#pieces_display');
$pieces_div.find('img').click( function( ) {
$('.selected').removeClass('selected');
selected = $(this).addClass('selected').attr('alt');
do_clear_laser( );
if ('Cancel' == selected) {
selected = false;
$('.selected').removeClass('selected');
}
});
// create the board upon selection
$('#init_setup').change( function( ) {
var $this = $(this);
var val = $this.val( );
if ('' === val) {
return;
}
do_clear_laser( );
if ((false === board) || confirm('This will delete all changes.\nAre you sure?')) {
board = setups[val];
board_changed = true;
$('#setup_display').find('#the_board').remove( ).end( ).prepend(create_board(board));
$('#name').val($this.find('option:selected').text( ) + ' Edit');
}
$this.val('');
});
// make the setup create/edit clicks work
$('#the_board div:not(.header)').live('click', function( ) {
var $this = $(this);
var id = $this.attr('id').slice(4);
var reflection = $('#reflection').val( );
if ( ! selected) {
return;
}
do_clear_laser( );
if ('Delete' == selected) {
$this.empty( );
board = board.replaceAt(id, '0');
board_changed = true;
if (reflection) {
id = get_reflected_id(id, reflection);
$('#idx_'+id).empty( );
board = board.replaceAt(id, '0');
board_changed = true;
}
return;
}
- if (('p' == selected.toLowerCase( )) && (-1 !== board.indexOf(selected))) {
- alert('Only one pharaoh of each color is allowed.\nPlease delete the current pharaoh to place a new one.');
- return;
+ if ('None' == reflection) {
+ if (('p' == selected.toLowerCase( )) && (-1 !== board.indexOf(selected))) {
+ alert('Only one pharaoh of each color is allowed.\nPlease delete the current pharaoh to place a new one.');
+ return;
+ }
+
+ if ((selected.match(/[efjk]/) && board.match(/[efjk]/)) || (selected.match(/[EFJK]/) && board.match(/[EFJK]/))) {
+ alert('Only one sphynx of each color is allowed.\nPlease delete the current sphynx to place a new one.');
+ return;
+ }
}
+ else { // there's a reflection at work
+ if (('p' == selected.toLowerCase( )) && (-1 !== board.toLowerCase( ).indexOf(selected.toLowerCase( )))) {
+ alert('Only one pharaoh of each color is allowed.\nPlease delete any pharaohs before placing the new ones.');
+ return;
+ }
- if (selected.toLowerCase( ).match(/[efjk]/) && board.toLowerCase( ).match(/[efjk]/)) {
- alert('Only one sphynx of each color is allowed.\nPlease delete the current sphynx to place a new one.');
- return;
+ if (selected.match(/[efjk]/i) && board.match(/[efjk]/i)) {
+ alert('Only one sphynx of each color is allowed.\nPlease delete any sphynxes before placing the new ones.');
+ return;
+ }
}
$this.empty( ).append(create_piece(selected));
board = board.replaceAt(id, selected);
board_changed = true;
// place the reflected piece
if (reflection && ('None' != reflection)) {
id = get_reflected_id(id, reflection);
new_selected = rotate_piece(selected, reflection, true);
$('#idx_'+id).empty( ).append(create_piece(new_selected));
board = board.replaceAt(id, new_selected);
board_changed = true;
}
});
// initialize a blank board
if (false === board) {
board = setups[0];
}
$('#setup_display').find('#the_board').remove( ).end( ).prepend(create_board(board));
// upon form submission, ajax validate the board first
// so we don't lose all the board data
// people might get a little upset about that
$('#setup_form').submit( function(event) {
// store the current board in the form
$('#setup').val(board);
do_clear_laser( );
if ('' == $('#name').val( )) {
alert('You must enter a Setup Name');
event.preventDefault( );
return false;
}
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+$('#setup_form').serialize( )+'&test_setup=1';
event.preventDefault( );
return false;
}
var valid = false;
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
async: false, // wait to continue script until this completes
data: $('#setup_form').serialize( )+'&test_setup=1',
success: function(msg) {
var reply = JSON.parse(msg);
if (reply.error) {
alert(reply.error);
event.preventDefault( );
valid = false;
}
else {
// run our actual form submit here
// because everything looks good
valid = true;
}
}
});
if (valid) {
return true;
}
event.preventDefault( );
return false;
});
});
function get_reflected_id(id, reflection) {
id = parseInt(id);
switch (reflection) {
case 'Origin' :
id = 79 - id;
break;
case 'Long' :
var tens = Math.floor(id / 10);
id = ((7 - tens) * 10) + (id % 10);
break;
case 'Short' :
var tens = Math.floor(id / 10);
id = (tens * 10) + (9 - (id % 10));
break;
default :
// do nothing
break;
}
return id;
}
var laser_path = { };
function do_fire_laser(color) {
color = color || 'silver';
// this stops the fire_laser function
// at the bottom from firing with
// incorrect path data
if (board_changed) {
laser_path = { };
}
if ( ! laser_path[color]) {
if (debug) {
window.location = 'ajax_helper.php'+debug_query+'&'+'color='+color+'&board='+board+'&test_fire=1';
return false;
}
$.ajax({
type: 'POST',
url: 'ajax_helper.php',
data: 'color='+color+'&board='+board+'&test_fire=1',
success: function(msg) {
var reply = JSON.parse(msg);
if (reply.error) {
alert(reply.error);
}
else {
laser_path[color] = reply.laser_path;
fire_laser(laser_path[color]);
board_changed = false;
}
}
});
}
fire_laser(laser_path[color]);
}
function do_clear_laser( ) {
clearTimeout(timer);
timer = false;
$('img.laser').remove( );
}
String.prototype.replaceAt = function(index, str) {
index = parseInt(index);
return this.slice(0, index) + str + this.slice(index + str.length);
}
String.prototype.repeat = function(num) {
num = parseInt(num);
return new Array(num + 1).join(this);
}
|
benjamw/pharaoh | cee51c18ebb507350a27dbad46e7a44c84b3a156 | make sure to cast vars in max function | diff --git a/classes/game.class.php b/classes/game.class.php
index 03ceff2..aff1c1e 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1,959 +1,959 @@
<?php
/*
+---------------------------------------------------------------------------
|
| game.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| This module is built to facilitate the game Pharaoh, it doesn't really
| care about how to play, or the deep goings on of the game, only about
| database structure and how to allow players to interact with the game.
|
+---------------------------------------------------------------------------
|
| > Pharaoh (Khet) Game module
| > Date started: 2008-02-28
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
if (defined('INCLUDE_DIR')) {
require_once INCLUDE_DIR.'func.array.php';
}
class Game
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property GAME_TABLE
* Holds the game table name
*
* @var string
*/
const GAME_TABLE = T_GAME;
/** const property GAME_HISTORY_TABLE
* Holds the game board table name
*
* @var string
*/
const GAME_HISTORY_TABLE = T_GAME_HISTORY;
/** const property GAME_NUDGE_TABLE
* Holds the game nudge table name
*
* @var string
*/
const GAME_NUDGE_TABLE = T_GAME_NUDGE;
/** const property GAME_STATS_TABLE
* Holds the game stats table name
*
* @var string
*/
const GAME_STATS_TABLE = T_STATS;
/** static protected property _EXTRA_INFO_DEFAULTS
* Holds the default extra info data
*
* @var array
*/
static protected $_EXTRA_INFO_DEFAULTS = array(
'white_color' => 'random',
'battle_dead' => false,
'battle_immune' => false,
'battle_front_only' => true,
'battle_hit_self' => false,
'move_sphynx' => false,
'draw_offered' => false,
'undo_requested' => false,
'custom_rules' => '',
'invite_setup' => '', // this is to hold the setup for invites only
);
/** static protected property _HISTORY_EXTRA_INFO_DEFAULTS
* Holds the default extra info data for the move history
*
* @var array
*/
static protected $_HISTORY_EXTRA_INFO_DEFAULTS = array(
'laser_hit' => false,
'laser_fired' => true,
'dead_for' => 0,
'immune_for' => 0,
);
/** public property id
* Holds the game's id
*
* @var int
*/
public $id;
/** public property state
* Holds the game's current state
* can be one of 'Waiting', 'Playing', 'Finished', 'Draw'
*
* @var string (enum)
*/
public $state;
/** public property turn
* Holds the game's current turn
* can be one of 'white', 'black'
*
* @var string
*/
public $turn;
/** public property paused
* Holds the game's current pause state
*
* @var bool
*/
public $paused;
/** public property create_date
* Holds the game's create date
*
* @var int (unix timestamp)
*/
public $create_date;
/** public property modify_date
* Holds the game's modified date
*
* @var int (unix timestamp)
*/
public $modify_date;
/** public property last_move
* Holds the game's last move date
*
* @var int (unix timestamp)
*/
public $last_move;
/** public property watch_mode
* Lets us know if we are just visiting this game
*
* @var bool
*/
public $watch_mode = false;
/** protected property _setup
* Holds the game's initial setup
* as an associative array
* array(
* 'id' => [setup_id],
* 'name' => [setup_name],
* );
*
* @var array
*/
protected $_setup;
/** protected property _laser_fired
* Holds the laser fired flag
*
* @var bool did we fire the laser?
*/
protected $_laser_fired = false;
/** protected property _extra_info
* Holds the extra game info
*
* @var array
*/
protected $_extra_info;
/** protected property _current_move_extra_info
* Holds the extra current move info
*
* @var array
*/
protected $_current_move_extra_info;
/** protected property _players
* Holds our player's object references
* along with other game data
*
* @var array of player data
*/
protected $_players;
/** protected property _pharaoh
* Holds the pharaoh object reference
*
* @var Pharaoh object reference
*/
protected $_pharaoh;
/** protected property _history
* Holds the board history
*
* @var array of pharaoh boards
*/
protected $_history;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional game id
* @param Mysql optional object reference
* @action instantiates object
* @return void
*/
public function __construct($id = 0, Mysql $Mysql = null)
{
call(__METHOD__);
$this->id = (int) $id;
call($this->id);
$this->_pharaoh = new Pharaoh($this->id);
if (is_null($Mysql)) {
$Mysql = Mysql::get_instance( );
}
$this->_mysql = $Mysql;
try {
$this->_pull( );
}
catch (MyException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action saves changed data
* @action destroys object
* @return void
*/
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if ($this->id && (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type']))) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
switch ($property) {
case 'name' :
return $this->_players['white']['object']->username.' vs '.$this->_players['black']['object']->username;
break;
case 'first_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return 'Your';
}
else {
return $this->_players['white']['object']->username.'\'s';
}
break;
case 'second_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return $this->_players['opponent']['object']->username.'\'s';
}
else {
return $this->_players['black']['object']->username.'\'s';
}
break;
default :
// go to next step
break;
}
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
$this->$property = $value;
}
/** static public function invite
* Creates the game from _POST data
*
* @param void
* @action creates an invite
* @return int game id
*/
static public function invite( )
{
call(__METHOD__);
call($_POST);
$Mysql = Mysql::get_instance( );
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
$_P = $_POST;
// translate (filter/sanitize) the data
$_P['white_id'] = (int) $_SESSION['player_id'];
$_P['black_id'] = (int) $_P['opponent'];
$_P['setup_id'] = (int) $_P['setup'];
$_P['laser_battle'] = is_checked($_P['laser_battle_box']);
$_P['battle_front_only'] = is_checked($_P['battle_front_only']);
$_P['battle_hit_self'] = is_checked($_P['battle_hit_self']);
$_P['move_sphynx'] = is_checked($_P['move_sphynx']);
call($_P);
// grab the setup
$query = "
SELECT setup_id
FROM ".Setup::SETUP_TABLE."
";
$setup_ids = $Mysql->fetch_value_array($query);
call($setup_ids);
// check for random setup
if (0 == $_P['setup_id']) {
shuffle($setup_ids);
shuffle($setup_ids);
$_P['setup_id'] = (int) reset($setup_ids);
sort($setup_ids);
}
// make sure the setup id is valid
if ( ! in_array($_P['setup_id'], $setup_ids)) {
throw new MyException(__METHOD__.': Setup is not valid');
}
$query = "
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$_P['setup_id']}'
";
$setup = $Mysql->fetch_value($query);
// laser battle cleanup
// only run this if the laser battle box was open
if ($_P['laser_battle']) {
ifer($_P['battle_dead'], 1, false);
ifer($_P['battle_immune'], 1);
// we can only hit ourselves in the sides or back, never front
if ($_P['battle_front_only']) {
$_P['battle_hit_self'] = false;
}
$extra_info = array(
- 'battle_dead' => (int) max($_P['battle_dead'], 1),
- 'battle_immune' => (int) max($_P['battle_immune'], 0),
+ 'battle_dead' => (int) max((int) $_P['battle_dead'], 1),
+ 'battle_immune' => (int) max((int) $_P['battle_immune'], 0),
'battle_front_only' => (bool) $_P['battle_front_only'],
'battle_hit_self' => (bool) $_P['battle_hit_self'],
);
}
$extra_info['white_color'] = $_P['color'];
$extra_info['move_sphynx'] = $_P['move_sphynx'];
$setup = expandFEN($setup);
if (is_checked($_P['convert_to_1'])) {
// add the sphynxes
$setup = preg_replace('/[efjk]/i', '0', $setup);
// replace the obelisks with anubises
$setup = preg_replace('/[lmno]/', 'w', $setup);
$setup = preg_replace('/[LMNO]/', 'W', $setup);
}
elseif (is_checked($_P['convert_to_2'])) {
// add the sphynxes
$setup = substr_replace($setup, 'j', 0, 1);
$setup = substr_replace($setup, 'E', -1, 1);
// replace the obelisks with anubises
$setup = str_replace('w', 'n', $setup);
$setup = str_replace('W', 'L', $setup);
}
$extra_info['invite_setup'] = packFEN($setup);
call($extra_info);
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
if ( ! empty($extra_info)) {
$_P['extra_info'] = serialize($extra_info);
}
// create the game
$required = array(
'white_id' ,
'setup_id' ,
);
$key_list = array_merge($required, array(
'black_id' ,
'extra_info' ,
));
try {
$_DATA = array_clean($_P, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['state'] = 'Waiting';
$_DATA['create_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$insert_id = $Mysql->insert(self::GAME_TABLE, $_DATA);
if (empty($insert_id)) {
throw new MyException(__METHOD__.': Invite could not be created');
}
// send the email
if ($_DATA['black_id']) {
Email::send('invite', $_DATA['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$_DATA['white_id']], 'page' => 'invite.php'));
}
return $insert_id;
}
/** static public function resend_invite
* Resends the invite email (if allowed)
*
* @param int game id
* @action resends an invite email
* @return bool invite email sent
*/
static public function resend_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$white_id = (int) $_SESSION['player_id'];
$Mysql = Mysql::get_instance( );
// grab the invite from the database
$query = "
SELECT *
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$invite = $Mysql->fetch_assoc($query);
if ( ! $invite) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend a non-existant invite (#'.$game_id.')');
}
if ((int) $invite['white_id'] !== (int) $white_id) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is not theirs');
}
if ( ! (int) $invite['black_id']) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is open');
}
if (strtotime($invite['modify_date']) >= strtotime($invite['resend_limit'])) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is too new');
}
// if we get here, all is good...
$sent = Email::send('invite', $invite['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$invite['white_id']], 'page' => 'invite.php'));
if ($sent) {
// update the modify_date to prevent invite resend flooding
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$Mysql->insert(self::GAME_TABLE, $_DATA, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
return $sent;
}
/** static public function accept_invite
* Creates the game from invite data
*
* @param int game id
* @action creates a game
* @return int game id
*/
static public function accept_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
// basically all we do, is set the state to Playing
// and set the player order based on the invite data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$game = $Mysql->fetch_assoc($query);
$invitor_id = $game['white_id']; // for use later
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($game['extra_info']));
if ((('random' == $extra_info['white_color']) && mt_rand(0, 1)) || ('white' == $extra_info['white_color'])) {
$game['white_id'] = $game['white_id'];
$game['black_id'] = $_SESSION['player_id'];
}
else {
$game['black_id'] = $game['white_id'];
$game['white_id'] = $_SESSION['player_id'];
}
call($extra_info);
unset($extra_info['white_color']);
$board = false;
if ( ! empty($extra_info['invite_setup'])) {
$board = $extra_info['invite_setup'];
}
$extra_info['invite_setup'] = '';
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
unset($game['extra_info']);
if ( ! empty($extra_info)) {
$game['extra_info'] = serialize($extra_info);
}
$game['state'] = 'Playing';
$Mysql->insert(self::GAME_TABLE, $game, " WHERE game_id = '{$game_id}' ");
// add the first entry in the history table
if (empty($board)) {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', (
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$game['setup_id']}'
))
";
$Mysql->query($query);
}
else {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', '{$board}')
";
$Mysql->query($query);
}
// add a used count to the setup table
Setup::add_used($game['setup_id']);
// send the email
Email::send('start', $invitor_id, array('opponent' => $GLOBALS['_PLAYERS'][$_SESSION['player_id']], 'game_id' => $game_id));
return $game_id;
}
/** static public function delete_invite
* Deletes the given invite
*
* @param int game id
* @action deletes the invite
* @return void
*/
static public function delete_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
$Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
/** static public function has_invite
* Tests if the given player has the given invite
*
* @param int game id
* @param int player id
* @param bool optional player can accept invite
* @return bool player has invite
*/
static public function has_invite($game_id, $player_id, $accept = false)
{
call(__METHOD__);
$game_id = (int) $game_id;
$player_id = (int) $player_id;
$accept = (bool) $accept;
$Mysql = Mysql::get_instance( );
$open = "";
if ($accept) {
$open = " OR black_id IS NULL
OR black_id = FALSE ";
}
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
{$open}
)
";
$has_invite = (bool) $Mysql->fetch_value($query);
return $has_invite;
}
public function can_fire_laser( )
{
call(__METHOD__);
if ( ! $this->_extra_info['battle_dead']) {
return true;
}
return ! $this->_current_move_extra_info['dead_for'];
}
public function prev_laser_fired( )
{
$last = end($this->_history);
return (bool) $last['laser_fired'];
}
/** public function do_move
* Do the given move and send out emails
*
* @param string move code
* @action performs the move
* @return array indexes hit
*/
public function do_move($move)
{
call(__METHOD__);
try {
$this->_laser_fired = $this->can_fire_laser( );
$hits = $this->_pharaoh->do_move($move, $this->_laser_fired);
$winner = $this->_pharaoh->winner;
}
catch (MyException $e) {
throw $e;
}
if ($winner) {
if ('draw' == $winner) {
$this->state = 'Draw';
$this->_players['silver']['object']->add_draw( );
$this->_players['red']['object']->add_draw( );
// send the email
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
else {
$this->state = 'Finished';
$this->_players[$winner]['object']->add_win( );
$this->_players[$this->_players[$winner]['opp_color']]['object']->add_loss( );
// send the email
$type = (($this->_players[$winner]['player_id'] == $_SESSION['player_id']) ? 'defeated' : 'won');
Email::send($type, $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
}
else {
// send the email
Email::send('turn', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
return $hits;
}
/** public function resign
* Resigns the given player from the game
*
* @param int player id
* @return void
*/
public function resign($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign from a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign opponent from a game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_win( );
$this->_players['player']['object']->add_loss( );
$this->state = 'Finished';
$this->_pharaoh->winner = 'opponent';
Email::send('resigned', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function offer_draw
* Offers a draw to the given player's apponent
*
* @param int player id
* @return void
*/
public function offer_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = $player_id;
Email::send('draw_offered', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function draw_offered
* Returns the state of the game draw for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function draw_offered($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the draw was offered AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['draw_offered']) && ( ! $player_id || ($player_id != $this->_extra_info['draw_offered']))) {
return true;
}
return false;
}
/** public function accept_draw
* Accepts a draw offered to the given player
*
* @param int player id
* @return void
*/
public function accept_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw for an opponent in game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_draw( );
$this->_players['player']['object']->add_draw( );
$this->state = 'Draw';
$this->_extra_info['draw_offered'] = false;
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_draw
* Rejects a draw offered to the given player
*
* @param int player id
* @return void
*/
public function reject_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to reject draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = false;
|
benjamw/pharaoh | f8b597470123baeed159877293ac8ff26b372d57 | made better ife (if-else) functions | diff --git a/classes/game.class.php b/classes/game.class.php
index 680f96b..03ceff2 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1,955 +1,950 @@
<?php
/*
+---------------------------------------------------------------------------
|
| game.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| This module is built to facilitate the game Pharaoh, it doesn't really
| care about how to play, or the deep goings on of the game, only about
| database structure and how to allow players to interact with the game.
|
+---------------------------------------------------------------------------
|
| > Pharaoh (Khet) Game module
| > Date started: 2008-02-28
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
if (defined('INCLUDE_DIR')) {
require_once INCLUDE_DIR.'func.array.php';
}
class Game
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property GAME_TABLE
* Holds the game table name
*
* @var string
*/
const GAME_TABLE = T_GAME;
/** const property GAME_HISTORY_TABLE
* Holds the game board table name
*
* @var string
*/
const GAME_HISTORY_TABLE = T_GAME_HISTORY;
/** const property GAME_NUDGE_TABLE
* Holds the game nudge table name
*
* @var string
*/
const GAME_NUDGE_TABLE = T_GAME_NUDGE;
/** const property GAME_STATS_TABLE
* Holds the game stats table name
*
* @var string
*/
const GAME_STATS_TABLE = T_STATS;
/** static protected property _EXTRA_INFO_DEFAULTS
* Holds the default extra info data
*
* @var array
*/
static protected $_EXTRA_INFO_DEFAULTS = array(
'white_color' => 'random',
'battle_dead' => false,
'battle_immune' => false,
'battle_front_only' => true,
'battle_hit_self' => false,
'move_sphynx' => false,
'draw_offered' => false,
'undo_requested' => false,
'custom_rules' => '',
'invite_setup' => '', // this is to hold the setup for invites only
);
/** static protected property _HISTORY_EXTRA_INFO_DEFAULTS
* Holds the default extra info data for the move history
*
* @var array
*/
static protected $_HISTORY_EXTRA_INFO_DEFAULTS = array(
'laser_hit' => false,
'laser_fired' => true,
'dead_for' => 0,
'immune_for' => 0,
);
/** public property id
* Holds the game's id
*
* @var int
*/
public $id;
/** public property state
* Holds the game's current state
* can be one of 'Waiting', 'Playing', 'Finished', 'Draw'
*
* @var string (enum)
*/
public $state;
/** public property turn
* Holds the game's current turn
* can be one of 'white', 'black'
*
* @var string
*/
public $turn;
/** public property paused
* Holds the game's current pause state
*
* @var bool
*/
public $paused;
/** public property create_date
* Holds the game's create date
*
* @var int (unix timestamp)
*/
public $create_date;
/** public property modify_date
* Holds the game's modified date
*
* @var int (unix timestamp)
*/
public $modify_date;
/** public property last_move
* Holds the game's last move date
*
* @var int (unix timestamp)
*/
public $last_move;
/** public property watch_mode
* Lets us know if we are just visiting this game
*
* @var bool
*/
public $watch_mode = false;
/** protected property _setup
* Holds the game's initial setup
* as an associative array
* array(
* 'id' => [setup_id],
* 'name' => [setup_name],
* );
*
* @var array
*/
protected $_setup;
/** protected property _laser_fired
* Holds the laser fired flag
*
* @var bool did we fire the laser?
*/
protected $_laser_fired = false;
/** protected property _extra_info
* Holds the extra game info
*
* @var array
*/
protected $_extra_info;
/** protected property _current_move_extra_info
* Holds the extra current move info
*
* @var array
*/
protected $_current_move_extra_info;
/** protected property _players
* Holds our player's object references
* along with other game data
*
* @var array of player data
*/
protected $_players;
/** protected property _pharaoh
* Holds the pharaoh object reference
*
* @var Pharaoh object reference
*/
protected $_pharaoh;
/** protected property _history
* Holds the board history
*
* @var array of pharaoh boards
*/
protected $_history;
/** protected property _mysql
* Stores a reference to the Mysql class object
*
* @param Mysql object
*/
protected $_mysql;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional game id
* @param Mysql optional object reference
* @action instantiates object
* @return void
*/
public function __construct($id = 0, Mysql $Mysql = null)
{
call(__METHOD__);
$this->id = (int) $id;
call($this->id);
$this->_pharaoh = new Pharaoh($this->id);
if (is_null($Mysql)) {
$Mysql = Mysql::get_instance( );
}
$this->_mysql = $Mysql;
try {
$this->_pull( );
}
catch (MyException $e) {
throw $e;
}
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action saves changed data
* @action destroys object
* @return void
*/
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if ($this->id && (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type']))) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
switch ($property) {
case 'name' :
return $this->_players['white']['object']->username.' vs '.$this->_players['black']['object']->username;
break;
case 'first_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return 'Your';
}
else {
return $this->_players['white']['object']->username.'\'s';
}
break;
case 'second_name' :
if ($_SESSION['player_id'] == $this->_players['player']['player_id']) {
return $this->_players['opponent']['object']->username.'\'s';
}
else {
return $this->_players['black']['object']->username.'\'s';
}
break;
default :
// go to next step
break;
}
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
$this->$property = $value;
}
/** static public function invite
* Creates the game from _POST data
*
* @param void
* @action creates an invite
* @return int game id
*/
static public function invite( )
{
call(__METHOD__);
call($_POST);
$Mysql = Mysql::get_instance( );
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
$_P = $_POST;
// translate (filter/sanitize) the data
$_P['white_id'] = (int) $_SESSION['player_id'];
$_P['black_id'] = (int) $_P['opponent'];
$_P['setup_id'] = (int) $_P['setup'];
$_P['laser_battle'] = is_checked($_P['laser_battle_box']);
$_P['battle_front_only'] = is_checked($_P['battle_front_only']);
$_P['battle_hit_self'] = is_checked($_P['battle_hit_self']);
$_P['move_sphynx'] = is_checked($_P['move_sphynx']);
call($_P);
// grab the setup
$query = "
SELECT setup_id
FROM ".Setup::SETUP_TABLE."
";
$setup_ids = $Mysql->fetch_value_array($query);
call($setup_ids);
// check for random setup
if (0 == $_P['setup_id']) {
shuffle($setup_ids);
shuffle($setup_ids);
$_P['setup_id'] = (int) reset($setup_ids);
sort($setup_ids);
}
// make sure the setup id is valid
if ( ! in_array($_P['setup_id'], $setup_ids)) {
throw new MyException(__METHOD__.': Setup is not valid');
}
$query = "
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$_P['setup_id']}'
";
$setup = $Mysql->fetch_value($query);
// laser battle cleanup
// only run this if the laser battle box was open
if ($_P['laser_battle']) {
- if (empty($_P['battle_dead'])) {
- $_P['battle_dead'] = 1;
- }
-
- if (empty($_P['battle_immune'])) {
- $_P['battle_immune'] = 1;
- }
+ ifer($_P['battle_dead'], 1, false);
+ ifer($_P['battle_immune'], 1);
// we can only hit ourselves in the sides or back, never front
if ($_P['battle_front_only']) {
$_P['battle_hit_self'] = false;
}
$extra_info = array(
'battle_dead' => (int) max($_P['battle_dead'], 1),
'battle_immune' => (int) max($_P['battle_immune'], 0),
'battle_front_only' => (bool) $_P['battle_front_only'],
'battle_hit_self' => (bool) $_P['battle_hit_self'],
);
}
$extra_info['white_color'] = $_P['color'];
$extra_info['move_sphynx'] = $_P['move_sphynx'];
$setup = expandFEN($setup);
if (is_checked($_P['convert_to_1'])) {
// add the sphynxes
$setup = preg_replace('/[efjk]/i', '0', $setup);
// replace the obelisks with anubises
$setup = preg_replace('/[lmno]/', 'w', $setup);
$setup = preg_replace('/[LMNO]/', 'W', $setup);
}
elseif (is_checked($_P['convert_to_2'])) {
// add the sphynxes
$setup = substr_replace($setup, 'j', 0, 1);
$setup = substr_replace($setup, 'E', -1, 1);
// replace the obelisks with anubises
$setup = str_replace('w', 'n', $setup);
$setup = str_replace('W', 'L', $setup);
}
$extra_info['invite_setup'] = packFEN($setup);
call($extra_info);
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
if ( ! empty($extra_info)) {
$_P['extra_info'] = serialize($extra_info);
}
// create the game
$required = array(
'white_id' ,
'setup_id' ,
);
$key_list = array_merge($required, array(
'black_id' ,
'extra_info' ,
));
try {
$_DATA = array_clean($_P, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['state'] = 'Waiting';
$_DATA['create_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$insert_id = $Mysql->insert(self::GAME_TABLE, $_DATA);
if (empty($insert_id)) {
throw new MyException(__METHOD__.': Invite could not be created');
}
// send the email
if ($_DATA['black_id']) {
Email::send('invite', $_DATA['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$_DATA['white_id']], 'page' => 'invite.php'));
}
return $insert_id;
}
/** static public function resend_invite
* Resends the invite email (if allowed)
*
* @param int game id
* @action resends an invite email
* @return bool invite email sent
*/
static public function resend_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$white_id = (int) $_SESSION['player_id'];
$Mysql = Mysql::get_instance( );
// grab the invite from the database
$query = "
SELECT *
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$invite = $Mysql->fetch_assoc($query);
if ( ! $invite) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend a non-existant invite (#'.$game_id.')');
}
if ((int) $invite['white_id'] !== (int) $white_id) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is not theirs');
}
if ( ! (int) $invite['black_id']) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is open');
}
if (strtotime($invite['modify_date']) >= strtotime($invite['resend_limit'])) {
throw new MyException(__METHOD__.': Player (#'.$white_id.') trying to resend an invite (#'.$game_id.') that is too new');
}
// if we get here, all is good...
$sent = Email::send('invite', $invite['black_id'], array('opponent' => $GLOBALS['_PLAYERS'][$invite['white_id']], 'page' => 'invite.php'));
if ($sent) {
// update the modify_date to prevent invite resend flooding
$_DATA['modify_date '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
$Mysql->insert(self::GAME_TABLE, $_DATA, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
return $sent;
}
/** static public function accept_invite
* Creates the game from invite data
*
* @param int game id
* @action creates a game
* @return int game id
*/
static public function accept_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
// basically all we do, is set the state to Playing
// and set the player order based on the invite data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
";
$game = $Mysql->fetch_assoc($query);
$invitor_id = $game['white_id']; // for use later
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($game['extra_info']));
if ((('random' == $extra_info['white_color']) && mt_rand(0, 1)) || ('white' == $extra_info['white_color'])) {
$game['white_id'] = $game['white_id'];
$game['black_id'] = $_SESSION['player_id'];
}
else {
$game['black_id'] = $game['white_id'];
$game['white_id'] = $_SESSION['player_id'];
}
call($extra_info);
unset($extra_info['white_color']);
$board = false;
if ( ! empty($extra_info['invite_setup'])) {
$board = $extra_info['invite_setup'];
}
$extra_info['invite_setup'] = '';
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
ksort($extra_info);
call($extra_info);
unset($game['extra_info']);
if ( ! empty($extra_info)) {
$game['extra_info'] = serialize($extra_info);
}
$game['state'] = 'Playing';
$Mysql->insert(self::GAME_TABLE, $game, " WHERE game_id = '{$game_id}' ");
// add the first entry in the history table
if (empty($board)) {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', (
SELECT board
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$game['setup_id']}'
))
";
$Mysql->query($query);
}
else {
$query = "
INSERT INTO ".self::GAME_HISTORY_TABLE."
(game_id, board)
VALUES
('{$game_id}', '{$board}')
";
$Mysql->query($query);
}
// add a used count to the setup table
Setup::add_used($game['setup_id']);
// send the email
Email::send('start', $invitor_id, array('opponent' => $GLOBALS['_PLAYERS'][$_SESSION['player_id']], 'game_id' => $game_id));
return $game_id;
}
/** static public function delete_invite
* Deletes the given invite
*
* @param int game id
* @action deletes the invite
* @return void
*/
static public function delete_invite($game_id)
{
call(__METHOD__);
$game_id = (int) $game_id;
$Mysql = Mysql::get_instance( );
$Mysql->delete(self::GAME_TABLE, " WHERE game_id = '{$game_id}' AND state = 'Waiting' ");
}
/** static public function has_invite
* Tests if the given player has the given invite
*
* @param int game id
* @param int player id
* @param bool optional player can accept invite
* @return bool player has invite
*/
static public function has_invite($game_id, $player_id, $accept = false)
{
call(__METHOD__);
$game_id = (int) $game_id;
$player_id = (int) $player_id;
$accept = (bool) $accept;
$Mysql = Mysql::get_instance( );
$open = "";
if ($accept) {
$open = " OR black_id IS NULL
OR black_id = FALSE ";
}
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE game_id = '{$game_id}'
AND state = 'Waiting'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
{$open}
)
";
$has_invite = (bool) $Mysql->fetch_value($query);
return $has_invite;
}
public function can_fire_laser( )
{
call(__METHOD__);
if ( ! $this->_extra_info['battle_dead']) {
return true;
}
return ! $this->_current_move_extra_info['dead_for'];
}
public function prev_laser_fired( )
{
$last = end($this->_history);
return (bool) $last['laser_fired'];
}
/** public function do_move
* Do the given move and send out emails
*
* @param string move code
* @action performs the move
* @return array indexes hit
*/
public function do_move($move)
{
call(__METHOD__);
try {
$this->_laser_fired = $this->can_fire_laser( );
$hits = $this->_pharaoh->do_move($move, $this->_laser_fired);
$winner = $this->_pharaoh->winner;
}
catch (MyException $e) {
throw $e;
}
if ($winner) {
if ('draw' == $winner) {
$this->state = 'Draw';
$this->_players['silver']['object']->add_draw( );
$this->_players['red']['object']->add_draw( );
// send the email
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
else {
$this->state = 'Finished';
$this->_players[$winner]['object']->add_win( );
$this->_players[$this->_players[$winner]['opp_color']]['object']->add_loss( );
// send the email
$type = (($this->_players[$winner]['player_id'] == $_SESSION['player_id']) ? 'defeated' : 'won');
Email::send($type, $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username));
}
}
else {
// send the email
Email::send('turn', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
return $hits;
}
/** public function resign
* Resigns the given player from the game
*
* @param int player id
* @return void
*/
public function resign($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign from a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to resign opponent from a game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_win( );
$this->_players['player']['object']->add_loss( );
$this->state = 'Finished';
$this->_pharaoh->winner = 'opponent';
Email::send('resigned', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function offer_draw
* Offers a draw to the given player's apponent
*
* @param int player id
* @return void
*/
public function offer_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw in a game (#'.$this->id.') they are not playing in');
}
if ($this->_players['player']['player_id'] != $player_id) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to offer draw for an opponent in game (#'.$this->id.')');
}
$this->_extra_info['draw_offered'] = $player_id;
Email::send('draw_offered', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function draw_offered
* Returns the state of the game draw for the given player
* or in general if no player given
*
* @param int [optional] player id
* @return bool draw state
*/
public function draw_offered($player_id = false)
{
call(__METHOD__);
$player_id = (int) $player_id;
// if the draw was offered AND player is blank or player is not the one who offered the draw
if (($this->_extra_info['draw_offered']) && ( ! $player_id || ($player_id != $this->_extra_info['draw_offered']))) {
return true;
}
return false;
}
/** public function accept_draw
* Accepts a draw offered to the given player
*
* @param int player id
* @return void
*/
public function accept_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
if ( ! $this->is_player($player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw in a game (#'.$this->id.') they are not playing in');
}
if (($this->_players['player']['player_id'] != $player_id) || ($this->_extra_info['draw_offered'] == $player_id)) {
throw new MyException(__METHOD__.': Player (#'.$player_id.') trying to accept draw for an opponent in game (#'.$this->id.')');
}
$this->_players['opponent']['object']->add_draw( );
$this->_players['player']['object']->add_draw( );
$this->state = 'Draw';
$this->_extra_info['draw_offered'] = false;
Email::send('draw', $this->_players['opponent']['player_id'], array('opponent' => $this->_players['player']['object']->username, 'game_id' => $this->id));
}
/** public function reject_draw
* Rejects a draw offered to the given player
*
* @param int player id
* @return void
*/
public function reject_draw($player_id)
{
call(__METHOD__);
if ($this->paused) {
throw new MyException(__METHOD__.': Trying to perform an action on a paused game');
}
$player_id = (int) $player_id;
if (empty($player_id)) {
throw new MyException(__METHOD__.': Missing required argument');
}
diff --git a/includes/func.global.php b/includes/func.global.php
index 2becaff..1650f2a 100644
--- a/includes/func.global.php
+++ b/includes/func.global.php
@@ -1,231 +1,293 @@
<?php
/** function call [dump] [debug]
* This function is for debugging only
* Outputs given var to screen
* or, if no var given, outputs stars to note position
*
* @param mixed optional var to output
* @param bool optional bypass debug value and output anyway
* @action outputs var to screen
* @return void
*/
function call($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false)
{
if ((( ! defined('DEBUG') || ! DEBUG) || ! empty($GLOBALS['NODEBUG'])) && ! (bool) $bypass) {
return false;
}
if ('Th&F=xUFucreSp2*ezAhe=ApuPR*$axe' === $var) {
$contents = '<span style="font-size:larger;font-weight:bold;color:red;">--==((OO88OO))==--</span>';
}
else {
// begin output buffering so we can escape any html
// and print_r is better at catching recursion than var_export
ob_start( );
if ( ! function_exists('xdebug_disable')) {
if ((is_string($var) && ! preg_match('/^\\s*$/', $var))) { // non-whitespace strings
print_r($var);
}
else {
if (is_array($var) || is_object($var)) {
print_r($var);
}
else {
var_dump($var);
}
}
}
else {
var_dump($var);
}
// end output buffering and output the result
if ( ! function_exists('xdebug_disable')) {
$contents = htmlentities(ob_get_contents( ));
}
else {
$contents = ob_get_contents( );
}
ob_end_clean( );
}
$j = 0;
$html = '';
$debug_funcs = array('dump', 'debug');
if ((bool) $show_from) {
$called_from = debug_backtrace( );
if (isset($called_from[$j + 1]) && in_array($called_from[$j + 1]['function'], $debug_funcs)) {
++$j;
}
$file0 = substr($called_from[$j]['file'], strlen($_SERVER['DOCUMENT_ROOT']));
$line0 = $called_from[$j]['line'];
$called = '';
if (isset($called_from[$j + 1]['file'])) {
$file1 = substr($called_from[$j + 1]['file'], strlen($_SERVER['DOCUMENT_ROOT']));
$line1 = $called_from[$j + 1]['line'];
$called = "{$file1} : {$line1} called ";
}
elseif (isset($called_from[$j + 1]['class'])) {
$called = $called_from[$j + 1]['class'].$called_from[$j + 1]['type'].$called_from[$j + 1]['function'].' called ';
}
$html = "<strong>{$called}{$file0} : {$line0}</strong>\n";
}
if ( ! $new_window) {
$color = '#000';
if ($error) {
$color = '#F00';
}
echo "\n\n<pre style=\"background:#FFF;color:{$color};font-size:larger;\">{$html}{$contents}\n<hr /></pre>\n\n";
}
else { ?>
<script language="javascript">
myRef = window.open('','debugWindow');
myRef.document.write('\n\n<pre style="background:#FFF;color:#000;font-size:larger;">');
myRef.document.write('<?php echo str_replace("'", "\'", str_replace("\n", "<br />", "{$html}{$contents}")); ?>');
myRef.document.write('\n<hr /></pre>\n\n');
</script>
<?php }
}
function dump($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = false, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); }
function debug($var = 'Th&F=xUFucreSp2*ezAhe=ApuPR*$axe', $bypass = true, $show_from = true, $new_window = false, $error = false) { call($var, $bypass, $show_from, $new_window, $error); }
/** function load_class
* This function automagically loads the class
* via the spl_autoload_register function above
* as it is instantiated (jit).
*
* @param string class name
* @action loads given class name if found
* @return bool success
*/
function load_class($class_name) {
$class_file = CLASSES_DIR.strtolower($class_name).'.class.php';
if (file_exists($class_file)) {
require_once $class_file;
return true;
}
else {
throw new MyException(__FUNCTION__.': Class file ('.$class_file.') not found');
}
}
/** function test_token
* This function tests the token given by the
* form and checks it against the session token
* and if they do not match, dies
*
* @param bool optional keep original token flag
* @action tests tokens and dies if bad
* @action optionally renews the session token
* @return void
*/
function test_token($keep = false) {
call($_SESSION['token']);
call($_POST['token']);
if (DEBUG || ('games' == $_SERVER['HTTP_HOST'])) {
return;
}
if ( ! isset($_SESSION['token']) || ! isset($_POST['token'])
|| (0 !== strcmp($_SESSION['token'], $_POST['token'])))
{
die('Hacking attempt detected.<br /><br />If you have reached this page in error, please go back,<br />clear your cache, refresh the page, and try again.');
}
// renew the token
if ( ! $keep) {
$_SESSION['token'] = md5(uniqid(rand( ), true));
}
}
/** function test_debug
* This function tests the debug given by the
* URL and checks it against the globals debug password
* and if they do not match, doesn't debug
*
* @param void
* @action tests debug pass
* @return bool success
*/
function test_debug( ) {
if ( ! isset($_GET['DEBUG'])) {
return false;
}
if ( ! class_exists('Settings') || ! Settings::test( )) {
return false;
}
if ('' == trim(Settings::read('debug_pass'))) {
return false;
}
if (0 !== strcmp($_GET['DEBUG'], Settings::read('debug_pass'))) {
return false;
}
$GLOBALS['_&_DEBUG_QUERY'] = '&DEBUG='.$_GET['DEBUG'];
$GLOBALS['_?_DEBUG_QUERY'] = '?DEBUG='.$_GET['DEBUG'];
return true;
}
/** function expandFEN
* This function expands a packed FEN into a
* string where each index is a valid location
*
* @param string packed FEN
* @return string expanded FEN
*/
function expandFEN($FEN)
{
$FEN = preg_replace('/\s+/', '', $FEN); // remove spaces
$FEN = preg_replace_callback('/\d+/', 'replace_callback', $FEN); // unpack the 0s
$xFEN = str_replace('/', '', $FEN); // remove the row separators
return $xFEN;
}
function replace_callback($match) {
return (((int) $match[0]) ? str_repeat('0', (int) $match[0]) : $match[0]);
}
/** function packFEN
* This function packs an expanded FEN into a
* string that takes up less space
*
* @param string expanded FEN
* @param int [optional] length of rows
* @return string packed FEN
*/
function packFEN($xFEN, $row_length = 10)
{
$xFEN = preg_replace('/\s+/', '', $xFEN); // remove spaces
$xFEN = preg_replace('/\//', '', $xFEN); // remove any row separators
$xFEN = trim(chunk_split($xFEN, $row_length, '/'), '/'); // add the row separators
$FEN = preg_replace('/(0+)/e', "strlen('\\1')", $xFEN); // pack the 0s
return $FEN;
}
+
+
+/** function ife
+ * if-else
+ * This function returns the value if it exists (or is optionally not empty)
+ * or a default value if it does not exist (or is empty)
+ *
+ * @param mixed var to test
+ * @param mixed optional default value
+ * @param bool optional allow empty value
+ * @param bool optional change the passed reference var
+ * @return mixed $var if exists (and not empty) or default otherwise
+ */
+function ife( & $var, $default = null, $allow_empty = true, $change_reference = false) {
+ if ( ! isset($var) || ( ! (bool) $allow_empty && empty($var))) {
+ if ((bool) $change_reference) {
+ $var = $default; // so it can also be used by reference
+ }
+
+ return $default;
+ }
+
+ return $var;
+}
+
+
+
+/** function ifer
+ * if-else reference
+ * This function returns the value if it exists (or is optionally not empty)
+ * or a default value if it does not exist (or is empty)
+ * It also changes the reference var
+ *
+ * @param mixed var to test
+ * @param mixed optional default value
+ * @param bool optional allow empty value
+ * @action updates/sets the reference var if needed
+ * @return mixed $var if exists (and not empty) or default otherwise
+ */
+function ifer( & $var, $default = null, $allow_empty = true) {
+ return ife($var, $default, $allow_empty, true);
+}
+
+
+
+/** function ifenr
+ * if-else non-reference
+ * This function returns the value if it is not empty
+ * or a default value if it is empty
+ *
+ * @param mixed var to test
+ * @param mixed optional default value
+ * @return mixed $var if not empty or default otherwise
+ */
+function ifenr($var, $default = null) {
+ if (empty($var)) {
+ return $default;
+ }
+
+ return $var;
+}
+
diff --git a/includes/html.tables.php b/includes/html.tables.php
index b150ba8..e8e10b4 100644
--- a/includes/html.tables.php
+++ b/includes/html.tables.php
@@ -1,523 +1,524 @@
<?php
// build table structure
/*
this file contains a function that will build an html table given some basic
information about that table, such as formatting, and data array
the format array may be a little confusing at first, because the format
layout has been overloaded a bit...
a column consists of 2 elements (2 more optional) which are:
- 'Header Text' - which gets printed in the table header as is (html allowed)
- 'column data' - which can contain several included markups: (parse in the following order)
- 'field_name' - where the data with key 'field_name' for this row gets inserted
- 'contents [[[field_name]]] contents' - where the [[[field_name]]] will be replaced by the data
- '###code to eval' - where the given code will be evaluated and output
- 'contents' - where, after all the above, will be output as is
NOTE: these types can be mixed together to form complex types, such as the following:
'###substr("[[[message]]]", 0, 50)."..."' - note the quotes inside the function to wrap the data
- 'sort_type' - OPTIONAL which denotes the sort type for this column
- 'extra_html' - OPTIONAL which gets placed in the td tag as html
there are two special cases for the format array
- if 'Header Text' contains 'SPECIAL_CLASS', then the second row contains a
snippet of code that should eval to true or false, this snippet of code can contain
anything that is allowed in the 'column data' field above (but does not need the leading ###
as it will always be eval'd). if the code evals to true, the tr tag gets the class name contained
in the third array element, and if false, gets the class name contained in the fourth element
both the third and fourth elements can contain [[[field_name]]].
- if 'Header Text' contains 'SPECIAL_HTML', then everything is the same as above, except
that instead of getting a class, the tr tag gets the html contained in the third and fourth elements
of the array, much like extra_html.
the data array is simply a 2-dimensional array, where each row is the first array
and each column is the second, as follows:
$table_data = array(
0 => array(
'field_name1' => 'field data' ,
'field_name2' => 'other field data' ,
) ,
1 => array(
'field_name1' => 'second row field data' ,
'field_name2' => 'second row other field data' ,
) ,
);
an example of the format array:
$table_format = array(
array('SPECIAL_CLASS', 'eval [[[field_name]]] code to bool', 'true_class', 'false_class') , // optional
array('SPECIAL_CLASS', 'eval [[[field_name]]] code to bool', 'other_true_class', 'other_false_class') , // optional
array('SPECIAL_HTML', 'eval [[[field_name]]] code to bool', 'id="true_html"', 'id="false_html"') , // optional
array('Header Text', 'field_name', 'sort_type', 'extra_html', 'count_field_name') ,
array('Header Text', 'contents [[[field_name]]] contents') ,
array('Header Text', '###code to [[[eval]]]') ,
);
the count_field_name is for columns that may have other data included, we can still get a total out of it
for instance, a column may have the format like '<a href="read.php?id=[[[message_id]]]">[[[message_count]]]</a>'
if we put 'message_count' in the count_field_name section, it will sum that field, instead of the link (which will error out)
###eval code and [[[meta]]] vars are also acceptable
// special
array( TYPE, CODE, TRU, FALS)
// data
array( HEADER, FIELD, SORT, EXTRA, TOTAL)
*/
// data format columns
define('HEADER', 0);
define('FIELD', 1);
define('SORT', 2);
define('EXTRA', 3);
define('TOTAL', 4);
// special format columns
define('TYPE', 0);
define('CODE', 1);
define('TRU', 2);
define('FALS', 3);
// table_format is as seen above, table_data is a two dimensional array of data
// meta vars are:
// alt_class, caption, class, extra_html, init_sort_column, no_data, sortable, totals
// init_sort_column is an array of the format col => dir where dir is 0 for ASC and 1 for DESC
function get_table($table_format, $table_data, $meta = null)
{
$meta_defaults = array(
'alt_class' => 'alt',
'caption' => '',
'class' => 'datatable',
'extra_html' => '',
'init_sort_column' => null,
'no_data' => 'There is no data',
'sortable' => false,
'totals' => false,
);
$opts = array_merge($meta_defaults, $meta);
if ( ! is_array($table_data) || (0 == count($table_data))) {
return $opts['no_data'];
}
$opts['caption'] = ('' != $opts['caption']) ? '<caption>'.$opts['caption'].'</caption>' : '';
// start building the header
$headhtml = '
<thead>
<tr>';
$total_cols = array( );
foreach ($table_format as $col) {
// test for SPECIAL data first
if ( ! is_array($col[TYPE]) && ('SPECIAL_' == substr($col[TYPE], 0, 8))) {
${$col[TYPE]}[] = $col; // will be named either SPECIAL_CLASS or SPECIAL_HTML
}
else {
$sort_types[] = (isset($col[SORT])) ? $col[SORT] : null;
if ( ! is_array($col[HEADER])) {
$headhtml .= '
<th>'.$col[HEADER].'</th>';
}
else {
$headhtml .= '
<th title="'.$col[HEADER][1].'">'.$col[HEADER][0].'</th>';
}
// do some stuff for the totals row
if ($opts['totals'] && isset($col[TOTAL])) {
if ((false != $col[TOTAL]) && ('total' != strtolower($col[TOTAL]))) {
// test if we have any [[[meta_vars]]]
// and make a total entry for those matches if any VALID ones are found
// if the code is eval'd, we'll do that when we put the total row on
if (preg_match_all('/\\[\\[\\[(\\w+)\\]\\]\\]/i', $col[TOTAL], $matches, PREG_PATTERN_ORDER)) {
foreach ($matches[1] as $match) {
if (in_array($match, array_keys(reset($table_data))) && ! in_array($match, $total_cols)) {
$total_cols[] = $match;
}
}
}
else {
$total_cols[] = $col[TOTAL];
}
}
}
}
}
$total_cols = array_unique($total_cols);
$headhtml .= '
</tr>
</thead>
';
// start building the body
$bodyhtml = '<tbody>
';
// start placing the data in the table
$i = 0;
foreach ($table_data as $rkey => $row) {
if ( ! is_array($row)) {
continue;
}
// clear out previous data
$classes = false;
// run our special class code
// this code adds a class (or not) to the table row based on field contents
if (isset($SPECIAL_CLASS)) {
foreach ($SPECIAL_CLASS as $SP_CLASS_USE) {
$SP_CLASS_USE[CODE] = replace_meta($row, $SP_CLASS_USE[CODE]);
# call('$do_it = (bool) ('.$SP_CLASS_USE[CODE].');');
eval('$do_it = (bool) ('.$SP_CLASS_USE[CODE].');');
if ($do_it && ! empty($SP_CLASS_USE[TRU])) {
$classes[] = massage_data($row, $SP_CLASS_USE[TRU]);
}
if ( ! $do_it && ! empty($SP_CLASS_USE[FALS])) {
$classes[] = massage_data($row, $SP_CLASS_USE[FALS]);
}
}
}
// run our special html code
// this code adds html (or not) to the table row based on field contents
$spec_html = '';
if (isset($SPECIAL_HTML)) {
foreach ($SPECIAL_HTML as $SP_HTML_USE) {
foreach ($SP_HTML_USE as $key => $col) {
$SP_HTML_USE[$key] = replace_meta($row, $col);
}
# call('$do_it = (bool) ('.$SP_HTML_USE[CODE].');');
eval('$do_it = (bool) ('.$SP_HTML_USE[CODE].');');
if ($do_it && ! empty($SP_HTML_USE[TRU])) {
$spec_html .= ' '.massage_data($row, $SP_HTML_USE[TRU]);
}
if ( ! $do_it && ! empty($SP_HTML_USE[FALS])) {
$spec_html .= ' '.massage_data($row, $SP_HTML_USE[FALS]);
}
}
}
if (0 == ($i % 2) && ! empty($opts['alt_class'])) {
$classes[] = $opts['alt_class'];
}
$class = (is_array($classes)) ? ' class="'.implode(' ', $classes).'"' : '';
$bodyhtml .= '<tr'.$class.$spec_html.'>';
// don't just start outputting the data
// output it in the order specified by the table_format
foreach ($table_format as $ckey => $col) {
if ( ! is_array($col)) {
continue;
}
if ( ! is_array($col[TYPE]) && ('SPECIAL_' == substr($col[TYPE], 0, 8))) {
continue;
}
$col[EXTRA] = (isset($col[EXTRA])) ? ' '.trim($col[EXTRA]) : '';
$bodyhtml .= '
<td'.$col[EXTRA].'>';
if (is_null($col[FIELD])) {
// we don't want to show anything in this column
// do nothing
}
elseif (isset($row[$col[FIELD]])) {
// we have normal data
$bodyhtml .= $row[$col[FIELD]];
}
else {
$bodyhtml .= massage_data($row, $col[FIELD]);
}
$bodyhtml .= '</td>';
}
// grab the totals
if ($opts['totals'] && (0 != count($total_cols))) {
foreach ($total_cols as $total_col) {
if ('__total' == $total_col) {
$totals[$total_col] = 'Total';
}
else {
$totals[$total_col] += $row[$total_col];
}
}
}
$bodyhtml .= '
</tr>';
++$i;
}
$bodyhtml .= '
</tbody>';
// start building the footer
if ($opts['totals'] && (0 != count($totals))) {
$foothtml = '
<tfoot>
<tr>';
foreach ($table_format as $ckey => $col) {
if ( ! is_array($col)) {
continue;
}
if ('SPECIAL_' == substr($col[TYPE], 0, 8)) {
continue;
}
$foothtml .= '
<td>';
if (is_null($col[TOTAL])) {
$foothtml .= '--';
}
elseif (isset($totals[$col[TOTAL]])) {
// we have normal data
$foothtml .= $totals[$col[TOTAL]];
}
else {
$foothtml .= massage_data($totals, $col[TOTAL]);
}
$foothtml .= '</td>';
}
$foothtml .= '
</tr>
</tfoot>';
}
else {
$foothtml = '';
}
// build the sortable script
if ($opts['sortable']) {
$table_id = get_table_id( );
$opts['extra_html'] .= ' id="'.$table_id.'"';
$sort_script = get_sort_script($table_id, $sort_types, $opts['alt_class'], $opts['init_sort_column']);
}
else {
$sort_script = '';
}
$html = '
<table class="'.$opts['class'].'" '.$opts['extra_html'].'>
'.$opts['caption']
.$headhtml
.$foothtml
.$bodyhtml.'
</table>'
.$sort_script;
return $html;
}
function print_table($table_format, $table_data, $meta = null) {
echo get_table($table_format, $table_data, $meta);
}
// sort_types can be a comma separated list or an array of sort types
function get_sort_script($table_id, $sort_types = '', $alt_class = 'alt', $init_sort_column = null)
{
if ( ! is_array($init_sort_column) || (0 == count($init_sort_column))) {
$init_sort_column = null;
}
$html = '
<script type="text/javascript">//<![CDATA[
$(document).ready(function( ) {';
if ( ! is_null($init_sort_column)) {
$html .= '
var c = [';
$sort = '';
foreach ($init_sort_column as $col => $dir) {
$sort .= '['.$col.','.$dir.'],';
}
$html .= substr($sort, 0, -1).']
';
}
$html .='
$("#'.$table_id.'").tablesorter({
textExtraction: "complex",
widgets: ["zebra"],
widgetZebra: {css: ["","'.$alt_class.'"]},
headers: {';
if ('' != $sort_types) {
array_trim($sort_types);
$keys = array_keys($sort_types);
$last_key = end($keys);
foreach ($sort_types as $key => $type) {
if ('' !== $type) {
if ('false' != $type) {
$type = "'{$type}'";
}
$html .= '
'.$key.': { sorter: '.$type.' }';
if ($last_key != $key){
$html .= ',';
}
}
}
}
$html .= '
}
});';
if ( ! is_null($init_sort_column)) {
$html .= '
$("#'.$table_id.'").trigger("sorton",[c]);';
}
$html .= '
});
//]]></script>';
return $html;
}
function print_sort_script($table_id, $sort_types = '', $alt_class = 'alt', $init_sort_column = null) {
echo get_sort_script($table_id, $sort_types, $alt_class, $init_sort_column);
}
function get_table_id($length = 8) {
--$length;
return 't' . substr(md5(substr(md5(uniqid(rand( ), true)), rand(0, 25), 7)), rand(0, (32 - $length)), $length);
}
function print_table_id($length = 8) {
echo get_table_id($length);
}
function replace_meta($row, $data) {
if (preg_match_all('/\\[\\[\\[(\\w+)\\]\\]\\]/i', $data, $matches, PREG_PATTERN_ORDER)) {
foreach ($matches[1] as $match) {
if (in_array($match, array_keys($row))) {
// clean up the data coming from the database, so we don't get more [[[meta]]] and ###code things
$row[$match] = htmlentities($row[$match], ENT_QUOTES, 'ISO-8859-1', false); // do this first, so we don't convert the &'s below
$row[$match] = str_replace('###', '###', $row[$match]);
$row[$match] = str_replace('[', '[', $row[$match]);
$row[$match] = str_replace(']', ']', $row[$match]);
$data = str_replace("[[[{$match}]]]", $row[$match], $data);
}
}
$data = trim($data);
}
return $data;
}
function massage_data($row, $data) {
$col_data = replace_meta($row, $data);
// test for '###eval code;'
if ('###' == substr($col_data, 0, 3)) {
# call('$col_data = '.substr($col_data, 3).';');
eval('$col_data = '.substr($col_data, 3).';');
# call($col_data);
}
return $col_data;
}
if ( ! function_exists('my_empty')) {
function my_empty($val = null) {
return empty($val);
}
}
if ( ! function_exists('ifsetor')) {
function ifsetor(& $param, $or) {
if ( ! isset($param)) {
$param = $or;
}
return $param;
}
}
if ( ! function_exists('ifemptyor')) {
function ifemptyor(& $param, $or) {
if (empty($param)) {
$param = $or;
}
return $param;
}
}
-if ( ! function_exists('ife')) {
- function ife($param, $or) {
+if ( ! function_exists('ifenr')) {
+ // if-else non-reference
+ function ifenr($param, $or = null) {
if (empty($param)) {
return $or;
}
return $param;
}
}
if ( ! function_exists('ifdateor')) {
function ifdateor($date_format, & $if, $or) {
$date = (isset($if) && is_int($if)) ? $if : $or;
if (is_int($date)) {
$date = date($date_format, $date);
}
return $date;
}
}
if ( ! function_exists('strmaxlen')) {
function strmaxlen($string, $length) {
if (strlen($string) > $length) {
return substr($string, 0, ($length - 3)).'...';
}
return $string;
}
}
diff --git a/invite.php b/invite.php
index 378a144..e3ab6fb 100644
--- a/invite.php
+++ b/invite.php
@@ -1,255 +1,255 @@
<?php
require_once 'includes/inc.global.php';
// this has nothing to do with creating a game
// but I'm running it here to prevent long load
// times on other pages where it would be run more often
GamePlayer::delete_inactive(Settings::read('expire_users'));
Game::delete_inactive(Settings::read('expire_games'));
Game::delete_finished(Settings::read('expire_finished_games'));
$Game = new Game( );
if (isset($_POST['invite'])) {
// make sure this user is not full
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
Flash::store('You have reached your maximum allowed games !', false);
}
test_token( );
try {
$game_id = $Game->invite( );
Flash::store('Invitation Sent Successfully', true);
}
catch (MyException $e) {
Flash::store('Invitation FAILED !', false);
}
}
// grab the full list of players
$players_full = GamePlayer::get_list(true);
$invite_players = array_shrink($players_full, 'player_id');
// grab the players who's max game count has been reached
$players_maxed = GamePlayer::get_maxed( );
$players_maxed[] = $_SESSION['player_id'];
// remove the maxed players from the invite list
$players = array_diff($invite_players, $players_maxed);
$opponent_selection = '';
$opponent_selection .= '<option value="">-- Open --</option>';
foreach ($players_full as $player) {
if ($_SESSION['player_id'] == $player['player_id']) {
continue;
}
if (in_array($player['player_id'], $players)) {
$opponent_selection .= '
<option value="'.$player['player_id'].'">'.$player['username'].'</option>';
}
}
$groups = array(
'Normal' => array(0, 0),
'Eye of Horus' => array(0, 1),
'Sphynx' => array(1, 0),
'Sphynx & Horus' => array(1, 1),
);
$group_names = array_keys($groups);
$group_markers = array_values($groups);
$setups = Setup::get_list( );
$setup_selection = '<option value="0">Random</option>';
$setup_javascript = '';
$cur_group = false;
$group_open = false;
foreach ($setups as $setup) {
$marker = array((int) $setup['has_sphynx'], (int) $setup['has_horus']);
$group_index = array_search($marker, $group_markers, true);
if ($cur_group !== $group_names[$group_index]) {
if ($group_open) {
$setup_selection .= '</optgroup>';
$group_open = false;
}
$cur_group = $group_names[$group_index];
$setup_selection .= '<optgroup label="'.$cur_group.'">';
$group_open = true;
}
$setup_selection .= '
<option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>';
$setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n";
}
$setup_javascript = substr(trim($setup_javascript), 0, -1);
if ($group_open) {
$setup_selection .= '</optgroup>';
}
$meta['title'] = 'Send Game Invitation';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">//<![CDATA[
var setups = {
'.$setup_javascript.'
};
/*]]>*/</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/invite.js"></script>
';
$hints = array(
'Invite a player to a game by filling out your desired game options.' ,
'<span class="highlight">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' ,
);
// make sure this user is not full
$submit_button = '<div><input type="submit" name="invite" value="Send Invitation" /></div>';
$warning = '';
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
$submit_button = $warning = '<p class="warning">You have reached your maximum allowed games, you can not create this game !</p>';
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="send"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="player_id" value="{$_SESSION['player_id']}" />
{$warning}
<div><label for="opponent">Opponent</label><select id="opponent" name="opponent">{$opponent_selection}</select></div>
<div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup">Show Setup</a></div>
<div><label for="color">Your Color</label><select id="color" name="color"><option value="random">Random</option><option value="white">Silver</option><option value="black">Red</option></select></div>
<div class="pharaoh_1">
<fieldset>
<legend>v1.0 Options</legend>
<p class="conversion">
Here you can convert old v1.0 setups to play v2.0 Pharaoh.<br />
The conversion places a Sphynx in your lower-right corner facing upwards (and opposite for your opponent)
and converts any double-stacked Obelisks to Anubises which face forward.
</p>
<p class="conversion">
When you select to convert, more options will be shown below, as well as the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_2" name="convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .pharaoh_1 -->
<div class="pharaoh_2 p2_box">
<fieldset>
<legend>v2.0 Options</legend>
<p class="conversion">
Here you can convert the new v2.0 setups to play v1.0 Pharaoh.<br />
The conversion removes any Sphynxes from the board and converts any Anubises to double-stacked Obelisks.
</p>
<p class="conversion">
When you select to convert, the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_1" name="convert_to_1" /> Convert to 1.0</label></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="move_sphynx" name="move_sphynx" /> Sphynx is movable</label></div>
</fieldset>
</div> <!-- .pharaoh_2 -->
<fieldset>
<legend><label class="inline"><input type="checkbox" name="laser_battle_box" id="laser_battle_box" class="fieldset_box" /> Laser Battle</label></legend>
<div id="laser_battle">
<p>
When a laser gets shot by the opponents laser, it will be disabled for a set number of turns, making that laser unable to shoot until those turns have passed.<br />
After those turns have passed, and the laser has recovered, it will be immune from further shots for a set number of turns.<br />
After the immunity turns have passed, whether or not the laser was shot again, it will now be susceptible to being shot again.
<span class="pharaoh_2"><br />You can also select if the Sphynx is hittable only in the front, or on all four sides.</span>
</p>
<div><label for="battle_dead">Dead for:</label><input type="text" id="battle_dead" name="battle_dead" size="4" /> <span class="info">(Default: 1; Minimum: 1)</span></div>
<div><label for="battle_immune">Immune for:</label><input type="text" id="battle_immune" name="battle_immune" size="4" /> <span class="info">(Default: 1; Minimum: 0)</span></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_front_only" name="battle_front_only" checked="checked" /> Only front hits on Sphynx count</label></div>
<!-- <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_hit_self" name="battle_hit_self" /> Hit Self</label></div> -->
<p>You can set the "Immune for" value to 0 to allow a laser to be shot continuously, but the minimum value for the "Dead for" value is 1, as it makes no sense otherwise.</p>
</div> <!-- #laser_battle -->
</fieldset>
{$submit_button}
<div class="clr"></div>
</div></form>
<div id="setup_display"></div>
EOF;
// create our invitation tables
list($in_vites, $out_vites, $open_vites) = Game::get_invites($_SESSION['player_id']);
$contents .= <<< EOT
<form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv" id="invites">
EOT;
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no received invites to show</p>' ,
'caption' => 'Invitations Received' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" /><input type="button" id="decline-[[[game_id]]]" value="Decline" />', false) ,
);
$contents .= get_table($table_format, $in_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no sent invites to show</p>' ,
'caption' => 'Invitations Sent' ,
);
$table_format = array(
- array('Invitee', '###ife(\'[[[invitee]]]\', \'-- OPEN --\')') ,
+ array('Invitee', '###ifenr(\'[[[invitee]]]\', \'-- OPEN --\')') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '###\'<input type="button" id="withdraw-[[[game_id]]]" value="Withdraw" />\'.((strtotime(\'[[[create_date]]]\') >= strtotime(\'[[[resend_limit]]]\')) ? \'\' : \'<input type="button" id="resend-[[[game_id]]]" value="Resend" />\')', false) ,
);
$contents .= get_table($table_format, $out_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no open invites to show</p>' ,
'caption' => 'Open Invitations' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" />', false) ,
);
$contents .= get_table($table_format, $open_vites, $table_meta);
$contents .= <<< EOT
</div></form>
EOT;
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer( );
diff --git a/send.php b/send.php
index 73d78cd..9b229ff 100644
--- a/send.php
+++ b/send.php
@@ -1,122 +1,122 @@
<?php
require_once 'includes/inc.global.php';
if (isset($_POST['submit'])) {
test_token( );
// clean the data
$subject = $_POST['subject'];
$message = $_POST['message'];
- $user_ids = $_POST['user_ids'];
- $send_date = ('' != $_POST['send_date']) ? $_POST['send_date'] : false;
- $expire_date = ('' != $_POST['expire_date']) ? $_POST['expire_date'] : false;
+ $user_ids = (array) ife($_POST['user_ids'], array( ), false);
+ $send_date = ife($_POST['send_date'], false, false);
+ $expire_date = ife($_POST['expire_date'], false, false);
try {
$Message->send_message($subject, $message, $user_ids, $send_date, $expire_date);
$sent = true;
}
catch (MyException $e) {
if ( ! defined('DEBUG') || ! DEBUG) {
Flash::store('Error Sending Message !', false);
}
else {
call('ERROR SENDING MESSAGE');
}
exit;
}
if (isset($_GET['id'])) {
Flash::store('Message Sent Successfully !', 'messages.php');
}
}
$message = array(
'subject' => '',
'message' => '',
);
if (isset($_GET['id'])) {
try {
if (isset($_GET['type']) && ('fw' == $_GET['type'])) { // forward
$message = $Message->get_message_forward((int) $_GET['id']);
}
elseif (isset($_GET['type']) && ('rs' == $_GET['type'])) { // resend
$message = $Message->get_message((int) $_GET['id']);
}
else { // reply
$message = $Message->get_message_reply((int) $_GET['id']);
$reply_flag = true;
}
}
catch (MyException $e) {
Flash::store('Error Retrieving Message !', 'messages.php');
}
}
$meta['title'] = 'Message Writer';
$meta['show_menu'] = false;
$meta['head_data'] = '
<style type="text/css">@import url(css/vader/jquery-ui-1.8.13.custom.css);</style>
<script type="text/javascript" src="scripts/jquery-ui-1.8.13.datepicker.min.js"></script>
<script type="text/javascript" src="scripts/messages.js"></script>
';
if (isset($sent)) {
Flash::store('Message Sent Successfully !', false);
}
// grab a list of the players
$list = GamePlayer::get_list(true);
$recipient_options = '';
if (is_array($list)) {
// send global messages if we can
if ($GLOBALS['Player']->is_admin) {
$recipient_options .= '<option value="0">GLOBAL</option>';
}
$recipient_id = (isset($message['recipients'][0]['from_id']) && ! empty($reply_flag)) ? $message['recipients'][0]['from_id'] : 0;
foreach ($list as $player) {
// remove ourselves from the list
if ($player['player_id'] == $_SESSION['player_id']) {
continue;
}
$recipient_options .= '<option value="'.$player['player_id'].'"'.get_selected($recipient_id, $player['player_id']).'>'.$player['username'].'</option>';
}
}
echo get_header($meta);
?>
<div id="content" class="msg">
<div class="link_date">
<a href="messages.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Return to Inbox</a>
<?php echo date(Settings::read('long_date')); ?>
</div>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"><div class="formdiv">
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
<div>
<div class="info">Press and hold CTRL while selecting to select multiple recipients</div>
<label for="user_ids">Recipients</label><select name="user_ids[]" id="user_ids" multiple="multiple" size="5">
<?php echo $recipient_options; ?>
</select>
</div>
<div><label for="send_date">Send Date</label><input type="text" name="send_date" id="send_date" /> <span class="info">Leave blank to send now</span></div>
<div><label for="expire_date">Expiration Date</label><input type="text" name="expire_date" id="expire_date" /> <span class="info">Leave blank to never expire</span></div>
<div><label for="subject">Subject</label><input type="text" name="subject" id="subject" value="<?php echo htmlentities($message['subject'], ENT_QUOTES, 'ISO-8859-1', false); ?>" size="50" maxlength="255" /></div>
<div><label for="message">Message</label><textarea name="message" id="message" rows="15" cols="50"><?php echo htmlentities($message['message'], ENT_QUOTES, 'ISO-8859-1', false); ?></textarea></div>
<div><label> </label><input type="submit" name="submit" value="Send Message" /></div>
</div></form>
</div>
<?php
call($GLOBALS);
echo get_footer( );
|
benjamw/pharaoh | a8149d3b37320bb332210184faf2449429ae8408 | switch to less intensive require | diff --git a/classes/email.class.php b/classes/email.class.php
index 7ff0627..1336591 100644
--- a/classes/email.class.php
+++ b/classes/email.class.php
@@ -1,269 +1,269 @@
<?php
/*
+---------------------------------------------------------------------------
|
| email.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Email module
| > Date started: 2009-04-27
|
| > Module Version Number: 0.9.0
|
+---------------------------------------------------------------------------
*/
/*
Requires
----------------------------------------------------------------------------
Settings class:
Settings::read('site_name')
Settings::read('from_email')
Log class:
Log::write(
Mysql class:
Mysql::get_instance( )->fetch_row(
MyException class
*/
class Email
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static private property _instance
* Holds the instance of this object
*
* @var Email object
*/
static private $_instance;
/** protected property email_data
* Holds the message data
*
* @var array
*/
protected $email_data = array( );
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** protected function __construct
* Class constructor
*
* @param void
* @action instantiates object
* @return void
*/
protected function __construct( )
{
if ( ! $this->email_data && defined('INCLUDE_DIR')) {
- require_once INCLUDE_DIR.'inc.email.php';
+ require INCLUDE_DIR.'inc.email.php';
$this->email_data = $GLOBALS['__EMAIL_DATA'];
unset($GLOBALS['__EMAIL_DATA']);
}
}
/** protected function _send
* Sends email messages of various types [optional data contents]
*
* @param string message type
* @param mixed player id OR email address OR mixed array of both
* @param array optional message data
* @action send emails
* @return bool success
*/
protected function _send($type, $to, $data = array( ))
{
call(__METHOD__);
call($type);
call($to);
call($data);
if (is_array($to)) {
$return = true;
foreach ($to as $player) {
$return = ($this->_send($type, trim($player), $data) && $return);
}
return $return;
}
// $to is an email address (or comma separated email addresses)
elseif (preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $to)) {
$email = $to;
}
else { // $to is a single player id
$player_id = (int) $to;
// test if this user accepts emails
$query = "
SELECT P.email
, PE.allow_email
FROM ".Player::PLAYER_TABLE." AS P
LEFT JOIN ".GamePlayer::EXTEND_TABLE." AS PE
ON P.player_id = PE.player_id
WHERE P.player_id = '{$player_id}'
";
list($email, $allow) = Mysql::get_instance( )->fetch_row($query);
call($email);call($allow);
if (empty($allow) || empty($email)) {
// no exception, just quit
return false;
}
}
call($email);
$site_name = Settings::read('site_name');
if ( ! in_array($type, array_keys($this->email_data))) {
throw new MyException(__METHOD__.': Trying to send email with unsupported type ('.$type.')');
}
$subject = $this->email_data[$type]['subject'];
$message = $this->email_data[$type]['message'];
// replace the meta vars
$replace = array(
'/\[\[\[GAME_NAME\]\]\]/' => GAME_NAME,
'/\[\[\[site_name\]\]\]/' => $site_name,
'/\[\[\[opponent\]\]\]/' => @$data['opponent'],
'/\[\[\[export_data\]\]\]/' => var_export($data, true),
);
$message = preg_replace(array_keys($replace), $replace, $message);
$subject = GAME_NAME.' - '.$subject;
if ( ! empty($data['game_id'])) {
$message .= "\n\n".'Game Link: '.$GLOBALS['_ROOT_URI'].'game.php?id='.(int) $data['game_id'];
}
elseif ( ! empty($data['page'])) {
$message .= "\n\n".'Direct Link: '.$GLOBALS['_ROOT_URI'].$data['page'];
}
$message .= '
=============================================
This message was automatically sent by
'.$site_name.'
and should not be replied to.
=============================================
'.$GLOBALS['_ROOT_URI'];
$from_email = Settings::read('from_email');
// send the email
$headers = "From: ".GAME_NAME." <{$from_email}>\r\n";
$message = html_entity_decode($message);
$this->_log($email."\n".$headers."\n".$subject."\n".$message);
call($subject);call($message);call($headers);
if ($GLOBALS['_USEEMAIL']) {
return mail($email, $subject, $message, $headers);
}
return false;
}
/** protected function _strip
* Strips out the bad stuff from the email
*
* @param string the string to clean
* @param bool optional this is a message string
* @return string clean string
*/
protected function _strip($value, $message = false) {
$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
$search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*';
if ( ! (bool) $message) {
$search .= '|\r|\n';
}
$search = '#(?:' . $search . ')#i';
while (preg_match($search, $value)) {
$value = preg_replace($search, '', $value);
}
return htmlentities($value, ENT_QUOTES, 'ISO-8859-1', false);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
// log the error
if (false && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** static public function get_instance
* Returns the singleton instance
* of the Email Object as a reference
*
* @param void
* @action optionally creates the instance
* @return Email Object reference
*/
static public function get_instance( )
{
if (is_null(self::$_instance)) {
self::$_instance = new Email( );
}
return self::$_instance;
}
/** static public function send
* Static access for _send
*
* @param string message type
* @param mixed player id OR email address OR mixed array of both
* @param array optional message data
* @action send emails
* @return bool success
* @see _send
*/
static public function send($type, $to, $data = array( ))
{
call(__METHOD__);
call($type);
$_this = self::get_instance( );
return $_this->_send($type, $to, $data);
}
} // end of Email class
|
benjamw/pharaoh | 6627604c50bc8f580ad81f4ba917d494cd8dbbab | Fixed missing game ID issues | diff --git a/ajax_helper.php b/ajax_helper.php
index b1cb4de..15e8bc7 100644
--- a/ajax_helper.php
+++ b/ajax_helper.php
@@ -1,274 +1,281 @@
<?php
$GLOBALS['NODEBUG'] = true;
$GLOBALS['AJAX'] = true;
// don't require log in when testing for used usernames and emails
if (isset($_POST['validity_test']) || (isset($_GET['validity_test']) && isset($_GET['DEBUG']))) {
define('LOGIN', false);
}
require_once 'includes/inc.global.php';
// if we are debugging, change some things for us
// (although REQUEST_METHOD may not always be valid)
if (('GET' == $_SERVER['REQUEST_METHOD']) && test_debug( )) {
$GLOBALS['NODEBUG'] = false;
$GLOBALS['AJAX'] = false;
$_GET['token'] = $_SESSION['token'];
$_GET['keep_token'] = true;
$_POST = $_GET;
$DEBUG = true;
call('AJAX HELPER');
call($_POST);
}
// run the index page refresh checks
if (isset($_POST['timer'])) {
$message_count = (int) Message::check_new($_SESSION['player_id']);
$turn_count = (int) Game::check_turns($_SESSION['player_id']);
echo $message_count + $turn_count;
exit;
}
// run registration checks
if (isset($_POST['validity_test'])) {
# if (('email' == $_POST['type']) && ('' == $_POST['value'])) {
# echo 'OK';
# exit;
# }
$player_id = 0;
if ( ! empty($_POST['profile'])) {
$player_id = (int) $_SESSION['player_id'];
}
switch ($_POST['validity_test']) {
case 'username' :
case 'email' :
$username = '';
$email = '';
${$_POST['validity_test']} = sani($_POST['value']);
$player_id = (isset($_POST['player_id']) ? (int) $_POST['player_id'] : 0);
try {
Player::check_database($username, $email, $player_id);
}
catch (MyException $e) {
echo $e->getCode( );
exit;
}
break;
default :
break;
}
echo 'OK';
exit;
}
// run the in game chat
if (isset($_POST['chat'])) {
try {
if ( ! isset($_SESSION['game_id'])) {
$_SESSION['game_id'] = 0;
}
$Chat = new Chat((int) $_SESSION['player_id'], (int) $_SESSION['game_id']);
$Chat->send_message($_POST['chat'], isset($_POST['private']), isset($_POST['lobby']));
$return = $Chat->get_box_list(1);
$return = $return[0];
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup validation
if (isset($_POST['test_setup'])) {
try {
Setup::is_valid_reflection($_POST['setup'], $_POST['reflection']);
$return['valid'] = true;
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run setup laser test fire
if (isset($_POST['test_fire'])) {
try {
// returns laser_path and hits arrays
$return = Pharaoh::fire_laser($_POST['color'], $_POST['board']);
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
// run the invites stuff
if (isset($_POST['invite'])) {
if ('delete' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
Game::delete_invite($_POST['game_id']);
echo 'Invite Deleted';
}
else {
echo 'ERROR: Not your invite';
}
}
else if ('resend' == $_POST['invite']) {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'])) {
if (Game::resend_invite($_POST['game_id'])) {
echo 'Invite Resent';
}
else {
echo 'Could not resend invite';
}
}
else {
echo 'ERROR: Not your invite';
}
}
else {
// make sure we are one of the two people in the invite
if (Game::has_invite($_POST['game_id'], $_SESSION['player_id'], $accept = true)) {
if ($game_id = Game::accept_invite($_POST['game_id'])) { // single equals intended
echo $game_id;
}
else {
echo 'ERROR: Could not create game';
}
}
else {
echo 'ERROR: Not your invite';
}
}
exit;
}
+// we'll need a game id from here forward, so make sure we have one
+if (empty($_SESSION['game_id'])) {
+ echo 'ERROR: Game not found';
+ exit;
+}
+
+
// init our game
if ( ! isset($Game)) {
$Game = new Game((int) $_SESSION['game_id']);
}
// run the game refresh check
if (isset($_POST['refresh'])) {
echo $Game->last_move;
exit;
}
// do some validity checking
if (empty($DEBUG) && empty($_POST['notoken'])) {
test_token( ! empty($_POST['keep_token']));
}
if ($_POST['game_id'] != $_SESSION['game_id']) {
throw new MyException('ERROR: Incorrect game id given');
}
// make sure we are the player we say we are
// unless we're an admin, then it's ok
$player_id = (int) $_POST['player_id'];
if (($player_id != $_SESSION['player_id']) && ! $GLOBALS['Player']->is_admin) {
throw new MyException('ERROR: Incorrect player id given');
}
// run the simple button actions
$actions = array(
'nudge',
'resign',
'offer_draw',
'accept_draw',
'reject_draw',
'request_undo',
'accept_undo',
'reject_undo',
);
foreach ($actions as $action) {
if (isset($_POST[$action])) {
try {
$Game->{$action}($player_id);
echo 'OK';
}
catch (MyException $e) {
echo $e;
}
exit;
}
}
// run the game actions
if (isset($_POST['turn'])) {
$return = array( );
try {
if (false !== strpos($_POST['to'], 'split')) { // splitting obelisk
$to = substr($_POST['to'], 0, 2);
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.'.'.$to);
$Game->do_move($from.'.'.$to);
}
elseif ((string) $_POST['to'] === (string) (int) $_POST['to']) { // moving
$to = $_POST['to'];
call($to);
$from = Pharaoh::index_to_target($_POST['from']);
$to = Pharaoh::index_to_target($to);
call($from.':'.$to);
$Game->do_move($from.':'.$to);
}
else { // rotating
$target = Pharaoh::index_to_target($_POST['from']);
$dir = (int) ('r' == strtolower($_POST['to']));
call($target.'-'.$dir);
$Game->do_move($target.'-'.$dir);
}
$return['action'] = 'RELOAD';
}
catch (MyException $e) {
$return['error'] = 'ERROR: '.$e->outputMessage( );
}
echo json_encode($return);
exit;
}
|
benjamw/pharaoh | ce19d7dcef781c6086023baba3ce31c594ec5fff | changed no registrations wording | diff --git a/register.php b/register.php
index 0b5ee04..c9d1660 100644
--- a/register.php
+++ b/register.php
@@ -1,118 +1,118 @@
<?php
define('LOGIN', false);
require_once 'includes/inc.global.php';
// if we have a player_id in session, log them in, and check for admin
if ( ! empty($_SESSION['player_id'])) {
$GLOBALS['Player'] = new GamePlayer( );
// this will redirect to login if failed
$GLOBALS['Player']->log_in( );
}
$no_new_users = (false == Settings::read('new_users'));
$max_users_set = (0 != Settings::read('max_users'));
$max_users_reached = (GamePlayer::get_count( ) >= Settings::read('max_users'));
$not_admin = empty($GLOBALS['Player']) || ! $GLOBALS['Player']->is_admin;
if ($not_admin && ($no_new_users || ($max_users_set && $max_users_reached))) {
- Flash::store('Sorry, but we are not accepting new applications at this time.');
+ Flash::store('Sorry, but we are not accepting new registrations at this time.');
}
if ($not_admin && isset($_SESSION['player_id'])) {
$GLOBALS['Player'] = array( );
$_SESSION['player_id'] = false;
unset($_SESSION['player_id']);
unset($GLOBALS['Player']);
}
if (isset($_POST['register'])) {
test_token( );
// die spammers
if ('' != $_POST['website']) {
header('Location: http://www.searchbliss.com/spambot/spambot-stopper.asp');
exit;
}
try {
$GLOBALS['Player'] = new GamePlayer( );
$GLOBALS['Player']->register( );
$Message = new Message($GLOBALS['Player']->id, $GLOBALS['Player']->is_admin);
$Message->grab_global_messages( );
Flash::store('Registration Successful !', 'login.php');
}
catch (MyException $e) {
if ( ! defined('DEBUG') || ! DEBUG) {
Flash::store('Registration Failed !\n\n'.$e->outputMessage( ), true);
}
else {
call('REGISTRATION ATTEMPT REDIRECTED TO REGISTER AND QUIT');
call($e->getMessage( ));
}
}
exit;
}
$meta['title'] = 'Registration';
$meta['head_data'] = '
<script type="text/javascript">//<![CDATA[
var profile = 0;
//]]></script>
<script type="text/javascript" src="scripts/register.js"></script>
';
$meta['show_menu'] = false;
echo get_header($meta);
$hints = array(
'Please Register' ,
'You must remember your username and password to be able to gain access to '.GAME_NAME.' later.' ,
);
if (Settings::read('approve_users')) {
$hints[] = '<span class="notice">NOTE</span>: You will be unable to log in if your account has not been approved yet.';
$hints[] = 'You should receive an email when your account has been approved.';
}
if (Settings::read('expire_users')) {
$hints[] = '<span class="warning">WARNING!</span><br />Inactive accounts will be deleted after '.Settings::read('expire_users').' days.';
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv">
<input type="hidden" name="token" id="token" value="{$_SESSION['token']}" />
<input type="hidden" name="errors" id="errors" />
<div><label for="first_name">First Name</label><input type="text" id="first_name" name="first_name" maxlength="20" tabindex="1" /></div>
<div><label for="last_name">Last Name</label><input type="text" id="last_name" name="last_name" maxlength="20" tabindex="2" /></div>
<div><label for="username" class="req">Username</label><input type="text" id="username" name="username" maxlength="20" tabindex="3" /><span id="username_check" class="test"></span></div>
<div><label for="email" class="req">Email</label><input type="text" id="email" name="email" tabindex="4" /><span id="email_check" class="test"></span></div>
<div style="visibility:hidden;"><label for="website">Leave Blank</label><input type="text" id="website" name="website" /></div>
<div><label for="password" class="req">Password</label><input type="password" id="password" name="password" tabindex="5" /></div>
<div><label for="passworda" class="req">Confirmation</label><input type="password" id="passworda" name="passworda" tabindex="6" /></div>
<div><input type="submit" name="register" value="Submit" tabindex="7" /> <a href="login.php{$GLOBALS['_?_DEBUG_QUERY']}">Return to login</a></div>
</div></form>
EOF;
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
// don't use the usual footer
?>
<div id="footerspacer"> </div>
<div id="footer"> </div>
</div>
</body>
</html>
|
benjamw/pharaoh | 8a47ba06e379725032ed26d00b9885a2d748bd2d | moved form buttons under game board | diff --git a/game.php b/game.php
index 253fd0d..514e2b8 100644
--- a/game.php
+++ b/game.php
@@ -1,272 +1,272 @@
<?php
require_once 'includes/inc.global.php';
// grab the game id
if (isset($_GET['id'])) {
$_SESSION['game_id'] = (int) $_GET['id'];
}
elseif ( ! isset($_SESSION['game_id'])) {
if ( ! defined('DEBUG') || ! DEBUG) {
Flash::store('No Game Id Given !');
}
else {
call('NO GAME ID GIVEN');
}
exit;
}
// load the game
// always refresh the game data, there may be more than one person online
try {
$Game = new Game((int) $_SESSION['game_id']);
$players = $Game->get_players( );
}
catch (MyException $e) {
if ( ! defined('DEBUG') || ! DEBUG) {
Flash::store('Error Accessing Game !');
}
else {
call('ERROR ACCESSING GAME :'.$e->outputMessage( ));
}
exit;
}
// MOST FORM SUBMISSIONS ARE AJAXED THROUGH /scripts/game.js
// game buttons and moves are passed through the game controller
if ( ! $Game->is_player($_SESSION['player_id'])) {
$Game->watch_mode = true;
$chat_html = '';
unset($Chat);
}
if ( ! $Game->watch_mode || $GLOBALS['Player']->is_admin) {
$Chat = new Chat($_SESSION['player_id'], $_SESSION['game_id']);
$chat_data = $Chat->get_box_list( );
$chat_html = '
<div id="chatbox">
<form action="'.$_SERVER['REQUEST_URI'].'" method="post"><div>
<input id="chat" type="text" name="chat" />
<label for="private" class="inline"><input type="checkbox" name="private" id="private" value="yes" /> Private</label>
</div></form>
<dl id="chats">';
if (is_array($chat_data)) {
foreach ($chat_data as $chat) {
if ('' == $chat['username']) {
$chat['username'] = '[deleted]';
}
$color = 'blue';
if ( ! empty($players[$chat['player_id']]['color']) && ('white' == $players[$chat['player_id']]['color'])) {
$color = 'silver';
}
if ( ! empty($players[$chat['player_id']]['color']) && ('black' == $players[$chat['player_id']]['color'])) {
$color = 'red';
}
// preserve spaces in the chat text
$chat['message'] = htmlentities($chat['message'], ENT_QUOTES, 'ISO-8859-1', false);
$chat['message'] = str_replace("\t", ' ', $chat['message']);
$chat['message'] = str_replace(' ', ' ', $chat['message']);
$chat_html .= '
<dt class="'.substr($color, 0, 3).'"><span>'.$chat['create_date'].'</span> '.$chat['username'].'</dt>
<dd'.($chat['private'] ? ' class="private"' : '').'>'.$chat['message'].'</dd>';
}
}
$chat_html .= '
</dl> <!-- #chats -->
</div> <!-- #chatbox -->';
}
// build the history table
$history_html = '';
$moves = $Game->get_move_history( );
foreach ($moves as $i => $move) {
if ( ! is_array($move)) {
break;
}
$id = ($i * 2) + 1;
$history_html .= '
<tr>
<td class="turn">'.($i + 1).'</td>
<td id="mv_'.$id.'">'.$move[0].'</td>
<td'.( ! empty($move[1]) ? ' id="mv_'.($id + 1).'"' : '').'>'.$move[1].'</td>
</tr>';
}
$turn = $Game->get_turn( );
if ($Game->draw_offered( )) {
$turn = '<span>Draw Offered</span>';
}
elseif ($Game->undo_requested( )) {
$turn = '<span>Undo Requested</span>';
}
elseif ($GLOBALS['Player']->username == $turn) {
$turn = '<span class="'.$Game->get_color( ).'">Your turn</span>';
}
elseif ( ! $turn) {
$turn = '';
}
else {
$turn = '<span class="'.$Game->get_color(false).'">'.$turn.'\'s turn</span>';
}
if (in_array($Game->state, array('Finished', 'Draw'))) {
list($win_text, $win_class) = $Game->get_outcome($_SESSION['player_id']);
$turn = '<span class="'.$win_class.'">Game Over: '.$win_text.'</span>';
}
$extra_info = $Game->get_extra_info( );
$meta['title'] = htmlentities($Game->name, ENT_QUOTES, 'ISO-8859-1', false).' - #'.$_SESSION['game_id'];
$meta['show_menu'] = false;
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/game.css" />
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript">/*<![CDATA[*/
var draw_offered = '.json_encode($Game->draw_offered($_SESSION['player_id'])).';
var undo_requested = '.json_encode($Game->undo_requested($_SESSION['player_id'])).';
var color = "'.(isset($players[$_SESSION['player_id']]) ? (('white' == $players[$_SESSION['player_id']]['color']) ? 'silver' : 'red') : '').'";
var state = "'.(( ! $Game->watch_mode) ? (( ! $Game->paused) ? strtolower($Game->state) : 'paused') : 'watching').'";
var invert = '.(( ! empty($players[$_SESSION['player_id']]['color']) && ('black' == $players[$_SESSION['player_id']]['color'])) ? 'true' : 'false').';
var last_move = '.$Game->last_move.';
var my_turn = '.($Game->is_turn( ) ? 'true' : 'false').';
var game_history = '.$Game->get_history(true).';
var move_count = game_history.length;
var move_index = (move_count - 1);
var laser_battle = '.json_encode( !! $extra_info['battle_dead']).';
var move_sphynx = '.json_encode( !! $extra_info['move_sphynx']).';
/*]]>*/</script>
<script type="text/javascript" src="scripts/game.js"></script>
';
echo get_header($meta);
?>
<div id="contents">
<ul id="buttons">
<li><a href="index.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Main Page</a></li>
<li><a href="game.php<?php echo $GLOBALS['_?_DEBUG_QUERY']; ?>">Reload Game Board</a></li>
</ul>
<h2>Game #<?php echo $_SESSION['game_id'].': '.htmlentities($Game->name, ENT_QUOTES, 'ISO-8859-1', false); ?>
<span class="turn"><?php echo $turn; ?></span>
<span class="setup"><a href="#setup" class="fancybox"><?php echo $Game->get_setup_name( ); ?></a> <a href="help/pieces.help" class="help">?</a></span>
<span class="extra"><?php echo $Game->get_extra( ); ?></span>
</h2>
<div id="history" class="box">
<div>
<div>
<span id="first">|<</span>
<span id="prev5"><<</span>
<span id="prev"><</span>
<span id="next">></span>
<span id="next5">>></span>
<span id="last">>|</span>
</div>
<table>
<thead>
<tr>
<th>#</th>
<th>Silver</th>
<th>Red</th>
</tr>
</thead>
<tbody>
<?php echo $history_html; ?>
</tbody>
</table>
</div>
</div> <!-- #history -->
<div id="board_wrapper">
<div id="board"></div> <!-- #board -->
<div class="buttons">
<a href="javascript:;" id="invert" style="float:right;">Invert Board</a>
<a href="javascript:;" id="show_full">Show Full Move</a> | |
<a href="javascript:;" id="show_move">Show Move</a> |
<a href="javascript:;" id="clear_move">Clear Move</a> |
<a href="javascript:;" id="fire_laser">Fire Laser</a> |
<a href="javascript:;" id="clear_laser">Clear Laser</a>
</div> <!-- .buttons -->
- </div> <!-- #board_wrapper -->
- <?php echo $chat_html; ?>
+ <form id="game" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"><div class="formdiv">
+ <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
+ <input type="hidden" name="game_id" value="<?php echo $_SESSION['game_id']; ?>" />
+ <input type="hidden" name="player_id" value="<?php echo $_SESSION['player_id']; ?>" />
+ <input type="hidden" name="from" id="from" value="" />
+ <input type="hidden" name="to" id="to" value="" />
- <form id="game" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"><div class="formdiv">
- <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
- <input type="hidden" name="game_id" value="<?php echo $_SESSION['game_id']; ?>" />
- <input type="hidden" name="player_id" value="<?php echo $_SESSION['player_id']; ?>" />
- <input type="hidden" name="from" id="from" value="" />
- <input type="hidden" name="to" id="to" value="" />
+ <?php if (('Playing' == $Game->state) && $Game->is_player($_SESSION['player_id'])) { ?>
- <?php if (('Playing' == $Game->state) && $Game->is_player($_SESSION['player_id'])) { ?>
+ <?php if ( ! $Game->draw_offered( )) { ?>
- <?php if ( ! $Game->draw_offered( )) { ?>
+ <input type="button" name="offer_draw" id="offer_draw" value="Offer Draw" />
- <input type="button" name="offer_draw" id="offer_draw" value="Offer Draw" />
+ <?php } elseif ($Game->draw_offered($_SESSION['player_id'])) { ?>
- <?php } elseif ($Game->draw_offered($_SESSION['player_id'])) { ?>
+ <input type="button" name="accept_draw" id="accept_draw" value="Accept Draw Offer" />
+ <input type="button" name="reject_draw" id="reject_draw" value="Reject Draw Offer" />
- <input type="button" name="accept_draw" id="accept_draw" value="Accept Draw Offer" />
- <input type="button" name="reject_draw" id="reject_draw" value="Reject Draw Offer" />
+ <?php } ?>
- <?php } ?>
+ <?php if ( ! $Game->undo_requested( ) && ! $Game->is_turn( ) && ! empty($moves)) { ?>
- <?php if ( ! $Game->undo_requested( ) && ! $Game->is_turn( ) && ! empty($moves)) { ?>
+ <input type="button" name="request_undo" id="request_undo" value="Request Undo" />
- <input type="button" name="request_undo" id="request_undo" value="Request Undo" />
+ <?php } elseif ($Game->undo_requested($_SESSION['player_id'])) { ?>
- <?php } elseif ($Game->undo_requested($_SESSION['player_id'])) { ?>
+ <input type="button" name="accept_undo" id="accept_undo" value="Accept Undo Request" />
+ <input type="button" name="reject_undo" id="reject_undo" value="Reject Undo Request" />
- <input type="button" name="accept_undo" id="accept_undo" value="Accept Undo Request" />
- <input type="button" name="reject_undo" id="reject_undo" value="Reject Undo Request" />
+ <?php } ?>
- <?php } ?>
+ <input type="button" name="resign" id="resign" value="Resign" />
- <input type="button" name="resign" id="resign" value="Resign" />
+ <?php if ($Game->test_nudge( )) { ?>
- <?php if ($Game->test_nudge( )) { ?>
+ <input type="button" name="nudge" id="nudge" value="Nudge" />
- <input type="button" name="nudge" id="nudge" value="Nudge" />
+ <?php } ?>
<?php } ?>
- <?php } ?>
+ </div></form>
+ </div> <!-- #board_wrapper -->
- </div></form>
+ <?php echo $chat_html; ?>
</div> <!-- #contents -->
<script type="text/javascript">
document.write('<'+'div id="setup"'+'>'+create_board('<?php echo expandFEN($Game->get_setup( )); ?>', true)+'<'+'/'+'div'+'>');
// run draw offer alert
if (draw_offered && ('watching' != state)) {
alert('Your opponent has offered you a draw.\n\nMake your decision with the draw\nbuttons below the game board.');
}
// run undo request alert
if (undo_requested && ('watching' != state)) {
alert('Your opponent has requested an undo.\n\nMake your decision with the undo\nbuttons below the game board.');
}
</script>
<?php
call($GLOBALS);
echo get_footer( );
|
benjamw/pharaoh | 3100c6eb81db0b73327ac34088ec9fe45cfec28f | fixed issue with disappearing newly registered players | diff --git a/classes/gameplayer.class.php b/classes/gameplayer.class.php
index b6d4bb3..8e043e5 100644
--- a/classes/gameplayer.class.php
+++ b/classes/gameplayer.class.php
@@ -1,697 +1,701 @@
<?php
/*
+---------------------------------------------------------------------------
|
| gameplayer.class.php (php 5.x)
|
| by Benjam Welker
| http://iohelix.net
|
+---------------------------------------------------------------------------
|
| > Game Player Extension module for Pharaoh (Khet)
| > Date started: 2008-02-28
|
| > Module Version Number: 0.8.0
|
+---------------------------------------------------------------------------
*/
// TODO: comments & organize better
class GamePlayer
extends Player
{
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property EXTEND_TABLE
* Holds the player extend table name
*
* @var string
*/
const EXTEND_TABLE = T_PHARAOH;
/** protected property allow_email
* Flag shows whether or not to send emails to this player
*
* @var bool
*/
protected $allow_email;
/** protected property max_games
* Number of games player can be in at one time
*
* @var int
*/
protected $max_games;
/** protected property current_games
* Number of games player is currently playing in
*
* @var int
*/
protected $current_games;
/** protected property color
* Holds the players skin color preference
*
* @var string
*/
protected $color;
/** protected property wins
* Holds the players win count
*
* @var int
*/
protected $wins;
/** protected property draws
* Holds the players draw count
*
* @var int
*/
protected $draws;
/** protected property losses
* Holds the players loss count
*
* @var int
*/
protected $losses;
/** protected property last_online
* Holds the date the player was last online
*
* @var int (unix timestamp)
*/
protected $last_online;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param int optional player id
* @action instantiates object
* @return void
*/
public function __construct($id = null)
{
$this->_mysql = Mysql::get_instance( );
// check and make sure we have logged into this game before
if (0 != (int) $id) {
$query = "
SELECT COUNT(*)
FROM ".self::EXTEND_TABLE."
WHERE player_id = '{$id}'
";
$count = (int) $this->_mysql->fetch_value($query);
if (0 == $count) {
throw new MyException(__METHOD__.': '.GAME_NAME.' Player (#'.$id.') not found in database');
}
}
parent::__construct($id);
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action destroys object
* @return void
*/
public function __destruct( )
{
return; // until i can figure out WTF?
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
/** public function log_in
* Runs the parent's log_in function
* then, if success, tests game player
* database to see if this player has been
* here before, if not, it adds then to the
* database, and if so, refreshes the last_online value
*
* @param void
* @action logs the player in
* @action optionally adds new game player data to the database
* @return bool success
*/
public function log_in( )
{
// this will redirect and exit upon failure
parent::log_in( );
// test an arbitrary property for existence, so we don't _pull twice unnecessarily
if (is_null($this->color)) {
$this->_mysql->insert(self::EXTEND_TABLE, array('player_id' => $this->id));
$this->_pull( );
}
// don't update the last online time if we logged in as an admin
if ( ! isset($_SESSION['admin_id'])) {
$this->_mysql->insert(self::EXTEND_TABLE, array('last_online' => NULL), " WHERE player_id = '{$this->id}' ");
}
return true;
}
/** public function register
* Registers a new player in the extend table
* also calls the parent register function
* which performs some validity checks
*
* @param void
* @action creates a new player in the database
* @return bool success
*/
public function register( )
{
call(__METHOD__);
try {
parent::register( );
}
catch (MyException $e) {
call('Exception Thrown: '.$e->getMessage( ));
throw $e;
}
if ($this->id) {
+ // add the user to the table
$this->_mysql->insert(self::EXTEND_TABLE, array('player_id' => $this->id));
+
+ // update the last_online time so we don't break things later
+ $this->_mysql->insert(self::EXTEND_TABLE, array('last_online' => NULL), " WHERE player_id = '{$this->id}' ");
}
}
/** public function add_win
* Adds a win to this player's stats
* both here, and in the database
*
* @param void
* @action adds a win in the database
* @return void
*/
public function add_win( )
{
$this->wins++;
// note the trailing space on the field name, it's not a typo
$this->_mysql->insert(self::EXTEND_TABLE, array('wins ' => 'wins + 1'), " WHERE player_id = '{$this->id}' ");
}
/** public function add_draw
* Adds a draw to this player's stats
* both here, and in the database
*
* @param void
* @action adds a draw in the database
* @return void
*/
public function add_draw( )
{
$this->draws++;
// note the trailing space on the field name, it's not a typo
$this->_mysql->insert(self::EXTEND_TABLE, array('draws ' => 'draws + 1'), " WHERE player_id = '{$this->id}' ");
}
/** public function add_loss
* Adds a loss to this player's stats
* both here, and in the database
*
* @param void
* @action adds a loss in the database
* @return void
*/
public function add_loss( )
{
$this->losses++;
// note the trailing space on the field name, it's not a typo
$this->_mysql->insert(self::EXTEND_TABLE, array('losses ' => 'losses + 1'), " WHERE player_id = '{$this->id}' ");
}
/** public function admin_delete
* Deletes the given players from the players database
*
* @param mixed csv or array of player ids
* @action deletes the players from the database
* @return void
*/
public function admin_delete($player_ids)
{
call(__METHOD__);
// make sure the user doing this is an admin
if ( ! $this->is_admin) {
throw new MyException(__METHOD__.': Player is not an admin');
}
array_trim($player_ids, 'int');
$player_ids = Player::clean_deleted($player_ids);
if ( ! $player_ids) {
throw new MyException(__METHOD__.': No player IDs given');
}
$this->_mysql->delete(self::EXTEND_TABLE, " WHERE player_id IN (".implode(',', $player_ids).") ");
}
/** public function admin_add_admin
* Gives the given players admin status
*
* @param mixed csv or array of player ids
* @action gives the given players admin status
* @return void
*/
public function admin_add_admin($player_ids)
{
// make sure the user doing this is an admin
if ( ! $this->is_admin) {
throw new MyException(__METHOD__.': Player is not an admin');
}
array_trim($player_ids, 'int');
$player_ids[] = 0; // make sure we have at least one entry
if (isset($GLOBALS['_ROOT_ADMIN'])) {
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
WHERE username = '{$GLOBALS['_ROOT_ADMIN']}'
";
$player_ids[] = (int) $this->_mysql->fetch_value($query);
}
$this->_mysql->insert(self::EXTEND_TABLE, array('is_admin' => 1), " WHERE player_id IN (".implode(',', $player_ids).") ");
}
/** public function admin_remove_admin
* Removes admin status from the given players
*
* @param mixed csv or array of player ids
* @action removes the given players admin status
* @return void
*/
public function admin_remove_admin($player_ids)
{
// make sure the user doing this is an admin
if ( ! $this->is_admin) {
throw new MyException(__METHOD__.': Player is not an admin');
}
array_trim($player_ids, 'int');
$player_ids[] = 0; // make sure we have at least one entry
if (isset($GLOBALS['_ROOT_ADMIN'])) {
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
WHERE username = '{$GLOBALS['_ROOT_ADMIN']}'
";
$root_admin = (int) $this->_mysql->fetch_value($query);
if (in_array($root_admin, $player_ids)) {
unset($player_ids[array_search($root_admin, $player_ids)]);
}
}
// remove the player doing the removing
unset($player_ids[array_search($_SESSION['player_id'], $player_ids)]);
// remove the admin doing the removing
unset($player_ids[array_search($_SESSION['admin_id'], $player_ids)]);
$this->_mysql->insert(self::EXTEND_TABLE, array('is_admin' => 0), " WHERE player_id IN (".implode(',', $player_ids).") ");
}
/** public function save
* Saves all changed data to the database
*
* @param void
* @action saves the player data
* @return void
*/
public function save( )
{
// update the player data
$query = "
SELECT allow_email
, max_games
, color
FROM ".self::EXTEND_TABLE."
WHERE player_id = '{$this->id}'
";
$player = $this->_mysql->fetch_assoc($query);
if ( ! $player) {
throw new MyException(__METHOD__.': Player data not found for player #'.$this->id);
}
// TODO: test the last online date and make sure we still have valid data
$update_player = false;
if ((bool) $player['allow_email'] != $this->allow_email) {
$update_player['allow_email'] = (int) $this->allow_email;
}
if ($player['max_games'] != $this->max_games) {
$update_player['max_games'] = (int) $this->max_games;
}
if ($player['color'] != $this->color) {
$update_player['color'] = $this->color;
}
if ($update_player) {
$this->_mysql->insert(self::EXTEND_TABLE, $update_player, " WHERE player_id = '{$this->id}' ");
}
}
/** protected function _pull
* Pulls all game player data from the database
* as well as the parent's data
*
* @param void
* @action pulls the player data
* @action pulls the game player data
* @return void
*/
protected function _pull( )
{
parent::_pull( );
$query = "
SELECT *
FROM ".self::EXTEND_TABLE."
WHERE player_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
if ( ! $result) {
// TODO: find out what is going on here and fix.
# throw new MyException(__METHOD__.': Data not found in database (#'.$this->id.')');
return false;
}
$this->is_admin = ( ! $this->is_admin) ? (bool) $result['is_admin'] : true;
$this->allow_email = (bool) $result['allow_email'];
$this->max_games = (int) $result['max_games'];
$this->color = $result['color'];
$this->wins = (int) $result['wins'];
$this->draws = (int) $result['draws'];
$this->losses = (int) $result['losses'];
$this->last_online = strtotime($result['last_online']);
// grab the player's current game count
$query = "
SELECT COUNT(*)
FROM ".Game::GAME_TABLE." AS G
LEFT JOIN ".Game::GAME_HISTORY_TABLE." AS GH
USING (game_id)
WHERE ((G.white_id = '{$this->id}'
OR G.black_id = '{$this->id}')
AND GH.board IS NOT NULL)
AND G.state = 'Playing'
";
$this->current_games = $this->_mysql->fetch_value($query);
}
/**
* STATIC METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static public function get_list
* Returns a list array of all game players
* in the database
* This function supersedes the parent's function and
* just grabs the whole lot in one query
*
* @param bool restrict to approved players
* @return array game player list (or bool false on failure)
*/
static public function get_list($only_approved = false)
{
$Mysql = Mysql::get_instance( );
$WHERE = ($only_approved) ? " WHERE P.is_approved = 1 " : '';
$query = "
SELECT *
, P.is_admin AS full_admin
, E.is_admin AS half_admin
FROM ".Player::PLAYER_TABLE." AS P
INNER JOIN ".self::EXTEND_TABLE." AS E
USING (player_id)
{$WHERE}
ORDER BY P.username
";
$list = $Mysql->fetch_array($query);
return $list;
}
/** static public function get_count
* Returns a count of all game players
* in the database
*
* @param void
* @return int game player count
*/
static public function get_count( )
{
$Mysql = Mysql::get_instance( );
$query = "
SELECT COUNT(*)
FROM ".self::EXTEND_TABLE." AS E
JOIN ".Player::PLAYER_TABLE." AS P
USING (player_id)
WHERE P.is_approved = 1
-- TODO: AND E.is_approved = 1
";
$count = $Mysql->fetch_value($query);
return $count;
}
/** static public function get_maxed
* Returns an array of all player ids
* who have reached their max games count
*
* @param void
* @return array of int player ids
*/
static public function get_maxed( )
{
$Mysql = Mysql::get_instance( );
// run through the maxed invites and set the key
// to the player id and the value to the invite count
// for ease of use later
$invites = array( );
// TODO: set a setting for this
if (true || $invites_count_toward_max_games) {
$query = "
SELECT COUNT(G.game_id) AS invite_count
, PE.player_id
FROM ".Game::GAME_TABLE." AS G
LEFT JOIN ".self::EXTEND_TABLE." AS PE
ON (PE.player_id = G.white_id
OR PE.player_id = G.black_id)
WHERE G.state = 'Waiting'
AND PE.max_games > 0
GROUP BY PE.player_id
";
$maxed_invites = $Mysql->fetch_array($query);
foreach ($maxed_invites as $invite) {
$invites[$invite['player_id']] = $invite['invite_count'];
}
}
$query = "
SELECT COUNT(G.game_id) AS game_count
, PE.player_id
, PE.max_games
FROM ".Game::GAME_TABLE." AS G
LEFT JOIN ".self::EXTEND_TABLE." AS PE
ON (PE.player_id = G.white_id
OR PE.player_id = G.black_id)
WHERE G.state = 'Playing'
AND PE.max_games > 0
GROUP BY PE.player_id
";
$maxed_players = $Mysql->fetch_array($query);
$player_ids = array( );
foreach ($maxed_players as $data) {
if ( ! isset($invites[$data['player_id']])) {
$invites[$data['player_id']] = 0;
}
if (($data['game_count'] + $invites[$data['player_id']]) >= $data['max_games']) {
$player_ids[] = $data['player_id'];
}
}
return $player_ids;
}
/** static public function delete_inactive
* Deletes the inactive users from the database
*
* @param int age in days
* @return void
*/
static public function delete_inactive($age)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$age = (int) abs($age);
if (0 == $age) {
return false;
}
$exception_ids = array( );
// make sure the 'unused' player is not an admin
$query = "
SELECT EP.player_id
FROM ".self::EXTEND_TABLE." AS EP
JOIN ".Player::PLAYER_TABLE." AS P
USING (player_id)
WHERE P.is_admin = 1
OR EP.is_admin = 1
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
// make sure the 'unused' player is not currently in a game
$query = "
SELECT DISTINCT white_id
FROM ".Game::GAME_TABLE."
WHERE state = 'Playing'
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
$query = "
SELECT DISTINCT black_id
FROM ".Game::GAME_TABLE."
WHERE state = 'Playing'
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
// make sure the 'unused' player isn't awaiting approval
$query = "
SELECT player_id
FROM ".Player::PLAYER_TABLE."
WHERE is_approved = 0
";
$results = $Mysql->fetch_value_array($query);
$exception_ids = array_merge($exception_ids, $results);
$exception_ids[] = 0;
$exception_id_list = implode(',', $exception_ids);
// select unused accounts
$query = "
SELECT player_id
FROM ".self::EXTEND_TABLE."
WHERE wins + losses <= 2
AND player_id NOT IN ({$exception_id_list})
AND last_online < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
";
$player_ids = $Mysql->fetch_value_array($query);
call($player_ids);
if ($player_ids) {
Game::player_deleted($player_ids);
$Mysql->delete(self::EXTEND_TABLE, " WHERE player_id IN (".implode(',', $player_ids).") ");
}
}
} // end of GamePlayer class
/* schemas
// ===================================
--
-- Table structure for table `ph_ph_player`
--
DROP TABLE IF EXISTS `ph_ph_player`;
CREATE TABLE IF NOT EXISTS `ph_ph_player` (
`player_id` int(11) unsigned NOT NULL DEFAULT '0',
`is_admin` tinyint(1) unsigned NOT NULL DEFAULT '0',
`allow_email` tinyint(1) unsigned NOT NULL DEFAULT '1',
`max_games` tinyint(2) unsigned NOT NULL DEFAULT '0',
`color` varchar(25) NOT NULL DEFAULT 'blue_white',
`wins` smallint(5) unsigned NOT NULL DEFAULT '0',
`draws` smallint(5) unsigned NOT NULL DEFAULT '0',
`losses` smallint(5) unsigned NOT NULL DEFAULT '0',
`last_online` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `id` (`player_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
*/
|
benjamw/pharaoh | 245a867855ca5d653fa3b59fca6d278c7959726b | sorted games in reverse order | diff --git a/classes/game.class.php b/classes/game.class.php
index 87fbaef..680f96b 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1862,1025 +1862,1025 @@ class Game
}
else {
$result = '0-1';
}
}
elseif ('Draw' == $Game->state) {
$result = '1/2-1/2';
}
$body .= $line;
if ((strlen($line) + strlen($result)) > 79) {
$body .= "\n";
}
elseif (strlen($line) > 0) {
$body .= ' ';
}
$body .= $result . "\n";
$xheader .= "[Result \"$result\"]\n";
$data = $xheader . $xheadxtra . "\n" . $body;
$filename = GAMES_DIR."/Pharoah_Game_{$Game->id}_".str_replace(array(' ','-',':'), '', $Game->_history[count($Game->_history) - 1]['move_date']).'.pgn';
file_put_contents($filename, $data);
return $data;
}
protected function _gen_move_extra_info($curr_move, $prev_move = null)
{
call(__METHOD__);
$m_extra_info = self::$_HISTORY_EXTRA_INFO_DEFAULTS;
if ( ! $this->_extra_info['battle_dead']) {
return $m_extra_info;
}
if ( ! $curr_move) {
throw new MyException(__METHOD__.': Move data not present for calculation');
}
// set our current move extra info
if ($prev_move) {
$m_extra_info['dead_for'] = $prev_move['dead_for'];
$m_extra_info['immune_for'] = $prev_move['immune_for'];
}
$dead = false;
if ($m_extra_info['dead_for']) {
$dead = true;
}
if (0 < $m_extra_info['dead_for']) {
--$m_extra_info['dead_for'];
}
// we are allowed to shoot now, set our immunity
if ($dead && ! $m_extra_info['dead_for']) {
$m_extra_info['immune_for'] = $this->_extra_info['battle_immune'];
}
if ( ! $dead && (0 < $m_extra_info['immune_for'])) {
--$m_extra_info['immune_for'];
}
if ( ! $m_extra_info['dead_for'] && ! $m_extra_info['immune_for'] && $curr_move['laser_hit']) {
$m_extra_info['dead_for'] = $this->_extra_info['battle_dead'];
}
return $m_extra_info;
}
/** protected function _pull
* Pulls the data from the database
* and sets up the objects
*
* @param void
* @action pulls the game data
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return false;
}
if ( ! $_SESSION['player_id']) {
throw new MyException(__METHOD__.': Player id is not in session when pulling game data');
}
// grab the game data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
call($result);
if ( ! $result) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
if ('Waiting' == $result['state']) {
throw new MyException(__METHOD__.': Game (#'.$this->id.') is still only an invite');
}
// set the properties
$this->state = $result['state'];
$this->paused = (bool) $result['paused'];
$this->create_date = strtotime($result['create_date']);
$this->modify_date = strtotime($result['modify_date']);
$this->_extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($result['extra_info']));
// just empty this out, we don't need it anymore
$this->_extra_info['invite_setup'] = '';
// grab the initial setup
// TODO: convert to the setup object
// (need to build more in the setup object)
$query = "
SELECT *
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$result['setup_id']}'
";
$setup = $this->_mysql->fetch_assoc($query);
call($setup);
// the setup may have been deleted
if ( ! $setup) {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => '[DELETED]',
);
}
else {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => $setup['name'],
);
}
// set up the players
$this->_players['white']['player_id'] = $result['white_id'];
$this->_players['white']['object'] = new GamePlayer($result['white_id']);
$this->_players['silver'] = & $this->_players['white'];
$this->_players['black']['player_id'] = $result['black_id'];
if (0 != $result['black_id']) { // we may have an open game
$this->_players['black']['object'] = new GamePlayer($result['black_id']);
$this->_players['red'] = & $this->_players['black'];
}
// we test this first one against the black id, so if it fails because
// the person viewing the game is not playing in the game (viewing it
// after it's finished) we want "player" to be equal to "white"
if ($_SESSION['player_id'] == $result['black_id']) {
$this->_players['player'] = & $this->_players['black'];
$this->_players['player']['color'] = 'black';
$this->_players['player']['opp_color'] = 'white';
$this->_players['opponent'] = & $this->_players['white'];
$this->_players['opponent']['color'] = 'white';
$this->_players['opponent']['opp_color'] = 'black';
}
else {
$this->_players['player'] = & $this->_players['white'];
$this->_players['player']['color'] = 'white';
$this->_players['player']['opp_color'] = 'black';
$this->_players['opponent'] = & $this->_players['black'];
$this->_players['opponent']['color'] = 'black';
$this->_players['opponent']['opp_color'] = 'white';
}
// set up the board
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date ASC
";
$result = $this->_mysql->fetch_array($query);
call($result);
if ($result) {
$count = count($result);
// integrate the extra info into the history array
foreach ($result as & $move) {
$m_extra = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, unserialize($move['extra_info']));
$move = array_merge($move, $m_extra);
}
unset($move); // kill the reference
$this->_history = $result;
$this->turn = ((0 == ($count % 2)) ? 'black' : 'white');
$this->last_move = strtotime($result[$count - 1]['move_date']);
try {
$this->_pharaoh = new Pharaoh( );
$this->_pharaoh->set_board(expandFEN($this->_history[$count - 1]['board']));
$this->_pharaoh->set_extra_info($this->_extra_info);
}
catch (MyException $e) {
throw $e;
}
$m_extra_info = $this->_gen_move_extra_info($this->_history[$count - 1], (isset($this->_history[$count - 2]) ? $this->_history[$count - 2] : null));
$this->_current_move_extra_info = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, $m_extra_info);
}
else {
$this->last_move = $this->create_date;
}
$this->_players[$this->turn]['turn'] = true;
}
/** protected function _save
* Saves all changed data to the database
*
* @param void
* @action saves the game data
* @return void
*/
protected function _save( )
{
call(__METHOD__);
// grab the base game data
$query = "
SELECT state
, extra_info
, modify_date
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
AND state <> 'Waiting'
";
$game = $this->_mysql->fetch_assoc($query);
call($game);
$update_modified = false;
if ( ! $game) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
$this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date']));
// test the modified date and make sure we still have valid data
call($this->modify_date);
call(strtotime($game['modify_date']));
if ($this->modify_date != strtotime($game['modify_date'])) {
$this->_log('== FAILED ==');
throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data');
}
$update_game = false;
call($game['state']);
call($this->state);
if ($game['state'] != $this->state) {
$update_game['state'] = $this->state;
if ('Finished' == $this->state) {
$update_game['winner_id'] = $this->_players[$this->_pharaoh->winner]['player_id'];
}
if (in_array($this->state, array('Finished', 'Draw'))) {
try {
$this->_add_stats( );
}
catch (MyException $e) {
// do nothing, it gets logged
}
}
}
$diff = array_compare($this->_extra_info, self::$_EXTRA_INFO_DEFAULTS);
$update_game['extra_info'] = $diff[0];
ksort($update_game['extra_info']);
$update_game['extra_info'] = serialize($update_game['extra_info']);
if ('a:0:{}' == $update_game['extra_info']) {
$update_game['extra_info'] = null;
}
if (0 === strcmp($game['extra_info'], $update_game['extra_info'])) {
unset($update_game['extra_info']);
}
if ($update_game) {
$update_modified = true;
$this->_mysql->insert(self::GAME_TABLE, $update_game, " WHERE game_id = '{$this->id}' ");
}
// update the board
$color = $this->_players['player']['color'];
call($color);
call('IN-GAME SAVE');
// grab the current board from the database
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date DESC
LIMIT 1
";
$move = $this->_mysql->fetch_assoc($query);
$board = $move['board'];
call($board);
$new_board = packFEN($this->_pharaoh->get_board( ));
call($new_board);
list($new_move, $new_hits) = $this->_pharaoh->get_move( );
call($new_move);
call($new_hits);
if (is_array($new_hits)) {
$new_hits = implode(',', $new_hits);
}
if ($new_board != $board) {
call('UPDATED BOARD');
$update_modified = true;
$this->_current_move_extra_info['laser_fired'] = (bool) $this->can_fire_laser( );
$this->_current_move_extra_info['laser_hit'] = (bool) $this->_pharaoh->laser_hit;
$diff = array_compare($this->_current_move_extra_info, self::$_HISTORY_EXTRA_INFO_DEFAULTS);
$m_extra_info = $diff[0];
ksort($m_extra_info);
$m_extra_info = serialize($m_extra_info);
if ('a:0:{}' == $m_extra_info) {
$m_extra_info = null;
}
$this->_mysql->insert(self::GAME_HISTORY_TABLE, array('board' => $new_board, 'move' => $new_move, 'hits' => $new_hits, 'extra_info' => $m_extra_info, 'game_id' => $this->id));
}
// update the game modified date
if ($update_modified) {
$this->_mysql->insert(self::GAME_TABLE, array('modify_date' => NULL), " WHERE game_id = '{$this->id}' ");
}
}
/** protected function _add_stats
* Adds data to the stats table
*
* @param void
* @action adds stats to stats table
* @return void
*/
protected function _add_stats( )
{
call(__METHOD__);
call($this);
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
throw new MyException (__METHOD__.': Game (#'.$this->id.') is not finished ('.$this->state.')');
}
$count = count($this->_history) - 1;
$start = $end = $this->_history[0]['move_date'];
if ($count) {
$start = $this->_history[1]['move_date'];
$end = $this->_history[$count]['move_date'];
}
$start_unix = strtotime($start);
$end_unix = strtotime($end);
$hours = round(($end_unix - $start_unix) / (60 * 60), 3);
$stat = array(
'game_id' => $this->id,
'setup_id' => $this->_setup['id'],
'move_count' => $count,
'start_date' => $start,
'end_date' => $end,
'hour_count' => $hours,
);
$white_outcome = $black_outcome = 0;
if ('Finished' == $this->state) {
$white_outcome = 1;
$black_outcome = -1;
if ('red' == $this->_pharaoh->winner) {
$white_outcome = -1;
$black_outcome = 1;
}
}
$white = array_merge($stat, array(
'player_id' => $this->_players['white']['player_id'],
'color' => 'white',
'win' => $white_outcome,
));
call($white);
$this->_mysql->insert(self::GAME_STATS_TABLE, $white);
$black = array_merge($stat, array(
'player_id' => $this->_players['black']['player_id'],
'color' => 'black',
'win' => $black_outcome,
));
call($black);
$this->_mysql->insert(self::GAME_STATS_TABLE, $black);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
// log the error
if (false && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** protected function _diff
* Compares two boards are returns the
* indexes of any differences
*
* @param string board
* @param string board
* @return array of difference indexes
*/
protected function _diff($board1, $board2)
{
$diff = array( );
for ($i = 0, $length = strlen($board1); $i < $length; ++$i) {
if ($board1[$i] != $board2[$i]) {
$diff[] = $i;
}
}
call($diff);
return $diff;
}
/**
* STATIC METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static public function get_list
* Returns a list array of all the games in the database
* with games which need the users attention highlighted
*
* NOTE: $player_id is required when not pulling all games
* (when $all is false)
*
* @param int optional player's id
* @param bool optional pull all games (vs only given player's games)
* @return array game list (or bool false on failure)
*/
static public function get_list($player_id = 0, $all = true)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
if ( ! $all && ! $player_id) {
throw new MyException(__METHOD__.': Player ID required when not pulling all games');
}
$WHERE = " WHERE state <> 'Waiting' ";
if ( ! $all) {
$WHERE .= "
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id})
";
}
$query = "
SELECT G.*
, MAX(GH.move_date) AS last_move
, COUNT(GH.move_date) AS count
, 0 AS my_turn
, 0 AS in_game
, W.username AS white
, B.username AS black
, S.name AS setup_name
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_HISTORY_TABLE." AS GH
ON GH.game_id = G.game_id
LEFT JOIN ".Player::PLAYER_TABLE." AS W
ON W.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS B
ON B.player_id = G.black_id
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
{$WHERE}
GROUP BY G.game_id
ORDER BY G.state ASC
- , last_move ASC
+ , last_move DESC
";
$list = $Mysql->fetch_array($query);
if (0 != $player_id) {
// run though the list and find games the user needs action on
foreach ($list as & $game) {
$game['turn'] = (0 == ($game['count'] % 2)) ? 'black' : 'white';
$game['in_game'] = (int) (($player_id == $game['white_id']) || ($player_id == $game['black_id']));
$game['my_turn'] = (int) ( ! empty($game['turn']) && ($player_id == $game[$game['turn'].'_id']));
if (in_array($game['state'], array('Finished', 'Draw'))) {
$game['my_turn'] = 0;
}
$game['my_color'] = ($player_id == $game['white_id']) ? 'white' : 'black';
$game['opp_color'] = ($player_id == $game['white_id']) ? 'black' : 'white';
$game['opponent'] = ($player_id == $game['white_id']) ? $game['black'] : $game['white'];
}
unset($game); // kill the reference
}
// run through the games, and set the current player to the winner if the game is finished
// and fix the setup name if it was deleted
foreach ($list as & $game) {
if ('Finished' == $game['state']) {
if ($game['winner_id']) {
$game['turn'] = ($game['winner_id'] == $game['white_id']) ? 'white' : 'black';
}
else {
$game['turn'] = 'draw';
}
}
if ( ! $game['setup_name']) {
$game['setup_name'] = '[DELETED]';
}
}
unset($game); // kill the reference
return $list;
}
/** static public function get_player_stats_list
* Returns a list array of all game players
* in the database with additional stats added
*
* @param void
* @return array game player list (or bool false on failure)
*/
static public function get_player_stats_list( )
{
$Mysql = Mysql::get_instance( );
$players = GamePlayer::get_list(true);
if ($players) {
// add some more stats
$query = "
SELECT o.player_id
, COUNT(ww.win) AS white_wins
, COUNT(wl.win) AS white_losses
, COUNT(wd.win) AS white_draws
, COUNT(bw.win) AS black_wins
, COUNT(bl.win) AS black_losses
, COUNT(bd.win) AS black_draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.player_id = ww.player_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wl
ON (o.player_id = wl.player_id
AND o.game_id = wl.game_id
AND wl.win = -1
AND wl.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wd
ON (o.player_id = wd.player_id
AND o.game_id = wd.game_id
AND wd.win = 0
AND wd.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.player_id = bw.player_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bl
ON (o.player_id = bl.player_id
AND o.game_id = bl.game_id
AND bl.win = -1
AND bl.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bd
ON (o.player_id = bd.player_id
AND o.game_id = bd.game_id
AND bd.win = 0
AND bd.color = 'black')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['player_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'white_losses' => 0,
'white_draws' => 0,
'black_wins' => 0,
'black_losses' => 0,
'black_draws' => 0,
);
foreach ($players as & $player) { // be careful with the reference
if (isset($stats[$player['player_id']])) {
$player = array_merge($player, $stats[$player['player_id']]);
}
else {
$player = array_merge($player, $empty);
}
}
unset($player); // kill the reference
}
return $players;
}
/** static public function get_setup_stats_list
* Gets the list of all the setups with
* additional stats included in the list
*
* @param void
* @return array setups
*/
static public function get_setup_stats_list( )
{
$Mysql = Mysql::get_instance( );
$setups = Setup::get_list(true);
if ($setups) {
// add some more stats
$query = "
SELECT o.setup_id
, COUNT(ww.win) AS white_wins
, COUNT(bw.win) AS black_wins
, COUNT(d.win) AS draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.setup_id = ww.setup_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.setup_id = bw.setup_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS d
ON (o.setup_id = d.setup_id
AND o.game_id = d.game_id
AND d.win = 0
AND d.color = 'white')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['setup_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'black_wins' => 0,
'draws' => 0,
);
foreach ($setups as & $setup) { // be careful with the reference
if (isset($stats[$setup['setup_id']])) {
$setup = array_merge($setup, $stats[$setup['setup_id']]);
}
else {
$setup = array_merge($setup, $empty);
}
}
unset($setup); // kill the reference
}
return $setups;
}
/** static public function get_invites
* Returns a list array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite list
*/
static public function get_invites($player_id)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT G.*
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
, R.username AS invitor
, E.username AS invitee
, S.name AS setup
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
LEFT JOIN ".Player::PLAYER_TABLE." AS R
ON R.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS E
ON E.player_id = G.black_id
WHERE G.state = 'Waiting'
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id}
OR G.black_id IS NULL
OR G.black_id = FALSE
)
ORDER BY G.create_date DESC
";
$list = $Mysql->fetch_array($query);
call($list);
$in_vites = $out_vites = $open_vites = array( );
foreach ($list as $item) {
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($item['extra_info']));
$white_color = (('random' == $extra_info['white_color']) ? 'Random' : (('white' == $extra_info['white_color']) ? 'Silver' : 'Red'));
$black_color = (('random' == $extra_info['white_color']) ? 'Random' : (('white' == $extra_info['white_color']) ? 'Red' : 'Silver'));
$hover = array( );
if ( ! empty($item['extra_info'])) {
$hover = unserialize($item['extra_info']);
unset($hover['invite_setup']);
unset($hover['white_color']);
}
$hover_text = array( );
foreach ($hover as $key => $value) {
if (is_bool($value)) {
$value = ($value ? 'Yes' : 'No');
}
$hover_text[] = humanize($key).': '.$value;
}
$item['hover_text'] = implode(' | ', $hover_text);
$item['board'] = 'setup_display';
if ( ! empty($extra_info['invite_setup'])) {
$item['board'] = expandFEN($extra_info['invite_setup']);
}
if ($player_id == $item['white_id']) {
$item['color'] = $white_color;
$out_vites[] = $item;
}
elseif ($player_id == $item['black_id']) {
$item['color'] = $black_color;
$in_vites[] = $item;
}
else {
$item['color'] = $black_color;
$open_vites[] = $item;
}
}
return array($in_vites, $out_vites, $open_vites);
}
/** static public function get_invite_count
* Returns a count array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite count
*/
static public function get_invite_count($player_id)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE black_id = {$player_id}
AND state = 'Waiting'
";
$in_vites = (int) $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE white_id = {$player_id}
AND state = 'Waiting'
";
$out_vites = (int) $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE white_id <> '{$player_id}'
AND state = 'Waiting'
AND (black_id IS NULL
OR black_id = FALSE
)
";
$open_vites = (int) $Mysql->fetch_value($query);
return array($in_vites, $out_vites, $open_vites);
}
/** static public function get_count
* Returns a count of all games in the database,
* as well as the highest game id (the total number of games played)
*
* @param void
* @return array (int current game count, int total game count)
*/
static public function get_count( )
{
$Mysql = Mysql::get_instance( );
// games in play
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE state = 'Playing'
";
$count = (int) $Mysql->fetch_value($query);
// total games
$query = "
SELECT MAX(game_id)
FROM ".self::GAME_TABLE."
";
$next = (int) $Mysql->fetch_value($query);
return array($count, $next);
}
/** static public function check_turns
* Returns a count of all games
* in which it is the user's turn
*
* @param int player id
* @return int number of games with player action
*/
static public function check_turns($player_id)
{
$list = self::get_list($player_id, false);
$turn_count = array_sum_field($list, 'my_turn');
return $turn_count;
}
/** static public function get_my_count
* Returns a count of all given player's games in the database,
* as well as the games in which it is the player's turn
*
* @param int player id
* @return array (int player game count, int turn game count)
*/
static public function get_my_count($player_id)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
// games in play
$query = "
SELECT game_id
, IF(white_id = {$player_id}, 'silver', 'red') AS color
FROM ".self::GAME_TABLE."
WHERE state = 'Playing'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
)
";
$games = $Mysql->fetch_array($query);
$mine = count($games);
// games with turns
$turn = 0;
foreach ($games as $game) {
$query = "
SELECT COUNT(*)
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$game['game_id']}'
";
$count = (int) $Mysql->fetch_value($query);
$odd = (bool) ($count % 2);
if ((('silver' == $game['color']) && $odd)
|| (('red' == $game['color']) && ! $odd)) {
++$turn;
}
}
return array($mine, $turn);
}
/** public function delete_inactive
* Deletes the inactive games from the database
*
* @param int age in days (0 = disable)
* @action deletes the inactive games
* @return void
*/
static public function delete_inactive($age)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$age = (int) $age;
if ( ! $age) {
return;
}
// don't auto delete paused games or invites
$query = "
SELECT game_id
FROM ".self::GAME_TABLE."
WHERE state <> 'Waiting'
AND modify_date < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
AND create_date < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
AND paused = 0
";
$game_ids = $Mysql->fetch_value_array($query);
if ($game_ids) {
self::delete($game_ids);
}
}
/** public function delete_finished
* Deletes the finished games from the database
*
* @param int age in days (0 = disable)
* @action deletes the finished games
* @return void
*/
static public function delete_finished($age)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$age = (int) $age;
if ( ! $age) {
return;
}
$query = "
SELECT game_id
FROM ".self::GAME_TABLE."
WHERE state IN ('Finished', 'Draw')
AND modify_date < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
";
$game_ids = $Mysql->fetch_value_array($query);
if ($game_ids) {
self::delete($game_ids);
}
}
/** static public function delete
* Deletes the given game and all related data
*
* @param mixed array or csv of game ids
* @action deletes the game and all related data from the database
* @return void
*/
static public function delete($ids)
{
$Mysql = Mysql::get_instance( );
array_trim($ids, 'int');
if (empty($ids)) {
throw new MyException(__METHOD__.': No game ids given');
}
foreach ($ids as $id) {
try {
self::write_game_file($id);
}
catch (MyException $e) { }
}
$tables = array(
self::GAME_HISTORY_TABLE ,
|
benjamw/pharaoh | 7c8e3f2308bec32e4ff263b5cb33beb9bafbacdc | fixed stat error | diff --git a/classes/game.class.php b/classes/game.class.php
index 532f3e8..87fbaef 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -1721,1026 +1721,1030 @@ class Game
}
if ('Draw' == $this->state) {
return array('Draw Game', 'lost');
}
if ( ! empty($this->_pharaoh->winner) && isset($this->_players[$this->_pharaoh->winner]['player_id'])) {
$winner = $this->_players[$this->_pharaoh->winner]['player_id'];
}
else {
$query = "
SELECT G.winner_id
FROM ".self::GAME_TABLE." AS G
WHERE G.game_id = '{$this->id}'
";
$winner = $this->_mysql->fetch_value($query);
}
if ( ! $winner) {
return false;
}
if ($player_id == $winner) {
return array('You Won !', 'won');
}
else {
return array($GLOBALS['_PLAYERS'][$winner].' Won', 'lost');
}
}
/** static public function write_game_file
* Writes the game to a text file for storage
*
* @param int game id
* @action writes the game PGN file
* @return string PGN
*/
static public function write_game_file($game_id)
{
// the PGN export format is very exact when it comes to what is allowed
// and what is not allowed when creating a PGN file.
// first, the only new line character that is allowed is a single line feed character
// output in PHP as \n, this means that \r is not allowed, nor is \r\n
// second, no tab characters are allowed, neither vertical, nor horizontal (\t)
// third, comments do NOT nest, thus { { } } will be in error, as will { ; }
// fourth, { } denotes an inline comment, where ; denotes a 'rest of line' comment
// fifth, a percent sign (%) at the beginning of a line denotes a whole line comment
// sixth, comments may not be included in the meta tags ( [Meta "data"] )
$Mysql = Mysql::get_instance( );
if (empty($game_id)) {
throw new MyException(__METHOD__.': No game id given');
}
try {
$Game = new Game($game_id);
}
catch (MyException $e) {
throw $e;
}
if ( ! isset($Game->_history[1])) {
return false;
}
$start_date = date('Y-m-d', strtotime($Game->_history[1]['move_date']));
$white_name = $Game->_players['white']['object']->lastname.', '.$Game->_players['white']['object']->firstname.' ('.$Game->_players['white']['object']->username.')';
$black_name = $Game->_players['black']['object']->lastname.', '.$Game->_players['black']['object']->firstname.' ('.$Game->_players['black']['object']->username.')';
$extra_info = $Game->_extra_info;
$diff = array_compare($extra_info, self::$_EXTRA_INFO_DEFAULTS);
$extra_info = $diff[0];
unset($extra_info['white_color']);
unset($extra_info['draw_offered']);
unset($extra_info['undo_requested']);
$xheadxtra = '';
$xheader = "[Event \"Pharaoh (Khet) Casual Game #{$Game->id}\"]\n"
. "[Site \"{$GLOBALS['_ROOT_URI']}\"]\n"
. "[Date \"{$start_date}\"]\n"
. "[Round \"-\"]\n"
. "[White \"{$white_name}\"]\n"
. "[Black \"{$black_name}\"]\n"
. "[Setup \"{$Game->_history[0]['board']}\"]\n";
if ($extra_info) {
$options = serialize($extra_info);
$xheadxtra .= "[Options \"{$options}\"]\n";
}
$xheadxtra .= "[Mode \"ICS\"]\n";
$body = '';
$line = '';
$token = '';
foreach ($Game->_history as $key => $move) {
// skip the first entry
if ( ! $key) {
continue;
}
if (0 != ($key % 2)) {
$token = floor(($key + 1) / 2) . '. ' . $move['move'];
}
else {
$token .= ' ' . $move['move'];
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
}
if ($token) {
if ((strlen($line) + strlen($token)) > 79) {
$body .= $line . "\n";
$line = '';
}
elseif (strlen($line) > 0) {
$line .= ' ';
}
$line .= $token;
$token = '';
}
// finish up the PGN with the game result
$result = '*';
if ('Finished' == $Game->state) {
if ('white' == $Game->turn) {
$result = '1-0';
}
else {
$result = '0-1';
}
}
elseif ('Draw' == $Game->state) {
$result = '1/2-1/2';
}
$body .= $line;
if ((strlen($line) + strlen($result)) > 79) {
$body .= "\n";
}
elseif (strlen($line) > 0) {
$body .= ' ';
}
$body .= $result . "\n";
$xheader .= "[Result \"$result\"]\n";
$data = $xheader . $xheadxtra . "\n" . $body;
$filename = GAMES_DIR."/Pharoah_Game_{$Game->id}_".str_replace(array(' ','-',':'), '', $Game->_history[count($Game->_history) - 1]['move_date']).'.pgn';
file_put_contents($filename, $data);
return $data;
}
protected function _gen_move_extra_info($curr_move, $prev_move = null)
{
call(__METHOD__);
$m_extra_info = self::$_HISTORY_EXTRA_INFO_DEFAULTS;
if ( ! $this->_extra_info['battle_dead']) {
return $m_extra_info;
}
if ( ! $curr_move) {
throw new MyException(__METHOD__.': Move data not present for calculation');
}
// set our current move extra info
if ($prev_move) {
$m_extra_info['dead_for'] = $prev_move['dead_for'];
$m_extra_info['immune_for'] = $prev_move['immune_for'];
}
$dead = false;
if ($m_extra_info['dead_for']) {
$dead = true;
}
if (0 < $m_extra_info['dead_for']) {
--$m_extra_info['dead_for'];
}
// we are allowed to shoot now, set our immunity
if ($dead && ! $m_extra_info['dead_for']) {
$m_extra_info['immune_for'] = $this->_extra_info['battle_immune'];
}
if ( ! $dead && (0 < $m_extra_info['immune_for'])) {
--$m_extra_info['immune_for'];
}
if ( ! $m_extra_info['dead_for'] && ! $m_extra_info['immune_for'] && $curr_move['laser_hit']) {
$m_extra_info['dead_for'] = $this->_extra_info['battle_dead'];
}
return $m_extra_info;
}
/** protected function _pull
* Pulls the data from the database
* and sets up the objects
*
* @param void
* @action pulls the game data
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return false;
}
if ( ! $_SESSION['player_id']) {
throw new MyException(__METHOD__.': Player id is not in session when pulling game data');
}
// grab the game data
$query = "
SELECT *
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
";
$result = $this->_mysql->fetch_assoc($query);
call($result);
if ( ! $result) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
if ('Waiting' == $result['state']) {
throw new MyException(__METHOD__.': Game (#'.$this->id.') is still only an invite');
}
// set the properties
$this->state = $result['state'];
$this->paused = (bool) $result['paused'];
$this->create_date = strtotime($result['create_date']);
$this->modify_date = strtotime($result['modify_date']);
$this->_extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($result['extra_info']));
// just empty this out, we don't need it anymore
$this->_extra_info['invite_setup'] = '';
// grab the initial setup
// TODO: convert to the setup object
// (need to build more in the setup object)
$query = "
SELECT *
FROM ".Setup::SETUP_TABLE."
WHERE setup_id = '{$result['setup_id']}'
";
$setup = $this->_mysql->fetch_assoc($query);
call($setup);
// the setup may have been deleted
if ( ! $setup) {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => '[DELETED]',
);
}
else {
$this->_setup = array(
'id' => $result['setup_id'],
'name' => $setup['name'],
);
}
// set up the players
$this->_players['white']['player_id'] = $result['white_id'];
$this->_players['white']['object'] = new GamePlayer($result['white_id']);
$this->_players['silver'] = & $this->_players['white'];
$this->_players['black']['player_id'] = $result['black_id'];
if (0 != $result['black_id']) { // we may have an open game
$this->_players['black']['object'] = new GamePlayer($result['black_id']);
$this->_players['red'] = & $this->_players['black'];
}
// we test this first one against the black id, so if it fails because
// the person viewing the game is not playing in the game (viewing it
// after it's finished) we want "player" to be equal to "white"
if ($_SESSION['player_id'] == $result['black_id']) {
$this->_players['player'] = & $this->_players['black'];
$this->_players['player']['color'] = 'black';
$this->_players['player']['opp_color'] = 'white';
$this->_players['opponent'] = & $this->_players['white'];
$this->_players['opponent']['color'] = 'white';
$this->_players['opponent']['opp_color'] = 'black';
}
else {
$this->_players['player'] = & $this->_players['white'];
$this->_players['player']['color'] = 'white';
$this->_players['player']['opp_color'] = 'black';
$this->_players['opponent'] = & $this->_players['black'];
$this->_players['opponent']['color'] = 'black';
$this->_players['opponent']['opp_color'] = 'white';
}
// set up the board
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date ASC
";
$result = $this->_mysql->fetch_array($query);
call($result);
if ($result) {
$count = count($result);
// integrate the extra info into the history array
foreach ($result as & $move) {
$m_extra = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, unserialize($move['extra_info']));
$move = array_merge($move, $m_extra);
}
unset($move); // kill the reference
$this->_history = $result;
$this->turn = ((0 == ($count % 2)) ? 'black' : 'white');
$this->last_move = strtotime($result[$count - 1]['move_date']);
try {
$this->_pharaoh = new Pharaoh( );
$this->_pharaoh->set_board(expandFEN($this->_history[$count - 1]['board']));
$this->_pharaoh->set_extra_info($this->_extra_info);
}
catch (MyException $e) {
throw $e;
}
$m_extra_info = $this->_gen_move_extra_info($this->_history[$count - 1], (isset($this->_history[$count - 2]) ? $this->_history[$count - 2] : null));
$this->_current_move_extra_info = array_merge_plus(self::$_HISTORY_EXTRA_INFO_DEFAULTS, $m_extra_info);
}
else {
$this->last_move = $this->create_date;
}
$this->_players[$this->turn]['turn'] = true;
}
/** protected function _save
* Saves all changed data to the database
*
* @param void
* @action saves the game data
* @return void
*/
protected function _save( )
{
call(__METHOD__);
// grab the base game data
$query = "
SELECT state
, extra_info
, modify_date
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
AND state <> 'Waiting'
";
$game = $this->_mysql->fetch_assoc($query);
call($game);
$update_modified = false;
if ( ! $game) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
$this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date']));
// test the modified date and make sure we still have valid data
call($this->modify_date);
call(strtotime($game['modify_date']));
if ($this->modify_date != strtotime($game['modify_date'])) {
$this->_log('== FAILED ==');
throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data');
}
$update_game = false;
call($game['state']);
call($this->state);
if ($game['state'] != $this->state) {
$update_game['state'] = $this->state;
if ('Finished' == $this->state) {
$update_game['winner_id'] = $this->_players[$this->_pharaoh->winner]['player_id'];
}
if (in_array($this->state, array('Finished', 'Draw'))) {
try {
$this->_add_stats( );
}
catch (MyException $e) {
// do nothing, it gets logged
}
}
}
$diff = array_compare($this->_extra_info, self::$_EXTRA_INFO_DEFAULTS);
$update_game['extra_info'] = $diff[0];
ksort($update_game['extra_info']);
$update_game['extra_info'] = serialize($update_game['extra_info']);
if ('a:0:{}' == $update_game['extra_info']) {
$update_game['extra_info'] = null;
}
if (0 === strcmp($game['extra_info'], $update_game['extra_info'])) {
unset($update_game['extra_info']);
}
if ($update_game) {
$update_modified = true;
$this->_mysql->insert(self::GAME_TABLE, $update_game, " WHERE game_id = '{$this->id}' ");
}
// update the board
$color = $this->_players['player']['color'];
call($color);
call('IN-GAME SAVE');
// grab the current board from the database
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date DESC
LIMIT 1
";
$move = $this->_mysql->fetch_assoc($query);
$board = $move['board'];
call($board);
$new_board = packFEN($this->_pharaoh->get_board( ));
call($new_board);
list($new_move, $new_hits) = $this->_pharaoh->get_move( );
call($new_move);
call($new_hits);
if (is_array($new_hits)) {
$new_hits = implode(',', $new_hits);
}
if ($new_board != $board) {
call('UPDATED BOARD');
$update_modified = true;
$this->_current_move_extra_info['laser_fired'] = (bool) $this->can_fire_laser( );
$this->_current_move_extra_info['laser_hit'] = (bool) $this->_pharaoh->laser_hit;
$diff = array_compare($this->_current_move_extra_info, self::$_HISTORY_EXTRA_INFO_DEFAULTS);
$m_extra_info = $diff[0];
ksort($m_extra_info);
$m_extra_info = serialize($m_extra_info);
if ('a:0:{}' == $m_extra_info) {
$m_extra_info = null;
}
$this->_mysql->insert(self::GAME_HISTORY_TABLE, array('board' => $new_board, 'move' => $new_move, 'hits' => $new_hits, 'extra_info' => $m_extra_info, 'game_id' => $this->id));
}
// update the game modified date
if ($update_modified) {
$this->_mysql->insert(self::GAME_TABLE, array('modify_date' => NULL), " WHERE game_id = '{$this->id}' ");
}
}
/** protected function _add_stats
* Adds data to the stats table
*
* @param void
* @action adds stats to stats table
* @return void
*/
protected function _add_stats( )
{
call(__METHOD__);
call($this);
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
throw new MyException (__METHOD__.': Game (#'.$this->id.') is not finished ('.$this->state.')');
}
$count = count($this->_history) - 1;
- $start = $this->_history[1]['move_date'];
- $end = $this->_history[$count]['move_date'];
+
+ $start = $end = $this->_history[0]['move_date'];
+ if ($count) {
+ $start = $this->_history[1]['move_date'];
+ $end = $this->_history[$count]['move_date'];
+ }
$start_unix = strtotime($start);
$end_unix = strtotime($end);
$hours = round(($end_unix - $start_unix) / (60 * 60), 3);
$stat = array(
'game_id' => $this->id,
'setup_id' => $this->_setup['id'],
'move_count' => $count,
'start_date' => $start,
'end_date' => $end,
'hour_count' => $hours,
);
$white_outcome = $black_outcome = 0;
if ('Finished' == $this->state) {
$white_outcome = 1;
$black_outcome = -1;
if ('red' == $this->_pharaoh->winner) {
$white_outcome = -1;
$black_outcome = 1;
}
}
$white = array_merge($stat, array(
'player_id' => $this->_players['white']['player_id'],
'color' => 'white',
'win' => $white_outcome,
));
call($white);
$this->_mysql->insert(self::GAME_STATS_TABLE, $white);
$black = array_merge($stat, array(
'player_id' => $this->_players['black']['player_id'],
'color' => 'black',
'win' => $black_outcome,
));
call($black);
$this->_mysql->insert(self::GAME_STATS_TABLE, $black);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
// log the error
if (false && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** protected function _diff
* Compares two boards are returns the
* indexes of any differences
*
* @param string board
* @param string board
* @return array of difference indexes
*/
protected function _diff($board1, $board2)
{
$diff = array( );
for ($i = 0, $length = strlen($board1); $i < $length; ++$i) {
if ($board1[$i] != $board2[$i]) {
$diff[] = $i;
}
}
call($diff);
return $diff;
}
/**
* STATIC METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static public function get_list
* Returns a list array of all the games in the database
* with games which need the users attention highlighted
*
* NOTE: $player_id is required when not pulling all games
* (when $all is false)
*
* @param int optional player's id
* @param bool optional pull all games (vs only given player's games)
* @return array game list (or bool false on failure)
*/
static public function get_list($player_id = 0, $all = true)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
if ( ! $all && ! $player_id) {
throw new MyException(__METHOD__.': Player ID required when not pulling all games');
}
$WHERE = " WHERE state <> 'Waiting' ";
if ( ! $all) {
$WHERE .= "
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id})
";
}
$query = "
SELECT G.*
, MAX(GH.move_date) AS last_move
, COUNT(GH.move_date) AS count
, 0 AS my_turn
, 0 AS in_game
, W.username AS white
, B.username AS black
, S.name AS setup_name
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_HISTORY_TABLE." AS GH
ON GH.game_id = G.game_id
LEFT JOIN ".Player::PLAYER_TABLE." AS W
ON W.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS B
ON B.player_id = G.black_id
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
{$WHERE}
GROUP BY G.game_id
ORDER BY G.state ASC
, last_move ASC
";
$list = $Mysql->fetch_array($query);
if (0 != $player_id) {
// run though the list and find games the user needs action on
foreach ($list as & $game) {
$game['turn'] = (0 == ($game['count'] % 2)) ? 'black' : 'white';
$game['in_game'] = (int) (($player_id == $game['white_id']) || ($player_id == $game['black_id']));
$game['my_turn'] = (int) ( ! empty($game['turn']) && ($player_id == $game[$game['turn'].'_id']));
if (in_array($game['state'], array('Finished', 'Draw'))) {
$game['my_turn'] = 0;
}
$game['my_color'] = ($player_id == $game['white_id']) ? 'white' : 'black';
$game['opp_color'] = ($player_id == $game['white_id']) ? 'black' : 'white';
$game['opponent'] = ($player_id == $game['white_id']) ? $game['black'] : $game['white'];
}
unset($game); // kill the reference
}
// run through the games, and set the current player to the winner if the game is finished
// and fix the setup name if it was deleted
foreach ($list as & $game) {
if ('Finished' == $game['state']) {
if ($game['winner_id']) {
$game['turn'] = ($game['winner_id'] == $game['white_id']) ? 'white' : 'black';
}
else {
$game['turn'] = 'draw';
}
}
if ( ! $game['setup_name']) {
$game['setup_name'] = '[DELETED]';
}
}
unset($game); // kill the reference
return $list;
}
/** static public function get_player_stats_list
* Returns a list array of all game players
* in the database with additional stats added
*
* @param void
* @return array game player list (or bool false on failure)
*/
static public function get_player_stats_list( )
{
$Mysql = Mysql::get_instance( );
$players = GamePlayer::get_list(true);
if ($players) {
// add some more stats
$query = "
SELECT o.player_id
, COUNT(ww.win) AS white_wins
, COUNT(wl.win) AS white_losses
, COUNT(wd.win) AS white_draws
, COUNT(bw.win) AS black_wins
, COUNT(bl.win) AS black_losses
, COUNT(bd.win) AS black_draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.player_id = ww.player_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wl
ON (o.player_id = wl.player_id
AND o.game_id = wl.game_id
AND wl.win = -1
AND wl.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wd
ON (o.player_id = wd.player_id
AND o.game_id = wd.game_id
AND wd.win = 0
AND wd.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.player_id = bw.player_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bl
ON (o.player_id = bl.player_id
AND o.game_id = bl.game_id
AND bl.win = -1
AND bl.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bd
ON (o.player_id = bd.player_id
AND o.game_id = bd.game_id
AND bd.win = 0
AND bd.color = 'black')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['player_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'white_losses' => 0,
'white_draws' => 0,
'black_wins' => 0,
'black_losses' => 0,
'black_draws' => 0,
);
foreach ($players as & $player) { // be careful with the reference
if (isset($stats[$player['player_id']])) {
$player = array_merge($player, $stats[$player['player_id']]);
}
else {
$player = array_merge($player, $empty);
}
}
unset($player); // kill the reference
}
return $players;
}
/** static public function get_setup_stats_list
* Gets the list of all the setups with
* additional stats included in the list
*
* @param void
* @return array setups
*/
static public function get_setup_stats_list( )
{
$Mysql = Mysql::get_instance( );
$setups = Setup::get_list(true);
if ($setups) {
// add some more stats
$query = "
SELECT o.setup_id
, COUNT(ww.win) AS white_wins
, COUNT(bw.win) AS black_wins
, COUNT(d.win) AS draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.setup_id = ww.setup_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.setup_id = bw.setup_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS d
ON (o.setup_id = d.setup_id
AND o.game_id = d.game_id
AND d.win = 0
AND d.color = 'white')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['setup_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'black_wins' => 0,
'draws' => 0,
);
foreach ($setups as & $setup) { // be careful with the reference
if (isset($stats[$setup['setup_id']])) {
$setup = array_merge($setup, $stats[$setup['setup_id']]);
}
else {
$setup = array_merge($setup, $empty);
}
}
unset($setup); // kill the reference
}
return $setups;
}
/** static public function get_invites
* Returns a list array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite list
*/
static public function get_invites($player_id)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT G.*
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
, R.username AS invitor
, E.username AS invitee
, S.name AS setup
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
LEFT JOIN ".Player::PLAYER_TABLE." AS R
ON R.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS E
ON E.player_id = G.black_id
WHERE G.state = 'Waiting'
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id}
OR G.black_id IS NULL
OR G.black_id = FALSE
)
ORDER BY G.create_date DESC
";
$list = $Mysql->fetch_array($query);
call($list);
$in_vites = $out_vites = $open_vites = array( );
foreach ($list as $item) {
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($item['extra_info']));
$white_color = (('random' == $extra_info['white_color']) ? 'Random' : (('white' == $extra_info['white_color']) ? 'Silver' : 'Red'));
$black_color = (('random' == $extra_info['white_color']) ? 'Random' : (('white' == $extra_info['white_color']) ? 'Red' : 'Silver'));
$hover = array( );
if ( ! empty($item['extra_info'])) {
$hover = unserialize($item['extra_info']);
unset($hover['invite_setup']);
unset($hover['white_color']);
}
$hover_text = array( );
foreach ($hover as $key => $value) {
if (is_bool($value)) {
$value = ($value ? 'Yes' : 'No');
}
$hover_text[] = humanize($key).': '.$value;
}
$item['hover_text'] = implode(' | ', $hover_text);
$item['board'] = 'setup_display';
if ( ! empty($extra_info['invite_setup'])) {
$item['board'] = expandFEN($extra_info['invite_setup']);
}
if ($player_id == $item['white_id']) {
$item['color'] = $white_color;
$out_vites[] = $item;
}
elseif ($player_id == $item['black_id']) {
$item['color'] = $black_color;
$in_vites[] = $item;
}
else {
$item['color'] = $black_color;
$open_vites[] = $item;
}
}
return array($in_vites, $out_vites, $open_vites);
}
/** static public function get_invite_count
* Returns a count array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite count
*/
static public function get_invite_count($player_id)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE black_id = {$player_id}
AND state = 'Waiting'
";
$in_vites = (int) $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE white_id = {$player_id}
AND state = 'Waiting'
";
$out_vites = (int) $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE white_id <> '{$player_id}'
AND state = 'Waiting'
AND (black_id IS NULL
OR black_id = FALSE
)
";
$open_vites = (int) $Mysql->fetch_value($query);
return array($in_vites, $out_vites, $open_vites);
}
/** static public function get_count
* Returns a count of all games in the database,
* as well as the highest game id (the total number of games played)
*
* @param void
* @return array (int current game count, int total game count)
*/
static public function get_count( )
{
$Mysql = Mysql::get_instance( );
// games in play
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE state = 'Playing'
";
$count = (int) $Mysql->fetch_value($query);
// total games
$query = "
SELECT MAX(game_id)
FROM ".self::GAME_TABLE."
";
$next = (int) $Mysql->fetch_value($query);
return array($count, $next);
}
/** static public function check_turns
* Returns a count of all games
* in which it is the user's turn
*
* @param int player id
* @return int number of games with player action
*/
static public function check_turns($player_id)
{
$list = self::get_list($player_id, false);
$turn_count = array_sum_field($list, 'my_turn');
return $turn_count;
}
/** static public function get_my_count
* Returns a count of all given player's games in the database,
* as well as the games in which it is the player's turn
*
* @param int player id
* @return array (int player game count, int turn game count)
|
benjamw/pharaoh | 37268258ae362f18cd6813ad25671a7bf28450a5 | fixed some css issues | diff --git a/css/c_blue_black.css b/css/c_blue_black.css
index 04fc474..4537482 100644
--- a/css/c_blue_black.css
+++ b/css/c_blue_black.css
@@ -1 +1 @@
-html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #777777}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#3380d7}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #2473e3;background-color:#282828;background:-o-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-ms-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-moz-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-webkit-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:radial-gradient(50% 100%, ellipse cover, #165aa6 30%,#282828 80%) #282828}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(12,14,40,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#3380d7}nav#mygames .my_turn a{color:#3380d7}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#0b2d53;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333}
+html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #777777}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#3380d7}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #2473e3;background-color:#282828;background:-o-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-ms-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-moz-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-webkit-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:radial-gradient(50% 100%, ellipse cover, #165aa6 30%,#282828 80%) #282828}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(12,14,40,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#3380d7}nav#mygames .my_turn a{color:#3380d7}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#0b2d53;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333}
diff --git a/css/c_red_black.css b/css/c_red_black.css
index 1f6eb77..779e283 100644
--- a/css/c_red_black.css
+++ b/css/c_red_black.css
@@ -1 +1 @@
-html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #777777}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#b00}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #ce3e47;background-color:#670b0c;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(40,14,12,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#b00}nav#mygames .my_turn a{color:#b00}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#670b0c;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333}
+html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #777777}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#b00}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #ce3e47;background-color:#670b0c;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(0,0,0,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(40,14,12,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#b00}nav#mygames .my_turn a{color:#b00}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#670b0c;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333;border-width:0 1px}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333}
diff --git a/css/scss/_c_template.scss b/css/scss/_c_template.scss
index 3e59de2..e5ab25d 100644
--- a/css/scss/_c_template.scss
+++ b/css/scss/_c_template.scss
@@ -1,302 +1,303 @@
/* Pharaoh color style */
/*
color style sheet template
*/
// set our default styles for red_black
$text_color: #FFF !default;
$link_color: $text_color !default;
$background_color: #27282B !default;
$basic_border: 1px solid #777 !default;
$h2_border: $basic_border !default;
$main_back_color: #670B0C !default;
$main_highlight_color: #A72819 !default;
$main_shadow_color: #000 !default;
$main_link_color: #DDD !default;
$main_link_hover_color: #FFF !default;
$help_border: $basic_border !default;
$help_hover_border: 1px solid #999 !default;
$abbr_border: 1px dashed #777;
$hr_fancy_back: #999 !default;
$hr_fancy_border: $basic_border;
$fieldset_border: $basic_border !default;
$warning_color: #B00 !default;
$notice_color: #DD0 !default;
$highlight_color: #B00 !default;
$instruction_color: #AAA !default;
$header_background_color: $main_back_color !default;
$header_highlight_color: $main_highlight_color !default;
$header_border_bottom: 1px solid #CE3E47 !default;
$header_h1_height: 45px !default;
$header_logo: url(../images/Pharaoh.png) !default;
$site_nav_link_color: $main_link_color !default;
$site_nav_link_hover_color: $main_link_hover_color !default;
$site_nav_text_shadow: $main_shadow_color 0 1px 1px !default;
$site_nav_hover_shadow_color: rgba(255, 255, 255, 0.35) !default;
$site_nav_hover_edge_shadow_color: rgba(255, 255, 255, 0.01) !default;
$box_border_gradient_background_color: $main_shadow_color !default;
$box_border_gradient_highlight_color: #232323 !default;
$box_gradient_background_color: #2E2F34 !default;
$box_gradient_highlight_color: #212225 !default;
-$box_highlight_dark_color: rgba(255, 255, 255, 0.1) !default;
-$box_highlight_light_color: rgba(255, 255, 255, 0.2) !default;
+$box_highlight_top_color: rgba(255, 255, 255, 0.1) !default;
+$box_highlight_bottom_color: rgba(0, 0, 0, 0.2) !default;
$nav_link_color: $main_link_color !default;
$nav_background_color: transparent !default;
$nav_separator: 1px solid #333 !default;
$nav_hover_color: $main_link_hover_color !default;
$nav_hover_background_color: rgba(40, 14, 12, 0.5) !default;
$nav_active_color: inherit !default;
$nav_active_background_color: rgba(255, 255, 255, 0.1) !default;
$nav_data_separator_color: #666 !default;
$chatbox_border: $basic_border !default;
$chatbox_item_border: $chatbox_border !default;
$chatbox_item_background_color: transparent !default;
$side_chat_background_color: #EEE !default;
$side_chat_border: $basic_border !default;
$finished_games_color: #999 !default;
$playing_games_color: $highlight_color !default;
$my_turn_games_color: $playing_games_color !default;
$main_games_color: $text_color !default;
$footer_color: $main_link_color !default;
$footer_background_color: $main_back_color !default;
$footer_shadow_color: $main_shadow_color !default;
// now create the styles
html, body {
background-color: $background_color;
color: $text_color;
}
a {
color: $link_color;
&.help {
border: $help_border;
&:hover {
border: $help_hover_border;
}
}
}
abbr,
acronym {
border-bottom: $abbr_border;
}
hr {
&.fancy {
background-color: $hr_fancy_back;
border: $hr_fancy_border;
}
}
fieldset {
border: $fieldset_border;
}
.warning, .warning * {
color: $warning_color;
}
.notice, .notice * {
color: $notice_color;
}
.highlight, .highlight * {
color: $highlight_color;
}
.instruction, .instruction * {
color: $instruction_color;
}
header {
border-bottom: $header_border_bottom;
background-color: $header_background_color;
background: -o-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
background: -ms-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
background: -moz-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
background: -webkit-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
background: radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
}
h1 {
height: $header_h1_height;
a {
background-image: $header_logo;
}
}
nav.site {
a {
color: $site_nav_link_color;
text-shadow: $site_nav_text_shadow;
&:hover {
color: $site_nav_link_hover_color;
background: -o-radial-gradient(50% 90%, ellipse closest-corner, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
background: -ms-radial-gradient(50% 90%, ellipse closest-corner, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
background: -moz-radial-gradient(50% 90%, ellipse closest-corner, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
background: -webkit-radial-gradient(50% 100%, 80% 20%, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
background: radial-gradient(50% 100%, 80% 20%, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
}
}
}
*.box {
background-color: $box_border_gradient_background_color;
background: -o-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
background: -ms-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
background: -moz-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
background: -webkit-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
background: linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
& > * {
background-color: $box_gradient_background_color;
background: -o-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
background: -ms-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
background: -moz-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
background: -webkit-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
background: linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
- -o-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
- -ms-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
- -moz-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
- -webkit-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
- box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
+ -o-box-shadow: 0px 1px 0px $box_highlight_top_color inset, 0px -2px 1px $box_highlight_bottom_color inset;
+ -ms-box-shadow: 0px 1px 0px $box_highlight_top_color inset, 0px -2px 1px $box_highlight_bottom_color inset;
+ -moz-box-shadow: 0px 1px 0px $box_highlight_top_color inset, 0px -2px 1px $box_highlight_bottom_color inset;
+ -webkit-box-shadow: 0px 1px 0px $box_highlight_top_color inset, 0px -2px 1px $box_highlight_bottom_color inset;
+ box-shadow: 0px 1px 0px $box_highlight_top_color inset, 0px -2px 1px $box_highlight_bottom_color inset;
}
}
nav#menu ,
nav#mygames {
a {
color: $nav_link_color;
background-color: $nav_background_color;
border-bottom: $nav_separator;
&:hover {
color: $nav_hover_color;
background-color: $nav_hover_background_color;
}
}
li {
&.active {
a {
color: $nav_active_color;
background-color: $nav_active_background_color;
}
}
span.sep {
color: $nav_data_separator_color;
}
}
}
nav#mygames {
.finished a { color: $finished_games_color; }
.playing a { color: $playing_games_color; }
.my_turn a { color: $my_turn_games_color; }
.none a { color: $main_games_color; }
}
aside#info {
#chatbox {
background-color: $side_chat_background_color;
border: $side_chat_border;
}
}
h2 {
border-bottom: $h2_border;
}
#index_page {
#chatbox {
border: $chatbox_border;
}
#chats {
border-top: $chatbox_item_border;
dt {
border-bottom: $chatbox_item_border;
background: $chatbox_item_background_color;
}
dd {
border-bottom: $chatbox_item_border;
}
}
}
footer {
color: $footer_color;
background-color: $footer_background_color;
-o-box-shadow: 0px 3px 16px $footer_shadow_color inset;
-ms-box-shadow: 0px 3px 16px $footer_shadow_color inset;
-moz-box-shadow: 0px 3px 16px $footer_shadow_color inset;
-webkit-box-shadow: 0px 3px 16px $footer_shadow_color inset;
box-shadow: 0px 3px 16px $footer_shadow_color inset;
}
#buttons {
a {
border: $nav_separator;
+ border-width: 0 1px; /* because we override this with the above property */
}
}
@import "c_game_template"
|
benjamw/pharaoh | ccb0ca2dd06fdb293fd8981b84e67dcf0392966a | added ability for colors and two color schemes | diff --git a/css/c_blue_black.css b/css/c_blue_black.css
new file mode 100644
index 0000000..04fc474
--- /dev/null
+++ b/css/c_blue_black.css
@@ -0,0 +1 @@
+html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #777777}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#3380d7}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #2473e3;background-color:#282828;background:-o-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-ms-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-moz-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:-webkit-radial-gradient(50% 100%, ellipse cover, #165aa6 30%, #282828 80%) #282828;background:radial-gradient(50% 100%, ellipse cover, #165aa6 30%,#282828 80%) #282828}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(12,14,40,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#3380d7}nav#mygames .my_turn a{color:#3380d7}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#0b2d53;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333}
diff --git a/css/c_red_black.css b/css/c_red_black.css
new file mode 100644
index 0000000..1f6eb77
--- /dev/null
+++ b/css/c_red_black.css
@@ -0,0 +1 @@
+html,body{background-color:#27282b;color:#fff}a{color:#fff}a.help{border:1px solid #777777}a.help:hover{border:1px solid #999999}abbr,acronym{border-bottom:1px dashed #777777}hr.fancy{background-color:#999;border:1px solid #777777}fieldset{border:1px solid #777777}.warning,.warning *{color:#b00}.notice,.notice *{color:#dd0}.highlight,.highlight *{color:#b00}.instruction,.instruction *{color:#aaa}header{border-bottom:1px solid #ce3e47;background-color:#670b0c;background:-o-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-ms-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-moz-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:-webkit-radial-gradient(50% 100%, ellipse cover, #a72819 30%, #670b0c 80%) #670b0c;background:radial-gradient(50% 100%, ellipse cover, #a72819 30%,#670b0c 80%) #670b0c}h1{height:45px}h1 a{background-image:url(../images/Pharaoh.png)}nav.site a{color:#ddd;text-shadow:black 0 1px 1px}nav.site a:hover{color:#fff;background:-o-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-ms-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-moz-radial-gradient(50% 90%, ellipse closest-corner, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:-webkit-radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%, rgba(255,255,255,0.01) 70%) transparent;background:radial-gradient(50% 100%, 80% 20%, rgba(255,255,255,0.35) 30%,rgba(255,255,255,0.01) 70%) transparent}*.box{background-color:black;background:-o-linear-gradient(#232323, black) #000;background:-ms-linear-gradient(#232323, #000) #000;background:-moz-linear-gradient(#232323, #000) #000;background:-webkit-linear-gradient(#232323, #000) #000;background:linear-gradient(#232323,#000000) #000}*.box > *{background-color:#2e2f34;background:-o-linear-gradient(#2e2f34, #212225) #2e2f34;background:-ms-linear-gradient(#2e2f34, #212225) #2e2f34;background:-moz-linear-gradient(#2e2f34, #212225) #2e2f34;background:-webkit-linear-gradient(#2e2f34, #212225) #2e2f34;background:linear-gradient(#2e2f34,#212225) #2e2f34;-o-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-ms-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-moz-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;-webkit-box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset;box-shadow:0px 1px 0px rgba(255,255,255,0.1) inset,0px -2px 1px rgba(255,255,255,0.2) inset}nav#menu a,nav#mygames a{color:#ddd;background-color:transparent;border-bottom:1px solid #333333}nav#menu a:hover,nav#mygames a:hover{color:#fff;background-color:rgba(40,14,12,0.5)}nav#menu li.active a,nav#mygames li.active a{color:inherit;background-color:rgba(255,255,255,0.1)}nav#menu li span.sep,nav#mygames li span.sep{color:#666}nav#mygames .finished a{color:#999}nav#mygames .playing a{color:#b00}nav#mygames .my_turn a{color:#b00}nav#mygames .none a{color:#fff}aside#info #chatbox{background-color:#eee;border:1px solid #777777}h2{border-bottom:1px solid #777777}#index_page #chatbox{border:1px solid #777777}#index_page #chats{border-top:1px solid #777777}#index_page #chats dt{border-bottom:1px solid #777777;background:transparent}#index_page #chats dd{border-bottom:1px solid #777777}footer{color:#ddd;background-color:#670b0c;-o-box-shadow:0px 3px 16px #000 inset;-ms-box-shadow:0px 3px 16px #000 inset;-moz-box-shadow:0px 3px 16px #000 inset;-webkit-box-shadow:0px 3px 16px #000 inset;box-shadow:0px 3px 16px #000 inset}#buttons a{border:1px solid #333333}#history table td.active,#history table td:hover{background-color:#444;color:#fff}#history div div span{border:1px solid #555555}#history div div span:hover{border-color:#aaa}#history div div span.disabled{color:#aaa;border-color:#333}
diff --git a/css/scss/_c_game_template.scss b/css/scss/_c_game_template.scss
new file mode 100644
index 0000000..0966689
--- /dev/null
+++ b/css/scss/_c_game_template.scss
@@ -0,0 +1,48 @@
+
+/* Pharaoh color style */
+
+/*
+ game color style sheet template
+*/
+
+// set our default styles for red_black
+
+$history_active_color: #FFF !default;
+$history_active_background_color: #444 !default;
+
+$history_replay_border: 1px solid #555 !default;
+$history_replay_hover_border_color: #AAA !default;
+
+$history_replay_disabled_color: #AAA !default;
+$history_replay_disabled_border_color: #333 !default;
+
+
+// now make the styles
+
+#history {
+ table {
+ td {
+ &.active,
+ &:hover {
+ background-color: $history_active_background_color;
+ color: $history_active_color;
+ }
+ }
+ }
+
+ div div {
+ span {
+ border: $history_replay_border;
+
+ &:hover {
+ border-color: $history_replay_hover_border_color;
+ }
+
+ &.disabled {
+ color: $history_replay_disabled_color;
+ border-color: $history_replay_disabled_border_color;
+ }
+ }
+ }
+}
+
diff --git a/css/scss/_c_template.scss b/css/scss/_c_template.scss
new file mode 100644
index 0000000..3e59de2
--- /dev/null
+++ b/css/scss/_c_template.scss
@@ -0,0 +1,302 @@
+
+/* Pharaoh color style */
+
+/*
+ color style sheet template
+*/
+
+// set our default styles for red_black
+
+$text_color: #FFF !default;
+$link_color: $text_color !default;
+$background_color: #27282B !default;
+
+$basic_border: 1px solid #777 !default;
+$h2_border: $basic_border !default;
+
+$main_back_color: #670B0C !default;
+$main_highlight_color: #A72819 !default;
+$main_shadow_color: #000 !default;
+
+$main_link_color: #DDD !default;
+$main_link_hover_color: #FFF !default;
+
+$help_border: $basic_border !default;
+$help_hover_border: 1px solid #999 !default;
+
+$abbr_border: 1px dashed #777;
+
+$hr_fancy_back: #999 !default;
+$hr_fancy_border: $basic_border;
+
+$fieldset_border: $basic_border !default;
+
+$warning_color: #B00 !default;
+$notice_color: #DD0 !default;
+$highlight_color: #B00 !default;
+
+$instruction_color: #AAA !default;
+
+$header_background_color: $main_back_color !default;
+$header_highlight_color: $main_highlight_color !default;
+$header_border_bottom: 1px solid #CE3E47 !default;
+
+$header_h1_height: 45px !default;
+$header_logo: url(../images/Pharaoh.png) !default;
+
+$site_nav_link_color: $main_link_color !default;
+$site_nav_link_hover_color: $main_link_hover_color !default;
+$site_nav_text_shadow: $main_shadow_color 0 1px 1px !default;
+$site_nav_hover_shadow_color: rgba(255, 255, 255, 0.35) !default;
+$site_nav_hover_edge_shadow_color: rgba(255, 255, 255, 0.01) !default;
+
+$box_border_gradient_background_color: $main_shadow_color !default;
+$box_border_gradient_highlight_color: #232323 !default;
+$box_gradient_background_color: #2E2F34 !default;
+$box_gradient_highlight_color: #212225 !default;
+$box_highlight_dark_color: rgba(255, 255, 255, 0.1) !default;
+$box_highlight_light_color: rgba(255, 255, 255, 0.2) !default;
+
+$nav_link_color: $main_link_color !default;
+$nav_background_color: transparent !default;
+$nav_separator: 1px solid #333 !default;
+$nav_hover_color: $main_link_hover_color !default;
+$nav_hover_background_color: rgba(40, 14, 12, 0.5) !default;
+$nav_active_color: inherit !default;
+$nav_active_background_color: rgba(255, 255, 255, 0.1) !default;
+$nav_data_separator_color: #666 !default;
+
+$chatbox_border: $basic_border !default;
+$chatbox_item_border: $chatbox_border !default;
+$chatbox_item_background_color: transparent !default;
+
+$side_chat_background_color: #EEE !default;
+$side_chat_border: $basic_border !default;
+
+$finished_games_color: #999 !default;
+$playing_games_color: $highlight_color !default;
+$my_turn_games_color: $playing_games_color !default;
+$main_games_color: $text_color !default;
+
+$footer_color: $main_link_color !default;
+$footer_background_color: $main_back_color !default;
+$footer_shadow_color: $main_shadow_color !default;
+
+
+
+// now create the styles
+
+html, body {
+ background-color: $background_color;
+ color: $text_color;
+}
+
+
+a {
+ color: $link_color;
+
+ &.help {
+ border: $help_border;
+
+ &:hover {
+ border: $help_hover_border;
+ }
+ }
+}
+
+
+abbr,
+acronym {
+ border-bottom: $abbr_border;
+}
+
+
+hr {
+ &.fancy {
+ background-color: $hr_fancy_back;
+ border: $hr_fancy_border;
+ }
+}
+
+
+fieldset {
+ border: $fieldset_border;
+}
+
+
+.warning, .warning * {
+ color: $warning_color;
+}
+
+
+.notice, .notice * {
+ color: $notice_color;
+}
+
+
+.highlight, .highlight * {
+ color: $highlight_color;
+}
+
+
+.instruction, .instruction * {
+ color: $instruction_color;
+}
+
+
+header {
+ border-bottom: $header_border_bottom;
+
+ background-color: $header_background_color;
+ background: -o-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
+ background: -ms-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
+ background: -moz-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
+ background: -webkit-radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
+ background: radial-gradient(50% 100%, ellipse cover, $header_highlight_color 30%, $header_background_color 80%) $header_background_color;
+}
+
+
+h1 {
+ height: $header_h1_height;
+
+ a {
+ background-image: $header_logo;
+ }
+}
+
+
+nav.site {
+ a {
+ color: $site_nav_link_color;
+
+ text-shadow: $site_nav_text_shadow;
+
+ &:hover {
+ color: $site_nav_link_hover_color;
+
+ background: -o-radial-gradient(50% 90%, ellipse closest-corner, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
+ background: -ms-radial-gradient(50% 90%, ellipse closest-corner, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
+ background: -moz-radial-gradient(50% 90%, ellipse closest-corner, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
+ background: -webkit-radial-gradient(50% 100%, 80% 20%, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
+ background: radial-gradient(50% 100%, 80% 20%, $site_nav_hover_shadow_color 30%, $site_nav_hover_edge_shadow_color 70%) transparent;
+ }
+ }
+}
+
+
+*.box {
+ background-color: $box_border_gradient_background_color;
+ background: -o-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
+ background: -ms-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
+ background: -moz-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
+ background: -webkit-linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
+ background: linear-gradient($box_border_gradient_highlight_color, $box_border_gradient_background_color) $box_border_gradient_background_color;
+
+ & > * {
+ background-color: $box_gradient_background_color;
+ background: -o-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
+ background: -ms-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
+ background: -moz-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
+ background: -webkit-linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
+ background: linear-gradient($box_gradient_background_color, $box_gradient_highlight_color) $box_gradient_background_color;
+
+ -o-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
+ -ms-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
+ -moz-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
+ -webkit-box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
+ box-shadow: 0px 1px 0px $box_highlight_dark_color inset, 0px -2px 1px $box_highlight_light_color inset;
+ }
+}
+
+
+nav#menu ,
+nav#mygames {
+ a {
+ color: $nav_link_color;
+ background-color: $nav_background_color;
+ border-bottom: $nav_separator;
+
+ &:hover {
+ color: $nav_hover_color;
+ background-color: $nav_hover_background_color;
+ }
+ }
+
+ li {
+ &.active {
+ a {
+ color: $nav_active_color;
+ background-color: $nav_active_background_color;
+ }
+ }
+
+ span.sep {
+ color: $nav_data_separator_color;
+ }
+ }
+}
+
+
+nav#mygames {
+ .finished a { color: $finished_games_color; }
+ .playing a { color: $playing_games_color; }
+ .my_turn a { color: $my_turn_games_color; }
+ .none a { color: $main_games_color; }
+}
+
+
+aside#info {
+ #chatbox {
+ background-color: $side_chat_background_color;
+ border: $side_chat_border;
+ }
+}
+
+
+h2 {
+ border-bottom: $h2_border;
+}
+
+
+#index_page {
+ #chatbox {
+ border: $chatbox_border;
+ }
+
+ #chats {
+ border-top: $chatbox_item_border;
+
+ dt {
+ border-bottom: $chatbox_item_border;
+ background: $chatbox_item_background_color;
+ }
+
+ dd {
+ border-bottom: $chatbox_item_border;
+ }
+ }
+}
+
+
+footer {
+ color: $footer_color;
+ background-color: $footer_background_color;
+
+ -o-box-shadow: 0px 3px 16px $footer_shadow_color inset;
+ -ms-box-shadow: 0px 3px 16px $footer_shadow_color inset;
+ -moz-box-shadow: 0px 3px 16px $footer_shadow_color inset;
+ -webkit-box-shadow: 0px 3px 16px $footer_shadow_color inset;
+ box-shadow: 0px 3px 16px $footer_shadow_color inset;
+}
+
+
+#buttons {
+ a {
+ border: $nav_separator;
+ }
+}
+
+
+@import "c_game_template"
+
+
diff --git a/css/scss/c_blue_black.scss b/css/scss/c_blue_black.scss
new file mode 100644
index 0000000..c2c84cb
--- /dev/null
+++ b/css/scss/c_blue_black.scss
@@ -0,0 +1,24 @@
+
+/* Game colors */
+/* blue-black created by Luke Larsen, coded by Benjam Welker */
+
+/*
+ all the layout for the webpages are specified in the layout.css
+ file. the colors have been separated out for ease of customization
+*/
+
+// set our default styles for blue_black
+
+$main_back_color: #282828 !default;
+$main_highlight_color: #165AA6 !default;
+
+$highlight_color: #3380D7 !default;
+
+$header_border_bottom: 1px solid #2473E3 !default;
+
+$nav_hover_background_color: rgba(12, 14, 40, 0.5) !default;
+
+$footer_background_color: $main_highlight_color / 2 !default;
+
+
+@import "c_template";
diff --git a/css/scss/c_red_black.scss b/css/scss/c_red_black.scss
new file mode 100644
index 0000000..92d9f62
--- /dev/null
+++ b/css/scss/c_red_black.scss
@@ -0,0 +1,10 @@
+
+/* Game colors */
+/* red-black created by Luke Larsen, coded by Benjam Welker */
+
+/*
+ all the layout for the webpages are specified in the layout.css
+ file. the colors have been separated out for ease of customization
+*/
+
+@import "c_template";
diff --git a/includes/html.general.php b/includes/html.general.php
index fb06e02..fc49130 100644
--- a/includes/html.general.php
+++ b/includes/html.general.php
@@ -1,328 +1,328 @@
<?php
/** function get_header
* Generate the HTML header portion of the page
*
* @param array [optional] meta variables
* @option string 'title' the page title
* @option string 'head_data' any HTML to be inserted in the head tag
* @option array 'menu_data' the data for the counts in the menu
* @option array 'game_data' the game data for my game list under the menu
* @option bool 'show_menu' show the menu
* @option string 'file_name' becomes the body id with _page appended
* @return string HTML header for page
*/
function get_header($meta = null) {
if ( ! defined('GAME_NAME')) {
define('GAME_NAME', 'Game');
}
$title = ( ! empty($meta['title'])) ? GAME_NAME.' :: '.$meta['title'] : GAME_NAME;
$show_menu = (isset($meta['show_menu'])) ? (bool) $meta['show_menu'] : true;
$show_nav_links = (isset($meta['show_nav_links'])) ? (bool) $meta['show_nav_links'] : true;
$menu_data = (isset($meta['menu_data'])) ? $meta['menu_data'] : false;
$head_data = (isset($meta['head_data'])) ? $meta['head_data'] : '';
$file_name = (isset($meta['file_name'])) ? $meta['file_name'] : basename($_SERVER['SCRIPT_NAME']);
$file_name = substr($file_name, 0, strrpos($file_name, '.'));
// make sure we have these
$GLOBALS['_&_DEBUG_QUERY'] = (isset($GLOBALS['_&_DEBUG_QUERY'])) ? $GLOBALS['_&_DEBUG_QUERY'] : '';
$GLOBALS['_?_DEBUG_QUERY'] = (isset($GLOBALS['_?_DEBUG_QUERY'])) ? $GLOBALS['_?_DEBUG_QUERY'] : '';
$flash = '';
if (class_exists('Flash')) {
$flash = Flash::retrieve( );
}
if ($show_menu) {
if ( ! $menu_data) {
$menu_data = array(
'my_turn' => 0,
'my_games' => 0,
'games' => 0,
'in_vites' => 0,
'out_vites' => 0,
'open_vites' => 0,
'new_msgs' => 0,
'msgs' => 0,
);
list($menu_data['games'], ) = Game::get_count( );
list($menu_data['setups'], $menu_data['my_setups']) = Setup::get_count($_SESSION['player_id']);
list($menu_data['my_games'], $menu_data['my_turn']) = Game::get_my_count($_SESSION['player_id']);
list($menu_data['in_vites'], $menu_data['out_vites'], $menu_data['open_vites']) = Game::get_invite_count($_SESSION['player_id']);
$messages = Message::get_count($_SESSION['player_id']);
$menu_data['msgs'] = (int) @$messages[0];
$menu_data['new_msgs'] = (int) @$messages[1];
$allow_blink = ('index.php' == basename($_SERVER['PHP_SELF']));
}
// highlight the important menu values
foreach ($menu_data as $key => $value) {
switch ($key) {
case 'my_turn' :
case 'new_msgs' :
case 'in_vites' :
if (0 < $value) {
$menu_data[$key] = '<span class="notice">'.$value.'</span>';
}
break;
default :
// do nothing
break;
}
}
$game_data = (isset($meta['game_data'])) ? $meta['game_data'] : Game::get_list($_SESSION['player_id'], false);
}
// if we are admin logged in as someone else, let us know
$admin_css = $admin_div = '';
if (isset($_SESSION['admin_id']) && isset($_SESSION['player_id']) && ($_SESSION['player_id'] != $_SESSION['admin_id'])) {
$admin_css = '
<style type="text/css">
html { border: 5px solid red; }
#admin_username {
background: red;
color: black;
position: fixed;
top: 0;
left: 50%;
z-index: 99999;
width: 200px;
margin-left: -100px;
text-align: center;
font-weight: bold;
font-size: larger;
padding: 3px;
}
</style>';
$admin_div = '<div id="admin_username">'.$GLOBALS['Player']->username.' [ '.$GLOBALS['Player']->id.' ]</div>';
}
$query_strings = 'var debug_query_ = "'.$GLOBALS['_&_DEBUG_QUERY'].'"; var debug_query = "'.$GLOBALS['_?_DEBUG_QUERY'].'";';
$debug_string = (defined('DEBUG') && DEBUG) ? 'var debug = true;' : 'var debug = false;';
$nav_links = '';
if ($show_nav_links && class_exists('Settings') && Settings::test( )) {
$nav_links = Settings::read('nav_links');
}
$GAME_NAME = GAME_NAME;
$html = <<< EOF
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>{$title}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
{$debug_string}
{$query_strings}
</script>
<script type="text/javascript" src="scripts/json.js"></script>
<script type="text/javascript" src="scripts/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="scripts/jquery.tablesorter.js"></script>
<!-- fancybox -->
<link rel="stylesheet" type="text/css" media="screen" href="scripts/jquery.fancybox/jquery.fancybox-1.3.4.css" />
<script type="text/javascript" src="scripts/jquery.fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript">
$(document).ready( function( ) {
// set fancybox defaults
$.fn.fancybox.defaults['overlayColor'] = '#000';
$('a.help').fancybox({
autoDimensions : false,
width: 500,
padding : 10,
hideOnContentClick : false
});
});
</script>
<!-- hide the fancybox titles -->
<style type="text/css">
#fancy_title { display: none !important; }
</style>
<link rel="stylesheet" type="text/css" media="screen" href="css/layout.css" />
{$head_data}
{$flash}
- <!--<link rel="stylesheet" type="text/css" media="screen" href="css/c_{$GLOBALS['_DEFAULT_COLOR']}.css" />-->
+ <link rel="stylesheet" type="text/css" media="screen" href="css/c_{$GLOBALS['_DEFAULT_COLOR']}.css" />
{$admin_css}
</head>
<body id="{$file_name}_page">
{$admin_div}
<header>
<h1><a href="index.php">{$GAME_NAME}</a></h1>
<nav class="site">{$nav_links}</nav>
</header>
EOF;
if ($show_menu) {
$html .= '
<aside id="nav">';
if ($menu_data) {
$html .= '
<nav id="menu" class="box">
<ul>
<li'.get_active('index').'><a href="index.php'.$GLOBALS['_?_DEBUG_QUERY'].'" title="(Your Turn | Your Games | Total Games)"'.(($allow_blink && $menu_data['my_turn']) ? ' class="blink"' : '').'>Games <span class="sep">(</span> '.$menu_data['my_turn'].' <span class="sep">|</span> '.$menu_data['my_games'].' <span class="sep">|</span> '.$menu_data['games'].' <span class="sep">)</span></a></li>
<li'.get_active('invite').'><a href="invite.php'.$GLOBALS['_?_DEBUG_QUERY'].'" title="(Received | Open | Sent)"'.(($allow_blink && $menu_data['in_vites']) ? ' class="blink"' : '').'>Invitations <span class="sep">(</span> '.$menu_data['in_vites'].' <span class="sep">|</span> '.$menu_data['open_vites'].' <span class="sep">|</span> '.$menu_data['out_vites'].' <span class="sep">)</span></a></li>
<li'.get_active('messages').'><a href="messages.php'.$GLOBALS['_?_DEBUG_QUERY'].'" title="(New Messages | Total Messages)"'.(($allow_blink && $menu_data['new_msgs']) ? ' class="blink"' : '').'>Messages <span class="sep">(</span> '.$menu_data['new_msgs'].' <span class="sep">|</span> '.$menu_data['msgs'].' <span class="sep">)</span></a></li>
<li'.get_active('setups').'><a href="setups.php'.$GLOBALS['_?_DEBUG_QUERY'].'" title="(Yours | Total)">Setups <span class="sep">(</span> '.$menu_data['my_setups'].' <span class="sep">|</span> '.$menu_data['setups'].' <span class="sep">)</span></a></li>
<li'.get_active('stats').'><a href="stats.php'.$GLOBALS['_?_DEBUG_QUERY'].'">Statistics</a></li>
<li'.get_active('prefs').'><a href="prefs.php'.$GLOBALS['_?_DEBUG_QUERY'].'">Preferences</a></li>
<li'.get_active('profile').'><a href="profile.php'.$GLOBALS['_?_DEBUG_QUERY'].'">Profile</a></li>
';
if (true == $GLOBALS['Player']->is_admin) {
$html .= '<li'.get_active('admin').'><a href="admin.php'.$GLOBALS['_?_DEBUG_QUERY'].'">Admin</a></li>';
}
$html .= '
<li><a href="login.php'.$GLOBALS['_?_DEBUG_QUERY'].'">Logout</a></li>
</ul>
</nav><!-- #menu -->';
}
if ($game_data) {
$html .= '
<div id="mygames_title">My Games</div>
<nav id="mygames" class="box">
<ul>';
foreach ($game_data as $game) {
$class = ($game['my_turn']) ? 'playing' : ((in_array($game['state'], array('Finished', 'Draw'))) ? 'finished' : 'waiting');
$html .= '
<li class="'.$class.'"><a href="game.php?id='.$game['game_id'].$GLOBALS['_&_DEBUG_QUERY'].'">'.htmlentities($game['opponent'], ENT_QUOTES, 'ISO-8859-1', false).'</a></li>';
}
$html .= '
</ul>
</nav><!-- #mygames -->';
}
$html .= '
</aside><!-- #nav -->';
}
return $html;
}
/** function get_footer
* Generate the HTML footer portion of the page
*
* @param array option meta info
* @return string HTML footer for page
*/
function get_footer($meta = array( )) {
$foot_data = (isset($meta['foot_data'])) ? $meta['foot_data'] : '';
$players = GamePlayer::get_count( );
list($cur_games, $total_games) = Game::get_count( );
$Mysql = Mysql::get_instance( );
$html = '
<div id="footerspacer"> </div>
<footer>
<span>Total Players - '.$players.'</span>
<span>Active Games - '.$cur_games.'</span>
<span>Games Played - '.$total_games.'</span>
</footer>
'.$foot_data.'
<!-- Queries = '.$Mysql->query_count.' -->
</body>
</html>';
return $html;
}
/** function get_item
* Generate the HTML content portion of the page
*
* @param string contents
* @param string instructions for page
* @param string [optional] title for page
* @return string HTML content for page
*/
function get_item($contents, $hint, $title = '', $extra_html = '') {
$hint_html = "\n\t\t\t<p><strong>Welcome";
if ( ! empty($GLOBALS['Player']) && ! empty($_SESSION['player_id'])) {
$hint_html .= ", {$GLOBALS['Player']->username}";
}
$hint_html .= '</strong></p>';
if (is_array($hint)) {
foreach ($hint as $line) {
$hint_html .= "\n\t\t\t<p>{$line}</p>";
}
}
else {
$hint_html .= "\n\t\t\t<p>{$hint}</p>";
}
if ('' != $title) {
$title = '<h2>'.$title.'</h2>';
}
$long_date = (class_exists('Settings') && Settings::test( )) ? Settings::read('long_date') : 'M j, Y g:i a';
$html = '
<aside id="info">
<div id="notes" class="box">
<div>
<div id="date">'.date($long_date).'</div>
'.$hint_html.'
</div>
</div>
'.$extra_html.'
</aside><!-- #info -->
<div id="content" class="box">
<div>
'.$title.'
'.$contents.'
</div>
</div><!-- #content -->
';
return $html;
}
/** function get_active
* Returns an active class string based on
* our current location
*
* @param string link URL to test against
* @return string HTML active class attribute (or empty string)
*/
function get_active($value) {
$self = substr(basename($_SERVER['SCRIPT_NAME']), 0, -4);
if ($value == $self) {
return ' class="active"';
}
return '';
}
diff --git a/includes/inc.global.php b/includes/inc.global.php
index 0fb9ed0..be694fb 100644
--- a/includes/inc.global.php
+++ b/includes/inc.global.php
@@ -1,187 +1,187 @@
<?php
$debug = false;
// set some ini stuff
ini_set('register_globals', 0); // you really should have this off anyways
// deal with those lame magic quotes
if (get_magic_quotes_gpc( )) {
function stripslashes_deep($value) {
$value = is_array($value)
? array_map('stripslashes_deep', $value)
: stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
/**
* GLOBAL INCLUDES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
define('ROOT_DIR', dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR);
define('INCLUDE_DIR', dirname(__FILE__).DIRECTORY_SEPARATOR);
define('CLASSES_DIR', ROOT_DIR.'classes'.DIRECTORY_SEPARATOR);
define('GAMES_DIR', ROOT_DIR.'games'.DIRECTORY_SEPARATOR);
define('LOG_DIR', ROOT_DIR.'logs'.DIRECTORY_SEPARATOR);
ini_set('error_log', LOG_DIR.'php.err');
if (is_file(INCLUDE_DIR.'config.php')) {
require_once INCLUDE_DIR.'config.php';
}
#/*/
#elseif ('setup-config.php' != basename($_SERVER['PHP_SELF'])) {
# header('Location: setup-config.php');
#/*/
#elseif ('install.php' != basename($_SERVER['PHP_SELF'])) {
# header('Location: install.php');
#//*/
# exit;
#}
require_once INCLUDE_DIR.'inc.settings.php';
require_once INCLUDE_DIR.'func.global.php';
require_once INCLUDE_DIR.'html.general.php';
require_once INCLUDE_DIR.'html.tables.php';
// MAKE SURE TO LOAD CLASS FILES BEFORE STARTING THE SESSION
// OR YOU END UP WITH INCOMPLETE OBJECTS PULLED FROM SESSION
spl_autoload_register('load_class');
// set the proper timezone
date_default_timezone_set($GLOBALS['_DEFAULT_TIMEZONE']);
/**
* GLOBAL DATA
* * * * * * * * * * * * * * * * * * * * * * * * * * */
$GLOBALS['_&_DEBUG_QUERY'] = '';
$GLOBALS['_?_DEBUG_QUERY'] = '';
// make a list of all the color files available to use
$GLOBALS['_COLORS'] = array( );
$dh = opendir(realpath(dirname(__FILE__).'/../css'));
while (false !== ($file = readdir($dh))) {
if (preg_match('/^c_(.+)\\.css$/i', $file, $match)) { // scanning for color files only
$GLOBALS['_COLORS'][] = $match[1];
}
}
// convert the full color file name to just the color portion
$GLOBALS['_DEFAULT_COLOR'] = '';
if (class_exists('Settings') && Settings::test( )) {
$GLOBALS['_DEFAULT_COLOR'] = preg_replace('/c_(.+)\\.css/i', '$1', Settings::read('default_color'));
}
if ('' == $GLOBALS['_DEFAULT_COLOR']) {
if (in_array('blue_white', $GLOBALS['_COLORS'])) {
- $GLOBALS['_DEFAULT_COLOR'] = 'blue_white';
+ $GLOBALS['_DEFAULT_COLOR'] = 'red_black';
}
elseif ($GLOBALS['_COLORS']) {
$GLOBALS['_DEFAULT_COLOR'] = $GLOBALS['_COLORS'][0];
}
else {
$GLOBALS['_DEFAULT_COLOR'] = '';
}
}
// set the session cookie parameters so the cookie is only valid for this game
$parts = pathinfo($_SERVER['REQUEST_URI']);
$path = $parts['dirname'];
if (empty($parts['extension'])) {
$path .= $parts['basename'];
}
$path = str_replace('\\', '/', $path).'/';
session_set_cookie_params(0, $path);
session_start( );
// make sure we don't cross site session steal in our own site
if ( ! isset($_SESSION['PWD']) || (__FILE__ != $_SESSION['PWD'])) {
$_SESSION = array( );
}
$_SESSION['PWD'] = __FILE__;
// set a token, we'll be passing one around a lot
if ( ! isset($_SESSION['token'])) {
$_SESSION['token'] = md5(uniqid(rand( ), true));
}
call($_SESSION['token']);
if ( ! defined('DEBUG')) {
if (test_debug( )) {
define('DEBUG', true); // DO NOT CHANGE THIS ONE
}
else {
define('DEBUG', (bool) $debug); // set to true for output of debugging code
}
}
$GLOBALS['_LOGGING'] = DEBUG; // do not change, rather, change debug value
if (Mysql::test( )) {
$Mysql = Mysql::get_instance( );
$Mysql->set_settings(array(
'log_path' => LOG_DIR,
'email_subject' => GAME_NAME.' Query Error',
));
if (class_exists('Settings') && Settings::test( )) {
$Mysql->set_settings(array(
'log_errors' => Settings::read('DB_error_log'),
'email_errors' => Settings::read('DB_error_email'),
'email_from' => Settings::read('from_email'),
'email_to' => Settings::read('to_email'),
));
}
}
if (defined('DEBUG') && DEBUG) {
ini_set('display_errors','On');
error_reporting(E_ALL | E_STRICT); // all errors, notices, and strict warnings
if (isset($Mysql)) {
$Mysql->set_error(3);
}
}
else { // do not edit the following
ini_set('display_errors','Off');
error_reporting(E_ALL & ~ E_NOTICE); // show errors, but not notices
}
// log the player in
if (( ! defined('LOGIN') || LOGIN) && isset($Mysql)) {
$GLOBALS['Player'] = new GamePlayer( );
// this will redirect to login if failed
$GLOBALS['Player']->log_in( );
if (0 != $_SESSION['player_id']) {
$Message = new Message($_SESSION['player_id'], $GLOBALS['Player']->is_admin);
}
// set the default color for the player
if (('' != $GLOBALS['Player']->color) && (in_array($GLOBALS['Player']->color, $GLOBALS['_COLORS']))) {
$GLOBALS['_DEFAULT_COLOR'] = $GLOBALS['Player']->color;
}
// set the default timezone for the player
if ('' !== $GLOBALS['Player']->timezone) {
date_default_timezone_set($GLOBALS['Player']->timezone);
}
}
// grab the list of players
if (isset($Mysql)) {
$GLOBALS['_PLAYERS'] = Player::get_array( );
}
diff --git a/invite.php b/invite.php
index fa09a00..378a144 100644
--- a/invite.php
+++ b/invite.php
@@ -1,256 +1,255 @@
<?php
require_once 'includes/inc.global.php';
// this has nothing to do with creating a game
// but I'm running it here to prevent long load
// times on other pages where it would be run more often
GamePlayer::delete_inactive(Settings::read('expire_users'));
Game::delete_inactive(Settings::read('expire_games'));
Game::delete_finished(Settings::read('expire_finished_games'));
$Game = new Game( );
if (isset($_POST['invite'])) {
// make sure this user is not full
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
Flash::store('You have reached your maximum allowed games !', false);
}
test_token( );
try {
$game_id = $Game->invite( );
Flash::store('Invitation Sent Successfully', true);
}
catch (MyException $e) {
Flash::store('Invitation FAILED !', false);
}
}
// grab the full list of players
$players_full = GamePlayer::get_list(true);
$invite_players = array_shrink($players_full, 'player_id');
// grab the players who's max game count has been reached
$players_maxed = GamePlayer::get_maxed( );
$players_maxed[] = $_SESSION['player_id'];
// remove the maxed players from the invite list
$players = array_diff($invite_players, $players_maxed);
$opponent_selection = '';
$opponent_selection .= '<option value="">-- Open --</option>';
foreach ($players_full as $player) {
if ($_SESSION['player_id'] == $player['player_id']) {
continue;
}
if (in_array($player['player_id'], $players)) {
$opponent_selection .= '
<option value="'.$player['player_id'].'">'.$player['username'].'</option>';
}
}
$groups = array(
'Normal' => array(0, 0),
'Eye of Horus' => array(0, 1),
'Sphynx' => array(1, 0),
'Sphynx & Horus' => array(1, 1),
);
$group_names = array_keys($groups);
$group_markers = array_values($groups);
$setups = Setup::get_list( );
$setup_selection = '<option value="0">Random</option>';
$setup_javascript = '';
$cur_group = false;
$group_open = false;
foreach ($setups as $setup) {
$marker = array((int) $setup['has_sphynx'], (int) $setup['has_horus']);
$group_index = array_search($marker, $group_markers, true);
if ($cur_group !== $group_names[$group_index]) {
if ($group_open) {
$setup_selection .= '</optgroup>';
$group_open = false;
}
$cur_group = $group_names[$group_index];
$setup_selection .= '<optgroup label="'.$cur_group.'">';
$group_open = true;
}
$setup_selection .= '
<option value="'.$setup['setup_id'].'">'.$setup['name'].'</option>';
$setup_javascript .= "'".$setup['setup_id']."' : '".expandFEN($setup['board'])."',\n";
}
$setup_javascript = substr(trim($setup_javascript), 0, -1);
if ($group_open) {
$setup_selection .= '</optgroup>';
}
$meta['title'] = 'Send Game Invitation';
$meta['head_data'] = '
<link rel="stylesheet" type="text/css" media="screen" href="css/board.css" />
<script type="text/javascript">//<![CDATA[
var setups = {
'.$setup_javascript.'
};
/*]]>*/</script>
<script type="text/javascript" src="scripts/board.js"></script>
<script type="text/javascript" src="scripts/invite.js"></script>
';
$hints = array(
'Invite a player to a game by filling out your desired game options.' ,
'<span class="highlight">WARNING!</span><br />Games will be deleted after '.Settings::read('expire_games').' days of inactivity.' ,
);
// make sure this user is not full
$submit_button = '<div><input type="submit" name="invite" value="Send Invitation" /></div>';
$warning = '';
if ($GLOBALS['Player']->max_games && ($GLOBALS['Player']->max_games <= $GLOBALS['Player']->current_games)) {
$submit_button = $warning = '<p class="warning">You have reached your maximum allowed games, you can not create this game !</p>';
}
$contents = <<< EOF
<form method="post" action="{$_SERVER['REQUEST_URI']}" id="send"><div class="formdiv">
<input type="hidden" name="token" value="{$_SESSION['token']}" />
<input type="hidden" name="player_id" value="{$_SESSION['player_id']}" />
{$warning}
<div><label for="opponent">Opponent</label><select id="opponent" name="opponent">{$opponent_selection}</select></div>
<div><label for="setup">Setup</label><select id="setup" name="setup">{$setup_selection}</select> <a href="#setup_display" id="show_setup">Show Setup</a></div>
<div><label for="color">Your Color</label><select id="color" name="color"><option value="random">Random</option><option value="white">Silver</option><option value="black">Red</option></select></div>
<div class="pharaoh_1">
<fieldset>
<legend>v1.0 Options</legend>
<p class="conversion">
Here you can convert old v1.0 setups to play v2.0 Pharaoh.<br />
The conversion places a Sphynx in your lower-right corner facing upwards (and opposite for your opponent)
and converts any double-stacked Obelisks to Anubises which face forward.
</p>
<p class="conversion">
When you select to convert, more options will be shown below, as well as the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_2" name="convert_to_2" /> Convert to 2.0</label></div>
</fieldset>
</div> <!-- .pharaoh_1 -->
<div class="pharaoh_2 p2_box">
<fieldset>
<legend>v2.0 Options</legend>
<p class="conversion">
Here you can convert the new v2.0 setups to play v1.0 Pharaoh.<br />
The conversion removes any Sphynxes from the board and converts any Anubises to double-stacked Obelisks.
</p>
<p class="conversion">
When you select to convert, the "Show Setup" link will show the updated setup.
</p>
<div class="conversion"><label class="inline"><input type="checkbox" id="convert_to_1" name="convert_to_1" /> Convert to 1.0</label></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="move_sphynx" name="move_sphynx" /> Sphynx is movable</label></div>
</fieldset>
</div> <!-- .pharaoh_2 -->
<fieldset>
<legend><label class="inline"><input type="checkbox" name="laser_battle_box" id="laser_battle_box" class="fieldset_box" /> Laser Battle</label></legend>
<div id="laser_battle">
<p>
When a laser gets shot by the opponents laser, it will be disabled for a set number of turns, making that laser unable to shoot until those turns have passed.<br />
After those turns have passed, and the laser has recovered, it will be immune from further shots for a set number of turns.<br />
After the immunity turns have passed, whether or not the laser was shot again, it will now be susceptible to being shot again.
<span class="pharaoh_2"><br />You can also select if the Sphynx is hittable only in the front, or on all four sides.</span>
</p>
<div><label for="battle_dead">Dead for:</label><input type="text" id="battle_dead" name="battle_dead" size="4" /> <span class="info">(Default: 1; Minimum: 1)</span></div>
<div><label for="battle_immune">Immune for:</label><input type="text" id="battle_immune" name="battle_immune" size="4" /> <span class="info">(Default: 1; Minimum: 0)</span></div>
<div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_front_only" name="battle_front_only" checked="checked" /> Only front hits on Sphynx count</label></div>
<!-- <div class="pharaoh_2"><label class="inline"><input type="checkbox" id="battle_hit_self" name="battle_hit_self" /> Hit Self</label></div> -->
<p>You can set the "Immune for" value to 0 to allow a laser to be shot continuously, but the minimum value for the "Dead for" value is 1, as it makes no sense otherwise.</p>
</div> <!-- #laser_battle -->
</fieldset>
-
{$submit_button}
<div class="clr"></div>
</div></form>
<div id="setup_display"></div>
EOF;
// create our invitation tables
list($in_vites, $out_vites, $open_vites) = Game::get_invites($_SESSION['player_id']);
$contents .= <<< EOT
<form method="post" action="{$_SERVER['REQUEST_URI']}"><div class="formdiv" id="invites">
EOT;
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no received invites to show</p>' ,
'caption' => 'Invitations Received' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" /><input type="button" id="decline-[[[game_id]]]" value="Decline" />', false) ,
);
$contents .= get_table($table_format, $in_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no sent invites to show</p>' ,
'caption' => 'Invitations Sent' ,
);
$table_format = array(
array('Invitee', '###ife(\'[[[invitee]]]\', \'-- OPEN --\')') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '###\'<input type="button" id="withdraw-[[[game_id]]]" value="Withdraw" />\'.((strtotime(\'[[[create_date]]]\') >= strtotime(\'[[[resend_limit]]]\')) ? \'\' : \'<input type="button" id="resend-[[[game_id]]]" value="Resend" />\')', false) ,
);
$contents .= get_table($table_format, $out_vites, $table_meta);
$table_meta = array(
'sortable' => true ,
'no_data' => '<p>There are no open invites to show</p>' ,
'caption' => 'Open Invitations' ,
);
$table_format = array(
array('Invitor', 'invitor') ,
array('Setup', '<a href="#[[[board]]]" class="setup" id="s_[[[setup_id]]]">[[[setup]]]</a>') ,
array('Color', 'color') ,
array('Extra', '<abbr title="[[[hover_text]]]">Hover</abbr>') ,
array('Date Sent', '###date(Settings::read(\'long_date\'), strtotime(\'[[[create_date]]]\'))', null, ' class="date"') ,
array('Action', '<input type="button" id="accept-[[[game_id]]]" value="Accept" />', false) ,
);
$contents .= get_table($table_format, $open_vites, $table_meta);
$contents .= <<< EOT
</div></form>
EOT;
echo get_header($meta);
echo get_item($contents, $hints, $meta['title']);
call($GLOBALS);
echo get_footer( );
|
benjamw/pharaoh | 4e7a42259f53e2b6a2366f752faab9be88cca231 | removed error when no extra_info found | diff --git a/classes/game.class.php b/classes/game.class.php
index 064455f..cc37a95 100644
--- a/classes/game.class.php
+++ b/classes/game.class.php
@@ -2102,930 +2102,933 @@ class Game
, modify_date
FROM ".self::GAME_TABLE."
WHERE game_id = '{$this->id}'
AND state <> 'Waiting'
";
$game = $this->_mysql->fetch_assoc($query);
call($game);
$update_modified = false;
if ( ! $game) {
throw new MyException(__METHOD__.': Game data not found for game #'.$this->id);
}
$this->_log('DATA SAVE: #'.$this->id.' @ '.time( )."\n".' - '.$this->modify_date."\n".' - '.strtotime($game['modify_date']));
// test the modified date and make sure we still have valid data
call($this->modify_date);
call(strtotime($game['modify_date']));
if ($this->modify_date != strtotime($game['modify_date'])) {
$this->_log('== FAILED ==');
throw new MyException(__METHOD__.': Trying to save game (#'.$this->id.') with out of sync data');
}
$update_game = false;
call($game['state']);
call($this->state);
if ($game['state'] != $this->state) {
$update_game['state'] = $this->state;
if ('Finished' == $this->state) {
$update_game['winner_id'] = $this->_players[$this->_pharaoh->winner]['player_id'];
}
if (in_array($this->state, array('Finished', 'Draw'))) {
try {
$this->_add_stats( );
}
catch (MyException $e) {
// do nothing, it gets logged
}
}
}
$diff = array_compare($this->_extra_info, self::$_EXTRA_INFO_DEFAULTS);
$update_game['extra_info'] = $diff[0];
ksort($update_game['extra_info']);
$update_game['extra_info'] = serialize($update_game['extra_info']);
if ('a:0:{}' == $update_game['extra_info']) {
$update_game['extra_info'] = null;
}
if (0 === strcmp($game['extra_info'], $update_game['extra_info'])) {
unset($update_game['extra_info']);
}
if ($update_game) {
$update_modified = true;
$this->_mysql->insert(self::GAME_TABLE, $update_game, " WHERE game_id = '{$this->id}' ");
}
// update the board
$color = $this->_players['player']['color'];
call($color);
call('IN-GAME SAVE');
// grab the current board from the database
$query = "
SELECT *
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$this->id}'
ORDER BY move_date DESC
LIMIT 1
";
$move = $this->_mysql->fetch_assoc($query);
$board = $move['board'];
call($board);
$new_board = packFEN($this->_pharaoh->get_board( ));
call($new_board);
list($new_move, $new_hits) = $this->_pharaoh->get_move( );
call($new_move);
call($new_hits);
if (is_array($new_hits)) {
$new_hits = implode(',', $new_hits);
}
if ($new_board != $board) {
call('UPDATED BOARD');
$update_modified = true;
$this->_current_move_extra_info['laser_fired'] = (bool) $this->can_fire_laser( );
$this->_current_move_extra_info['laser_hit'] = (bool) $this->_pharaoh->laser_hit;
$diff = array_compare($this->_current_move_extra_info, self::$_HISTORY_EXTRA_INFO_DEFAULTS);
$m_extra_info = $diff[0];
ksort($m_extra_info);
$m_extra_info = serialize($m_extra_info);
if ('a:0:{}' == $m_extra_info) {
$m_extra_info = null;
}
$this->_mysql->insert(self::GAME_HISTORY_TABLE, array('board' => $new_board, 'move' => $new_move, 'hits' => $new_hits, 'extra_info' => $m_extra_info, 'game_id' => $this->id));
}
// update the game modified date
if ($update_modified) {
$this->_mysql->insert(self::GAME_TABLE, array('modify_date' => NULL), " WHERE game_id = '{$this->id}' ");
}
}
/** protected function _add_stats
* Adds data to the stats table
*
* @param void
* @action adds stats to stats table
* @return void
*/
protected function _add_stats( )
{
call(__METHOD__);
call($this);
if ( ! in_array($this->state, array('Finished', 'Draw'))) {
throw new MyException (__METHOD__.': Game (#'.$this->id.') is not finished ('.$this->state.')');
}
$count = count($this->_history) - 1;
$start = $this->_history[1]['move_date'];
$end = $this->_history[$count]['move_date'];
$start_unix = strtotime($start);
$end_unix = strtotime($end);
$hours = round(($end_unix - $start_unix) / (60 * 60), 3);
$stat = array(
'game_id' => $this->id,
'setup_id' => $this->_setup['id'],
'move_count' => $count,
'start_date' => $start,
'end_date' => $end,
'hour_count' => $hours,
);
$white_outcome = $black_outcome = 0;
if ('Finished' == $this->state) {
$white_outcome = 1;
$black_outcome = -1;
if ('red' == $this->_pharaoh->winner) {
$white_outcome = -1;
$black_outcome = 1;
}
}
$white = array_merge($stat, array(
'player_id' => $this->_players['white']['player_id'],
'color' => 'white',
'win' => $white_outcome,
));
call($white);
$this->_mysql->insert(self::GAME_STATS_TABLE, $white);
$black = array_merge($stat, array(
'player_id' => $this->_players['black']['player_id'],
'color' => 'black',
'win' => $black_outcome,
));
call($black);
$this->_mysql->insert(self::GAME_STATS_TABLE, $black);
}
/** protected function _log
* Report messages to a file
*
* @param string message
* @action log messages to file
* @return void
*/
protected function _log($msg)
{
// log the error
if (false && class_exists('Log')) {
Log::write($msg, __CLASS__);
}
}
/** protected function _diff
* Compares two boards are returns the
* indexes of any differences
*
* @param string board
* @param string board
* @return array of difference indexes
*/
protected function _diff($board1, $board2)
{
$diff = array( );
for ($i = 0, $length = strlen($board1); $i < $length; ++$i) {
if ($board1[$i] != $board2[$i]) {
$diff[] = $i;
}
}
call($diff);
return $diff;
}
/**
* STATIC METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** static public function get_list
* Returns a list array of all the games in the database
* with games which need the users attention highlighted
*
* NOTE: $player_id is required when not pulling all games
* (when $all is false)
*
* @param int optional player's id
* @param bool optional pull all games (vs only given player's games)
* @return array game list (or bool false on failure)
*/
static public function get_list($player_id = 0, $all = true)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
if ( ! $all && ! $player_id) {
throw new MyException(__METHOD__.': Player ID required when not pulling all games');
}
$WHERE = " WHERE state <> 'Waiting' ";
if ( ! $all) {
$WHERE .= "
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id})
";
}
$query = "
SELECT G.*
, MAX(GH.move_date) AS last_move
, COUNT(GH.move_date) AS count
, 0 AS my_turn
, 0 AS in_game
, W.username AS white
, B.username AS black
, S.name AS setup_name
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".self::GAME_HISTORY_TABLE." AS GH
ON GH.game_id = G.game_id
LEFT JOIN ".Player::PLAYER_TABLE." AS W
ON W.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS B
ON B.player_id = G.black_id
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
{$WHERE}
GROUP BY G.game_id
ORDER BY G.state ASC
, last_move ASC
";
$list = $Mysql->fetch_array($query);
if (0 != $player_id) {
// run though the list and find games the user needs action on
foreach ($list as & $game) {
$game['turn'] = (0 == ($game['count'] % 2)) ? 'black' : 'white';
$game['in_game'] = (int) (($player_id == $game['white_id']) || ($player_id == $game['black_id']));
$game['my_turn'] = (int) ( ! empty($game['turn']) && ($player_id == $game[$game['turn'].'_id']));
if (in_array($game['state'], array('Finished', 'Draw'))) {
$game['my_turn'] = 0;
}
$game['my_color'] = ($player_id == $game['white_id']) ? 'white' : 'black';
$game['opp_color'] = ($player_id == $game['white_id']) ? 'black' : 'white';
$game['opponent'] = ($player_id == $game['white_id']) ? $game['black'] : $game['white'];
}
unset($game); // kill the reference
}
// run through the games, and set the current player to the winner if the game is finished
// and fix the setup name if it was deleted
foreach ($list as & $game) {
if ('Finished' == $game['state']) {
if ($game['winner_id']) {
$game['turn'] = ($game['winner_id'] == $game['white_id']) ? 'white' : 'black';
}
else {
$game['turn'] = 'draw';
}
}
if ( ! $game['setup_name']) {
$game['setup_name'] = '[DELETED]';
}
}
unset($game); // kill the reference
return $list;
}
/** static public function get_player_stats_list
* Returns a list array of all game players
* in the database with additional stats added
*
* @param void
* @return array game player list (or bool false on failure)
*/
static public function get_player_stats_list( )
{
$Mysql = Mysql::get_instance( );
$players = GamePlayer::get_list(true);
if ($players) {
// add some more stats
$query = "
SELECT o.player_id
, COUNT(ww.win) AS white_wins
, COUNT(wl.win) AS white_losses
, COUNT(wd.win) AS white_draws
, COUNT(bw.win) AS black_wins
, COUNT(bl.win) AS black_losses
, COUNT(bd.win) AS black_draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.player_id = ww.player_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wl
ON (o.player_id = wl.player_id
AND o.game_id = wl.game_id
AND wl.win = -1
AND wl.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS wd
ON (o.player_id = wd.player_id
AND o.game_id = wd.game_id
AND wd.win = 0
AND wd.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.player_id = bw.player_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bl
ON (o.player_id = bl.player_id
AND o.game_id = bl.game_id
AND bl.win = -1
AND bl.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bd
ON (o.player_id = bd.player_id
AND o.game_id = bd.game_id
AND bd.win = 0
AND bd.color = 'black')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['player_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'white_losses' => 0,
'white_draws' => 0,
'black_wins' => 0,
'black_losses' => 0,
'black_draws' => 0,
);
foreach ($players as & $player) { // be careful with the reference
if (isset($stats[$player['player_id']])) {
$player = array_merge($player, $stats[$player['player_id']]);
}
else {
$player = array_merge($player, $empty);
}
}
unset($player); // kill the reference
}
return $players;
}
/** static public function get_setup_stats_list
* Gets the list of all the setups with
* additional stats included in the list
*
* @param void
* @return array setups
*/
static public function get_setup_stats_list( )
{
$Mysql = Mysql::get_instance( );
$setups = Setup::get_list(true);
if ($setups) {
// add some more stats
$query = "
SELECT o.setup_id
, COUNT(ww.win) AS white_wins
, COUNT(bw.win) AS black_wins
, COUNT(d.win) AS draws
FROM ".self::GAME_STATS_TABLE." AS o
LEFT JOIN ".self::GAME_STATS_TABLE." AS ww
ON (o.setup_id = ww.setup_id
AND o.game_id = ww.game_id
AND ww.win = 1
AND ww.color = 'white')
LEFT JOIN ".self::GAME_STATS_TABLE." AS bw
ON (o.setup_id = bw.setup_id
AND o.game_id = bw.game_id
AND bw.win = 1
AND bw.color = 'black')
LEFT JOIN ".self::GAME_STATS_TABLE." AS d
ON (o.setup_id = d.setup_id
AND o.game_id = d.game_id
AND d.win = 0
AND d.color = 'white')
GROUP BY o.player_id
";
$results = $Mysql->fetch_array($query);
$stats = array( );
foreach ($results as $stat) {
$stats[$stat['setup_id']] = $stat;
}
$empty = array(
'white_wins' => 0,
'black_wins' => 0,
'draws' => 0,
);
foreach ($setups as & $setup) { // be careful with the reference
if (isset($stats[$setup['setup_id']])) {
$setup = array_merge($setup, $stats[$setup['setup_id']]);
}
else {
$setup = array_merge($setup, $empty);
}
}
unset($setup); // kill the reference
}
return $setups;
}
/** static public function get_invites
* Returns a list array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite list
*/
static public function get_invites($player_id)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT G.*
, DATE_ADD(NOW( ), INTERVAL -1 DAY) AS resend_limit
, R.username AS invitor
, E.username AS invitee
, S.name AS setup
FROM ".self::GAME_TABLE." AS G
LEFT JOIN ".Setup::SETUP_TABLE." AS S
ON S.setup_id = G.setup_id
LEFT JOIN ".Player::PLAYER_TABLE." AS R
ON R.player_id = G.white_id
LEFT JOIN ".Player::PLAYER_TABLE." AS E
ON E.player_id = G.black_id
WHERE G.state = 'Waiting'
AND (G.white_id = {$player_id}
OR G.black_id = {$player_id}
OR G.black_id IS NULL
OR G.black_id = FALSE
)
ORDER BY G.create_date DESC
";
$list = $Mysql->fetch_array($query);
call($list);
$in_vites = $out_vites = $open_vites = array( );
foreach ($list as $item) {
$extra_info = array_merge_plus(self::$_EXTRA_INFO_DEFAULTS, unserialize($item['extra_info']));
$white_color = (('random' == $extra_info['white_color']) ? 'Random' : (('white' == $extra_info['white_color']) ? 'Silver' : 'Red'));
$black_color = (('random' == $extra_info['white_color']) ? 'Random' : (('white' == $extra_info['white_color']) ? 'Red' : 'Silver'));
- $hover = unserialize($item['extra_info']);
- unset($hover['invite_setup']);
- unset($hover['white_color']);
+ $hover = array( );
+ if ( ! empty($item['extra_info'])) {
+ $hover = unserialize($item['extra_info']);
+ unset($hover['invite_setup']);
+ unset($hover['white_color']);
+ }
$hover_text = array( );
foreach ($hover as $key => $value) {
if (is_bool($value)) {
$value = ($value ? 'Yes' : 'No');
}
$hover_text[] = humanize($key).': '.$value;
}
$item['hover_text'] = implode(' | ', $hover_text);
$item['board'] = 'setup_display';
if ( ! empty($extra_info['invite_setup'])) {
$item['board'] = expandFEN($extra_info['invite_setup']);
}
if ($player_id == $item['white_id']) {
$item['color'] = $white_color;
$out_vites[] = $item;
}
elseif ($player_id == $item['black_id']) {
$item['color'] = $black_color;
$in_vites[] = $item;
}
else {
$item['color'] = $black_color;
$open_vites[] = $item;
}
}
return array($in_vites, $out_vites, $open_vites);
}
/** static public function get_invite_count
* Returns a count array of all the invites in the database
* for the given player
*
* @param int player's id
* @return 2D array invite count
*/
static public function get_invite_count($player_id)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE black_id = {$player_id}
AND state = 'Waiting'
";
$in_vites = (int) $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE white_id = {$player_id}
AND state = 'Waiting'
";
$out_vites = (int) $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE white_id <> '{$player_id}'
AND state = 'Waiting'
AND (black_id IS NULL
OR black_id = FALSE
)
";
$open_vites = (int) $Mysql->fetch_value($query);
return array($in_vites, $out_vites, $open_vites);
}
/** static public function get_count
* Returns a count of all games in the database,
* as well as the highest game id (the total number of games played)
*
* @param void
* @return array (int current game count, int total game count)
*/
static public function get_count( )
{
$Mysql = Mysql::get_instance( );
// games in play
$query = "
SELECT COUNT(*)
FROM ".self::GAME_TABLE."
WHERE state = 'Playing'
";
$count = (int) $Mysql->fetch_value($query);
// total games
$query = "
SELECT MAX(game_id)
FROM ".self::GAME_TABLE."
";
$next = (int) $Mysql->fetch_value($query);
return array($count, $next);
}
/** static public function check_turns
* Returns a count of all games
* in which it is the user's turn
*
* @param int player id
* @return int number of games with player action
*/
static public function check_turns($player_id)
{
$list = self::get_list($player_id, false);
$turn_count = array_sum_field($list, 'my_turn');
return $turn_count;
}
/** static public function get_my_count
* Returns a count of all given player's games in the database,
* as well as the games in which it is the player's turn
*
* @param int player id
* @return array (int player game count, int turn game count)
*/
static public function get_my_count($player_id)
{
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
// games in play
$query = "
SELECT game_id
, IF(white_id = {$player_id}, 'silver', 'red') AS color
FROM ".self::GAME_TABLE."
WHERE state = 'Playing'
AND (white_id = '{$player_id}'
OR black_id = '{$player_id}'
)
";
$games = $Mysql->fetch_array($query);
$mine = count($games);
// games with turns
$turn = 0;
foreach ($games as $game) {
$query = "
SELECT COUNT(*)
FROM ".self::GAME_HISTORY_TABLE."
WHERE game_id = '{$game['game_id']}'
";
$count = (int) $Mysql->fetch_value($query);
$odd = (bool) ($count % 2);
if ((('silver' == $game['color']) && $odd)
|| (('red' == $game['color']) && ! $odd)) {
++$turn;
}
}
return array($mine, $turn);
}
/** public function delete_inactive
* Deletes the inactive games from the database
*
* @param int age in days (0 = disable)
* @action deletes the inactive games
* @return void
*/
static public function delete_inactive($age)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$age = (int) $age;
if ( ! $age) {
return;
}
// don't auto delete paused games or invites
$query = "
SELECT game_id
FROM ".self::GAME_TABLE."
WHERE state <> 'Waiting'
AND modify_date < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
AND create_date < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
AND paused = 0
";
$game_ids = $Mysql->fetch_value_array($query);
if ($game_ids) {
self::delete($game_ids);
}
}
/** public function delete_finished
* Deletes the finished games from the database
*
* @param int age in days (0 = disable)
* @action deletes the finished games
* @return void
*/
static public function delete_finished($age)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$age = (int) $age;
if ( ! $age) {
return;
}
$query = "
SELECT game_id
FROM ".self::GAME_TABLE."
WHERE state IN ('Finished', 'Draw')
AND modify_date < DATE_SUB(NOW( ), INTERVAL {$age} DAY)
";
$game_ids = $Mysql->fetch_value_array($query);
if ($game_ids) {
self::delete($game_ids);
}
}
/** static public function delete
* Deletes the given game and all related data
*
* @param mixed array or csv of game ids
* @action deletes the game and all related data from the database
* @return void
*/
static public function delete($ids)
{
$Mysql = Mysql::get_instance( );
array_trim($ids, 'int');
if (empty($ids)) {
throw new MyException(__METHOD__.': No game ids given');
}
foreach ($ids as $id) {
try {
self::write_game_file($id);
}
catch (MyException $e) { }
}
$tables = array(
self::GAME_HISTORY_TABLE ,
self::GAME_NUDGE_TABLE ,
self::GAME_TABLE ,
);
$Mysql->multi_delete($tables, " WHERE game_id IN (".implode(',', $ids).") ");
$query = "
OPTIMIZE TABLE ".self::GAME_TABLE."
, ".self::GAME_NUDGE_TABLE."
, ".self::GAME_HISTORY_TABLE."
";
$Mysql->query($query);
}
/** static public function player_deleted
* Deletes the games the given players are in
*
* @param mixed array or csv of player ids
* @action deletes the players games
* @return void
*/
static public function player_deleted($ids)
{
$Mysql = Mysql::get_instance( );
array_trim($ids, 'int');
if (empty($ids)) {
throw new MyException(__METHOD__.': No player ids given');
}
$query = "
SELECT DISTINCT(game_id)
FROM ".self::GAME_TABLE."
WHERE white_id IN (".implode(',', $ids).")
OR black_id IN (".implode(',', $ids).")
";
$game_ids = $Mysql->fetch_value_array($query);
if ($game_ids) {
self::delete($game_ids);
}
}
/** static public function pause
* Pauses the given games
*
* @param mixed array or csv of game ids
* @param bool optional pause game (false = unpause)
* @action pauses the games
* @return void
*/
static public function pause($ids, $pause = true)
{
$Mysql = Mysql::get_instance( );
array_trim($ids, 'int');
$pause = (int) (bool) $pause;
if (empty($ids)) {
throw new MyException(__METHOD__.': No game ids given');
}
$Mysql->insert(self::GAME_TABLE, array('paused' => $pause), " WHERE game_id IN (".implode(',', $ids).") ");
}
} // end of Game class
/* schemas
// ===================================
Game table
----------------------
DROP TABLE IF EXISTS `ph_game`;
CREATE TABLE IF NOT EXISTS `ph_game` (
`game_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`white_id` int(10) unsigned DEFAULT NULL,
`black_id` int(10) unsigned DEFAULT NULL,
`state` enum('Playing','Finished','Draw') COLLATE latin1_general_ci NOT NULL DEFAULT 'Playing',
`extra_info` text COLLATE latin1_general_ci,
`winner_id` int(10) unsigned DEFAULT NULL,
`setup_id` int(10) unsigned NOT NULL,
`paused` tinyint(1) NOT NULL DEFAULT '0',
`create_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`modify_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`game_id`),
KEY `state` (`state`),
KEY `white_id` (`white_id`),
KEY `black_id` (`black_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
History Table
----------------------
DROP TABLE IF EXISTS `ph_game_history`;
CREATE TABLE IF NOT EXISTS `ph_game_history` (
`game_id` int(10) unsigned NOT NULL DEFAULT '0',
`move` varchar(255) COLLATE latin1_general_ci DEFAULT NULL,
`hits` varchar(255) COLLATE latin1_general_ci DEFAULT NULL,
`board` varchar(87) COLLATE latin1_general_ci NOT NULL,
`extra_info` text COLLATE latin1_general_ci NULL DEFAULT NULL,
`move_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY `game_id` (`game_id`),
KEY `move_date` (`move_date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Table structure for table `ph_game_nudge`
--
DROP TABLE IF EXISTS `ph_game_nudge`;
CREATE TABLE IF NOT EXISTS `bs_game_nudge` (
`game_id` int(10) unsigned NOT NULL DEFAULT '0',
`player_id` int(10) unsigned NOT NULL DEFAULT '0',
`nudged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY `game_player` (`game_id`,`player_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
--
-- Table structure for table `ph_stats`
--
DROP TABLE IF EXISTS `ph_stats`;
CREATE TABLE IF NOT EXISTS `ph_stats` (
`player_id` int(10) unsigned NOT NULL,
`game_id` int(10) unsigned NOT NULL,
`setup_id` int(10) unsigned NOT NULL,
`color` enum('white','black') COLLATE latin1_general_ci NOT NULL,
`win` tinyint(1) NOT NULL DEFAULT '0',
`move_count` int(10) unsigned NOT NULL DEFAULT '0',
`start_date` datetime NOT NULL,
`end_date` datetime NOT NULL,
`hour_count` float(8,3) NOT NULL DEFAULT '0.000',
UNIQUE KEY `player_id` (`player_id`,`game_id`,`setup_id`),
KEY `move_count` (`move_count`),
KEY `hour_count` (`hour_count`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
*/
|
benjamw/pharaoh | 79ae009e9783720585316fb88b09cff334aa3f98 | added titles to piece selection in setup creator | diff --git a/scripts/board.js b/scripts/board.js
index 77be158..8286b0c 100644
--- a/scripts/board.js
+++ b/scripts/board.js
@@ -1,482 +1,488 @@
// creates and manipulates the game board
/*
jQuery('<a/>', {
- id: 'foo',
- href: 'http://google.com',
- title: 'Become a Googler',
- rel: 'external',
- text: 'Go to Google!'
+ id: 'foo',
+ href: 'http://google.com',
+ title: 'Become a Googler',
+ rel: 'external',
+ text: 'Go to Google!'
});
P - pharaoh (target)
E - sphynx (Khet 2.0 laser, N | ) - needs 4 characters to show orientation
F - E --
J - S |
K - W --
A - pyramid (1-sided mirror, NE .\ ) - needs 4 characters to show orientation
B - SE `/
C - SW \`
D - NW /.
X - djed (2-sided mirror, NE-SW \ ) - needs 2 characters to show orientation
Y - NW-SE /
V - Obelisk (defense block) - needs 2 characters to show stacking
W - double stacked obelisks
L - anubis (Khet 2.0 one-sided defense block, N | ) - needs 4 characters to show orientation
M - E --
N - S |
O - W --
H - eye of horus (splitter, NE-SW \ ) - needs 2 characters to show orientation
I - NW-SE /
T - Tower
0000wpwb0000c0000000000D000000a0C0xy0b0Db0D0YX0a0C000000b0000000000A0000DWPW0000
*/
var image_dir = 'images/pieces/',
laser_dir = 'images/laser/',
pieces = {
'P' : 'pharaoh',
'A' : 'pyramid_ne',
'B' : 'pyramid_se',
'C' : 'pyramid_sw',
'D' : 'pyramid_nw',
'X' : 'djed_ne',
'Y' : 'djed_nw',
'V' : 'obelisk',
'W' : 'obelisk_stack',
'H' : 'horus_ne',
'I' : 'horus_nw',
'E' : 'sphynx_n',
'F' : 'sphynx_e',
'J' : 'sphynx_s',
'K' : 'sphynx_w',
'L' : 'anubis_n',
'M' : 'anubis_e',
'N' : 'anubis_s',
'O' : 'anubis_w',
// 'T' : 'tower'
};
var timer = false;
function rotate_piece(piece, rotation, toggle_color) {
var rotate,
lower = (piece !== piece.toUpperCase( ));
rotation = rotation || 'origin';
toggle_color = !! (toggle_color || false);
switch (rotation.toLowerCase( )) {
case 'short' :
rotate = {
'A' : 'D',
'B' : 'C',
'C' : 'B',
'D' : 'A',
'X' : 'Y',
'Y' : 'X',
'H' : 'I',
'I' : 'H',
'F' : 'K',
'K' : 'F',
'M' : 'O',
'O' : 'M'
};
break;
case 'long' :
rotate = {
'A' : 'B',
'B' : 'A',
'C' : 'D',
'D' : 'C',
'X' : 'Y',
'Y' : 'X',
'H' : 'I',
'I' : 'H',
'E' : 'J',
'J' : 'E',
'L' : 'N',
'N' : 'L'
};
break;
case 'origin' :
default :
rotate = {
'A' : 'C',
'B' : 'D',
'C' : 'A',
'D' : 'B',
'E' : 'J',
'F' : 'K',
'J' : 'E',
'K' : 'F',
'L' : 'N',
'M' : 'O',
'N' : 'L',
'O' : 'M'
};
break;
}
piece = piece.toUpperCase( );
if (undefined != rotate[piece]) {
piece = rotate[piece];
}
if (lower) {
piece = ( ! toggle_color) ? piece.toLowerCase( ) : piece.toUpperCase( );
}
else {
piece = (toggle_color) ? piece.toLowerCase( ) : piece.toUpperCase( );
}
return piece;
}
function create_board(xFEN, blank) {
blank = !! (blank || false);
if ( ! xFEN) {
return false;
}
var flip = ('undefined' !== typeof invert) ? !! invert : false;
var i,j,n,idx,
row,piece,color,img,
letters = 'ABCDEFGHIJ',
html = '',
classes = [],
silver = 'silver',
red = 'red',
temp,
id = ' id="the_board"',
idx_id;
// chunk the xFEN into rows
xFEN = xFEN.match(RegExp('.{1,10}','g'));
if (flip) {
letters = letters.split('');
letters = letters.reverse( );
letters = letters.join('');
temp = silver;
silver = red;
red = temp;
xFEN = xFEN.reverse( );
}
if (blank) {
id = '';
}
html += '<div'+id+' class="a_board">'
+'<div class="header corner '+red+'_laser"> </div>';
for (i = 0; i < 10; ++i) {
html += '<div class="header horz">'+letters.charAt(i).toLowerCase( )+'</div>';
}
html += '<div class="header corner"> </div>';
for (i in xFEN) {
i = parseInt(i);
row = xFEN[i];
n = 1 + i;
if (flip) {
n = 8 - i;
row = row.split('');
row = row.reverse( );
row = row.join('');
}
html += '<div class="header vert">'+(9 - n)+'</div>';
for (j = 0; j < 10; ++j) {
classes = [];
piece = row.charAt(j);
if (flip) {
piece = rotate_piece(piece);
}
color = (piece == piece.toUpperCase( )) ? 'silver' : 'red';
idx = ((i * 10) + j);
if (flip) {
idx = 79 - idx;
}
idx_id = ' id="idx_'+idx+'"';
if (blank) {
idx_id = '';
}
html += '<div'+idx_id;
if ((0 == j) || ((0 == i) && (8 == j)) || ((7 == i) && (8 == j))) {
classes.push('c_'+red);
}
else if ((9 == j) || ((0 == i) && (1 == j)) || ((7 == i) && (1 == j))) {
classes.push('c_'+silver);
}
img = '';
if ('0' != piece) {
classes.push('piece');
classes.push('p_'+color);
classes.push('i_'+piece);
classes.push(pieces[piece.toUpperCase( )]);
img = create_piece(piece);
}
if (classes.length) {
html += ' class="'+classes.join(' ')+'"';
}
html += '>'+img+'</div>';
} // end foreach piece loop
html += '<div class="header vert">'+(9 - n)+'</div>';
} // end foreach row loop
html += '<div class="header corner"> </div>';
for (i = 0; i < 10; ++i) {
html += '<div class="header horz">'+letters.charAt(i).toLowerCase( )+'</div>';
}
html += '<div class="header corner '+silver+'_laser"> </div>'
+ '</div> <!-- .a_board -->';
if ( ! blank) {
html += ' <!-- #the_board -->';
}
return html;
}
-function create_piece(piece, hit) {
+function create_piece(piece, hit, title) {
hit = !! (hit || false);
+ title = !! (title || false);
var color = (piece == piece.toUpperCase( )) ? 'silver' : 'red';
var hit = (hit) ? ' hit' : '';
+ var piece_name = '';
- return '<img src="'+image_dir+color+'_'+pieces[piece.toUpperCase( )].toLowerCase( )+'.png" alt="'+piece+'" class="piece'+hit+'" />';
+ if (title) {
+ piece_name = ' title="'+color+' '+pieces[piece.toUpperCase( )].toLowerCase( ).sliceToChar(0, '_')+'"';
+ }
+
+ return '<img src="'+image_dir+color+'_'+pieces[piece.toUpperCase( )].toLowerCase( )+'.png" alt="'+piece+'"'+piece_name+' class="piece'+hit+'" />';
}
function fire_laser(path, i) {
if ( ! path) {
return false;
}
i = parseInt(i) || 0;
var flip = ('undefined' !== typeof invert) ? !! invert : false;
var j,
dir,next_dir,add_dir,nodes,
timeout = 150,
length = path.length;
if ( ! length) {
return false;
}
nodes = path[i].length;
for (j = 0; j < nodes; ++j) {
// grab the next node and see where we went
// if it's an actual node, and not an endpoint
if ('boolean' != typeof path[i][j][0]) {
dir = -path[i][j][1];
// check if we split here, and add the other direction
add_dir = 0;
if (path[i + 1][j][2]) {
add_dir = path[i + 1][path[i + 1][j][2]][1];
}
// if the next node is an endpoint (hit, wall, or looped)
if ('boolean' == typeof path[i + 1][j][0]) {
// if it's a hit
if (true === path[i + 1][j][0]) {
// show the hit (only one direction)
next_dir = 0;
}
else {
// just run it into the wall
next_dir = path[i + 1][j][1];
}
}
else { // the next node is a valid node
next_dir = path[i + 1][j][1];
}
if (flip) {
dir = -dir;
next_dir = -next_dir;
add_dir = -add_dir;
}
// add the laser image
$('#idx_'+path[i][j][0]).append('<img src="'+laser_dir+'new_'+c_sort(dc(dir) + dc(next_dir) + dc(add_dir))+'.png" class="laser new" />');
}
}
if (++i < length) { // increment then read
path = JSON.stringify(path);
timer = setTimeout('fade_laser( ); fire_laser('+path+', '+i+');', timeout);
}
else {
timer = setTimeout('fade_laser(true);', timeout);
}
return false;
}
function fade_laser(end) {
end = !! (end || false);
// find the greatest common multiple and use that image
// but we only need to search divs with new images
// (old images are already minified and faded)
// but don't include hits
$('img.laser.new').each( function( ) {
var $div = $(this).parent( ),
dirs = '',
hits = '';
$('img.laser', $div).each( function( ) {
var match,
$img = $(this);
// make a list of all the directions shown (excluding hits)
if (match = $img.prop('src').match(/\/(?:new_)?([nwse]{2,4})\.png/i)) {
dirs += match[1];
$img.remove( );
}
// loop through all faded hits, and convert them all to faded laser
// (they'll get filtered out and removed if this is the only dir)
if (match = $img.prop('src').match(/\/([nwse])\.png/i)) {
hits += match[1];
$img.remove( );
}
// now loop through any new hits, and convert them to faded hits, but still hits
// but only if there isn't already a hit image here already
// (can happen when firing laser over and over again)
if (match = $img.prop('src').match(/\/new_([nwse])\.png/i)) {
$img.removeClass('new').attr('src', $img.prop('src').replace(/new_/i, ''));
}
});
dirs = c_sort(dirs);
if (1 < dirs.length) {
$div.append('<img src="'+laser_dir+dirs+'.png" class="laser" />');
}
for (var i = 0; i < hits.length; ++i) {
$div.append('<img src="'+laser_dir+hits.charAt(i)+'.png" class="laser" />');
}
});
if (end) {
clearTimeout(timer);
timer = false;
// blink then fade all the hit pieces
$('img.hit')
.delay(125).fadeIn(50).delay(125).fadeOut(50)
.delay(125).fadeIn(50).delay(125).fadeOut(50)
.delay(125).fadeIn(50).delay(125).fadeOut(50)
.delay(125).fadeIn(50).delay(125).fadeTo(50, 0.25);
}
}
// converts dir value to cardinal point
function dc(dir) {
switch (dir) {
case -10: return 'n';
case -1: return 'w';
case 10: return 's';
case 1: return 'e';
}
return '';
}
// sorts the cardinal points for a laser beam
function c_sort(dirs) {
var output = '';
if (-1 != dirs.indexOf('n')) { output += 'n'; }
if (-1 != dirs.indexOf('w')) { output += 'w'; }
if (-1 != dirs.indexOf('s')) { output += 's'; }
if (-1 != dirs.indexOf('e')) { output += 'e'; }
return output;
}
String.prototype.sliceToChar = function(idx, str) {
if ('number' === typeof str) {
var tmp = idx;
idx = str;
str = tmp;
if (-1 == this.indexOf(str)) {
return this;
}
return this.slice(this.indexOf(str), idx);
}
if (-1 == this.indexOf(str)) {
return this;
}
return this.slice(idx, this.indexOf(str));
}
String.prototype.repeat = function(num) {
return new Array(parseInt(num) + 1).join(this);
}
String.prototype.expandFEN = function( ) {
return this.replace(/\s*/g, '').replace(/(?:10|[1-9])/g, function(len) { return '0'.repeat(len); }).replace(/\//g, '');
}
|
benjamw/pharaoh | e4177ef308c7788f67cca31ae438bb197c782fe0 | made is_checked function allow for empty values | diff --git a/includes/func.html.php b/includes/func.html.php
index 6704707..8aa52b9 100644
--- a/includes/func.html.php
+++ b/includes/func.html.php
@@ -1,172 +1,176 @@
<?php
/**
* HTML FUNCTIONS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** function is_checked [isChecked]
* Checks the value for a 'true' value
* and returns true if found
*
* Good for use in database inserts
* $data['field'] = is_checked($_POST['field']);
*
* @param string field value
* @return bool checked
*/
-function is_checked($value) {
+function is_checked( & $value) {
+ if (empty($value)) {
+ return false;
+ }
+
switch (strtolower($value)) {
case 'checked':
case 'true':
case 'yes':
case 'on':
case 'y':
case '1':
return true;
break;
}
return false;
}
function isChecked($value) { return is_checked($value); }
/** function get_selected [getSelected] [printable]
* Checks the two given values to see if
* they are the same and returns the HTML input
* attribute to either check the box, or select
* the option
*
* Good for prepopulating an html form
* <input type="checkbox" name="foo" value="bar" <?php print_selected('bar', $_POST['foo'], false); ?> />
*
* @param mixed value one
* @param mixed value two
* @param bool select box
* @return string html attribute
*/
function get_selected($one, $two, $selected = true) {
if ( ($one === (int) $two) || ($one === (string) $two) || ($one === $two) ) {
if ( $selected ) {
return ' selected="selected" ';
} else {
return ' checked="checked" ';
}
} else {
return ' ';
}
}
function getSelected($one, $two, $selected = true) { return get_selected($one, $two, $selected); }
function print_selected($one, $two, $selected = true) { echo get_selected($one, $two, $selected); }
function printSelected($one, $two, $selected = true) { echo get_selected($one, $two, $selected); }
/** function get_selected_bitwise [getSelectedBitwise] [printable]
* Checks the two given values to see if they
* have a common bit and returns the HTML input
* attribute to either check the box, or select
* the option
*
* Good for prepopulating an html form
* <input type="checkbox" name="foo" value="2" <?php print_selected_bitwise(2, $_POST['foo'], false); ?> />
*
* @param int value one
* @param int value two
* @param bool select box
* @return string html attribute
*/
function get_selected_bitwise($one, $two, $selected = true) {
if (0 != ($one & $two)) {
if ( $selected ) {
return ' selected="selected" ';
} else {
return ' checked="checked" ';
}
} else {
return ' ';
}
}
function getSelectedBitwise($one, $two, $selected = true) { return get_selected_bitwise($one, $two, $selected); }
function print_selected_bitwise($one, $two, $selected = true) { echo get_selected_bitwise($one, $two, $selected); }
function printSelectedBitwise($one, $two, $selected = true) { echo get_selected_bitwise($one, $two, $selected); }
/** function perc
* Returns a number formatted as a percentage
*
* @param float value (should be less than 1)
* @param int number of decimal digits to show
* @return string formatted percentage
*/
function perc($num, $digits = 2) {
return number_format($num * 100, $digits).' %';
}
/** function humanize
* Returns a variable string as human readable
*
* @param string variable string
* @return string formatted as human readable
*/
function humanize($string) {
// convert camelCase to under_scored
$string = strtolower(preg_replace('/([A-Z])/', '_$1', $string));
// convert under_scored to Human Readable
$string = ucwords(trim(preg_replace('/_+/', ' ', $string)));
return $string;
}
/** function plural
* Returns a plural version of a string if needed
*
* @param int number of items
* @param string singular version of item name
* @param string plural version of item name
* @return string formatted as needed
*/
function plural($items, $singular, $plural = null) {
if (is_null($plural)) {
// if there are lowercase letters in the singular string
if (preg_match('/[a-z]/', $singular)) {
$plural = $singular.'s';
}
else {
$plural = $singular.'S';
}
}
return (1 == abs($items)) ? $singular : $plural;
}
/** function singular
* Returns a singular version of a string if needed
* basically removes a trailing "s" if found
*
* @param string input string
* @return string formatted as needed
*/
function singular($string) {
if ('s' == strtolower($string[strlen($string) - 1])) {
$string = substr($string, 0, -1);
}
return $string;
}
/** function human
* Returns a human version of a string if needed
*
* @param string input string
* @return string with _ replaced with space
*/
function human($string) {
return str_replace('_', ' ', $string);
}
|
benjamw/pharaoh | 02f0fd03fa235000703e2e9cc14d32620c53af06 | fixed setup not recognizing both pharaohs properly | diff --git a/classes/setup.class.php b/classes/setup.class.php
index d7745d9..c12c67e 100644
--- a/classes/setup.class.php
+++ b/classes/setup.class.php
@@ -22,950 +22,950 @@ class Setup {
/**
* PROPERTIES
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** const property SETUP_TABLE
* Holds the game setup table name
*
* @var string
*/
const SETUP_TABLE = T_SETUP;
/** protected property id
* Holds the setup id
*
* @var int
*/
protected $id;
/** protected property board
* Holds the game board as expanded FEN
*
* @var string
*/
protected $board;
/** protected property name
* Holds the name of the setup
*
* @var string
*/
protected $name = '';
/** protected property creator
* Holds the id of the creator (player)
*
* @var int
*/
protected $creator = 0;
/**
* METHODS
* * * * * * * * * * * * * * * * * * * * * * * * * * */
/** public function __construct
* Class constructor
* Sets all outside data
*
* @param void
* @action instantiates object
* @return void
*/
public function __construct($id = null)
{
$id = (int) $id;
call(__METHOD__);
$this->_init_board( );
if ($id) {
$this->id = $id;
}
$this->_pull( );
}
/** public function __destruct
* Class destructor
* Gets object ready for destruction
*
* @param void
* @action destroys object
* @return void
*/
public function __destruct( )
{
// save anything changed to the database
// BUT... only if PHP didn't die because of an error
$error = error_get_last( );
if (0 == ((E_ERROR | E_WARNING | E_PARSE) & $error['type'])) {
try {
$this->_save( );
}
catch (MyException $e) {
// do nothing, it will be logged
}
}
}
/** public function __get
* Class getter
* Returns the requested property if the
* requested property is not _private
*
* @param string property name
* @return mixed property value
*/
public function __get($property)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 2);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 2);
}
return $this->$property;
}
/** public function __set
* Class setter
* Sets the requested property if the
* requested property is not _private
*
* @param string property name
* @param mixed property value
* @action optional validation
* @return bool success
*/
public function __set($property, $value)
{
if ( ! property_exists($this, $property)) {
throw new MyException(__METHOD__.': Trying to access non-existent property ('.$property.')', 3);
}
if ('_' === $property[0]) {
throw new MyException(__METHOD__.': Trying to access _private property ('.$property.')', 3);
}
switch ($property) {
case 'name' :
// make sure this name isn't in use
$test_value = sani($value);
$query = "
SELECT COUNT(*)
FROM ".self::SETUP_TABLE."
WHERE name = '{$test_value}'
AND setup_id <> '{$this->id}'
";
$count = Mysql::get_instance( )->fetch_value($query);
if ($count) {
throw new MyException(__METHOD__.': That setup name ('.$value.') is already in use');
}
break;
case 'board' :
try {
self::is_valid_setup($value);
}
catch (MyExecption $e) {
throw $e;
}
$value = expandFEN($value);
break;
case 'id' :
$value = (int) $value;
break;
default :
// do nothing
break;
}
$this->$property = $value;
}
/** public function __toString
* Returns the ascii version of the board
* when asked to output the object
*
* @param void
* @return string ascii version of the board
*/
public function __toString( )
{
return $this->_get_board_ascii( );
}
/** static public function get_board_ascii
* Returns the board in an ASCII format
*
* A B C D E F G H I J
* +---+---+---+---+---+---+---+---+---+---+
* 8 | R | S | | | | | | | R | S | 8
* +---+---+---+---+---+---+---+---+---+---+
* 7 | R | | | | | | | | | S | 7
* +---+---+---+---+---+---+---+---+---+---+
* 6 | R | | | | | | | | | S | 6
* +---+---+---+---+---+---+---+---+---+---+
* 5 | R | | | | | | | | | S | 5
* +---+---+---+---+---o---+---+---+---+---+
* 4 | R | | | | | | | | | S | 4
* +---+---+---+---+---+---+---+---+---+---+
* 3 | R | | | | | | | | | S | 3
* +---+---+---+---+---+---+---+---+---+---+
* 2 | R | | | | | | | | | S | 2
* +---+---+---+---+---+---+---+---+---+---+
* 1 | R | S | | | | | | | R | S | 1
* +---+---+---+---+---+---+---+---+---+---+
* A B C D E F G H I J
*
* @param string expanded board FEN
* @return string ascii board
*/
static public function get_board_ascii($board)
{
$ascii = '
A B C D E F G H I J
+---+---+---+---+---+---+---+---+---+---+';
for ($length = strlen($board), $i = 0; $i < $length; ++$i) {
$char = $board[$i];
if (0 == ($i % 10)) {
$ascii .= "\n ".(8 - floor($i / 10)).' |';
}
if ('0' == $char) {
$char = ' ';
}
$ascii .= ' '.$char.' |';
if (9 == ($i % 10)) {
$ascii .= ' '.(8 - floor($i / 10)).'
+---+---+---+---+---+---+---+---+---+---+';
}
}
$ascii .= '
A B C D E F G H I J
';
return $ascii;
}
/** protected function _get_board_ascii
* Returns the board in an ASCII format
*
* @see get_board_ascii
* @param string optional expanded board FEN
* @return string ascii board
*/
protected function _get_board_ascii($board = null)
{
if ( ! $board) {
$board = $this->_board;
}
return self::get_board_ascii($board);
}
/** protected function _pull
* Pulls the setup data from the database
*
* @param void
* @action pulls the setup data and sets the class properties
* @return void
*/
protected function _pull( )
{
call(__METHOD__);
if ( ! $this->id) {
return;
}
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE setup_id = '{$this->id}'
";
$setup = Mysql::get_instance( )->fetch_assoc($query);
$this->board = expandFEN($setup['board']);
$this->creator = $setup['created_by'];
$this->name = $setup['name'];
}
/** protected function _init_board
* Initializes an empty board
*
* @param void
* @action initializes an empty board
* @return void
*/
protected function _init_board( )
{
$this->board = expandFEN('10/10/10/10/10/10/10/10');
}
/** public function validate
* Validates the current setup
*
* @param string [optional] reflection type (Origin, Long, Short)
* @return bool if the setup is valid
*/
public function validate($reflection = 'Origin')
{
call(__METHOD__);
call($this->board);
$Mysql = Mysql::get_instance( );
try {
// will run is_valid_setup as well
self::is_valid_reflection($this->board, $reflection);
}
catch (MyExecption $e) {
throw $e;
}
// test for pre-existing setup
$FEN = packFEN($this->board);
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE board = '{$FEN}'
AND setup_id <> '{$this->id}'
";
$result = $Mysql->fetch_assoc($query);
if ($result) {
throw new MyException(__METHOD__.': Setup already exists as "'.$result['name'].'" (#'.$result['setup_id'].')');
}
// test for pre-existing setup name
$name = sani($this->name);
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE name = '{$name}'
AND setup_id <> '{$this->id}'
";
$result = $Mysql->fetch_assoc($query);
if ($result) {
throw new MyException(__METHOD__.': Setup name ('.$name.') already used (#'.$result['setup_id'].')');
}
return true;
}
/** protected function _save
* Saves the setup data to the database
*
* @param string [optional] reflection type (Origin, Long, Short)
* @action saves the setup data
* @return void
*/
protected function _save($reflection = 'Origin')
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
try {
$this->validate($reflection);
}
catch (MyException $e) {
throw $e;
}
// DON'T sanitize the data
// it gets sani'd in the MySQL->insert method
// translate (filter/sanitize) the data
$data['name'] = $this->name;
$data['board'] = packFEN($this->board);
$data['reflection'] = self::_get_reflection($this->board);
$data['has_horus'] = self::has_horus($this->board);
$data['has_sphynx'] = self::has_sphynx($this->board);
$data['has_tower'] = self::has_tower($this->board);
$data['created_by'] = (int) $this->creator;
call($data);
// create the setup
$required = array(
'name',
'board',
);
$key_list = array_merge($required, array(
'reflection',
'has_horus',
'has_sphynx',
'has_tower',
'created_by',
));
try {
$_DATA = array_clean($data, $key_list, $required);
}
catch (MyException $e) {
throw $e;
}
$_DATA['created '] = 'NOW( )'; // note the trailing space in the field name, this is not a typo
// grab the original setup data
$query = "
SELECT *
FROM ".self::SETUP_TABLE."
WHERE setup_id = '{$this->id}'
";
$setup = $Mysql->fetch_assoc($query);
call($setup);
if ( ! empty($this->id) && ! $setup) {
// we must have deleted the setup, just stop
return false;
}
if ( ! $setup) {
$this->id = $Mysql->insert(self::SETUP_TABLE, $_DATA);
if (empty($this->id)) {
throw new MyException(__METHOD__.': Setup could not be created');
}
return $this->id;
}
$update_setup = false;
// don't change the creator
// in case of admin edits
unset($_DATA['created_by']);
foreach ($setup as $key => $value) {
if (empty($_DATA[$key])) {
continue;
}
if ($_DATA[$key] != $value) {
$update_setup[$key] = $_DATA[$key];
}
}
call($update_setup);
if ($update_setup) {
$Mysql->insert(self::SETUP_TABLE, $update_setup, " WHERE setup_id = '{$this->id}' ");
return true;
}
return false;
}
public function save( )
{
call(__METHOD__);
call($_POST);
// set the post stuff into the object
try {
$this->name = $_POST['name'];
$this->board = $_POST['setup'];
$this->creator = $_SESSION['player_id'];
}
catch (MyException $e) {
throw $e;
}
return $this->_save($_POST['reflection']);
}
/** static public function is_valid_setup
* Tests the validity of the given setup
*
* @param string setup
* @return bool valid setup
*/
static public function is_valid_setup($setup)
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
if (80 != strlen($xFEN)) {
throw new MyException(__METHOD__.': Incorrect board size');
}
// test for a pharaoh on both sides
if ( ! preg_match('/P/', $xFEN, $s_match) || ! preg_match('/p/', $xFEN, $r_match)) {
throw new MyException(__METHOD__.': Missing one or both Pharaohs');
}
// make sure there's only one of each pharaoh
- if ((1 != count($s_match)) || (1 != count($s_match))) {
+ if ((1 != count($s_match)) || (1 != count($r_match))) {
throw new MyException(__METHOD__.': Too many of one or both Pharaohs');
}
// test for a sphynx on both sides (if any)
if (preg_match('/[EFJK]/i', $xFEN) && ( ! preg_match('/[EFJK]/', $xFEN, $s_match) || ! preg_match('/[efjk]/', $xFEN, $r_match))) {
throw new MyException(__METHOD__.': Missing one or both Sphynxes');
}
// make sure there's only one of each sphynx
if ((1 != count($s_match)) || (1 != count($r_match))) {
throw new MyException(__METHOD__.': Too many of one or both Sphynxes');
}
// look for invalid characters
if (preg_match('/[^abcdefhijklmnoptvwxy0]/i', $xFEN)) {
throw new MyException(__METHOD__.': Invalid characters found in setup');
}
// test for pieces on incorrect colors
$not_silver = array(0, 10, 20, 30, 40, 50, 60, 70, 8, 78);
foreach ($not_silver as $i) {
if (('0' != $xFEN[$i]) && ('silver' == Pharaoh::get_piece_color($xFEN[$i]))) {
throw new MyException(__METHOD__.': Silver piece on red square at '.$i);
}
}
$not_red = array(9, 19, 29, 39, 49, 59, 69, 79, 1, 71);
foreach ($not_red as $i) {
if (('0' != $xFEN[$i]) && ('red' == Pharaoh::get_piece_color($xFEN[$i]))) {
throw new MyException(__METHOD__.': Red piece on silver square at '.$i);
}
}
return true;
}
/** static public function test_reflection
* Tests the validity of the given reflection
* for the given setup
*
* @param string setup
* @param string [optional] reflection type (Origin, Long, Short)
* @return bool if the reflection is valid
*/
static public function is_valid_reflection($setup, $type = 'Origin')
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
// validate the setup
try {
self::is_valid_setup($xFEN);
}
catch (MyException $e) {
throw $e;
}
// make sure the given xFEN has all the pieces reflected properly
switch ($type) {
case 'Origin' :
$reflect = array(
// pyramids
'A' => 'c', 'C' => 'a',
'B' => 'd', 'D' => 'b',
// djeds
'X' => 'x', 'Y' => 'y',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'h', 'I' => 'i',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$return = 79 - $i;
';
break;
case 'Long' :
$reflect = array(
// pyramids
'A' => 'b', 'B' => 'a',
'C' => 'd', 'D' => 'c',
// djeds
'X' => 'y', 'Y' => 'x',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'i', 'I' => 'h',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$tens = (int) floor($i / 10);
$return = ((7 - $tens) * 10) + ($i % 10);
';
break;
case 'Short' :
$reflect = array(
// pyramids
'A' => 'd', 'D' => 'a',
'B' => 'c', 'C' => 'b',
// djeds
'X' => 'y', 'Y' => 'x',
// obelisks
'V' => 'v',
'W' => 'w',
// pharaoh
'P' => 'p',
// eye of horus
'H' => 'i', 'I' => 'h',
);
$reflect_keys = array_keys($reflect);
// TOWER: may need to add some more reflect algorithms
$_reflect = '
$tens = (int) floor($i / 10);
$return = ($tens * 10) + (9 - ($i % 10));
';
break;
default :
return true;
break;
}
// TOWER: may need to change limits
for ($i = 0; $i < 80; ++$i) {
$c = $xFEN[$i];
if (('0' !== $c) && (strtoupper($c) === $c) && in_array($c, $reflect_keys)) {
eval($_reflect); // creates $return
if ($reflect[$c] !== $xFEN[$return]) {
throw new MyException(__METHOD__.': Invalid reflected character found at index '.$i.' ('.Pharaoh::index_to_target($i).') = '.$c.'->'.$xFEN[$return].' should be '.$reflect[$c]);
}
// remove the tested chars
$xFEN[$i] = '.';
$xFEN[$return] = '.';
}
}
// we tested all silver -> red
// and matching pairs were removed
// now look for any remaining red
if (preg_match('/[a-dhipvwxy]/', $xFEN, $matches, PREG_OFFSET_CAPTURE)) {
// TODO: get index for faulty red pieces
throw new MyException(__METHOD__.': Red piece found without matching Silver piece');
}
return true;
}
/** static public function _get_reflection
* Gets the reflection type for the given setup
*
* @param string board
* @return string reflection type
*/
static public function _get_reflection($setup)
{
call(__METHOD__);
call($setup);
// expand the board FEN
$xFEN = expandFEN($setup);
foreach (array('Origin', 'Long', 'Short', 'None') as $type) {
try {
self::is_valid_reflection($xFEN, $type);
}
catch (MyException $e) {
continue;
}
break;
}
return $type;
}
/** public function get_reflection
* Gets the reflection type for the current setup
*
* @param void
* @return string reflection type
*/
public function get_reflection( )
{
return self::_get_reflection($this->board);
}
/** static public function has_tower
* Does the given setup use the tower?
*
* @param void
* @return bool setup has tower
*/
static public function has_tower($setup)
{
return preg_match('/[t]/i', $setup);
}
/** static public function has_horus
* Does the given setup use the Eye of Horus?
*
* @param void
* @return bool setup has eye of horus
*/
static public function has_horus($setup)
{
return preg_match('/[hi]/i', $setup);
}
/** static public function has_sphynx
* Does the given setup use the Sphynx?
*
* @param void
* @return bool setup has sphynx
*/
static public function has_sphynx($setup)
{
return preg_match('/[efjk]/i', $setup);
}
/** static public function delete
* Deletes the given setup and all related data
*
* @param mixed array or csv of setup ids
* @action deletes the setup and all related data from the database
* @return void
*/
static public function delete($ids)
{
$Mysql = Mysql::get_instance( );
array_trim($ids, 'int');
if (empty($ids)) {
throw new MyException(__METHOD__.': No game ids given');
}
$tables = array(
self::SETUP_TABLE ,
);
$Mysql->multi_delete($tables, " WHERE setup_id IN (".implode(',', $ids).") ");
$query = "
OPTIMIZE TABLE ".self::SETUP_TABLE."
";
$Mysql->query($query);
}
/** static public function get_list
* Gets the list of all the setups
*
* @param void
* @return array setups
*/
static public function get_list( )
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$query = "
SELECT S.*
, COUNT(G.game_id) AS current_games
FROM ".self::SETUP_TABLE." AS S
LEFT JOIN ".Game::GAME_TABLE." AS G
ON (G.setup_id = S.setup_id)
GROUP BY S.setup_id
ORDER BY S.has_tower ASC
, S.has_sphynx ASC
, S.has_horus ASC
, S.name ASC
";
$setups = $Mysql->fetch_array($query);
return $setups;
}
/** static public function get_count
* Gets the count of all the setups
* optionally filters by creator
*
* @param int [optipnal] player id
* @return array (total, owned by player)
*/
static public function get_count($player_id = 0)
{
call(__METHOD__);
$Mysql = Mysql::get_instance( );
$player_id = (int) $player_id;
$query = "
SELECT COUNT(*)
FROM ".self::SETUP_TABLE."
";
$total = $Mysql->fetch_value($query);
$query = "
SELECT COUNT(*)
FROM ".self::SETUP_TABLE."
WHERE created_by = '{$player_id}'
";
$mine = $Mysql->fetch_value($query);
return array($total, $mine);
}
/** static public function add_used
* Increments the 'used' count for the given setup
*
* @param int setup id
* @action increments the 'used' count
* @return void
*/
static public function add_used($setup_id)
{
call(__METHOD__);
$setup_id = (int) $setup_id;
$query = "
UPDATE ".self::SETUP_TABLE."
SET used = used + 1
WHERE setup_id = '{$setup_id}'
";
Mysql::get_instance( )->query($query);
}
} // end Setup
/*
--
-- Table structure for table `ph_setup`
--
DROP TABLE IF EXISTS `ph_setup`;
CREATE TABLE IF NOT EXISTS `ph_setup` (
`setup_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE latin1_general_ci NOT NULL,
`board` varchar(87) COLLATE latin1_general_ci NOT NULL,
`reflection` enum('Origin','Short','Long','None') COLLATE latin1_general_ci NOT NULL DEFAULT 'Origin',
`has_horus` tinyint(1) NOT NULL DEFAULT '0',
`has_sphynx` tinyint(1) NOT NULL DEFAULT '0',
`has_tower` tinyint(1) NOT NULL DEFAULT '0',
`used` int(11) NOT NULL DEFAULT '0',
`silver_wins` int(10) unsigned NOT NULL DEFAULT '0',
`draws` int(10) unsigned NOT NULL DEFAULT '0',
`red_wins` int(10) unsigned NOT NULL DEFAULT '0',
`shortest_game` int(10) unsigned DEFAULT NULL,
`longest_game` int(10) unsigned DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1',
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'the player id of the player that created the setup',
PRIMARY KEY (`setup_id`),
KEY `has_horus` (`has_horus`),
KEY `has_tower` (`has_tower`),
KEY `active` (`active`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ;
--
-- Dumping data for table `ph_setup`
--
INSERT INTO `ph_setup` (`setup_id`, `name`, `board`, `reflection`, `has_horus`, `has_tower`, `used`, `created`, `created_by`) VALUES
(NULL, 'Classic', '4wpwb2/2c7/3D6/a1C1xy1b1D/b1D1YX1a1C/6b3/7A2/2DWPW4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Dynasty', '4cwb3/5p4/a3cwy3/b1x1D1B3/3d1b1X1D/3YWA3C/4P5/3DWA4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Imhotep', '4wpwy2/10/3D2a3/aC2By2bD/bD2Yd2aC/3C2b3/10/2YWPW4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Osiris', '1Y3cp1bC/2w3wb2/6D3/a3ix3D/b3XI3C/3b6/2DW3W2/aD1PA3y1', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Isis', '6wpb1/a1x3cw2/1X8/a1a1DI2c1/1A2ib1C1C/8x1/2WA3X1C/1DPW6', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Classic 2', '4wpwb2/2c7/3D6/a1C1xi1b1D/b1D1IX1a1C/6b3/7A2/2DWPW4', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Dynasty 2', '4cwb3/5p4/a3cwy3/b1h1D1B3/3d1b1H1D/3YWA3C/4P5/3DWA4', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Imhotep 2', '4wpwy2/10/3D2a3/aC2Bi2bD/bD2Id2aC/3C2b3/10/2YWPW4', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Khufu', '4wpwb2/5cb3/a5D3/4yX1a1D/b1C1Xy4/3b5C/3DA5/2DWPW4', 'None', 0, 0, 0, NOW( ), 0),
(NULL, 'Imseti', '1B1wpb4/2Xbcw4/10/a3xc3D/b3AX3C/10/4WADx2/4DPW1d1', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Nefertiti', '4w1w3/3c1pb3/2C1cy1c2/a1Y6D/b6y1C/2A1YA1a2/3DP1A3/3W1W4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Rameses', '3w1pwb2/4bc4/2Cb2x3/a4X3D/b3x4C/3X2Da2/4AD4/2DWP1W3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Amarna', '1CBcwpw3/4bcb3/10/a2x2x3/3X2X2C/10/3DAD4/3WPWAda1', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Saqqara', '3cwp1wb1/4bxb3/a2D6/4X4D/b4x4/6b2C/3DXD4/1DW1PWA3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Djoser''s Step', '3cw1w1b1/5p1b2/4bxb3/a4y3D/b3Y4C/3DXD4/2D1P5/1D1W1WA3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Horemheb', '3c3b2/4wpw3/3x1x1b2/a3c1b2D/b2D1A3C/2D1X1X3/3WPW4/2D3A3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Senet', '4cwb3/a2c1p1b2/4xwy3/5b3C/a3D5/3YWX4/2D1P1A2C/3DWA4', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Tutankhamun', '3w4b1/a1cpb5/3w1b4/b1x1y1b3/3D1Y1X1D/4D1W3/5DPA1C/1D4W3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Offla', '3c1pwb2/4cwb3/2X2x4/a4D3D/b3b4C/4X2x2/3DWA4/2DWP1A3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Ebana', '3xwpwb2/5x4/2DA6/a1CB5D/b5da1C/6cb2/4X5/2DWPWX3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Qa''a', '3xwpwb2/4cy4/8bD/3c2b2C/a2D2A3/bD8/4YA4/2DWPWX3', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Qa''a 2', '3xwpwb2/4cy4/8bD/3c2b1hC/aH1D2A3/bD8/4YA4/2DWPWX3', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Seti I', '1XB1cw1pb1/a4cwy1D/6b3/5i4/4I5/3D6/b1YWA4C/1DP1WA1dx1', 'Origin', 1, 0, 0, NOW( ), 0),
(NULL, 'Seti II', '1XB1cw1pb1/a4cwy1D/6b3/10/10/3D6/b1YWA4C/1DP1WA1dx1', 'Origin', 0, 0, 0, NOW( ), 0),
(NULL, 'Ay', '4cw1wbC/3CB5/5x4/a3Ypb3/3DPy3C/4X5/5da3/aDW1WA4', 'Origin', 0, 0, 0, NOW( ), 0);
*/
|
petrsigut/unico | e9afdcfad441a0428258c18e4003cb101e79693e | changed default route | diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
deleted file mode 100644
index 15fb864..0000000
Binary files a/app/models/.content.rb.swp and /dev/null differ
diff --git a/app/models/.googlepocasi.rb.swp b/app/models/.googlepocasi.rb.swp
deleted file mode 100644
index 3c67c1a..0000000
Binary files a/app/models/.googlepocasi.rb.swp and /dev/null differ
diff --git a/config/.environment.rb.swp b/config/.environment.rb.swp
deleted file mode 100644
index f7a90be..0000000
Binary files a/config/.environment.rb.swp and /dev/null differ
diff --git a/config/routes.rb b/config/routes.rb
index 13424a5..05cf4f5 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,49 +1,47 @@
ActionController::Routing::Routes.draw do |map|
map.connect 'movies/feed.:format', :controller => 'movies', :action => 'index'
#map.connect 'cnb/feed.:format', :controller => 'cnb', :action => 'index'
- map.resources :pcfilmtydne
-
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
- # map.root :controller => "welcome"
+ map.root :controller => "contents"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
diff --git a/public/index.html b/public/index.html
deleted file mode 100644
index 0dd5189..0000000
--- a/public/index.html
+++ /dev/null
@@ -1,275 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html>
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>Ruby on Rails: Welcome aboard</title>
- <style type="text/css" media="screen">
- body {
- margin: 0;
- margin-bottom: 25px;
- padding: 0;
- background-color: #f0f0f0;
- font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
- font-size: 13px;
- color: #333;
- }
-
- h1 {
- font-size: 28px;
- color: #000;
- }
-
- a {color: #03c}
- a:hover {
- background-color: #03c;
- color: white;
- text-decoration: none;
- }
-
-
- #page {
- background-color: #f0f0f0;
- width: 750px;
- margin: 0;
- margin-left: auto;
- margin-right: auto;
- }
-
- #content {
- float: left;
- background-color: white;
- border: 3px solid #aaa;
- border-top: none;
- padding: 25px;
- width: 500px;
- }
-
- #sidebar {
- float: right;
- width: 175px;
- }
-
- #footer {
- clear: both;
- }
-
-
- #header, #about, #getting-started {
- padding-left: 75px;
- padding-right: 30px;
- }
-
-
- #header {
- background-image: url("images/rails.png");
- background-repeat: no-repeat;
- background-position: top left;
- height: 64px;
- }
- #header h1, #header h2 {margin: 0}
- #header h2 {
- color: #888;
- font-weight: normal;
- font-size: 16px;
- }
-
-
- #about h3 {
- margin: 0;
- margin-bottom: 10px;
- font-size: 14px;
- }
-
- #about-content {
- background-color: #ffd;
- border: 1px solid #fc0;
- margin-left: -11px;
- }
- #about-content table {
- margin-top: 10px;
- margin-bottom: 10px;
- font-size: 11px;
- border-collapse: collapse;
- }
- #about-content td {
- padding: 10px;
- padding-top: 3px;
- padding-bottom: 3px;
- }
- #about-content td.name {color: #555}
- #about-content td.value {color: #000}
-
- #about-content.failure {
- background-color: #fcc;
- border: 1px solid #f00;
- }
- #about-content.failure p {
- margin: 0;
- padding: 10px;
- }
-
-
- #getting-started {
- border-top: 1px solid #ccc;
- margin-top: 25px;
- padding-top: 15px;
- }
- #getting-started h1 {
- margin: 0;
- font-size: 20px;
- }
- #getting-started h2 {
- margin: 0;
- font-size: 14px;
- font-weight: normal;
- color: #333;
- margin-bottom: 25px;
- }
- #getting-started ol {
- margin-left: 0;
- padding-left: 0;
- }
- #getting-started li {
- font-size: 18px;
- color: #888;
- margin-bottom: 25px;
- }
- #getting-started li h2 {
- margin: 0;
- font-weight: normal;
- font-size: 18px;
- color: #333;
- }
- #getting-started li p {
- color: #555;
- font-size: 13px;
- }
-
-
- #search {
- margin: 0;
- padding-top: 10px;
- padding-bottom: 10px;
- font-size: 11px;
- }
- #search input {
- font-size: 11px;
- margin: 2px;
- }
- #search-text {width: 170px}
-
-
- #sidebar ul {
- margin-left: 0;
- padding-left: 0;
- }
- #sidebar ul h3 {
- margin-top: 25px;
- font-size: 16px;
- padding-bottom: 10px;
- border-bottom: 1px solid #ccc;
- }
- #sidebar li {
- list-style-type: none;
- }
- #sidebar ul.links li {
- margin-bottom: 5px;
- }
-
- </style>
- <script type="text/javascript" src="javascripts/prototype.js"></script>
- <script type="text/javascript" src="javascripts/effects.js"></script>
- <script type="text/javascript">
- function about() {
- if (Element.empty('about-content')) {
- new Ajax.Updater('about-content', 'rails/info/properties', {
- method: 'get',
- onFailure: function() {Element.classNames('about-content').add('failure')},
- onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})}
- });
- } else {
- new Effect[Element.visible('about-content') ?
- 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25});
- }
- }
-
- window.onload = function() {
- $('search-text').value = '';
- $('search').onsubmit = function() {
- $('search-text').value = 'site:rubyonrails.org ' + $F('search-text');
- }
- }
- </script>
- </head>
- <body>
- <div id="page">
- <div id="sidebar">
- <ul id="sidebar-items">
- <li>
- <form id="search" action="http://www.google.com/search" method="get">
- <input type="hidden" name="hl" value="en" />
- <input type="text" id="search-text" name="q" value="site:rubyonrails.org " />
- <input type="submit" value="Search" /> the Rails site
- </form>
- </li>
-
- <li>
- <h3>Join the community</h3>
- <ul class="links">
- <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li>
- <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li>
- <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li>
- </ul>
- </li>
-
- <li>
- <h3>Browse the documentation</h3>
- <ul class="links">
- <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
- <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
- <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
- <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
- </ul>
- </li>
- </ul>
- </div>
-
- <div id="content">
- <div id="header">
- <h1>Welcome aboard</h1>
- <h2>You’re riding Ruby on Rails!</h2>
- </div>
-
- <div id="about">
- <h3><a href="rails/info/properties" onclick="about(); return false">About your application’s environment</a></h3>
- <div id="about-content" style="display: none"></div>
- </div>
-
- <div id="getting-started">
- <h1>Getting started</h1>
- <h2>Here’s how to get rolling:</h2>
-
- <ol>
- <li>
- <h2>Use <tt>script/generate</tt> to create your models and controllers</h2>
- <p>To see all available options, run it without parameters.</p>
- </li>
-
- <li>
- <h2>Set up a default route and remove or rename this file</h2>
- <p>Routes are set up in config/routes.rb.</p>
- </li>
-
- <li>
- <h2>Create your database</h2>
- <p>Run <tt>rake db:migrate</tt> to create your database. If you're not using SQLite (the default), edit <tt>config/database.yml</tt> with your username and password.</p>
- </li>
- </ol>
- </div>
- </div>
-
- <div id="footer"> </div>
- </div>
- </body>
-</html>
\ No newline at end of file
|
petrsigut/unico | 849ad54ba9ff063f21e8a703765eddb39826fb4e | pryc libxml | diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
index 92f6c49..15fb864 100644
Binary files a/app/models/.content.rb.swp and b/app/models/.content.rb.swp differ
diff --git a/app/models/content.rb b/app/models/content.rb
index b5c5fdf..c4033d6 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,140 +1,140 @@
class Content < ActiveRecord::Base
has_one :category
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
- require 'xml/libxml'
- require 'xml/libxslt'
+ #require 'xml/libxml'
+ #require 'xml/libxslt'
def self.mylayout
"application"
end
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml_data)
xslt = Nokogiri::XSLT(File.open("#{RAILS_ROOT}/public/xml2html.xsl", 'r'))
xml = Nokogiri::XML(xml_data.to_s)
logger.info xml_data.inspect
xslt.transform(xml).to_s
end
def create_xml_head
@xml = REXML::Document.new
#@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@xml_doc = @xml.add_element 'document'
self.xml = @xml_doc
end
def create_xml_body(entity_name, entity_text)
(@xml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @xml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
|
petrsigut/unico | 5a81bf6928fb581e9c8a58a669a064ce2122146d | predelavka na nokiri | diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
new file mode 100644
index 0000000..92f6c49
Binary files /dev/null and b/app/models/.content.rb.swp differ
diff --git a/vendor/gems/libxslt-ruby-0.9.2/.README.swp b/app/models/.googlepocasi.rb.swp
similarity index 61%
rename from vendor/gems/libxslt-ruby-0.9.2/.README.swp
rename to app/models/.googlepocasi.rb.swp
index 0cf8b57..3c67c1a 100644
Binary files a/vendor/gems/libxslt-ruby-0.9.2/.README.swp and b/app/models/.googlepocasi.rb.swp differ
diff --git a/app/models/content.rb b/app/models/content.rb
index 7df5481..b5c5fdf 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,140 +1,140 @@
class Content < ActiveRecord::Base
has_one :category
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
def self.mylayout
"application"
end
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml_data)
- xslt = XML::XSLT.new()
- xslt.xml = xml_data.to_s
- xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
- xslt.serve()
+ xslt = Nokogiri::XSLT(File.open("#{RAILS_ROOT}/public/xml2html.xsl", 'r'))
+ xml = Nokogiri::XML(xml_data.to_s)
+ logger.info xml_data.inspect
+ xslt.transform(xml).to_s
end
def create_xml_head
@xml = REXML::Document.new
#@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@xml_doc = @xml.add_element 'document'
self.xml = @xml_doc
end
def create_xml_body(entity_name, entity_text)
(@xml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @xml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/config/.environment.rb.swp b/config/.environment.rb.swp
index 3dadf02..f7a90be 100644
Binary files a/config/.environment.rb.swp and b/config/.environment.rb.swp differ
diff --git a/config/environment.rb b/config/environment.rb
index 0bdb096..cb42db0 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,45 +1,46 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
PUSH_ENABLE = false
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# config.gem "libxslt-ruby"
+ config.gem "nokogiri"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
|
petrsigut/unico | 5d7958361b5296ba147a00d7314e29379806d9f0 | freeze again | diff --git a/config/.environment.rb.swp b/config/.environment.rb.swp
deleted file mode 100644
index 9566dab..0000000
Binary files a/config/.environment.rb.swp and /dev/null differ
diff --git a/config/environment.rb b/config/environment.rb
index a916b82..54b14b2 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,45 +1,45 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
PUSH_ENABLE = false
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
- config.gem "libxslt-ruby"
+ config.gem "libxslt-ruby", :version => '0.9.2'
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
|
petrsigut/unico | a61625839f45838cf57f9b497d29690878b06790 | trying to freeze libxslt | diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index af62f18..026b284 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,109 +1,91 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
- def send_data
- render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
- page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
- end
- render :nothing => true
- end
-
+ # get data to show all contents
def index
category = params[:category_id]
if (category == "0")
@contents = Content.find(:all, :order => "name")
else
@contents = Content.find(:all, :order => "name", :conditions => ["category_id = ?", category])
end
# @categories = Category.find(:all)
# http://keepwithinthelines.wordpress.com/2008/03/17/using-select-helper-in-rails/
@categories = Category.find(:all)
@categories = [ ["all", 0] ] + @categories.map {|p| [ p.name, p.id ] }
@layout = "index"
end
def show
-
name = params[:id]
@query = {}
params.each do |param|
if (param[0] =~ /^\w+$/i and
param[1] =~ /^\w+$/i and
param[0] != "id" and
param[0] != "format" and
param[0] != "action" and
param[0] != "controller") then
@query[param[0]] = param[1]
end
end
- logger.fatal "Query"
- logger.fatal @query.inspect
- logger.fatal "Query NIL?"
- logger.fatal @query.empty?
-
-
-
-
- # at nam pod to name nepodstrci nejakou zlou vec
+ #logger.fatal "Query"
+ #logger.fatal @query.inspect
+ #logger.fatal "Query NIL?"
+ #logger.fatal @query.empty?
- # zautomatizovat to a udelat automaticky generovany index s prehledem...
- # (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |content_name|
if name == content_name.name
found_in_db = true
end
end
if found_in_db
@content = Content.find_by_name(name, :select => 'updated_at')
# the time should be setable by variable in content model
@layout = (name).constantize.mylayout
if (@content.updated_at < 10.seconds.ago or not @query.empty?)
- @content = (name).constantize.parse_content(@query)
+ @content = (name).constantize.parse_content(@query) # make objeckt from var name
logger.fatal "call parse_content"
else # we want content from db
@content = Content.find_by_name(name)
end
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
- # udelat pres tridni promenou?
- # a pak v tom modelu aby si moh programator vybrat jestli se to obali
- # standardni HTML hlavickou a tak nebo ne...
-
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/content.rb b/app/models/content.rb
index 14acd94..7df5481 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,140 +1,140 @@
class Content < ActiveRecord::Base
has_one :category
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
def self.mylayout
"application"
end
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml_data)
xslt = XML::XSLT.new()
xslt.xml = xml_data.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
xslt.serve()
end
-
+
def create_xml_head
@xml = REXML::Document.new
- @kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
- @kml_doc = @kml.add_element 'document'
- self.xml = @kml_doc
+ #@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
+ @xml_doc = @xml.add_element 'document'
+ self.xml = @xml_doc
end
def create_xml_body(entity_name, entity_text)
- (@kml_doc.add_element entity_name).text = entity_text
+ (@xml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
- self.xml = @kml_doc.to_s
+ self.xml = @xml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/app/models/sablona.rb b/app/models/sablona.rb
index 4d4d6d2..ac200bc 100644
--- a/app/models/sablona.rb
+++ b/app/models/sablona.rb
@@ -1,13 +1,13 @@
class Model < Content
def self.parse_content(query = {})
content = Model.new
content.name_human = "Human name"
rawhtml = Hpricot(open(""))
- content = rawhtml
+ content.rawhtml = rawhtml.to_s
content.save_me(query)
end
end
diff --git a/app/models/sigutgalerie.rb b/app/models/sigutgalerie.rb
new file mode 100644
index 0000000..4a1de69
--- /dev/null
+++ b/app/models/sigutgalerie.rb
@@ -0,0 +1,27 @@
+class Sigutgalerie < Content
+ def self.mylayout
+ "slideshow"
+ end
+
+
+
+ def self.parse_content(query = {})
+ content = Sigutgalerie.new
+ content.name_human = "Fotogalerie Petr Å igut"
+
+ url = "http://www.sigut.net/"
+
+ rawhtml = Hpricot(open(url))
+ rawhtml = rawhtml.at("//span[@class='photos']")
+ rawhtml = rawhtml.search("//img")
+
+ slideshow = []
+ rawhtml.each do |image|
+ slideshow << (url + image.attributes['src'])
+ end
+
+ content.rawhtml = create_gallery(slideshow)
+ content.save_me(query)
+ end
+
+end
diff --git a/app/models/youtube b/app/models/youtube
deleted file mode 100644
index 2043742..0000000
--- a/app/models/youtube
+++ /dev/null
@@ -1,15 +0,0 @@
-class Youtube < Content
- attr_accessor :name
-
- def self.parse_raw_html
- @doc = Hpricot(open(""))
-
- save_me
- end
-
- def self.parse_xml
- #http://www.youtube.com/get_video?video_id=v_4-zRVFLnY&t=vjVQa1PpcFMoUet4DvWYTUuw
- save_me
- end
-
-end
diff --git a/app/views/contents/_juggernaut_head.html.erb b/app/views/contents/_juggernaut_head.html.erb
index 9839687..407ccc6 100644
--- a/app/views/contents/_juggernaut_head.html.erb
+++ b/app/views/contents/_juggernaut_head.html.erb
@@ -1,17 +1,18 @@
<%= javascript_include_tag :defaults, :juggernaut %>
<script>
// firebug console faker, for non-firefox browsers
+ // http://www.dorkalev.com/2008/04/juggernaut-up-to-date-tutorial-1042008.html
window.console = {
firebug: '1.0',
log: function() {
$('console_text').innerHTML = arguments[0] + "\n" + $('console_text').innerHTML;
},
clear: function() {
$('console_text').innerHTML = '';
}
}
</script>
<%= juggernaut %>
diff --git a/config/environment.rb b/config/environment.rb
index 0e20abb..ceb73af 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,44 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
-PUSH_ENABLE = true
+PUSH_ENABLE = false
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
diff --git a/lib/libxslt-ruby-0.9.2/LICENSE b/lib/libxslt-ruby-0.9.2/LICENSE
new file mode 100644
index 0000000..accc9ad
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/LICENSE
@@ -0,0 +1,21 @@
+# $Id: LICENSE 33 2007-08-29 18:18:15Z transami $
+
+Copyright (c) 2002-2006 Sean Chittenden <[email protected]> and contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/lib/libxslt-ruby-0.9.2/README b/lib/libxslt-ruby-0.9.2/README
new file mode 100644
index 0000000..d2add03
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/README
@@ -0,0 +1,164 @@
+= libxslt-ruby
+
+== Overview
+
+The libxslt gem provides Ruby language bindings for GNOME's Libxslt
+toolkit. It is free software, released under the MIT License.
+
+
+== Requirements
+
+libxslt-ruby requires Ruby 1.8.4 or higher. It is dependent on
+the following libraries to function properly:
+
+* libm (math routines: very standard)
+* libz (zlib)
+* libiconv
+* libxml2
+* libxslt
+* libxml-ruby bindings
+
+If you are running Linux or Unix you'll need a C compiler so the extension
+can be compiled when it is installed. If you are running Windows, then install the Windows specific RubyGem which
+includes an already built extension.
+
+!!!NOTE!!! The libxml-ruby and libxslt-ruby bindings must absolutely, positively,
+without a doubt share the same libxml2 library. This is because libxslt modifies
+XML documents created by libxml2. If there are two copies of libxml2 on your
+system, then when XML documents allocated in copy #1 are manipulated by copy #2,
+a segmentation fault will occur. So make sure that your system has only one copy of libxml2
+installed.
+
+
+== INSTALLATION
+
+The easiest way to install libxslt-ruby is via Ruby Gems. To install:
+
+<tt>gem install libxslt-ruby</tt>
+
+If you are running Windows, make sure to install the Win32 RubyGem which
+includes an already built binary file. The binary is built against
+libxml2 version 2.6.32, iconv version 1.11 and libxslt version 1.1.24.
+Binaries for libxml2 and iconv are provided in the libxml-ruby bindings,
+while a binary for libxslt is provided in the libxslt-ruby bindings.
+
+The Windows binaries are biult with MingW. The gem also includes
+a Microsoft VC++ 2005 solution. If you wish to run a debug version
+of libxml-ruby on Windows, then it is highly recommended
+you use VC++.
+
+
+== USAGE
+
+For in-depth information about using libxslt-ruby please refer
+to its online Rdoc documentation.
+
+All libxslt classes are in the LibXSLT::XSLT module. The simplest
+way to use libxslt is to require 'xslt'. This will mixin the
+LibXML and LibXSLT modules into the global namespace, allowing you to
+write code like this:
+
+require 'xslt'
+document = XML::Document.new
+stylesheett = XSLT::Stylesheet.new(document)
+
+If you prefer not to add the LibXSLT module to the global namepace, then
+write your code like this:
+
+require 'libxslt'
+
+class MyClass
+ def some_method
+ document = LibXML::XML::Document.new
+ stylesheett = LibXSLT::XSLT::Stylesheet.new(document)
+ end
+end
+
+Given an XML file like:
+
+ <?xml version="1.0" encoding="UTF-8"?>
+ <?xml-stylesheet href="fuzface.xsl" type="text/xsl"?>
+
+ <commentary>
+ <meta>
+ <author>
+ <first_name>Sean</first_name>
+ <last_name>Chittenden</last_name>
+ <email>[email protected]</email>
+ </author>
+ <version>$Version$</version>
+ <date>$Date: 2008-07-21 20:44:12 -0600 (Mon, 21 Jul 2008) $</date>
+ <id>$Id: README 109 2008-07-22 02:44:12Z cfis $</id> <title>Fuzface...</title>
+ <subtitle>The Internet's a big place and here's some proof...</subtitle>
+ </meta>
+
+ <body>
+ <para>
+ I think it's a tragedy that I'm going to start off my new
+ commentary by talking about facial hair and the Internet.
+ Something about that just screams pathetic, but whatever: it's
+ humor and that's life.
+ </para>
+ </body>
+ </commentary>
+
+And an XSLT file like this:
+
+ <?xml version="1.0" ?>
+ <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+ <xsl:template match="/">
+ <xsl:element name="html">
+ <xsl:element name="head">
+ <xsl:element name="title">Ramblings - <xsl:value-of select="commentary/meta/title" /> - <xsl:value-of select="commentary/meta/subtitle" /></xsl:element>
+ </xsl:element>
+
+ <xsl:element name="body">
+ <xsl:element name="h1"><xsl:value-of select="commentary/meta/title" /></xsl:element>
+ <xsl:element name="h3"><xsl:value-of select="commentary/meta/subtitle" /></xsl:element>
+ By: <xsl:value-of select="commentary/meta/author/first_name" /> <xsl:value-of select="commentary/meta/author/last_name" /><xsl:element name="br" />
+ Date: <xsl:value-of select="commentary/meta/date" /><xsl:element name="br" />
+
+ <xsl:for-each select="./commentary/body">
+ <xsl:apply-templates />
+ </xsl:for-each>
+
+ </xsl:element>
+ </xsl:element>
+ </xsl:template>
+
+ <xsl:template match="para">
+ <xsl:element name="p">
+ <xsl:value-of select="." />
+ </xsl:element>
+ </xsl:template>
+ </xsl:stylesheet>
+
+We can easily transform the XML with the following ruby code:
+
+ require 'xslt'
+
+ # Create a new XSL Transform
+ stylesheet_doc = XML::Document.file('files/fuzface.xsl')
+ stylesheet = LibXSLT::Stylesheet.new(stylesheet_doc)
+
+ # Transform a xml document
+ xml_doc = XML::Document.file('files/fuzface.xml')
+ result = stylesheet.apply(xml_doc)
+
+You can then print, save or manipulate the returned document.
+
+== License
+
+See LICENSE for license information.
+
+== DOCUMENTATION
+
+RDoc comments are included - run 'rake doc' to generate documentation.
+You can find the latest documentation at:
+
+* http://libxsl.rubyforge.org/
+
+== MORE INFORMATION
+
+For more information please refer to the documentation. If you have any
+questions, please send email to [email protected].
\ No newline at end of file
diff --git a/lib/libxslt-ruby-0.9.2/Rakefile b/lib/libxslt-ruby-0.9.2/Rakefile
new file mode 100644
index 0000000..db513aa
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/Rakefile
@@ -0,0 +1,108 @@
+require 'rubygems'
+require 'date'
+require 'rake/gempackagetask'
+require 'rake/rdoctask'
+require 'rake/testtask'
+require 'date'
+
+# ------- Default Package ----------
+FILES = FileList[
+ 'Rakefile',
+ 'README',
+ 'LICENSE',
+ 'setup.rb',
+ 'doc/**/*',
+ 'lib/**/*',
+ 'ext/libxslt/*.h',
+ 'ext/libxslt/*.c',
+ 'ext/mingw/Rakefile',
+ 'ext/vc/*.sln',
+ 'ext/vc/*.vcproj',
+ 'test/**/*'
+]
+
+# Default GEM Specification
+default_spec = Gem::Specification.new do |spec|
+ spec.name = "libxslt-ruby"
+
+ spec.homepage = "http://libxslt.rubyforge.org/"
+ spec.summary = "Ruby libxslt bindings"
+ spec.description = <<-EOF
+ The Libxslt-Ruby project provides Ruby language bindings for the GNOME
+ XSLT C library. It is free software, released under the MIT License.
+ EOF
+
+ # Determine the current version of the software
+ spec.version =
+ if File.read('ext/libxslt/version.h') =~ /\s*RUBY_LIBXSLT_VERSION\s*['"](\d.+)['"]/
+ CURRENT_VERSION = $1
+ else
+ CURRENT_VERSION = "0.0.0"
+ end
+
+ spec.author = "Charlie Savage"
+ spec.email = "[email protected]"
+ spec.add_dependency('libxml-ruby','>=0.9.4')
+ spec.platform = Gem::Platform::RUBY
+ spec.require_paths = ["lib", "ext/libxslt"]
+
+ spec.bindir = "bin"
+ spec.extensions = ["ext/libxslt/extconf.rb"]
+ spec.files = FILES.to_a
+ spec.test_files = Dir.glob("test/tc_*.rb")
+
+ spec.required_ruby_version = '>= 1.8.4'
+ spec.date = DateTime.now
+ spec.rubyforge_project = 'libxslt-ruby'
+
+ spec.has_rdoc = true
+end
+
+# Rake task to build the default package
+Rake::GemPackageTask.new(default_spec) do |pkg|
+ pkg.package_dir = 'admin/pkg'
+ pkg.need_tar = true
+end
+
+# ------- Windows GEM ----------
+if RUBY_PLATFORM.match(/win32/)
+ binaries = (FileList['ext/mingw/*.so',
+ 'ext/mingw/*.dll*'])
+
+ # Windows specification
+ win_spec = default_spec.clone
+ win_spec.extensions = ['ext/mingw/Rakefile']
+ win_spec.platform = Gem::Platform::CURRENT
+ win_spec.files += binaries.to_a
+
+ # Rake task to build the windows package
+ Rake::GemPackageTask.new(win_spec) do |pkg|
+ pkg.package_dir = 'admin/pkg'
+ end
+end
+
+# --------- RDoc Documentation ------
+desc "Generate rdoc documentation"
+Rake::RDocTask.new("rdoc") do |rdoc|
+ rdoc.rdoc_dir = 'doc'
+ rdoc.title = "libxml-xslt"
+ # Show source inline with line numbers
+ rdoc.options << "--inline-source" << "--line-numbers"
+ # Make the readme file the start page for the generated html
+ rdoc.options << '--main' << 'README'
+ rdoc.rdoc_files.include('doc/*.rdoc',
+ 'ext/**/*.c',
+ 'lib/**/*.rb',
+ 'CHANGES',
+ 'README',
+ 'LICENSE')
+end
+
+
+Rake::TestTask.new do |t|
+ t.libs << "test"
+ t.libs << "ext"
+end
+
+task :package => :rdoc
+task :default => :package
\ No newline at end of file
diff --git a/lib/libxslt-ruby-0.9.2/ext/libxslt/extconf.rb b/lib/libxslt-ruby-0.9.2/ext/libxslt/extconf.rb
new file mode 100644
index 0000000..e1999d7
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/libxslt/extconf.rb
@@ -0,0 +1,122 @@
+#!/usr/local/bin/ruby -w
+
+# $Id: extconf.rb 43 2007-12-07 12:38:59Z transami $
+#
+# See the LICENSE file for copyright and distribution information
+
+require 'mkmf'
+
+$preload = nil
+$LIBPATH.push(Config::CONFIG['libdir'])
+
+def crash(str)
+ print(" extconf failure: %s\n", str)
+ exit 1
+end
+
+require 'rubygems'
+gem_specs = Gem::SourceIndex.from_installed_gems.search('libxml-ruby')
+if gem_specs.empty?
+ crash(<<EOL)
+libxml-ruby bindings must be installed
+EOL
+end
+
+# Sort by version, newest first
+gem_specs = gem_specs.sort_by {|spec| spec.version}.reverse
+
+libxml_ruby_path = gem_specs.first.full_gem_path
+
+$INCFLAGS += " -I#{libxml_ruby_path}/ext"
+
+# Directories
+dir_config('xml2')
+dir_config('xslt')
+
+unless have_library('m', 'atan')
+ # try again for gcc 4.0
+ saveflags = $CFLAGS
+ $CFLAGS += ' -fno-builtin'
+ unless have_library('m', 'atan')
+ crash('need libm')
+ end
+ $CFLAGS = saveflags
+end
+
+unless have_library("z", "inflate")
+ crash("need zlib")
+else
+ $defs.push('-DHAVE_ZLIB_H')
+end
+
+unless (have_library('xml2', 'xmlXPtrNewRange') or
+ find_library('xml2', 'xmlXPtrNewRange', '/opt/lib', '/usr/local/lib', '/usr/lib')) and
+ (have_header('libxml/xmlversion.h') or
+ find_header('libxml/xmlversion.h',
+ '/opt/include/libxml2',
+ '/usr/local/include/libxml2',
+ '/usr/include/libxml2'))
+ crash(<<EOL)
+need libxml2.
+
+ Install the library or try one of the following options to extconf.rb:
+
+ --with-xml2-dir=/path/to/libxml2
+ --with-xml2-lib=/path/to/libxml2/lib
+ --with-xml2-include=/path/to/libxml2/include
+EOL
+end
+
+unless (have_library('xslt','xsltApplyStylesheet') or
+ find_library('xslt', 'xsltApplyStylesheet', '/opt/lib', '/usr/local/lib', '/usr/lib')) and
+ (have_header('xslt.h') or
+ find_header('xslt.h',
+ '/opt/include/libxslt',
+ '/usr/local/include/libxslt',
+ '/usr/include/libxslt'))
+ crash(<<EOL)
+need libxslt.
+
+ Install the library or try one of the following options to extconf.rb:
+
+ --with-xslt-dir=/path/to/libxslt
+ --with-xslt-lib=/path/to/libxslt/lib
+ --with-xslt-include=/path/to/libxslt/include
+EOL
+end
+
+unless (have_library('exslt','exsltLibexsltVersion') or
+ find_library('exslt', 'exsltLibexsltVersion', '/opt/lib', '/usr/local/lib', '/usr/lib')) and
+ (have_header('exslt.h') or
+ find_header('exslt.h',
+ '/opt/include/libexslt',
+ '/usr/local/include/libexslt',
+ '/usr/include/libexslt'))
+ crash(<<EOL)
+need libexslt.
+
+ Install the library or try one of the following options to extconf.rb:
+
+ --with-exslt-dir=/path/to/libexslt
+ --with-exslt-lib=/path/to/libexslt/lib
+ --with-exslt-include=/path/to/libexslt/include
+EOL
+end
+
+unless have_header('libxml/ruby_libxml.h') and
+ have_header('libxml/ruby_xml_document.h')
+ crash(<<EOL)
+need headers for libxml-ruby.
+
+ If you downloaded a release, this is a bug - please inform
+ [email protected] including the release version and
+ download URL you obtained it from.
+
+ If you checked libxslt-ruby out from CVS, you will need to
+ obtain the headers from CVS (using the same version tag if
+ applicable) and place them in directory 'ext/xml/libxml-ruby'.
+EOL
+end
+
+create_header()
+create_makefile("libxslt_ruby")
diff --git a/lib/libxslt-ruby-0.9.2/ext/libxslt/libxslt.c b/lib/libxslt-ruby-0.9.2/ext/libxslt/libxslt.c
new file mode 100644
index 0000000..0c3385d
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/libxslt/libxslt.c
@@ -0,0 +1,66 @@
+/* $Id: libxslt.c 42 2007-12-07 06:09:35Z transami $ */
+
+/* Please see the LICENSE file for copyright and distribution information */
+
+#include "libxslt.h"
+#include "libxml/xmlversion.h"
+
+VALUE cLibXSLT;
+VALUE cXSLT;
+VALUE eXSLTError;
+
+/*
+ * Document-class: LibXSLT::XSLT
+ *
+ * The libxslt gem provides Ruby language bindings for GNOME's Libxslt
+ * toolkit. It is free software, released under the MIT License.
+ *
+ * Using the bindings is straightforward:
+ *
+ * stylesheet_doc = XML::Document.file('stylesheet_file')
+ * stylesheet = XSLT::Stylesheet.new(stylesheet_doc)
+ *
+ * xml_doc = XML::Document.file('xml_file')
+ * result = stylesheet.apply(xml_doc)
+ *
+ *
+*/
+
+#ifdef RDOC_NEVER_DEFINED
+ cLibXSLT = rb_define_module("XSLT");
+#endif
+
+
+#if defined(_WIN32)
+__declspec(dllexport)
+#endif
+
+void
+Init_libxslt_ruby(void) {
+ LIBXML_TEST_VERSION;
+
+ cLibXSLT = rb_define_module("LibXSLT");
+ cXSLT = rb_define_module_under(cLibXSLT, "XSLT");
+
+ rb_define_const(cXSLT, "MAX_DEPTH", INT2NUM(xsltMaxDepth));
+ rb_define_const(cXSLT, "MAX_SORT", INT2NUM(XSLT_MAX_SORT));
+ rb_define_const(cXSLT, "ENGINE_VERSION", rb_str_new2(xsltEngineVersion));
+ rb_define_const(cXSLT, "LIBXSLT_VERSION", INT2NUM(xsltLibxsltVersion));
+ rb_define_const(cXSLT, "LIBXML_VERSION", INT2NUM(xsltLibxmlVersion));
+ rb_define_const(cXSLT, "XSLT_NAMESPACE", rb_str_new2((const char*)XSLT_NAMESPACE));
+ rb_define_const(cXSLT, "DEFAULT_VENDOR", rb_str_new2(XSLT_DEFAULT_VENDOR));
+ rb_define_const(cXSLT, "DEFAULT_VERSION", rb_str_new2(XSLT_DEFAULT_VERSION));
+ rb_define_const(cXSLT, "DEFAULT_URL", rb_str_new2(XSLT_DEFAULT_URL));
+ rb_define_const(cXSLT, "NAMESPACE_LIBXSLT", rb_str_new2((const char*)XSLT_LIBXSLT_NAMESPACE));
+ rb_define_const(cXSLT, "NAMESPACE_NORM_SAXON", rb_str_new2((const char*)XSLT_NORM_SAXON_NAMESPACE));
+ rb_define_const(cXSLT, "NAMESPACE_SAXON", rb_str_new2((const char*)XSLT_SAXON_NAMESPACE));
+ rb_define_const(cXSLT, "NAMESPACE_XT", rb_str_new2((const char*)XSLT_XT_NAMESPACE));
+ rb_define_const(cXSLT, "NAMESPACE_XALAN", rb_str_new2((const char*)XSLT_XALAN_NAMESPACE));
+
+ eXSLTError = rb_define_class_under(cLibXSLT, "XSLTError", rb_eRuntimeError);
+
+ ruby_init_xslt_stylesheet();
+
+ /* Now load exslt. */
+ exsltRegisterAll();
+}
diff --git a/lib/libxslt-ruby-0.9.2/ext/libxslt/libxslt.h b/lib/libxslt-ruby-0.9.2/ext/libxslt/libxslt.h
new file mode 100644
index 0000000..14badf2
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/libxslt/libxslt.h
@@ -0,0 +1,27 @@
+/* $Id: libxslt.h 43 2007-12-07 12:38:59Z transami $ */
+
+/* Please see the LICENSE file for copyright and distribution information */
+
+#ifndef __RUBY_LIBXSLT_H__
+#define __RUBY_LIBXSLT_H__
+
+#include <ruby.h>
+#include <rubyio.h>
+#include <libxml/parser.h>
+#include <libxml/debugXML.h>
+#include <libxslt/extra.h>
+#include <libxslt/xslt.h>
+#include <libxslt/xsltInternals.h>
+#include <libxslt/transform.h>
+#include <libxslt/xsltutils.h>
+#include <libexslt/exslt.h>
+
+#include "ruby_xslt_stylesheet.h"
+
+#include "version.h"
+
+extern VALUE cLibXSLT;
+extern VALUE cXSLT;
+extern VALUE eXSLTError;
+
+#endif
diff --git a/lib/libxslt-ruby-0.9.2/ext/libxslt/ruby_xslt_stylesheet.c b/lib/libxslt-ruby-0.9.2/ext/libxslt/ruby_xslt_stylesheet.c
new file mode 100644
index 0000000..8659542
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/libxslt/ruby_xslt_stylesheet.c
@@ -0,0 +1,277 @@
+/* $Id: ruby_xslt_stylesheet.c 42 2007-12-07 06:09:35Z transami $ */
+
+/* See the LICENSE file for copyright and distribution information. */
+
+#include "libxslt.h"
+#include "ruby_xslt_stylesheet.h"
+
+/*
+ * Document-class: LibXSLT::XSLT::Stylesheet
+ *
+ * The XSLT::Stylesheet represents a XSL stylesheet that
+ * can be used to transform an XML document. For usage information
+ * refer to XSLT::Stylesheet#apply
+ *
+*/
+
+VALUE cXSLTStylesheet;
+
+static VALUE
+ruby_xslt_stylesheet_document_klass() {
+ VALUE mXML = rb_const_get(rb_cObject, rb_intern("XML"));
+ return rb_const_get(mXML, rb_intern("Document"));
+}
+
+void
+ruby_xslt_stylesheet_free(xsltStylesheetPtr xstylesheet) {
+ xsltFreeStylesheet(xstylesheet);
+}
+
+static VALUE
+ruby_xslt_stylesheet_alloc(VALUE klass) {
+ return Data_Wrap_Struct(cXSLTStylesheet,
+ NULL, ruby_xslt_stylesheet_free,
+ NULL);
+}
+
+
+/* call-seq:
+ * XSLT::Stylesheet.new(document) -> XSLT::Stylesheet
+ *
+ * Creates a new XSLT stylesheet based on the specified document.
+ * For memory management reasons, a copy of the specified document
+ * will be made, so its best to create a single copy of a stylesheet
+ * and use it multiple times.
+ *
+ * stylesheet_doc = XML::Document.file('stylesheet_file')
+ * stylesheet = XSLT::Stylesheet.new(stylesheet_doc)
+ *
+ */
+static VALUE
+ruby_xslt_stylesheet_initialize(VALUE self, VALUE document) {
+ xmlDocPtr xdoc;
+ xmlDocPtr xcopy;
+ xsltStylesheetPtr xstylesheet;
+
+ if (!rb_obj_is_kind_of(document, ruby_xslt_stylesheet_document_klass()))
+ rb_raise(rb_eTypeError, "Must pass in an XML::Document instance.");
+
+ /* NOTE!! Since the stylesheet own the specified document, the easiest
+ * thing to do from a memory standpoint is too copy it and not expose
+ * the copy to Ruby. The other solution is expose a memory management
+ * API on the document object for taking ownership of the document
+ * and specifying when it has been freed. Then the document class
+ * has to be updated to always check and see if the document is
+ * still valid. That's all doable, but seems like a pain, so
+ * just copy the document for now. */
+ Data_Get_Struct(document, xmlDoc, xdoc);
+ xcopy = xmlCopyDoc(xdoc, 1);
+ xstylesheet = xsltParseStylesheetDoc(xcopy);
+ xstylesheet->_private = (void *)self;
+ DATA_PTR(self) = xstylesheet;
+
+ /* Save a reference to the document as an attribute accessable to ruby*/
+ return self;
+}
+
+/* Helper method to convert Ruby params to C params */
+char **
+ruby_xslt_coerce_params(VALUE params) {
+ char** result;
+ size_t length;
+ size_t i;
+
+ length = RARRAY(params)->len;
+ result = ALLOC_N(char *, length + 2);
+
+ for (i=0; i<length; i++) {
+ VALUE str = rb_String(RARRAY(params)->ptr[i]);
+ int strLen = RSTRING(str)->len;
+ result[i] = ALLOC_N(char, strLen + 1);
+ memset(result[i], 0, strLen + 1);
+ strncpy(result[i], RSTRING(str)->ptr, strLen);
+ }
+
+ /* Null terminate the array - need to empty elements */
+ result[i] = NULL;
+ result[i+1] = NULL;
+
+ return result;
+}
+
+
+/* call-seq:
+ * stylesheet.apply(document, {params}) -> XML::Document
+ *
+ * Apply this stylesheet transformation to the provided document.
+ * This method may be invoked multiple times.
+ *
+ * Params:
+ * * document - An instance of an XML::Document
+ * * params - An optional hash table that specifies the values for xsl:param values embedded in the stylesheet.
+ *
+ * Example:
+ *
+ * stylesheet_doc = XML::Document.file('stylesheet_file')
+ * stylesheet = XSLT::Stylesheet.new(stylesheet_doc)
+ *
+ * xml_doc = XML::Document.file('xml_file')
+ * result = stylesheet.apply(xml_doc)
+ * result = stylesheet.apply(xml_doc, {:foo => 'bar'})
+ */
+static VALUE
+ruby_xslt_stylesheet_apply(int argc, VALUE *argv, VALUE self) {
+ xmlDocPtr xdoc;
+ xsltStylesheetPtr xstylesheet;
+ xmlDocPtr result;
+ VALUE document;
+ VALUE params;
+ int i;
+
+ char** pParams;
+
+ if (argc > 2 || argc < 1)
+ rb_raise(rb_eArgError, "wrong number of arguments (need 1 or 2)");
+
+ document = argv[0];
+
+ if (!rb_obj_is_kind_of(document, ruby_xslt_stylesheet_document_klass()))
+ rb_raise(rb_eTypeError, "Must pass in an XML::Document instance.");
+
+ /* Make sure params is a flat array */
+ params = (argc == 2 ? argv[1]: Qnil);
+ params = rb_Array(params);
+ rb_funcall(params, rb_intern("flatten!"), 0);
+ pParams = ruby_xslt_coerce_params(params);
+
+ Data_Get_Struct(document, xmlDoc, xdoc);
+ Data_Get_Struct(self, xsltStylesheet, xstylesheet);
+
+ result = xsltApplyStylesheet(xstylesheet, xdoc, (const char**)pParams);
+
+ if (!result)
+ rb_raise(eXSLTError, "Transformation failed");
+
+ /* Free allocated array of *chars. Note we don't have to
+ free the last array item since its set to NULL. */
+ for (i=0; i<(RARRAY(params)->len); i++) {
+ ruby_xfree(pParams[i]);
+ }
+ ruby_xfree(pParams);
+
+ return rxml_document_wrap(result);
+}
+
+
+/* call-seq:
+ * sheet.debug(to = $stdout) => (true|false)
+ *
+ * Output a debug dump of this stylesheet to the specified output
+ * stream (an instance of IO, defaults to $stdout). Requires
+ * libxml/libxslt be compiled with debugging enabled. If this
+ * is not the case, a warning is triggered and the method returns
+ * false.
+ */
+/*VALUE
+ruby_xslt_stylesheet_debug(int argc, VALUE *argv, VALUE self) {
+#ifdef LIBXML_DEBUG_ENABLED
+ OpenFile *fptr;
+ VALUE io;
+ FILE *out;
+ rxml_document_t *parsed;
+ ruby_xslt_stylesheet *xss;
+
+ Data_Get_Struct(self, ruby_xslt_stylesheet, xss);
+ if (NIL_P(xss->parsed))
+ rb_raise(eXMLXSLTStylesheetRequireParsedDoc, "must have a parsed XML result");
+
+ switch (argc) {
+ case 0:
+ io = rb_stdout;
+ break;
+ case 1:
+ io = argv[0];
+ if (rb_obj_is_kind_of(io, rb_cIO) == Qfalse)
+ rb_raise(rb_eTypeError, "need an IO object");
+ break;
+ default:
+ rb_raise(rb_eArgError, "wrong number of arguments (0 or 1)");
+ }
+
+ Data_Get_Struct(xss->parsed, rxml_document_t, parsed);
+ if (parsed->doc == NULL)
+ return(Qnil);
+
+ GetOpenFile(io, fptr);
+ rb_io_check_writable(fptr);
+ out = GetWriteFile(fptr);
+ xmlDebugDumpDocument(out, parsed->doc);
+ return(Qtrue);
+#else
+ rb_warn("libxml/libxslt was compiled without debugging support. Please recompile libxml/libxslt and their Ruby modules");
+ return(Qfalse);
+#endif
+}
+*/
+
+// TODO should this automatically apply the sheet if not already,
+// given that we're unlikely to do much else with it?
+
+/* call-seq:
+ * sheet.print(to = $stdout) => number_of_bytes
+ *
+ * Output the result of the transform to the specified output
+ * stream (an IO instance, defaults to $stdout). You *must* call
+ * +apply+ before this method or an exception will be raised.
+ */
+/*VALUE
+ruby_xslt_stylesheet_print(int argc, VALUE *argv, VALUE self) {
+ OpenFile *fptr;
+ VALUE io;
+ FILE *out;
+ rxml_document_t *parsed;
+ ruby_xslt_stylesheet *xss;
+ int bytes;
+
+ Data_Get_Struct(self, ruby_xslt_stylesheet, xss);
+ if (NIL_P(xss->parsed))
+ rb_raise(eXMLXSLTStylesheetRequireParsedDoc, "must have a parsed XML result");
+
+ switch (argc) {
+ case 0:
+ io = rb_stdout;
+ break;
+ case 1:
+ io = argv[0];
+ if (rb_obj_is_kind_of(io, rb_cIO) == Qfalse)
+ rb_raise(rb_eTypeError, "need an IO object");
+ break;
+ default:
+ rb_raise(rb_eArgError, "wrong number of arguments (0 or 1)");
+ }
+
+ Data_Get_Struct(xss->parsed, rxml_document_t, parsed);
+ if (parsed->doc == NULL)
+ return(Qnil);
+
+ GetOpenFile(io, fptr);
+ rb_io_check_writable(fptr);
+ out = GetWriteFile(fptr);
+ bytes = xsltSaveResultToFile(out, parsed->doc, xss->xsp);
+
+ return(INT2NUM(bytes));
+}*/
+
+
+#ifdef RDOC_NEVER_DEFINED
+ cLibXSLT = rb_define_module("LibXSLT");
+ cXSLT = rb_define_module_under(cLibXSLT, "XSLT");
+#endif
+
+void
+ruby_init_xslt_stylesheet(void) {
+ cXSLTStylesheet = rb_define_class_under(cXSLT, "Stylesheet", rb_cObject);
+ rb_define_alloc_func(cXSLTStylesheet, ruby_xslt_stylesheet_alloc);
+ rb_define_method(cXSLTStylesheet, "initialize", ruby_xslt_stylesheet_initialize, 1);
+ rb_define_method(cXSLTStylesheet, "apply", ruby_xslt_stylesheet_apply, -1);
+}
diff --git a/lib/libxslt-ruby-0.9.2/ext/libxslt/ruby_xslt_stylesheet.h b/lib/libxslt-ruby-0.9.2/ext/libxslt/ruby_xslt_stylesheet.h
new file mode 100644
index 0000000..60d783e
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/libxslt/ruby_xslt_stylesheet.h
@@ -0,0 +1,16 @@
+/* $Id: ruby_xslt_stylesheet.h 42 2007-12-07 06:09:35Z transami $ */
+
+/* Please see the LICENSE file for copyright and distribution information. */
+
+#ifndef __RUBY_LIBXSLT_STYLESHEET__
+#define __RUBY_LIBXSLT_STYLESHEET__
+
+// Includes from libxml-ruby
+#include <libxml/ruby_libxml.h>
+#include <libxml/ruby_xml_document.h>
+
+extern VALUE cXSLTStylesheet;
+
+void ruby_init_xslt_stylesheet(void);
+
+#endif
diff --git a/lib/libxslt-ruby-0.9.2/ext/libxslt/version.h b/lib/libxslt-ruby-0.9.2/ext/libxslt/version.h
new file mode 100644
index 0000000..d3c7ed7
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/libxslt/version.h
@@ -0,0 +1,5 @@
+#define RUBY_LIBXSLT_VERSION "0.9.2"
+#define RUBY_LIBXSLT_VERNUM 0
+#define RUBY_LIBXSLT_VER_MAJ 0
+#define RUBY_LIBXSLT_VER_MIN 9
+#define RUBY_LIBXSLT_VER_MIC 2
diff --git a/lib/libxslt-ruby-0.9.2/ext/mingw/Rakefile b/lib/libxslt-ruby-0.9.2/ext/mingw/Rakefile
new file mode 100644
index 0000000..146a999
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/mingw/Rakefile
@@ -0,0 +1,28 @@
+# We can't use Ruby's standard build procedures
+# on Windows because the Ruby executable is
+# built with VC++ while here we want to build
+# with MingW. So just roll our own...
+
+require 'fileutils'
+require 'rbconfig'
+
+EXTENSION_NAME = "libxslt_ruby.#{Config::CONFIG["DLEXT"]}"
+
+# This is called when the Windows GEM is installed!
+task :install do
+ # Gems will pass these two environment variables:
+ # RUBYARCHDIR=#{dest_path}
+ # RUBYLIBDIR=#{dest_path}
+
+ dest_path = ENV['RUBYLIBDIR']
+
+ # Copy the extension
+ cp(EXTENSION_NAME, dest_path)
+
+ # Copy dllss
+ Dir.glob('*.dll').each do |dll|
+ cp(dll, dest_path)
+ end
+end
+
+task :default => :install
diff --git a/lib/libxslt-ruby-0.9.2/ext/vc/libxslt_ruby.sln b/lib/libxslt-ruby-0.9.2/ext/vc/libxslt_ruby.sln
new file mode 100644
index 0000000..39ab0bf
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/vc/libxslt_ruby.sln
@@ -0,0 +1,26 @@
+
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libxslt_ruby", "libxslt_ruby.vcproj", "{6DCFD1E6-224E-479C-BBD9-B6931DFCD02C}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libxml_ruby", "..\..\..\libxml-ruby\ext\vc\libxml_ruby.vcproj", "{0B65CD1D-EEB9-41AE-93BB-75496E504152}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Release|Win32 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {6DCFD1E6-224E-479C-BBD9-B6931DFCD02C}.Debug|Win32.ActiveCfg = Debug|Win32
+ {6DCFD1E6-224E-479C-BBD9-B6931DFCD02C}.Debug|Win32.Build.0 = Debug|Win32
+ {6DCFD1E6-224E-479C-BBD9-B6931DFCD02C}.Release|Win32.ActiveCfg = Release|Win32
+ {6DCFD1E6-224E-479C-BBD9-B6931DFCD02C}.Release|Win32.Build.0 = Release|Win32
+ {0B65CD1D-EEB9-41AE-93BB-75496E504152}.Debug|Win32.ActiveCfg = Debug|Win32
+ {0B65CD1D-EEB9-41AE-93BB-75496E504152}.Debug|Win32.Build.0 = Debug|Win32
+ {0B65CD1D-EEB9-41AE-93BB-75496E504152}.Release|Win32.ActiveCfg = Release|Win32
+ {0B65CD1D-EEB9-41AE-93BB-75496E504152}.Release|Win32.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/lib/libxslt-ruby-0.9.2/ext/vc/libxslt_ruby.vcproj b/lib/libxslt-ruby-0.9.2/ext/vc/libxslt_ruby.vcproj
new file mode 100644
index 0000000..f1a5e70
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/ext/vc/libxslt_ruby.vcproj
@@ -0,0 +1,224 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9.00"
+ Name="libxslt_ruby"
+ ProjectGUID="{6DCFD1E6-224E-479C-BBD9-B6931DFCD02C}"
+ RootNamespace="libxsl"
+ Keyword="Win32Proj"
+ TargetFrameworkVersion="131072"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory="C:\Development\ruby\lib\ruby\gems\1.8\gems\libxslt-ruby-0.8.2-x86-mswin32-60\lib"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="2"
+ CharacterSet="1"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories=""C:\Development\src\libxml-ruby\ext";"C:\Development\ruby\lib\ruby\1.8\i386-mswin32";C:\Development\msys\local\include;C:\Development\msys\local\include\libxml2"
+ PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;libxsl_EXPORTS"
+ MinimalRebuild="true"
+ BasicRuntimeChecks="3"
+ RuntimeLibrary="3"
+ UsePrecompiledHeader="0"
+ WarningLevel="3"
+ Detect64BitPortabilityProblems="true"
+ DebugInformationFormat="4"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="msvcrt-ruby18.lib libxml2.lib libxslt.lib libexslt.lib"
+ OutputFile="C:\Development\ruby\lib\ruby\gems\1.8\gems\libxslt-ruby-0.9.1-x86-mswin32-60\lib\$(ProjectName).so"
+ LinkIncremental="2"
+ AdditionalLibraryDirectories="C:\Development\ruby\lib;C:\Development\msys\local\lib"
+ GenerateDebugInformation="true"
+ SubSystem="2"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory="$(SolutionDir)$(ConfigurationName)"
+ IntermediateDirectory="$(ConfigurationName)"
+ ConfigurationType="2"
+ CharacterSet="1"
+ WholeProgramOptimization="1"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories=""C:\Development\msys\src\libiconv-1.12\include";"C:\Development\ruby\lib\ruby\1.8\i386-mswin32";"C:\Development\msys\src\libxml2-2.6.32\include";"C:\Development\msys\src\libxslt-1.1.24";C:\Development\msys\src\rlibxml\ext"
+ PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBXML_EXPORTS"
+ RuntimeLibrary="2"
+ UsePrecompiledHeader="0"
+ WarningLevel="3"
+ Detect64BitPortabilityProblems="true"
+ DebugInformationFormat="3"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="msvcrt-ruby18.lib libxml2.lib libxslt.lib libexslt.lib"
+ OutputFile="$(OutDir)\$(ProjectName).so"
+ LinkIncremental="1"
+ AdditionalLibraryDirectories="C:\Development\ruby\lib;"C:\Development\msys\src\libxslt-1.1.24\win32\bin.msvc""
+ GenerateDebugInformation="true"
+ SubSystem="2"
+ OptimizeReferences="2"
+ EnableCOMDATFolding="2"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ <ProjectReference
+ ReferencedProjectIdentifier="{0B65CD1D-EEB9-41AE-93BB-75496E504152}"
+ RelativePathToProject="..\..\..\libxml-ruby\ext\vc\libxml_ruby.vcproj"
+ />
+ </References>
+ <Files>
+ <Filter
+ Name="Source Files"
+ Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+ UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+ >
+ <File
+ RelativePath="..\libxslt\libxslt.c"
+ >
+ </File>
+ <File
+ RelativePath="..\libxslt\ruby_xslt_stylesheet.c"
+ >
+ </File>
+ </Filter>
+ <Filter
+ Name="Header Files"
+ Filter="h;hpp;hxx;hm;inl;inc;xsd"
+ UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+ >
+ <File
+ RelativePath="..\libxslt\libxslt.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libxslt\ruby_xslt_stylesheet.h"
+ >
+ </File>
+ <File
+ RelativePath="..\libxslt\version.h"
+ >
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+ UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+ >
+ </Filter>
+ </Files>
+ <Globals>
+ </Globals>
+</VisualStudioProject>
diff --git a/lib/libxslt-ruby-0.9.2/lib/libxslt.rb b/lib/libxslt-ruby-0.9.2/lib/libxslt.rb
new file mode 100644
index 0000000..b712ad8
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/lib/libxslt.rb
@@ -0,0 +1,13 @@
+# First make sure libxml is loaded
+require 'libxml'
+
+# Now if running on Windows, then add the current directory to the PATH
+# for the current process so it can find the pre-built libxml2 and
+# iconv2 shared libraries (dlls).
+if RUBY_PLATFORM.match(/mswin/i)
+ ENV['PATH'] += ";#{File.dirname(__FILE__)}"
+end
+
+require 'libxslt_ruby'
+
+require 'libxslt/deprecated'
diff --git a/lib/libxslt-ruby-0.9.2/lib/libxslt/deprecated.rb b/lib/libxslt-ruby-0.9.2/lib/libxslt/deprecated.rb
new file mode 100644
index 0000000..8239e90
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/lib/libxslt/deprecated.rb
@@ -0,0 +1,67 @@
+# :enddoc:
+# These classes provide provide backwards compatibility with
+# versions of libxslt-ruby prior to version 0.7.0
+
+module LibXML
+ module XML
+ module XSLT
+ MAX_DEPTH = LibXSLT::XSLT::MAX_DEPTH
+ MAX_SORT = LibXSLT::XSLT::MAX_SORT
+ ENGINE_VERSION = LibXSLT::XSLT::ENGINE_VERSION
+ LIBXSLT_VERSION = LibXSLT::XSLT::LIBXSLT_VERSION
+ LIBXML_VERSION = LibXSLT::XSLT::LIBXML_VERSION
+ XSLT_NAMESPACE = LibXSLT::XSLT::XSLT_NAMESPACE
+ DEFAULT_VENDOR = LibXSLT::XSLT::DEFAULT_VENDOR
+ DEFAULT_VERSION = LibXSLT::XSLT::DEFAULT_VERSION
+ DEFAULT_URL = LibXSLT::XSLT::DEFAULT_URL
+ NAMESPACE_LIBXSLT = LibXSLT::XSLT::NAMESPACE_LIBXSLT
+ NAMESPACE_NORM_SAXON = LibXSLT::XSLT::NAMESPACE_NORM_SAXON
+ NAMESPACE_SAXON = LibXSLT::XSLT::NAMESPACE_SAXON
+ NAMESPACE_XT = LibXSLT::XSLT::NAMESPACE_XT
+ NAMESPACE_XALAN = LibXSLT::XSLT::NAMESPACE_XALAN
+
+ def self.new
+ Stylesheet.new(nil)
+ end
+
+ def self.file(filename)
+ doc = ::LibXML::XML::Document.file(filename)
+ stylesheet = LibXSLT::XSLT::Stylesheet.new(doc)
+
+ result = Stylesheet.new(stylesheet)
+ result.filename = filename
+ result
+ end
+
+ class Stylesheet
+ attr_accessor :doc, :filename
+
+ def initialize(stylesheet)
+ @stylesheet = stylesheet
+ end
+
+ def filename=(value)
+ @doc = ::LibXML::XML::Document.file(value)
+ @filename = value
+ end
+
+ def parse
+ self
+ end
+
+ def apply
+ @result = @stylesheet.apply(@doc)
+ end
+
+ def save(filename)
+ raise(ArgumentError) unless @result
+ @result.save(filename)
+ end
+
+ def print(filename)
+ raise(ArgumentError) unless @result
+ end
+ end
+ end
+ end
+end
diff --git a/lib/libxslt-ruby-0.9.2/lib/xslt.rb b/lib/libxslt-ruby-0.9.2/lib/xslt.rb
new file mode 100644
index 0000000..7d616e1
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/lib/xslt.rb
@@ -0,0 +1,15 @@
+# This file loads libxslt and adds the LibXSLT namespace
+# to the toplevel for conveneience. The end result
+# is to have XSLT:: universally exposed.
+#
+# It is recommend that you only load this file for libs
+# that do not have their own namespace, eg. administrative
+# scripts, personal programs, etc. For other applications
+# require 'libxslt' instead and include LibXSLT into your
+# app/libs namespace.
+
+require 'libxslt'
+
+include LibXML
+include LibXSLT
+
diff --git a/lib/libxslt-ruby-0.9.2/setup.rb b/lib/libxslt-ruby-0.9.2/setup.rb
new file mode 100644
index 0000000..4cc23b1
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/setup.rb
@@ -0,0 +1,1585 @@
+#
+# setup.rb
+#
+# Copyright (c) 2000-2005 Minero Aoki
+#
+# This program is free software.
+# You can distribute/modify this program under the terms of
+# the GNU LGPL, Lesser General Public License version 2.1.
+#
+
+unless Enumerable.method_defined?(:map) # Ruby 1.4.6
+ module Enumerable
+ alias map collect
+ end
+end
+
+unless File.respond_to?(:read) # Ruby 1.6
+ def File.read(fname)
+ open(fname) {|f|
+ return f.read
+ }
+ end
+end
+
+unless Errno.const_defined?(:ENOTEMPTY) # Windows?
+ module Errno
+ class ENOTEMPTY
+ # We do not raise this exception, implementation is not needed.
+ end
+ end
+end
+
+def File.binread(fname)
+ open(fname, 'rb') {|f|
+ return f.read
+ }
+end
+
+# for corrupted Windows' stat(2)
+def File.dir?(path)
+ File.directory?((path[-1,1] == '/') ? path : path + '/')
+end
+
+
+class ConfigTable
+
+ include Enumerable
+
+ def initialize(rbconfig)
+ @rbconfig = rbconfig
+ @items = []
+ @table = {}
+ # options
+ @install_prefix = nil
+ @config_opt = nil
+ @verbose = true
+ @no_harm = false
+ end
+
+ attr_accessor :install_prefix
+ attr_accessor :config_opt
+
+ attr_writer :verbose
+
+ def verbose?
+ @verbose
+ end
+
+ attr_writer :no_harm
+
+ def no_harm?
+ @no_harm
+ end
+
+ def [](key)
+ lookup(key).resolve(self)
+ end
+
+ def []=(key, val)
+ lookup(key).set val
+ end
+
+ def names
+ @items.map {|i| i.name }
+ end
+
+ def each(&block)
+ @items.each(&block)
+ end
+
+ def key?(name)
+ @table.key?(name)
+ end
+
+ def lookup(name)
+ @table[name] or setup_rb_error "no such config item: #{name}"
+ end
+
+ def add(item)
+ @items.push item
+ @table[item.name] = item
+ end
+
+ def remove(name)
+ item = lookup(name)
+ @items.delete_if {|i| i.name == name }
+ @table.delete_if {|name, i| i.name == name }
+ item
+ end
+
+ def load_script(path, inst = nil)
+ if File.file?(path)
+ MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path
+ end
+ end
+
+ def savefile
+ '.config'
+ end
+
+ def load_savefile
+ begin
+ File.foreach(savefile()) do |line|
+ k, v = *line.split(/=/, 2)
+ self[k] = v.strip
+ end
+ rescue Errno::ENOENT
+ setup_rb_error $!.message + "\n#{File.basename($0)} config first"
+ end
+ end
+
+ def save
+ @items.each {|i| i.value }
+ File.open(savefile(), 'w') {|f|
+ @items.each do |i|
+ f.printf "%s=%s\n", i.name, i.value if i.value? and i.value
+ end
+ }
+ end
+
+ def load_standard_entries
+ standard_entries(@rbconfig).each do |ent|
+ add ent
+ end
+ end
+
+ def standard_entries(rbconfig)
+ c = rbconfig
+
+ rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT'])
+
+ major = c['MAJOR'].to_i
+ minor = c['MINOR'].to_i
+ teeny = c['TEENY'].to_i
+ version = "#{major}.#{minor}"
+
+ # ruby ver. >= 1.4.4?
+ newpath_p = ((major >= 2) or
+ ((major == 1) and
+ ((minor >= 5) or
+ ((minor == 4) and (teeny >= 4)))))
+
+ if c['rubylibdir']
+ # V > 1.6.3
+ libruby = "#{c['prefix']}/lib/ruby"
+ librubyver = c['rubylibdir']
+ librubyverarch = c['archdir']
+ siteruby = c['sitedir']
+ siterubyver = c['sitelibdir']
+ siterubyverarch = c['sitearchdir']
+ elsif newpath_p
+ # 1.4.4 <= V <= 1.6.3
+ libruby = "#{c['prefix']}/lib/ruby"
+ librubyver = "#{c['prefix']}/lib/ruby/#{version}"
+ librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
+ siteruby = c['sitedir']
+ siterubyver = "$siteruby/#{version}"
+ siterubyverarch = "$siterubyver/#{c['arch']}"
+ else
+ # V < 1.4.4
+ libruby = "#{c['prefix']}/lib/ruby"
+ librubyver = "#{c['prefix']}/lib/ruby/#{version}"
+ librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}"
+ siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby"
+ siterubyver = siteruby
+ siterubyverarch = "$siterubyver/#{c['arch']}"
+ end
+ parameterize = lambda {|path|
+ path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix')
+ }
+
+ if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg }
+ makeprog = arg.sub(/'/, '').split(/=/, 2)[1]
+ else
+ makeprog = 'make'
+ end
+
+ [
+ ExecItem.new('installdirs', 'std/site/home',
+ 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\
+ {|val, table|
+ case val
+ when 'std'
+ table['rbdir'] = '$librubyver'
+ table['sodir'] = '$librubyverarch'
+ when 'site'
+ table['rbdir'] = '$siterubyver'
+ table['sodir'] = '$siterubyverarch'
+ when 'home'
+ setup_rb_error '$HOME was not set' unless ENV['HOME']
+ table['prefix'] = ENV['HOME']
+ table['rbdir'] = '$libdir/ruby'
+ table['sodir'] = '$libdir/ruby'
+ end
+ },
+ PathItem.new('prefix', 'path', c['prefix'],
+ 'path prefix of target environment'),
+ PathItem.new('bindir', 'path', parameterize.call(c['bindir']),
+ 'the directory for commands'),
+ PathItem.new('libdir', 'path', parameterize.call(c['libdir']),
+ 'the directory for libraries'),
+ PathItem.new('datadir', 'path', parameterize.call(c['datadir']),
+ 'the directory for shared data'),
+ PathItem.new('mandir', 'path', parameterize.call(c['mandir']),
+ 'the directory for man pages'),
+ PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']),
+ 'the directory for system configuration files'),
+ PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']),
+ 'the directory for local state data'),
+ PathItem.new('libruby', 'path', libruby,
+ 'the directory for ruby libraries'),
+ PathItem.new('librubyver', 'path', librubyver,
+ 'the directory for standard ruby libraries'),
+ PathItem.new('librubyverarch', 'path', librubyverarch,
+ 'the directory for standard ruby extensions'),
+ PathItem.new('siteruby', 'path', siteruby,
+ 'the directory for version-independent aux ruby libraries'),
+ PathItem.new('siterubyver', 'path', siterubyver,
+ 'the directory for aux ruby libraries'),
+ PathItem.new('siterubyverarch', 'path', siterubyverarch,
+ 'the directory for aux ruby binaries'),
+ PathItem.new('rbdir', 'path', '$siterubyver',
+ 'the directory for ruby scripts'),
+ PathItem.new('sodir', 'path', '$siterubyverarch',
+ 'the directory for ruby extentions'),
+ PathItem.new('rubypath', 'path', rubypath,
+ 'the path to set to #! line'),
+ ProgramItem.new('rubyprog', 'name', rubypath,
+ 'the ruby program using for installation'),
+ ProgramItem.new('makeprog', 'name', makeprog,
+ 'the make program to compile ruby extentions'),
+ SelectItem.new('shebang', 'all/ruby/never', 'ruby',
+ 'shebang line (#!) editing mode'),
+ BoolItem.new('without-ext', 'yes/no', 'no',
+ 'does not compile/install ruby extentions')
+ ]
+ end
+ private :standard_entries
+
+ def load_multipackage_entries
+ multipackage_entries().each do |ent|
+ add ent
+ end
+ end
+
+ def multipackage_entries
+ [
+ PackageSelectionItem.new('with', 'name,name...', '', 'ALL',
+ 'package names that you want to install'),
+ PackageSelectionItem.new('without', 'name,name...', '', 'NONE',
+ 'package names that you do not want to install')
+ ]
+ end
+ private :multipackage_entries
+
+ ALIASES = {
+ 'std-ruby' => 'librubyver',
+ 'stdruby' => 'librubyver',
+ 'rubylibdir' => 'librubyver',
+ 'archdir' => 'librubyverarch',
+ 'site-ruby-common' => 'siteruby', # For backward compatibility
+ 'site-ruby' => 'siterubyver', # For backward compatibility
+ 'bin-dir' => 'bindir',
+ 'bin-dir' => 'bindir',
+ 'rb-dir' => 'rbdir',
+ 'so-dir' => 'sodir',
+ 'data-dir' => 'datadir',
+ 'ruby-path' => 'rubypath',
+ 'ruby-prog' => 'rubyprog',
+ 'ruby' => 'rubyprog',
+ 'make-prog' => 'makeprog',
+ 'make' => 'makeprog'
+ }
+
+ def fixup
+ ALIASES.each do |ali, name|
+ @table[ali] = @table[name]
+ end
+ @items.freeze
+ @table.freeze
+ @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/
+ end
+
+ def parse_opt(opt)
+ m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}"
+ m.to_a[1,2]
+ end
+
+ def dllext
+ @rbconfig['DLEXT']
+ end
+
+ def value_config?(name)
+ lookup(name).value?
+ end
+
+ class Item
+ def initialize(name, template, default, desc)
+ @name = name.freeze
+ @template = template
+ @value = default
+ @default = default
+ @description = desc
+ end
+
+ attr_reader :name
+ attr_reader :description
+
+ attr_accessor :default
+ alias help_default default
+
+ def help_opt
+ "--#{@name}=#{@template}"
+ end
+
+ def value?
+ true
+ end
+
+ def value
+ @value
+ end
+
+ def resolve(table)
+ @value.gsub(%r<\$([^/]+)>) { table[$1] }
+ end
+
+ def set(val)
+ @value = check(val)
+ end
+
+ private
+
+ def check(val)
+ setup_rb_error "config: --#{name} requires argument" unless val
+ val
+ end
+ end
+
+ class BoolItem < Item
+ def config_type
+ 'bool'
+ end
+
+ def help_opt
+ "--#{@name}"
+ end
+
+ private
+
+ def check(val)
+ return 'yes' unless val
+ case val
+ when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes'
+ when /\An(o)?\z/i, /\Af(alse)\z/i then 'no'
+ else
+ setup_rb_error "config: --#{@name} accepts only yes/no for argument"
+ end
+ end
+ end
+
+ class PathItem < Item
+ def config_type
+ 'path'
+ end
+
+ private
+
+ def check(path)
+ setup_rb_error "config: --#{@name} requires argument" unless path
+ path[0,1] == '$' ? path : File.expand_path(path)
+ end
+ end
+
+ class ProgramItem < Item
+ def config_type
+ 'program'
+ end
+ end
+
+ class SelectItem < Item
+ def initialize(name, selection, default, desc)
+ super
+ @ok = selection.split('/')
+ end
+
+ def config_type
+ 'select'
+ end
+
+ private
+
+ def check(val)
+ unless @ok.include?(val.strip)
+ setup_rb_error "config: use --#{@name}=#{@template} (#{val})"
+ end
+ val.strip
+ end
+ end
+
+ class ExecItem < Item
+ def initialize(name, selection, desc, &block)
+ super name, selection, nil, desc
+ @ok = selection.split('/')
+ @action = block
+ end
+
+ def config_type
+ 'exec'
+ end
+
+ def value?
+ false
+ end
+
+ def resolve(table)
+ setup_rb_error "$#{name()} wrongly used as option value"
+ end
+
+ undef set
+
+ def evaluate(val, table)
+ v = val.strip.downcase
+ unless @ok.include?(v)
+ setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})"
+ end
+ @action.call v, table
+ end
+ end
+
+ class PackageSelectionItem < Item
+ def initialize(name, template, default, help_default, desc)
+ super name, template, default, desc
+ @help_default = help_default
+ end
+
+ attr_reader :help_default
+
+ def config_type
+ 'package'
+ end
+
+ private
+
+ def check(val)
+ unless File.dir?("packages/#{val}")
+ setup_rb_error "config: no such package: #{val}"
+ end
+ val
+ end
+ end
+
+ class MetaConfigEnvironment
+ def initialize(config, installer)
+ @config = config
+ @installer = installer
+ end
+
+ def config_names
+ @config.names
+ end
+
+ def config?(name)
+ @config.key?(name)
+ end
+
+ def bool_config?(name)
+ @config.lookup(name).config_type == 'bool'
+ end
+
+ def path_config?(name)
+ @config.lookup(name).config_type == 'path'
+ end
+
+ def value_config?(name)
+ @config.lookup(name).config_type != 'exec'
+ end
+
+ def add_config(item)
+ @config.add item
+ end
+
+ def add_bool_config(name, default, desc)
+ @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc)
+ end
+
+ def add_path_config(name, default, desc)
+ @config.add PathItem.new(name, 'path', default, desc)
+ end
+
+ def set_config_default(name, default)
+ @config.lookup(name).default = default
+ end
+
+ def remove_config(name)
+ @config.remove(name)
+ end
+
+ # For only multipackage
+ def packages
+ raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer
+ @installer.packages
+ end
+
+ # For only multipackage
+ def declare_packages(list)
+ raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer
+ @installer.packages = list
+ end
+ end
+
+end # class ConfigTable
+
+
+# This module requires: #verbose?, #no_harm?
+module FileOperations
+
+ def mkdir_p(dirname, prefix = nil)
+ dirname = prefix + File.expand_path(dirname) if prefix
+ $stderr.puts "mkdir -p #{dirname}" if verbose?
+ return if no_harm?
+
+ # Does not check '/', it's too abnormal.
+ dirs = File.expand_path(dirname).split(%r<(?=/)>)
+ if /\A[a-z]:\z/i =~ dirs[0]
+ disk = dirs.shift
+ dirs[0] = disk + dirs[0]
+ end
+ dirs.each_index do |idx|
+ path = dirs[0..idx].join('')
+ Dir.mkdir path unless File.dir?(path)
+ end
+ end
+
+ def rm_f(path)
+ $stderr.puts "rm -f #{path}" if verbose?
+ return if no_harm?
+ force_remove_file path
+ end
+
+ def rm_rf(path)
+ $stderr.puts "rm -rf #{path}" if verbose?
+ return if no_harm?
+ remove_tree path
+ end
+
+ def remove_tree(path)
+ if File.symlink?(path)
+ remove_file path
+ elsif File.dir?(path)
+ remove_tree0 path
+ else
+ force_remove_file path
+ end
+ end
+
+ def remove_tree0(path)
+ Dir.foreach(path) do |ent|
+ next if ent == '.'
+ next if ent == '..'
+ entpath = "#{path}/#{ent}"
+ if File.symlink?(entpath)
+ remove_file entpath
+ elsif File.dir?(entpath)
+ remove_tree0 entpath
+ else
+ force_remove_file entpath
+ end
+ end
+ begin
+ Dir.rmdir path
+ rescue Errno::ENOTEMPTY
+ # directory may not be empty
+ end
+ end
+
+ def move_file(src, dest)
+ force_remove_file dest
+ begin
+ File.rename src, dest
+ rescue
+ File.open(dest, 'wb') {|f|
+ f.write File.binread(src)
+ }
+ File.chmod File.stat(src).mode, dest
+ File.unlink src
+ end
+ end
+
+ def force_remove_file(path)
+ begin
+ remove_file path
+ rescue
+ end
+ end
+
+ def remove_file(path)
+ File.chmod 0777, path
+ File.unlink path
+ end
+
+ def install(from, dest, mode, prefix = nil)
+ $stderr.puts "install #{from} #{dest}" if verbose?
+ return if no_harm?
+
+ realdest = prefix ? prefix + File.expand_path(dest) : dest
+ realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest)
+ str = File.binread(from)
+ if diff?(str, realdest)
+ verbose_off {
+ rm_f realdest if File.exist?(realdest)
+ }
+ File.open(realdest, 'wb') {|f|
+ f.write str
+ }
+ File.chmod mode, realdest
+
+ File.open("#{objdir_root()}/InstalledFiles", 'a') {|f|
+ if prefix
+ f.puts realdest.sub(prefix, '')
+ else
+ f.puts realdest
+ end
+ }
+ end
+ end
+
+ def diff?(new_content, path)
+ return true unless File.exist?(path)
+ new_content != File.binread(path)
+ end
+
+ def command(*args)
+ $stderr.puts args.join(' ') if verbose?
+ system(*args) or raise RuntimeError,
+ "system(#{args.map{|a| a.inspect }.join(' ')}) failed"
+ end
+
+ def ruby(*args)
+ command config('rubyprog'), *args
+ end
+
+ def make(task = nil)
+ command(*[config('makeprog'), task].compact)
+ end
+
+ def extdir?(dir)
+ File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb")
+ end
+
+ def files_of(dir)
+ Dir.open(dir) {|d|
+ return d.select {|ent| File.file?("#{dir}/#{ent}") }
+ }
+ end
+
+ DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn )
+
+ def directories_of(dir)
+ Dir.open(dir) {|d|
+ return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT
+ }
+ end
+
+end
+
+
+# This module requires: #srcdir_root, #objdir_root, #relpath
+module HookScriptAPI
+
+ def get_config(key)
+ @config[key]
+ end
+
+ alias config get_config
+
+ # obsolete: use metaconfig to change configuration
+ def set_config(key, val)
+ @config[key] = val
+ end
+
+ #
+ # srcdir/objdir (works only in the package directory)
+ #
+
+ def curr_srcdir
+ "#{srcdir_root()}/#{relpath()}"
+ end
+
+ def curr_objdir
+ "#{objdir_root()}/#{relpath()}"
+ end
+
+ def srcfile(path)
+ "#{curr_srcdir()}/#{path}"
+ end
+
+ def srcexist?(path)
+ File.exist?(srcfile(path))
+ end
+
+ def srcdirectory?(path)
+ File.dir?(srcfile(path))
+ end
+
+ def srcfile?(path)
+ File.file?(srcfile(path))
+ end
+
+ def srcentries(path = '.')
+ Dir.open("#{curr_srcdir()}/#{path}") {|d|
+ return d.to_a - %w(. ..)
+ }
+ end
+
+ def srcfiles(path = '.')
+ srcentries(path).select {|fname|
+ File.file?(File.join(curr_srcdir(), path, fname))
+ }
+ end
+
+ def srcdirectories(path = '.')
+ srcentries(path).select {|fname|
+ File.dir?(File.join(curr_srcdir(), path, fname))
+ }
+ end
+
+end
+
+
+class ToplevelInstaller
+
+ Version = '3.4.1'
+ Copyright = 'Copyright (c) 2000-2005 Minero Aoki'
+
+ TASKS = [
+ [ 'all', 'do config, setup, then install' ],
+ [ 'config', 'saves your configurations' ],
+ [ 'show', 'shows current configuration' ],
+ [ 'setup', 'compiles ruby extentions and others' ],
+ [ 'install', 'installs files' ],
+ [ 'test', 'run all tests in test/' ],
+ [ 'clean', "does `make clean' for each extention" ],
+ [ 'distclean',"does `make distclean' for each extention" ]
+ ]
+
+ def ToplevelInstaller.invoke
+ config = ConfigTable.new(load_rbconfig())
+ config.load_standard_entries
+ config.load_multipackage_entries if multipackage?
+ config.fixup
+ klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller)
+ klass.new(File.dirname($0), config).invoke
+ end
+
+ def ToplevelInstaller.multipackage?
+ File.dir?(File.dirname($0) + '/packages')
+ end
+
+ def ToplevelInstaller.load_rbconfig
+ if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg }
+ ARGV.delete(arg)
+ load File.expand_path(arg.split(/=/, 2)[1])
+ $".push 'rbconfig.rb'
+ else
+ require 'rbconfig'
+ end
+ ::Config::CONFIG
+ end
+
+ def initialize(ardir_root, config)
+ @ardir = File.expand_path(ardir_root)
+ @config = config
+ # cache
+ @valid_task_re = nil
+ end
+
+ def config(key)
+ @config[key]
+ end
+
+ def inspect
+ "#<#{self.class} #{__id__()}>"
+ end
+
+ def invoke
+ run_metaconfigs
+ case task = parsearg_global()
+ when nil, 'all'
+ parsearg_config
+ init_installers
+ exec_config
+ exec_setup
+ exec_install
+ else
+ case task
+ when 'config', 'test'
+ ;
+ when 'clean', 'distclean'
+ @config.load_savefile if File.exist?(@config.savefile)
+ else
+ @config.load_savefile
+ end
+ __send__ "parsearg_#{task}"
+ init_installers
+ __send__ "exec_#{task}"
+ end
+ end
+
+ def run_metaconfigs
+ @config.load_script "#{@ardir}/metaconfig"
+ end
+
+ def init_installers
+ @installer = Installer.new(@config, @ardir, File.expand_path('.'))
+ end
+
+ #
+ # Hook Script API bases
+ #
+
+ def srcdir_root
+ @ardir
+ end
+
+ def objdir_root
+ '.'
+ end
+
+ def relpath
+ '.'
+ end
+
+ #
+ # Option Parsing
+ #
+
+ def parsearg_global
+ while arg = ARGV.shift
+ case arg
+ when /\A\w+\z/
+ setup_rb_error "invalid task: #{arg}" unless valid_task?(arg)
+ return arg
+ when '-q', '--quiet'
+ @config.verbose = false
+ when '--verbose'
+ @config.verbose = true
+ when '--help'
+ print_usage $stdout
+ exit 0
+ when '--version'
+ puts "#{File.basename($0)} version #{Version}"
+ exit 0
+ when '--copyright'
+ puts Copyright
+ exit 0
+ else
+ setup_rb_error "unknown global option '#{arg}'"
+ end
+ end
+ nil
+ end
+
+ def valid_task?(t)
+ valid_task_re() =~ t
+ end
+
+ def valid_task_re
+ @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/
+ end
+
+ def parsearg_no_options
+ unless ARGV.empty?
+ task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1)
+ setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}"
+ end
+ end
+
+ alias parsearg_show parsearg_no_options
+ alias parsearg_setup parsearg_no_options
+ alias parsearg_test parsearg_no_options
+ alias parsearg_clean parsearg_no_options
+ alias parsearg_distclean parsearg_no_options
+
+ def parsearg_config
+ evalopt = []
+ set = []
+ @config.config_opt = []
+ while i = ARGV.shift
+ if /\A--?\z/ =~ i
+ @config.config_opt = ARGV.dup
+ break
+ end
+ name, value = *@config.parse_opt(i)
+ if @config.value_config?(name)
+ @config[name] = value
+ else
+ evalopt.push [name, value]
+ end
+ set.push name
+ end
+ evalopt.each do |name, value|
+ @config.lookup(name).evaluate value, @config
+ end
+ # Check if configuration is valid
+ set.each do |n|
+ @config[n] if @config.value_config?(n)
+ end
+ end
+
+ def parsearg_install
+ @config.no_harm = false
+ @config.install_prefix = ''
+ while a = ARGV.shift
+ case a
+ when '--no-harm'
+ @config.no_harm = true
+ when /\A--prefix=/
+ path = a.split(/=/, 2)[1]
+ path = File.expand_path(path) unless path[0,1] == '/'
+ @config.install_prefix = path
+ else
+ setup_rb_error "install: unknown option #{a}"
+ end
+ end
+ end
+
+ def print_usage(out)
+ out.puts 'Typical Installation Procedure:'
+ out.puts " $ ruby #{File.basename $0} config"
+ out.puts " $ ruby #{File.basename $0} setup"
+ out.puts " # ruby #{File.basename $0} install (may require root privilege)"
+ out.puts
+ out.puts 'Detailed Usage:'
+ out.puts " ruby #{File.basename $0} <global option>"
+ out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]"
+
+ fmt = " %-24s %s\n"
+ out.puts
+ out.puts 'Global options:'
+ out.printf fmt, '-q,--quiet', 'suppress message outputs'
+ out.printf fmt, ' --verbose', 'output messages verbosely'
+ out.printf fmt, ' --help', 'print this message'
+ out.printf fmt, ' --version', 'print version and quit'
+ out.printf fmt, ' --copyright', 'print copyright and quit'
+ out.puts
+ out.puts 'Tasks:'
+ TASKS.each do |name, desc|
+ out.printf fmt, name, desc
+ end
+
+ fmt = " %-24s %s [%s]\n"
+ out.puts
+ out.puts 'Options for CONFIG or ALL:'
+ @config.each do |item|
+ out.printf fmt, item.help_opt, item.description, item.help_default
+ end
+ out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's"
+ out.puts
+ out.puts 'Options for INSTALL:'
+ out.printf fmt, '--no-harm', 'only display what to do if given', 'off'
+ out.printf fmt, '--prefix=path', 'install path prefix', ''
+ out.puts
+ end
+
+ #
+ # Task Handlers
+ #
+
+ def exec_config
+ @installer.exec_config
+ @config.save # must be final
+ end
+
+ def exec_setup
+ @installer.exec_setup
+ end
+
+ def exec_install
+ @installer.exec_install
+ end
+
+ def exec_test
+ @installer.exec_test
+ end
+
+ def exec_show
+ @config.each do |i|
+ printf "%-20s %s\n", i.name, i.value if i.value?
+ end
+ end
+
+ def exec_clean
+ @installer.exec_clean
+ end
+
+ def exec_distclean
+ @installer.exec_distclean
+ end
+
+end # class ToplevelInstaller
+
+
+class ToplevelInstallerMulti < ToplevelInstaller
+
+ include FileOperations
+
+ def initialize(ardir_root, config)
+ super
+ @packages = directories_of("#{@ardir}/packages")
+ raise 'no package exists' if @packages.empty?
+ @root_installer = Installer.new(@config, @ardir, File.expand_path('.'))
+ end
+
+ def run_metaconfigs
+ @config.load_script "#{@ardir}/metaconfig", self
+ @packages.each do |name|
+ @config.load_script "#{@ardir}/packages/#{name}/metaconfig"
+ end
+ end
+
+ attr_reader :packages
+
+ def packages=(list)
+ raise 'package list is empty' if list.empty?
+ list.each do |name|
+ raise "directory packages/#{name} does not exist"\
+ unless File.dir?("#{@ardir}/packages/#{name}")
+ end
+ @packages = list
+ end
+
+ def init_installers
+ @installers = {}
+ @packages.each do |pack|
+ @installers[pack] = Installer.new(@config,
+ "#{@ardir}/packages/#{pack}",
+ "packages/#{pack}")
+ end
+ with = extract_selection(config('with'))
+ without = extract_selection(config('without'))
+ @selected = @installers.keys.select {|name|
+ (with.empty? or with.include?(name)) \
+ and not without.include?(name)
+ }
+ end
+
+ def extract_selection(list)
+ a = list.split(/,/)
+ a.each do |name|
+ setup_rb_error "no such package: #{name}" unless @installers.key?(name)
+ end
+ a
+ end
+
+ def print_usage(f)
+ super
+ f.puts 'Inluded packages:'
+ f.puts ' ' + @packages.sort.join(' ')
+ f.puts
+ end
+
+ #
+ # Task Handlers
+ #
+
+ def exec_config
+ run_hook 'pre-config'
+ each_selected_installers {|inst| inst.exec_config }
+ run_hook 'post-config'
+ @config.save # must be final
+ end
+
+ def exec_setup
+ run_hook 'pre-setup'
+ each_selected_installers {|inst| inst.exec_setup }
+ run_hook 'post-setup'
+ end
+
+ def exec_install
+ run_hook 'pre-install'
+ each_selected_installers {|inst| inst.exec_install }
+ run_hook 'post-install'
+ end
+
+ def exec_test
+ run_hook 'pre-test'
+ each_selected_installers {|inst| inst.exec_test }
+ run_hook 'post-test'
+ end
+
+ def exec_clean
+ rm_f @config.savefile
+ run_hook 'pre-clean'
+ each_selected_installers {|inst| inst.exec_clean }
+ run_hook 'post-clean'
+ end
+
+ def exec_distclean
+ rm_f @config.savefile
+ run_hook 'pre-distclean'
+ each_selected_installers {|inst| inst.exec_distclean }
+ run_hook 'post-distclean'
+ end
+
+ #
+ # lib
+ #
+
+ def each_selected_installers
+ Dir.mkdir 'packages' unless File.dir?('packages')
+ @selected.each do |pack|
+ $stderr.puts "Processing the package `#{pack}' ..." if verbose?
+ Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}")
+ Dir.chdir "packages/#{pack}"
+ yield @installers[pack]
+ Dir.chdir '../..'
+ end
+ end
+
+ def run_hook(id)
+ @root_installer.run_hook id
+ end
+
+ # module FileOperations requires this
+ def verbose?
+ @config.verbose?
+ end
+
+ # module FileOperations requires this
+ def no_harm?
+ @config.no_harm?
+ end
+
+end # class ToplevelInstallerMulti
+
+
+class Installer
+
+ FILETYPES = %w( bin lib ext data conf man )
+
+ include FileOperations
+ include HookScriptAPI
+
+ def initialize(config, srcroot, objroot)
+ @config = config
+ @srcdir = File.expand_path(srcroot)
+ @objdir = File.expand_path(objroot)
+ @currdir = '.'
+ end
+
+ def inspect
+ "#<#{self.class} #{File.basename(@srcdir)}>"
+ end
+
+ def noop(rel)
+ end
+
+ #
+ # Hook Script API base methods
+ #
+
+ def srcdir_root
+ @srcdir
+ end
+
+ def objdir_root
+ @objdir
+ end
+
+ def relpath
+ @currdir
+ end
+
+ #
+ # Config Access
+ #
+
+ # module FileOperations requires this
+ def verbose?
+ @config.verbose?
+ end
+
+ # module FileOperations requires this
+ def no_harm?
+ @config.no_harm?
+ end
+
+ def verbose_off
+ begin
+ save, @config.verbose = @config.verbose?, false
+ yield
+ ensure
+ @config.verbose = save
+ end
+ end
+
+ #
+ # TASK config
+ #
+
+ def exec_config
+ exec_task_traverse 'config'
+ end
+
+ alias config_dir_bin noop
+ alias config_dir_lib noop
+
+ def config_dir_ext(rel)
+ extconf if extdir?(curr_srcdir())
+ end
+
+ alias config_dir_data noop
+ alias config_dir_conf noop
+ alias config_dir_man noop
+
+ def extconf
+ ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt
+ end
+
+ #
+ # TASK setup
+ #
+
+ def exec_setup
+ exec_task_traverse 'setup'
+ end
+
+ def setup_dir_bin(rel)
+ files_of(curr_srcdir()).each do |fname|
+ update_shebang_line "#{curr_srcdir()}/#{fname}"
+ end
+ end
+
+ alias setup_dir_lib noop
+
+ def setup_dir_ext(rel)
+ make if extdir?(curr_srcdir())
+ end
+
+ alias setup_dir_data noop
+ alias setup_dir_conf noop
+ alias setup_dir_man noop
+
+ def update_shebang_line(path)
+ return if no_harm?
+ return if config('shebang') == 'never'
+ old = Shebang.load(path)
+ if old
+ $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1
+ new = new_shebang(old)
+ return if new.to_s == old.to_s
+ else
+ return unless config('shebang') == 'all'
+ new = Shebang.new(config('rubypath'))
+ end
+ $stderr.puts "updating shebang: #{File.basename(path)}" if verbose?
+ open_atomic_writer(path) {|output|
+ File.open(path, 'rb') {|f|
+ f.gets if old # discard
+ output.puts new.to_s
+ output.print f.read
+ }
+ }
+ end
+
+ def new_shebang(old)
+ if /\Aruby/ =~ File.basename(old.cmd)
+ Shebang.new(config('rubypath'), old.args)
+ elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby'
+ Shebang.new(config('rubypath'), old.args[1..-1])
+ else
+ return old unless config('shebang') == 'all'
+ Shebang.new(config('rubypath'))
+ end
+ end
+
+ def open_atomic_writer(path, &block)
+ tmpfile = File.basename(path) + '.tmp'
+ begin
+ File.open(tmpfile, 'wb', &block)
+ File.rename tmpfile, File.basename(path)
+ ensure
+ File.unlink tmpfile if File.exist?(tmpfile)
+ end
+ end
+
+ class Shebang
+ def Shebang.load(path)
+ line = nil
+ File.open(path) {|f|
+ line = f.gets
+ }
+ return nil unless /\A#!/ =~ line
+ parse(line)
+ end
+
+ def Shebang.parse(line)
+ cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ')
+ new(cmd, args)
+ end
+
+ def initialize(cmd, args = [])
+ @cmd = cmd
+ @args = args
+ end
+
+ attr_reader :cmd
+ attr_reader :args
+
+ def to_s
+ "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}")
+ end
+ end
+
+ #
+ # TASK install
+ #
+
+ def exec_install
+ rm_f 'InstalledFiles'
+ exec_task_traverse 'install'
+ end
+
+ def install_dir_bin(rel)
+ install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755
+ end
+
+ def install_dir_lib(rel)
+ install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644
+ end
+
+ def install_dir_ext(rel)
+ return unless extdir?(curr_srcdir())
+ install_files rubyextentions('.'),
+ "#{config('sodir')}/#{File.dirname(rel)}",
+ 0555
+ end
+
+ def install_dir_data(rel)
+ install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644
+ end
+
+ def install_dir_conf(rel)
+ # FIXME: should not remove current config files
+ # (rename previous file to .old/.org)
+ install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644
+ end
+
+ def install_dir_man(rel)
+ install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644
+ end
+
+ def install_files(list, dest, mode)
+ mkdir_p dest, @config.install_prefix
+ list.each do |fname|
+ install fname, dest, mode, @config.install_prefix
+ end
+ end
+
+ def libfiles
+ glob_reject(%w(*.y *.output), targetfiles())
+ end
+
+ def rubyextentions(dir)
+ ents = glob_select("*.#{@config.dllext}", targetfiles())
+ if ents.empty?
+ setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first"
+ end
+ ents
+ end
+
+ def targetfiles
+ mapdir(existfiles() - hookfiles())
+ end
+
+ def mapdir(ents)
+ ents.map {|ent|
+ if File.exist?(ent)
+ then ent # objdir
+ else "#{curr_srcdir()}/#{ent}" # srcdir
+ end
+ }
+ end
+
+ # picked up many entries from cvs-1.11.1/src/ignore.c
+ JUNK_FILES = %w(
+ core RCSLOG tags TAGS .make.state
+ .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb
+ *~ *.old *.bak *.BAK *.orig *.rej _$* *$
+
+ *.org *.in .*
+ )
+
+ def existfiles
+ glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.')))
+ end
+
+ def hookfiles
+ %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt|
+ %w( config setup install clean ).map {|t| sprintf(fmt, t) }
+ }.flatten
+ end
+
+ def glob_select(pat, ents)
+ re = globs2re([pat])
+ ents.select {|ent| re =~ ent }
+ end
+
+ def glob_reject(pats, ents)
+ re = globs2re(pats)
+ ents.reject {|ent| re =~ ent }
+ end
+
+ GLOB2REGEX = {
+ '.' => '\.',
+ '$' => '\$',
+ '#' => '\#',
+ '*' => '.*'
+ }
+
+ def globs2re(pats)
+ /\A(?:#{
+ pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|')
+ })\z/
+ end
+
+ #
+ # TASK test
+ #
+
+ TESTDIR = 'test'
+
+ def exec_test
+ unless File.directory?('test')
+ $stderr.puts 'no test in this package' if verbose?
+ return
+ end
+ $stderr.puts 'Running tests...' if verbose?
+ begin
+ require 'test/unit'
+ rescue LoadError
+ setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.'
+ end
+ runner = Test::Unit::AutoRunner.new(true)
+ runner.to_run << TESTDIR
+ runner.run
+ end
+
+ #
+ # TASK clean
+ #
+
+ def exec_clean
+ exec_task_traverse 'clean'
+ rm_f @config.savefile
+ rm_f 'InstalledFiles'
+ end
+
+ alias clean_dir_bin noop
+ alias clean_dir_lib noop
+ alias clean_dir_data noop
+ alias clean_dir_conf noop
+ alias clean_dir_man noop
+
+ def clean_dir_ext(rel)
+ return unless extdir?(curr_srcdir())
+ make 'clean' if File.file?('Makefile')
+ end
+
+ #
+ # TASK distclean
+ #
+
+ def exec_distclean
+ exec_task_traverse 'distclean'
+ rm_f @config.savefile
+ rm_f 'InstalledFiles'
+ end
+
+ alias distclean_dir_bin noop
+ alias distclean_dir_lib noop
+
+ def distclean_dir_ext(rel)
+ return unless extdir?(curr_srcdir())
+ make 'distclean' if File.file?('Makefile')
+ end
+
+ alias distclean_dir_data noop
+ alias distclean_dir_conf noop
+ alias distclean_dir_man noop
+
+ #
+ # Traversing
+ #
+
+ def exec_task_traverse(task)
+ run_hook "pre-#{task}"
+ FILETYPES.each do |type|
+ if type == 'ext' and config('without-ext') == 'yes'
+ $stderr.puts 'skipping ext/* by user option' if verbose?
+ next
+ end
+ traverse task, type, "#{task}_dir_#{type}"
+ end
+ run_hook "post-#{task}"
+ end
+
+ def traverse(task, rel, mid)
+ dive_into(rel) {
+ run_hook "pre-#{task}"
+ __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '')
+ directories_of(curr_srcdir()).each do |d|
+ traverse task, "#{rel}/#{d}", mid
+ end
+ run_hook "post-#{task}"
+ }
+ end
+
+ def dive_into(rel)
+ return unless File.dir?("#{@srcdir}/#{rel}")
+
+ dir = File.basename(rel)
+ Dir.mkdir dir unless File.dir?(dir)
+ prevdir = Dir.pwd
+ Dir.chdir dir
+ $stderr.puts '---> ' + rel if verbose?
+ @currdir = rel
+ yield
+ Dir.chdir prevdir
+ $stderr.puts '<--- ' + rel if verbose?
+ @currdir = File.dirname(rel)
+ end
+
+ def run_hook(id)
+ path = [ "#{curr_srcdir()}/#{id}",
+ "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) }
+ return unless path
+ begin
+ instance_eval File.read(path), path, 1
+ rescue
+ raise if $DEBUG
+ setup_rb_error "hook #{path} failed:\n" + $!.message
+ end
+ end
+
+end # class Installer
+
+
+class SetupError < StandardError; end
+
+def setup_rb_error(msg)
+ raise SetupError, msg
+end
+
+if $0 == __FILE__
+ begin
+ ToplevelInstaller.invoke
+ rescue SetupError
+ raise if $DEBUG
+ $stderr.puts $!.message
+ $stderr.puts "Try 'ruby #{$0} --help' for detailed usage."
+ exit 1
+ end
+end
diff --git a/lib/libxslt-ruby-0.9.2/test/files/commentary.dtd b/lib/libxslt-ruby-0.9.2/test/files/commentary.dtd
new file mode 100644
index 0000000..af58087
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/files/commentary.dtd
@@ -0,0 +1,34 @@
+<!ELEMENT commentary (meta, body)>
+<!ELEMENT meta (author, version, date, id, title, subtitle?)>
+
+<!-- Metadata about the requirements -->
+<!ENTITY % string "#PCDATA">
+<!ENTITY % character "#PCDATA">
+<!ENTITY % letter "#PCDATA">
+<!ENTITY % number_att "CDATA">
+
+
+<!ELEMENT author (first_name, last_name, email)>
+
+<!ELEMENT first_name (%string;)>
+<!ELEMENT last_name (%string;)>
+<!ELEMENT email (%string;)>
+
+<!ELEMENT version (#PCDATA)>
+<!ELEMENT date (#PCDATA)>
+<!ELEMENT id (#PCDATA)>
+<!ELEMENT title (#PCDATA)>
+<!ELEMENT subtitle (#PCDATA)>
+
+<!ELEMENT body (para+)>
+
+
+<!ELEMENT para (#PCDATA|thought|url|ol)*>
+<!ATTLIST para
+ style (default|ps) "default">
+
+<!ELEMENT ol (li+)>
+<!ELEMENT li (#PCDATA)>
+<!ELEMENT url (#PCDATA)>
+<!ELEMENT thought (#PCDATA)>
+
diff --git a/lib/libxslt-ruby-0.9.2/test/files/fuzface.xml b/lib/libxslt-ruby-0.9.2/test/files/fuzface.xml
new file mode 100644
index 0000000..e1bd14f
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/files/fuzface.xml
@@ -0,0 +1,154 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?xml-stylesheet href="fuzface.xsl" type="text/xsl"?>
+
+<!DOCTYPE commentary SYSTEM "commentary.dtd">
+
+<commentary>
+ <meta>
+ <author>
+ <first_name>Sean</first_name>
+ <last_name>Chittenden</last_name>
+ <email>[email protected]</email>
+ </author>
+ <version>$Version$</version>
+ <date>$Date: 2008-07-09 23:35:19 -0600 (Wed, 09 Jul 2008) $</date>
+ <id>$Id: fuzface.xml 58 2008-07-10 05:35:19Z cfis $</id>
+ <title>Fuzface...</title>
+ <subtitle>The Internet's a big place and here's some proof...</subtitle>
+ </meta>
+
+ <body>
+ <para>
+ I think it's a tragedy that I'm going to start off my new
+ commentary by talking about facial hair and the Internet.
+ Something about that just screams pathetic, but whatever: it's
+ humor and that's life.
+ </para>
+
+ <para>
+ I've been working at home for a while now, which has been great.
+ I've been doing a lot of reading, good work, contributing to the
+ FreeBSD project, and living life at my own pace. The problem?
+ I don't have to interact with people, so I've let my appearance
+ slide a bit, most notably I've gone two weeks without shaving
+ and I have an awful hairy face.
+ </para>
+
+ <para>
+ Nothing is worse than going for a hard run, coming back, and
+ then bending your head down so that the hairs under your chin
+ touch the hairs on your neck. This has to be one of the most
+ disgusting/gross feelings I've experienced in a while. While
+ today wasn't the first time I'd experienced such a slimy tangled
+ mess, it is the first time I seriously considered shaving part
+ of my face, but not all of it: I was considering a beard.
+ </para>
+
+ <para>
+ Alright, so it's 5pm and I'm a sweaty post-run mess (it was 110
+ degrees in direct sunlight according to my thermometer) and
+ considering the possibility of growing a beard. Swifty nift?
+ Maybe. This is something I'd never done before, let alone
+ seriously consider. Normally I'd call my dad for such manly
+ advice, but he is: a) normally in another state, and; b) in
+ another country right now probably growing a beard (he's
+ notorious for coming back from a trip with a gnarly unshaven
+ face, sometimes he'll shape it into a decent beard). So, what's
+ a tech-junkie to do? Hop on the Internet and see if Google's
+ able to provide me with some inspiration.
+ </para>
+
+ <para>
+ Sure enough, I typed in "pictures of bearded men" and I was able
+ to find something: 14,000 pages of something to be exact.
+ Anyway, so most of these were rinky dink sites, a few of them
+ had some promise. One guy was trying to start a tradition where
+ everyone grows a beard for New Years. As I was scrolling down
+ the page trying to find some pictures, my mind was having the
+ following thought process: <thought>This seems like a dumb
+ idea... New Years provides a perfectly good excuse to kiss some
+ total stranger that you've had your eye on for the duration of a
+ New Years party. Why waste such an opportunity with a crappy
+ kiss?</thought> And at about this point I said this page sucks,
+ and flipped back to my search results.
+ </para>
+
+ <para>
+ Since I'd never done this before, I didn't know what was
+ fashionably correct in terms of where a guy should shave under
+ his neck, or what the deal was... I knew there were lots of
+ styles out there, just none that I could picture in my mind
+ (save maybe Santa Claus and a few really gnarly beards that are
+ long enough to be used as full-body covering. Oooh! And don't
+ forget the Russian and Amish beards, those stand out in my mind
+ too.). Google, being pretty comprehensive, and the Internet
+ being huge, found the exact screwball page I was looking for:
+ <url>http://fuzface-gallery.tripod.com/</url>
+ </para>
+
+ <para>
+ I don't know if I really should be amazed at the sheer number of
+ entries that Google returned, or that the Internet is big enough
+ to house such random gallery of crap, but it is and it never
+ ceases to amaze me... it's almost as amazing as the fact that
+ some bozo spent the time to create such a page. Don't people
+ have lives? Oh wait, I just visited his page... so back to my
+ diatribe...
+ </para>
+
+ <para>
+ There were tons of faces, lots of men, lots of hair, and plenty
+ of styles to choose from. Page after page of faces and hair.
+ Ugh. This wasn't getting any where and I was now entertaining
+ the rebound though of shaving my head. Time to close my browser
+ and hop in the shower: I reak. So what'd I do? Well, after
+ looking through enough of those pictures, I decided a few
+ things:
+ </para>
+
+ <para>
+ <ol>
+ <li>
+ I'm amazed that the Internet is big enough to foster the
+ creation of such random and utterly useless information. Then
+ again, I've been on and using the Net since '95, so this
+ shouldn't surprise me that much.
+ </li>
+
+ <li>
+ There are a lot of guys out there with varying tastes in,
+ shall we say, "facial hair styles," most of which I find
+ pretty unappealing.
+ </li>
+
+ <li>
+ I don't like beards. After one clogged drain, two
+ reapplications of shaving cream, and a few pases with the
+ razor, it took me about 5-10 minutes to get a nice cleanly
+ shaven face.
+ </li>
+
+ <li>
+ <crass comment>And - back me up here fellas, you can
+ sympathize with this feeling after you get done looking
+ through a magazine for a hair-cut style (ladies.. just smile
+ and nod and pretend you care) - after looking at a few dozen
+ pictures of men, I was able to safely reaffirm my desire for
+ heterosexual relations (translation from Bill Clintonese: have
+ sex with a woman). And with that thought in mind, I began to
+ pine for the college porn collection of old. Mmmm,
+ Playboy.</crass comment>
+ </li>
+ </ol>
+ </para>
+
+ <para>
+ ::grin:: Until next time. -Sean
+ </para>
+
+ <para style="ps">
+ P.S. To the guys out there with beards, this is just my
+ opinion: take it with a grain of salt.
+ </para>
+ </body>
+</commentary>
diff --git a/lib/libxslt-ruby-0.9.2/test/files/fuzface.xsl b/lib/libxslt-ruby-0.9.2/test/files/fuzface.xsl
new file mode 100644
index 0000000..2ea49f0
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/files/fuzface.xsl
@@ -0,0 +1,4 @@
+<?xml version="1.0" ?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+<xsl:include href="ramblings.xsl" />
+</xsl:stylesheet>
diff --git a/lib/libxslt-ruby-0.9.2/test/files/params.xml b/lib/libxslt-ruby-0.9.2/test/files/params.xml
new file mode 100644
index 0000000..58d14b3
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/files/params.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<doc>abc</doc>
diff --git a/lib/libxslt-ruby-0.9.2/test/files/params.xsl b/lib/libxslt-ruby-0.9.2/test/files/params.xsl
new file mode 100644
index 0000000..26e4d32
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/files/params.xsl
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version='1.0'
+ xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
+ xmlns:foo='http://example.com/foo'
+ exclude-result-prefixes='foo'>
+
+ <xsl:param name='bar'>failure</xsl:param>
+ <xsl:template match='/'>
+ <article><xsl:value-of select='$bar'/></article>
+ </xsl:template>
+</xsl:stylesheet>
\ No newline at end of file
diff --git a/lib/libxslt-ruby-0.9.2/test/files/ramblings.xsl b/lib/libxslt-ruby-0.9.2/test/files/ramblings.xsl
new file mode 100644
index 0000000..8326fb6
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/files/ramblings.xsl
@@ -0,0 +1,46 @@
+<?xml version="1.0" ?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+<xsl:template match="/">
+ <xsl:element name="html">
+ <xsl:element name="head">
+ <xsl:element name="title">Ramblings - <xsl:value-of select="commentary/meta/title" /> - <xsl:value-of select="commentary/meta/subtitle" /></xsl:element>
+ </xsl:element>
+
+ <xsl:element name="body">
+ <xsl:element name="h1"><xsl:value-of select="commentary/meta/title" /></xsl:element>
+ <xsl:element name="h3"><xsl:value-of select="commentary/meta/subtitle" /></xsl:element>
+ By: <xsl:value-of select="commentary/meta/author/first_name" /> <xsl:value-of select="commentary/meta/author/last_name" /><xsl:element name="br" />
+ Date: <xsl:value-of select="commentary/meta/date" /><xsl:element name="br" />
+
+ <xsl:for-each select="./commentary/body">
+ <xsl:apply-templates />
+ </xsl:for-each>
+
+ </xsl:element>
+ </xsl:element>
+</xsl:template>
+
+<xsl:template match="para">
+ <xsl:element name="p">
+ <xsl:apply-templates />
+ </xsl:element>
+</xsl:template>
+
+<xsl:template match="ol">
+ <xsl:element name="ol">
+ <xsl:apply-templates select="li" />
+ </xsl:element>
+</xsl:template>
+
+<xsl:template match="li">
+ <xsl:element name="li">
+ <xsl:value-of select="." />
+ </xsl:element>
+</xsl:template>
+
+<xsl:template match="thought">
+ <xsl:element name="i">
+ <xsl:value-of select="." />
+ </xsl:element>
+</xsl:template>
+</xsl:stylesheet>
diff --git a/lib/libxslt-ruby-0.9.2/test/test_deprecated.rb b/lib/libxslt-ruby-0.9.2/test/test_deprecated.rb
new file mode 100644
index 0000000..69c0252
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/test_deprecated.rb
@@ -0,0 +1,97 @@
+require 'xslt'
+require 'test/unit'
+
+class TestDeprecated < Test::Unit::TestCase
+ def setup()
+ xsl_file = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ xml_file = File.join(File.dirname(__FILE__), 'files/fuzface.xml')
+
+ @xslt = XML::XSLT.file(xsl_file)
+ @xslt.doc = XML::Document.file(xml_file)
+ @stylesheet = @xslt.parse
+ end
+
+ def tear_down()
+ @xslt = nil
+ @stylesheet = nil
+ end
+
+ def test_constants
+ assert_instance_of(Fixnum, XML::XSLT::MAX_DEPTH)
+ assert_instance_of(Fixnum, XML::XSLT::MAX_SORT)
+ assert_instance_of(String, XML::XSLT::ENGINE_VERSION)
+ assert_instance_of(Fixnum, XML::XSLT::LIBXSLT_VERSION)
+ assert_instance_of(Fixnum, XML::XSLT::LIBXML_VERSION)
+ assert_instance_of(String, XML::XSLT::XSLT_NAMESPACE)
+ assert_instance_of(String, XML::XSLT::DEFAULT_URL)
+ assert_instance_of(String, XML::XSLT::DEFAULT_VENDOR)
+ assert_instance_of(String, XML::XSLT::DEFAULT_VERSION)
+ assert_instance_of(String, XML::XSLT::NAMESPACE_LIBXSLT)
+ assert_instance_of(String, XML::XSLT::NAMESPACE_SAXON)
+ assert_instance_of(String, XML::XSLT::NAMESPACE_XT)
+ assert_instance_of(String, XML::XSLT::NAMESPACE_XALAN)
+ assert_instance_of(String, XML::XSLT::NAMESPACE_NORM_SAXON)
+ end
+
+ def test_new
+ xslt = XML::XSLT.new
+ assert_instance_of(XML::XSLT::Stylesheet, xslt)
+
+ xslt.filename = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ assert_instance_of(String, xslt.filename)
+ end
+
+ def test_file_type
+ assert_instance_of(XML::XSLT::Stylesheet, @xslt)
+ end
+
+ def test_doc
+ xsl_file = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ xml_file = File.join(File.dirname(__FILE__), 'files/fuzface.xml')
+
+ xslt = XML::XSLT.file(xsl_file)
+ xslt.doc = XML::Document.file(xml_file)
+ assert_instance_of(XML::Document, xslt.doc)
+ end
+
+ def test_parse
+ xsl_file = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ xml_file = File.join(File.dirname(__FILE__), 'files/fuzface.xml')
+
+ xslt = XML::XSLT.file(xsl_file)
+ stylesheet = xslt.parse
+ assert_instance_of(XML::XSLT::Stylesheet, stylesheet)
+ end
+
+ def test_parse
+ assert_instance_of(XML::XSLT::Stylesheet, @stylesheet)
+ end
+
+ def test_to_s
+ @stylesheet.apply
+ str = @stylesheet.to_s
+ assert_instance_of(String, str)
+ end
+
+ def test_save
+ @stylesheet.apply
+ @stylesheet.save("text.xml")
+ end
+
+ def test_print_invalid
+ @stylesheet.apply
+ @stylesheet.print
+ end
+
+ def test_save_invalid
+ assert_raises(ArgumentError) do
+ @stylesheet.save("str")
+ end
+ end
+
+ def test_print_invalid
+ assert_raises(ArgumentError) do
+ @stylesheet.print
+ end
+ end
+end
diff --git a/lib/libxslt-ruby-0.9.2/test/test_libxslt.rb b/lib/libxslt-ruby-0.9.2/test/test_libxslt.rb
new file mode 100644
index 0000000..043e7be
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/test_libxslt.rb
@@ -0,0 +1,21 @@
+require 'xslt'
+require 'test/unit'
+
+class TextLibXslt < Test::Unit::TestCase
+ def test_constants
+ assert_instance_of(Fixnum, XSLT::MAX_DEPTH)
+ assert_instance_of(Fixnum, XSLT::MAX_SORT)
+ assert_instance_of(String, XSLT::ENGINE_VERSION)
+ assert_instance_of(Fixnum, XSLT::LIBXSLT_VERSION)
+ assert_instance_of(Fixnum, XSLT::LIBXML_VERSION)
+ assert_instance_of(String, XSLT::XSLT_NAMESPACE)
+ assert_instance_of(String, XSLT::DEFAULT_URL)
+ assert_instance_of(String, XSLT::DEFAULT_VENDOR)
+ assert_instance_of(String, XSLT::DEFAULT_VERSION)
+ assert_instance_of(String, XSLT::NAMESPACE_LIBXSLT)
+ assert_instance_of(String, XSLT::NAMESPACE_SAXON)
+ assert_instance_of(String, XSLT::NAMESPACE_XT)
+ assert_instance_of(String, XSLT::NAMESPACE_XALAN)
+ assert_instance_of(String, XSLT::NAMESPACE_NORM_SAXON)
+ end
+end
diff --git a/lib/libxslt-ruby-0.9.2/test/test_stylesheet.rb b/lib/libxslt-ruby-0.9.2/test/test_stylesheet.rb
new file mode 100644
index 0000000..3686338
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/test_stylesheet.rb
@@ -0,0 +1,108 @@
+require 'xslt'
+require 'test/unit'
+
+class TestStylesheet < Test::Unit::TestCase
+ def setup
+ filename = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ doc = XML::Document.file(filename)
+ @stylesheet = XSLT::Stylesheet.new(doc)
+ end
+
+ def tear_down
+ @stylesheet = nil
+ end
+
+ def doc
+ filename = File.join(File.dirname(__FILE__), 'files/fuzface.xml')
+ XML::Document.file(filename)
+ end
+
+ def test_class
+ assert_instance_of(XSLT::Stylesheet, @stylesheet)
+ end
+
+ def test_apply
+ result = @stylesheet.apply(doc)
+ assert_instance_of(XML::Document, result)
+
+ paragraphs = result.find('//p')
+ assert_equal(11, paragraphs.length)
+ end
+
+ def test_apply_multiple
+ 10.times do
+ test_apply
+ end
+ end
+
+ def test_params
+ filename = File.join(File.dirname(__FILE__), 'files/params.xsl')
+ sdoc = XML::Document.file(filename)
+
+ filename = File.join(File.dirname(__FILE__), 'files/params.xml')
+ stylesheet = XSLT::Stylesheet.new(sdoc)
+ doc = XML::Document.file(filename)
+
+ # Start with no params
+ result = stylesheet.apply(doc)
+ assert_equal('<article>failure</article>', result.root.to_s)
+
+ # Now try with params as hash. /doc is evaluated
+ # as an xpath expression
+ result = stylesheet.apply(doc, 'bar' => "/doc")
+ assert_equal('<article>abc</article>', result.root.to_s)
+
+ # Now try with params as hash. Note the double quote
+ # on success - we want to pass a literal string and
+ # not an xpath expression.
+ result = stylesheet.apply(doc, 'bar' => "'success'")
+ assert_equal('<article>success</article>', result.root.to_s)
+
+ # Now try with params as an array.
+ result = stylesheet.apply(doc, ['bar', "'success'"])
+ assert_equal('<article>success</article>', result.root.to_s)
+
+ # Now try with invalid array.
+ result = stylesheet.apply(doc, ['bar'])
+ assert_equal('<article>failure</article>', result.root.to_s)
+ end
+
+ # -- Memory Tests ----
+ def test_doc_ownership
+ 10.times do
+ filename = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ sdoc = XML::Document.file(filename)
+ stylesheet = XSLT::Stylesheet.new(sdoc)
+
+ stylesheet = nil
+ GC.start
+ assert_equal(156, sdoc.to_s.length)
+ end
+ end
+
+ def test_stylesheet_ownership
+ 10.times do
+ filename = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ sdoc = XML::Document.file(filename)
+ stylesheet = XSLT::Stylesheet.new(sdoc)
+
+ sdoc = nil
+ GC.start
+
+ rdoc = stylesheet.apply(doc)
+ assert_equal(5993, rdoc.to_s.length)
+ end
+ end
+
+ def test_result_ownership
+ 10.times do
+ filename = File.join(File.dirname(__FILE__), 'files/fuzface.xsl')
+ sdoc = XML::Document.file(filename)
+ stylesheet = XSLT::Stylesheet.new(sdoc)
+
+ rdoc = stylesheet.apply(doc)
+ rdoc = nil
+ GC.start
+ end
+ end
+end
diff --git a/lib/libxslt-ruby-0.9.2/test/test_suite.rb b/lib/libxslt-ruby-0.9.2/test/test_suite.rb
new file mode 100644
index 0000000..36774a3
--- /dev/null
+++ b/lib/libxslt-ruby-0.9.2/test/test_suite.rb
@@ -0,0 +1,3 @@
+require 'test_libxslt'
+require 'test_stylesheet'
+require 'test_deprecated'
\ No newline at end of file
|
petrsigut/unico | c25478027e8274cb4617e0466aa04c4e585d9574 | checking if query is empty before including push things in views | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
deleted file mode 100644
index de9a3f3..0000000
Binary files a/app/controllers/.contents_controller.rb.swp and /dev/null differ
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 441cc90..af62f18 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,109 +1,109 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
def send_data
render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
end
render :nothing => true
end
def index
category = params[:category_id]
if (category == "0")
@contents = Content.find(:all, :order => "name")
else
@contents = Content.find(:all, :order => "name", :conditions => ["category_id = ?", category])
end
# @categories = Category.find(:all)
# http://keepwithinthelines.wordpress.com/2008/03/17/using-select-helper-in-rails/
@categories = Category.find(:all)
@categories = [ ["all", 0] ] + @categories.map {|p| [ p.name, p.id ] }
@layout = "index"
end
def show
name = params[:id]
- query = {}
+ @query = {}
params.each do |param|
if (param[0] =~ /^\w+$/i and
param[1] =~ /^\w+$/i and
param[0] != "id" and
param[0] != "format" and
param[0] != "action" and
param[0] != "controller") then
- query[param[0]] = param[1]
+ @query[param[0]] = param[1]
end
end
logger.fatal "Query"
- logger.fatal query.inspect
+ logger.fatal @query.inspect
logger.fatal "Query NIL?"
- logger.fatal query.empty?
+ logger.fatal @query.empty?
# at nam pod to name nepodstrci nejakou zlou vec
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |content_name|
if name == content_name.name
found_in_db = true
end
end
if found_in_db
@content = Content.find_by_name(name, :select => 'updated_at')
# the time should be setable by variable in content model
@layout = (name).constantize.mylayout
- if (@content.updated_at < 10.seconds.ago or not query.empty?)
- @content = (name).constantize.parse_content(query)
+ if (@content.updated_at < 10.seconds.ago or not @query.empty?)
+ @content = (name).constantize.parse_content(@query)
logger.fatal "call parse_content"
else # we want content from db
@content = Content.find_by_name(name)
end
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
deleted file mode 100644
index 8e6694c..0000000
Binary files a/app/models/.content.rb.swp and /dev/null differ
diff --git a/app/models/.pcfilmtydne.rb.swp b/app/models/.pcfilmtydne.rb.swp
deleted file mode 100644
index d17806e..0000000
Binary files a/app/models/.pcfilmtydne.rb.swp and /dev/null differ
diff --git a/app/views/contents/show.html.erb b/app/views/contents/show.html.erb
index d8279e4..0ece6ea 100644
--- a/app/views/contents/show.html.erb
+++ b/app/views/contents/show.html.erb
@@ -1,9 +1,9 @@
<html>
<head>
- <%= if PUSH_ENABLE then render :partial => "juggernaut_head" end %>
+ <%= if (PUSH_ENABLE and @query.empty?) then render :partial => "juggernaut_head" end %>
</head>
<body>
<%= @content.rawhtml %>
- <%= if PUSH_ENABLE then render :partial => "juggernaut_body" end %>
+ <%= if (PUSH_ENABLE and @query.empty?) then render :partial => "juggernaut_body" end %>
</body>
</html>
diff --git a/config/environment.rb b/config/environment.rb
index ceb73af..0e20abb 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,44 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
-PUSH_ENABLE = false
+PUSH_ENABLE = true
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
|
petrsigut/unico | 6a3c330c79a11b8d37a12d56bef14382cd901954 | fix xslt/xml paths again | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
new file mode 100644
index 0000000..de9a3f3
Binary files /dev/null and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 07e6d18..441cc90 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,106 +1,109 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
def send_data
render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
end
render :nothing => true
end
def index
category = params[:category_id]
if (category == "0")
@contents = Content.find(:all, :order => "name")
else
@contents = Content.find(:all, :order => "name", :conditions => ["category_id = ?", category])
end
# @categories = Category.find(:all)
# http://keepwithinthelines.wordpress.com/2008/03/17/using-select-helper-in-rails/
@categories = Category.find(:all)
@categories = [ ["all", 0] ] + @categories.map {|p| [ p.name, p.id ] }
@layout = "index"
end
def show
name = params[:id]
query = {}
params.each do |param|
if (param[0] =~ /^\w+$/i and
param[1] =~ /^\w+$/i and
param[0] != "id" and
param[0] != "format" and
param[0] != "action" and
param[0] != "controller") then
query[param[0]] = param[1]
end
end
logger.fatal "Query"
logger.fatal query.inspect
logger.fatal "Query NIL?"
logger.fatal query.empty?
# at nam pod to name nepodstrci nejakou zlou vec
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |content_name|
if name == content_name.name
found_in_db = true
end
end
if found_in_db
- #@content = Content.find_by_name(@name, :select => 'updated_at')
- #if @content.updated_at < 10.seconds.ago # should be set by variable in content model
+ @content = Content.find_by_name(name, :select => 'updated_at')
+
+ # the time should be setable by variable in content model
+ @layout = (name).constantize.mylayout
+ if (@content.updated_at < 10.seconds.ago or not query.empty?)
@content = (name).constantize.parse_content(query)
- @layout = (name).constantize.mylayout
logger.fatal "call parse_content"
- #end
- #@content = Content.find_by_name(@name)
+ else # we want content from db
+ @content = Content.find_by_name(name)
+ end
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
index 0420964..8e6694c 100644
Binary files a/app/models/.content.rb.swp and b/app/models/.content.rb.swp differ
diff --git a/app/models/.pcfilmtydne.rb.swp b/app/models/.pcfilmtydne.rb.swp
new file mode 100644
index 0000000..d17806e
Binary files /dev/null and b/app/models/.pcfilmtydne.rb.swp differ
diff --git a/app/models/content.rb b/app/models/content.rb
index f803e57..14acd94 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,140 +1,140 @@
class Content < ActiveRecord::Base
has_one :category
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
-# require 'rubygems'
+ require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
- require 'libxml'
- require 'libxslt'
+ require 'xml/libxml'
+ require 'xml/libxslt'
def self.mylayout
"application"
end
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
- def transform_xml2html(xml)
+ def transform_xml2html(xml_data)
xslt = XML::XSLT.new()
- xslt.xml = xml.to_s
+ xslt.xml = xml_data.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
xslt.serve()
end
def create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
self.xml = @kml_doc
end
def create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @kml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/config/environment.rb b/config/environment.rb
index b5b1610..ceb73af 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,44 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
PUSH_ENABLE = false
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{RAILS_ROOT}/extras )
+ # config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
|
petrsigut/unico | 340c43e08a65c74745ff49b44341f63f6d14030d | fixing freebsd xslt | diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 3e90f19..07e6d18 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,97 +1,106 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
def send_data
render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
end
render :nothing => true
end
def index
- @contents = Content.find(:all, :order => "name")
+ category = params[:category_id]
+
+ if (category == "0")
+ @contents = Content.find(:all, :order => "name")
+ else
+ @contents = Content.find(:all, :order => "name", :conditions => ["category_id = ?", category])
+ end
# @categories = Category.find(:all)
+ # http://keepwithinthelines.wordpress.com/2008/03/17/using-select-helper-in-rails/
+ @categories = Category.find(:all)
+ @categories = [ ["all", 0] ] + @categories.map {|p| [ p.name, p.id ] }
@layout = "index"
end
def show
name = params[:id]
query = {}
params.each do |param|
if (param[0] =~ /^\w+$/i and
param[1] =~ /^\w+$/i and
param[0] != "id" and
param[0] != "format" and
param[0] != "action" and
param[0] != "controller") then
query[param[0]] = param[1]
end
end
logger.fatal "Query"
logger.fatal query.inspect
logger.fatal "Query NIL?"
logger.fatal query.empty?
# at nam pod to name nepodstrci nejakou zlou vec
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |content_name|
if name == content_name.name
found_in_db = true
end
end
if found_in_db
#@content = Content.find_by_name(@name, :select => 'updated_at')
#if @content.updated_at < 10.seconds.ago # should be set by variable in content model
@content = (name).constantize.parse_content(query)
@layout = (name).constantize.mylayout
logger.fatal "call parse_content"
#end
#@content = Content.find_by_name(@name)
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/controllers/.contents_controller.rb.swp b/app/models/.content.rb.swp
similarity index 53%
rename from app/controllers/.contents_controller.rb.swp
rename to app/models/.content.rb.swp
index f632696..0420964 100644
Binary files a/app/controllers/.contents_controller.rb.swp and b/app/models/.content.rb.swp differ
diff --git a/app/models/capitolwords.rb b/app/models/capitolwords.rb
index 05d9e8e..80ddce7 100644
--- a/app/models/capitolwords.rb
+++ b/app/models/capitolwords.rb
@@ -1,28 +1,29 @@
class Capitolwords < Content
def self.parse_content(query = {})
content = Capitolwords.new
content.name_human = "Top capitol words today"
+ content.category_id = 3
if query["number"].nil?
url = "http://capitolwords.org/api/wod/latest/top10.xml"
else
url = "http://capitolwords.org/api/wod/latest/top#{query["number"]}.xml"
end
xml_data = Net::HTTP.get_response(URI.parse(url)).body
doc = REXML::Document.new(xml_data)
content.create_xml_head
doc.elements.each("xml/wordsofday/*") do |element|
word = element.attributes.get_attribute("word").value
word_count = element.attributes.get_attribute("word_count").value
content.create_xml_body("label", word+" "+word_count)
end
content.save_me(query)
end
end
diff --git a/app/models/content.rb b/app/models/content.rb
index d1173d2..f803e57 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,140 +1,140 @@
class Content < ActiveRecord::Base
has_one :category
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
# require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
- require 'xml/libxml'
- require 'xml/libxslt'
+ require 'libxml'
+ require 'libxslt'
def self.mylayout
"application"
end
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml)
xslt = XML::XSLT.new()
xslt.xml = xml.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
xslt.serve()
end
def create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
self.xml = @kml_doc
end
def create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @kml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/app/models/photoofthedaycom.rb b/app/models/photoofthedaycom.rb
index d66b778..6d21a38 100644
--- a/app/models/photoofthedaycom.rb
+++ b/app/models/photoofthedaycom.rb
@@ -1,35 +1,36 @@
class Photoofthedaycom < Content
def self.mylayout
"slideshow"
end
def self.parse_content(query = {})
content = Photoofthedaycom.new
content.name_human = "Photo of the Day"
+ content.category_id = 3
year = Time.now.strftime("%Y")
# with leading zeros
month = Time.now.strftime("%m")
day = Time.now.strftime("%d")
content.create_xml_head
rawhtml = []
10.times.with_index do |x, index|
if index < 9
rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
else
rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
end
content.create_xml_body("image", rawhtml[index])
end
content.rawhtml = create_gallery(rawhtml)
content.save_me(query)
end
end
diff --git a/app/views/contents/index.html.erb b/app/views/contents/index.html.erb
index afcd753..ad5d3a4 100644
--- a/app/views/contents/index.html.erb
+++ b/app/views/contents/index.html.erb
@@ -1,32 +1,40 @@
<div class="logo">
<img src="/images/logo.png" alt="Unico" />
</div>
<div class="filter">
+ <% form_tag do %>
+
+ <%#= select_tag "category", options_for_select(@categories, :category.name) %>
+ <%= select_tag(:category_id,
+ options_for_select(@categories, params[:category_id].to_i)) %>
+ <%= submit_tag 'Filter' %>
+
+<% end %>
<%#= select @categories %>
</div>
<% for content in @contents %>
<div class="content">
<span><%=h content.name_human %></span>
<% unless content.rawhtml.nil? %>
<span><%= link_to "HTML", "/contents/show/"+content.name+".html" %></span>
<% end %>
<% unless content.xml.nil? %>
<span><%= link_to "XML", "/contents/show/"+content.name+".xml" %></span>
<span><%= link_to "XHTML", "/contents/show/"+content.name+".xhtml" %></span>
<% end %>
<% unless content.plaintext.nil? %>
<span><%= link_to "TXT", "/contents/show/"+content.name+".txt" %></span>
<% end %>
<% unless content.rawhtml.nil? %>
<%= content.rawhtml %>
<% else %>
<%= content.xhtml %>
<% end %>
</div>
<% end %>
|
petrsigut/unico | 294e1ce392cc22309eecf0313feac9aa6b51775f | better look-feel; starting implementing categories | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
index b069210..f632696 100644
Binary files a/app/controllers/.contents_controller.rb.swp and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 17aad04..3e90f19 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,95 +1,97 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
def send_data
render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
end
render :nothing => true
end
def index
@contents = Content.find(:all, :order => "name")
- @layout = "application"
+# @categories = Category.find(:all)
+
+ @layout = "index"
end
def show
name = params[:id]
query = {}
params.each do |param|
if (param[0] =~ /^\w+$/i and
param[1] =~ /^\w+$/i and
param[0] != "id" and
param[0] != "format" and
param[0] != "action" and
param[0] != "controller") then
query[param[0]] = param[1]
end
end
logger.fatal "Query"
logger.fatal query.inspect
logger.fatal "Query NIL?"
logger.fatal query.empty?
# at nam pod to name nepodstrci nejakou zlou vec
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |content_name|
if name == content_name.name
found_in_db = true
end
end
if found_in_db
#@content = Content.find_by_name(@name, :select => 'updated_at')
#if @content.updated_at < 10.seconds.ago # should be set by variable in content model
@content = (name).constantize.parse_content(query)
@layout = (name).constantize.mylayout
logger.fatal "call parse_content"
#end
#@content = Content.find_by_name(@name)
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
deleted file mode 100644
index 37e8a2f..0000000
Binary files a/app/models/.content.rb.swp and /dev/null differ
diff --git a/app/models/.photoofthedaycom.rb.swp b/app/models/.photoofthedaycom.rb.swp
deleted file mode 100644
index 9d36505..0000000
Binary files a/app/models/.photoofthedaycom.rb.swp and /dev/null differ
diff --git a/app/models/category.rb b/app/models/category.rb
new file mode 100644
index 0000000..1a1008f
--- /dev/null
+++ b/app/models/category.rb
@@ -0,0 +1,3 @@
+class Category < ActiveRecord::Base
+ has_many :contents
+end
diff --git a/app/models/content.rb b/app/models/content.rb
index b043f25..d1173d2 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,138 +1,140 @@
class Content < ActiveRecord::Base
+ has_one :category
+
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
# require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
def self.mylayout
"application"
end
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml)
xslt = XML::XSLT.new()
xslt.xml = xml.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
xslt.serve()
end
def create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
self.xml = @kml_doc
end
def create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @kml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/app/models/fiterminy.rb b/app/models/fiterminy.rb
index 7382707..7b5cb90 100644
--- a/app/models/fiterminy.rb
+++ b/app/models/fiterminy.rb
@@ -1,21 +1,21 @@
class Fiterminy < Content
def self.parse_content(query = {})
content = Fiterminy.new
content.name_human = "FI MUNI: aktuálnà termÃny"
rawhtml = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
rawhtml = rawhtml.search("//table")
- logger.fatal rawhtml.inspect
+ #logger.fatal rawhtml.inspect
if (query["mgr"] == "yes")
content.rawhtml = rawhtml.second.to_s
else
content.rawhtml = rawhtml.first.to_s
end
content.save_me(query)
end
end
diff --git a/app/models/idsjmk.rb b/app/models/idsjmk.rb
index 7ae66a6..0224dcc 100644
--- a/app/models/idsjmk.rb
+++ b/app/models/idsjmk.rb
@@ -1,20 +1,22 @@
class Idsjmk < Content
def self.parse_content(query = {})
content = Idsjmk.new
content.name_human = "IDS JMK odjezdy"
if (query["stopId"].nil? or query["poleId"].nil?)
url = "http://wap.aspone.cz/GetDepartures.ashx?stopId=1166&poleId=1"
else
url = "http://wap.aspone.cz/GetDepartures.ashx?stopId=#{query["stopId"]}&poleId=#{query["poleId"]}"
end
rawhtml = Hpricot(open(url))
+ rawhtml = rawhtml.at("//div")
+
content.rawhtml = rawhtml.to_s
content.save_me(query)
end
end
diff --git a/app/views/contents/index.html.erb b/app/views/contents/index.html.erb
index 19cdeec..afcd753 100644
--- a/app/views/contents/index.html.erb
+++ b/app/views/contents/index.html.erb
@@ -1,24 +1,32 @@
+<div class="logo">
+ <img src="/images/logo.png" alt="Unico" />
+</div>
+
+<div class="filter">
+ <%#= select @categories %>
+</div>
+
<% for content in @contents %>
<div class="content">
<span><%=h content.name_human %></span>
<% unless content.rawhtml.nil? %>
<span><%= link_to "HTML", "/contents/show/"+content.name+".html" %></span>
<% end %>
<% unless content.xml.nil? %>
<span><%= link_to "XML", "/contents/show/"+content.name+".xml" %></span>
<span><%= link_to "XHTML", "/contents/show/"+content.name+".xhtml" %></span>
<% end %>
<% unless content.plaintext.nil? %>
<span><%= link_to "TXT", "/contents/show/"+content.name+".txt" %></span>
<% end %>
<% unless content.rawhtml.nil? %>
<%= content.rawhtml %>
<% else %>
<%= content.xhtml %>
<% end %>
</div>
<% end %>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index eaf40ee..a6f6090 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,16 +1,14 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
- <%= stylesheet_link_tag 'index' %>
+ <%#= stylesheet_link_tag 'index' %>
</head>
<body>
-<p style="color: green"><%= flash[:notice] %></p>
-
<%= yield %>
</body>
</html>
diff --git a/app/views/layouts/application.xhtml.erb b/app/views/layouts/application.xhtml.erb
deleted file mode 100644
index eaf40ee..0000000
--- a/app/views/layouts/application.xhtml.erb
+++ /dev/null
@@ -1,16 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
- <%= stylesheet_link_tag 'index' %>
-</head>
-<body>
-
-<p style="color: green"><%= flash[:notice] %></p>
-
-<%= yield %>
-
-</body>
-</html>
diff --git a/app/views/layouts/application.xhtml.erb b/app/views/layouts/application.xhtml.erb
new file mode 120000
index 0000000..589623a
--- /dev/null
+++ b/app/views/layouts/application.xhtml.erb
@@ -0,0 +1 @@
+application.html.erb
\ No newline at end of file
diff --git a/app/views/layouts/index.html.erb b/app/views/layouts/index.html.erb
new file mode 100644
index 0000000..50b3f90
--- /dev/null
+++ b/app/views/layouts/index.html.erb
@@ -0,0 +1,17 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
+ <%= stylesheet_link_tag 'index' %>
+ <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
+</head>
+<body>
+
+<p style="color: green"><%= flash[:notice] %></p>
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/db/migrate/20091122202720_create_categories.rb b/db/migrate/20091122202720_create_categories.rb
new file mode 100644
index 0000000..7aac11a
--- /dev/null
+++ b/db/migrate/20091122202720_create_categories.rb
@@ -0,0 +1,13 @@
+class CreateCategories < ActiveRecord::Migration
+ def self.up
+ create_table :categories do |t|
+ t.string :name
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :categories
+ end
+end
diff --git a/db/migrate/20091122210816_add_category_id_to_contents.rb b/db/migrate/20091122210816_add_category_id_to_contents.rb
new file mode 100644
index 0000000..87b03fa
--- /dev/null
+++ b/db/migrate/20091122210816_add_category_id_to_contents.rb
@@ -0,0 +1,9 @@
+class AddCategoryIdToContents < ActiveRecord::Migration
+ def self.up
+ add_column :contents, :category_id, :integer
+ end
+
+ def self.down
+ remove_column :contents, :category_id
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index d9bd60e..ffe427c 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,25 +1,32 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20091031120615) do
+ActiveRecord::Schema.define(:version => 20091122210816) do
+
+ create_table "categories", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
create_table "contents", :force => true do |t|
t.string "name"
t.text "rawhtml"
t.text "xml"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name_human"
t.text "xhtml"
t.text "plaintext"
+ t.integer "category_id"
end
end
diff --git a/lib/tasks/downloadall.rake b/lib/tasks/downloadall.rake
index 9540b59..7d8bcc4 100644
--- a/lib/tasks/downloadall.rake
+++ b/lib/tasks/downloadall.rake
@@ -1,20 +1,20 @@
desc "Iterate thru all contents and download new content, if it differs from
old, then push"
task(:downloadall => :environment) do
# @contents = Content.find(:all)
# @contents.each do |content|
basedir = 'app/models/'
Dir.chdir(basedir)
files = Dir.glob("*.rb")
files.each do |model|
model.chomp!('.rb')
- if (model != 'sablona' and model != 'content')
+ if (model != 'sablona' and model != 'content' and model != 'category')
(model).humanize.constantize.parse_content
puts (model).humanize + " called parse_content"
end
end
# puts content.name
# puts "parsed"
# end
end
diff --git a/public/images/favicon.ico b/public/images/favicon.ico
new file mode 100644
index 0000000..1d89d20
Binary files /dev/null and b/public/images/favicon.ico differ
diff --git a/public/images/favicon.xcf b/public/images/favicon.xcf
new file mode 100644
index 0000000..83be6a5
Binary files /dev/null and b/public/images/favicon.xcf differ
diff --git a/public/images/logo.png b/public/images/logo.png
new file mode 100644
index 0000000..c95a67a
Binary files /dev/null and b/public/images/logo.png differ
diff --git a/public/images/logo.xcf b/public/images/logo.xcf
new file mode 100644
index 0000000..63c586e
Binary files /dev/null and b/public/images/logo.xcf differ
diff --git a/public/images/stripes.png b/public/images/stripes.png
new file mode 100644
index 0000000..7eb9235
Binary files /dev/null and b/public/images/stripes.png differ
diff --git a/public/logo.png b/public/logo.png
new file mode 100644
index 0000000..4c62cba
Binary files /dev/null and b/public/logo.png differ
diff --git a/public/logo.xcf b/public/logo.xcf
new file mode 100644
index 0000000..35d9051
Binary files /dev/null and b/public/logo.xcf differ
diff --git a/public/stylesheets/index.css b/public/stylesheets/index.css
index 656f82e..a924eb6 100644
--- a/public/stylesheets/index.css
+++ b/public/stylesheets/index.css
@@ -1,9 +1,23 @@
div.content {
border: 1px solid gray;
width: 250px;
height: 200px;
- overflow: auto;
+ overflow: hidden;
float: left;
margin: 20px;
padding: 12px;
+ background-color: white;
+}
+
+div.content:hover {
+ border: 1px solid #009fe5;
+}
+
+
+.logo {
+ margin-left: 20px;
+}
+
+body {
+ background-color: #ebebeb;
}
diff --git a/test/fixtures/categories.yml b/test/fixtures/categories.yml
new file mode 100644
index 0000000..157d747
--- /dev/null
+++ b/test/fixtures/categories.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+
+two:
+ name: MyString
diff --git a/test/unit/category_test.rb b/test/unit/category_test.rb
new file mode 100644
index 0000000..233dacb
--- /dev/null
+++ b/test/unit/category_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class CategoryTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
|
petrsigut/unico | ad75eb95e2abb10a22f00bdf9f1463d36ea030f1 | fixed layouts | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
index 9b1336a..b069210 100644
Binary files a/app/controllers/.contents_controller.rb.swp and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
index 2a9f15c..37e8a2f 100644
Binary files a/app/models/.content.rb.swp and b/app/models/.content.rb.swp differ
diff --git a/app/models/content.rb b/app/models/content.rb
index c654c62..b043f25 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,134 +1,138 @@
class Content < ActiveRecord::Base
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
# require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
+ def self.mylayout
+ "application"
+ end
+
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml)
xslt = XML::XSLT.new()
xslt.xml = xml.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
xslt.serve()
end
def create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
self.xml = @kml_doc
end
def create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @kml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/app/views/layouts/application.xhtml.erb b/app/views/layouts/application.xhtml.erb
new file mode 100644
index 0000000..eaf40ee
--- /dev/null
+++ b/app/views/layouts/application.xhtml.erb
@@ -0,0 +1,16 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
+ <%= stylesheet_link_tag 'index' %>
+</head>
+<body>
+
+<p style="color: green"><%= flash[:notice] %></p>
+
+<%= yield %>
+
+</body>
+</html>
|
petrsigut/unico | 78eeef07d614014a7b345b630d144fd1e4d50380 | deleted old files. fixed slideshow | diff --git a/Capfile b/Capfile
new file mode 100644
index 0000000..e04728e
--- /dev/null
+++ b/Capfile
@@ -0,0 +1,4 @@
+load 'deploy' if respond_to?(:namespace) # cap2 differentiator
+Dir['vendor/plugins/*/recipes/*.rb'].each { |plugin| load(plugin) }
+
+load 'config/deploy' # remove this line to skip loading any of the default tasks
\ No newline at end of file
diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
new file mode 100644
index 0000000..9b1336a
Binary files /dev/null and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/controllers/cnb_controller.rb b/app/controllers/cnb_controller.rb
deleted file mode 100644
index 1ac42fc..0000000
--- a/app/controllers/cnb_controller.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-class CnbController < ApplicationController
- require 'hpricot'
- # na otvirani urlek
- require 'open-uri'
-
- def index
- # tady tahaji z imdb:
- # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
-
- @doc = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
- @doc = @doc.search("//table[@class='kurzy_tisk']")
-
- @doc = @doc.to_s()
-
-
- # @movies.gsub!(/[\n\r]/, "")
- # /m nam zajisti ze neresi newlines
- # http://www.regular-expressions.info/ruby.html
-# @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
- # @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
-# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
- # @movies = Hpricot(@movies)
-
- #@kurzy = {}
-# (@movies/"//table//tr").each do |row|
-# (row/"//td").each do |cell|
-# logger.fatal cell.inner_html
-# end
-# logger.fatal "XXX"
-# end
-
-
- end
-end
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 0000478..17aad04 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,94 +1,95 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
def send_data
render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
end
render :nothing => true
end
def index
@contents = Content.find(:all, :order => "name")
@layout = "application"
end
def show
name = params[:id]
query = {}
params.each do |param|
if (param[0] =~ /^\w+$/i and
param[1] =~ /^\w+$/i and
param[0] != "id" and
param[0] != "format" and
param[0] != "action" and
param[0] != "controller") then
query[param[0]] = param[1]
end
end
logger.fatal "Query"
logger.fatal query.inspect
logger.fatal "Query NIL?"
logger.fatal query.empty?
# at nam pod to name nepodstrci nejakou zlou vec
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |content_name|
if name == content_name.name
found_in_db = true
end
end
if found_in_db
#@content = Content.find_by_name(@name, :select => 'updated_at')
#if @content.updated_at < 10.seconds.ago # should be set by variable in content model
@content = (name).constantize.parse_content(query)
+ @layout = (name).constantize.mylayout
logger.fatal "call parse_content"
#end
#@content = Content.find_by_name(@name)
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/controllers/exchange_controller.rb b/app/controllers/exchange_controller.rb
deleted file mode 100644
index b6d945a..0000000
--- a/app/controllers/exchange_controller.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-class ExchangeController < ApplicationController
- require 'hpricot'
- # na otvirani urlek
- require 'open-uri'
-
- def index
- # tady tahaji z imdb:
- # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
-
- @doc = Hpricot(open("http://www.kurzy.cz/kurzy-men/"))
- #doc = doc.to_s()
- @movies = @doc.search("//body")
- @movies = @movies.to_s()
-
-
- # @movies.gsub!(/[\n\r]/, "")
- # /m nam zajisti ze neresi newlines
- # http://www.regular-expressions.info/ruby.html
- @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
- @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
-# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
- @movies = Hpricot(@movies)
- end
-end
diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb
deleted file mode 100644
index cd3a6d2..0000000
--- a/app/controllers/movies_controller.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-class MoviesController < ApplicationController
- require 'hpricot'
- # na otvirani urlek
- require 'open-uri'
-
- def index
- # tady tahaji z imdb:
- # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
-
- @doc = Hpricot(open("http://www.csfd.cz/"))
- @movies = @doc.search("//body")
- @movies = @movies.to_s()
-
-
- # @movies.gsub!(/[\n\r]/, "")
- # /m nam zajisti ze neresi newlines
- # http://www.regular-expressions.info/ruby.html
- @movies.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
- @movies.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
- @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
- @movies = Hpricot(@movies)
-
- end
-end
diff --git a/app/controllers/pcfilmtydne_controller.rb b/app/controllers/pcfilmtydne_controller.rb
deleted file mode 100644
index 1e74c20..0000000
--- a/app/controllers/pcfilmtydne_controller.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-class PcfilmtydneController < ApplicationController
- require 'hpricot'
- # na otvirani urlek
- require 'open-uri'
- require 'net/http'
- # require 'builder'
- require "rexml/document"
-
-
- def index
- # tady tahaji z imdb:
- # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
-
- # film tydne ve Spalicku
- @doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1&cin=411&td=2008-09-21&id=0&uid=7c18c3c1b38f4081e601bf2d5eb63b73"))
- #doc = doc.to_s()
- #@movies = @doc.at("//table/#kurzy_tisk").xpath
- @doc = @doc.search("//div[@class='frame red']")
-
- #@movies = @movies.to_s()
-
- # @movies.gsub!(/[\n\r]/, "")
- # /m nam zajisti ze neresi newlines
- # http://www.regular-expressions.info/ruby.html
-# @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
- # @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
-# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
- #@movies = Hpricot(@movies)
-
-
- @label1 = @doc.search("//h3")
- @label2 = @doc.search("//h2")
- @image1 = @doc.at("//img")
- @image1 = @image1.attributes['src']
- @label3 = @doc.at("//p")
-
-# @x = Builder::XmlMarkup.new
-# @x.instruct!
-# @x.label @label1
-
- @xml = REXML::Document.new
- @kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
- @kml_doc = @kml.add_element 'document'
- (@kml_doc.add_element 'label').text = @label1
- (@kml_doc.add_element 'label').text = @label2
- (@kml_doc.add_element 'image').text = @image1
- (@kml_doc.add_element 'label').text = @label3
- #(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
-
-
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml }
- end
-
-#<label>obsah labelu1</label>
- #
-
-
- # ted musime nejak kesovat ten obrazek, takhle?
- # http://www.ruby-forum.com/topic/133981
- #
-
-#--------------------------------------------------
-# Net::HTTP.start( 'www.sigut.net' ) { |http|
-# resp = http.get( '/fotky/_obr300.jpg' )
-# open( '/tmp/ror_vs_c_asm.jpg', 'wb' ) { |file|
-# file.write(resp.body)
-# }
-# }
-#
-#--------------------------------------------------
-
-
-
- end
-end
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
new file mode 100644
index 0000000..2a9f15c
Binary files /dev/null and b/app/models/.content.rb.swp differ
diff --git a/app/models/.photoofthedaycom.rb.swp b/app/models/.photoofthedaycom.rb.swp
new file mode 100644
index 0000000..9d36505
Binary files /dev/null and b/app/models/.photoofthedaycom.rb.swp differ
diff --git a/app/models/content.rb b/app/models/content.rb
index 3eb482a..c654c62 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,133 +1,134 @@
class Content < ActiveRecord::Base
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# do decode html entities in html2txt
# require 'rubygems'
# script/server needs restart after installing new gem
require 'htmlentities'
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
coder = HTMLEntities.new
html = coder.decode(html)
# convert newlines from DOS to UNIX
html.gsub!(/[\n\r]+/, "\n")
html.gsub!(/^\s*/,'')
#ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
# html = sanitize(html)
end
def transform_xml2html(xml)
xslt = XML::XSLT.new()
xslt.xml = xml.to_s
- xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xls"
+ xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xsl"
xslt.serve()
end
def create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
self.xml = @kml_doc
end
def create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
self.xml = @kml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
- html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index]}\" alt=\"Slideshow Image 1\" /></a>\n"
+ html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index+1]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
# content.save_me - compare to old cached content in db and if we have newer
# data, save to database, automaticly trigger creation of plaintext etc.,
# and content.save at the end
def save_me(query)
content_old = Content.find_by_name(self.class.name)
#logger.info "The old content: "
#logger.info content_old
#
# happens only at first run, when we call ModelName.parse_content - it
# creats just empty content_old so we can compare content to it
if content_old.nil?
content_old = Content.new
end
if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
# so we have newer content
# automagicly creates xhtml from xml
unless self.xml.nil?
html_from_xml = transform_xml2html(self.xml)
#self.xml = @kml_doc.to_s
self.xhtml = html_from_xml
end
logger.info "Entering rawhtml processing"
if not self.rawhtml.nil?
if (PUSH_ENABLE and (query.empty?))
Juggernaut.send_to_channel("location.reload();", [self.class.name])
logger.info "Pushing:"
logger.info self.class.name
end
end
logger.info "Leaving HTML processing"
# automagicly creates plain text from rawhtml or xhtml
if not self.rawhtml.nil?
txt = html2txt(self.rawhtml)
else
txt = html2txt(self.xhtml)
end
if txt.empty?
self.plaintext = nil
else
self.plaintext = txt
end
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
self.updated_at = Time.now
+ self.created_at = content_old.created_at
self.name = self.class.name
# we do not want do save/cache contents with user's query
if query.empty?
self.save
logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
puts Content.delete(content_old.id)
end
logger.fatal "SAVE ME"
self
else
content_old
end
end
end
diff --git a/app/models/fiterminy.rb b/app/models/fiterminy.rb
index bf8b492..7382707 100644
--- a/app/models/fiterminy.rb
+++ b/app/models/fiterminy.rb
@@ -1,15 +1,21 @@
class Fiterminy < Content
def self.parse_content(query = {})
content = Fiterminy.new
content.name_human = "FI MUNI: aktuálnà termÃny"
rawhtml = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
- rawhtml = rawhtml.at("//table")
- content.rawhtml = rawhtml.to_s
+ rawhtml = rawhtml.search("//table")
+ logger.fatal rawhtml.inspect
+
+ if (query["mgr"] == "yes")
+ content.rawhtml = rawhtml.second.to_s
+ else
+ content.rawhtml = rawhtml.first.to_s
+ end
content.save_me(query)
end
end
diff --git a/app/models/googlepocasi.rb b/app/models/googlepocasi.rb
index e8909db..587ab6b 100644
--- a/app/models/googlepocasi.rb
+++ b/app/models/googlepocasi.rb
@@ -1,46 +1,50 @@
class Googlepocasi < Content
def self.parse_content(query = {})
content = Googlepocasi.new
content.name_human = "Google poÄasÃ"
if query["city"].nil?
url="http://www.google.com/ig/api?weather=brno,czech+republic&hl=en"
+ city = "brno"
else
url="http://www.google.com/ig/api?weather=#{query["city"]},czech+republic&hl=en"
+ city = query["city"]
end
xml_data = Net::HTTP.get_response(URI.parse(url)).body
doc = REXML::Document.new(xml_data)
content.create_xml_head
- content.create_xml_body("label", query["city"])
+ content.create_xml_body("label", city)
url_base = "http://www.google.com"
doc.elements.each("xml_api_reply/weather/current_conditions/*") do |element|
# element_data = (element.text)
logger.fatal "Element:"
element.attributes.each do |name, value|
element_data = value
extension = element_data.split('.').last
if (extension == "gif")
element_data = url_base + element_data
element_name = "image"
else
element_name = "label"
end
content.create_xml_body(element_name, element_data)
end
end
+
+ content.create_xml_body("video", "nejaka vec")
content.save_me(query)
end
end
diff --git a/app/models/photoofthedaycom.rb b/app/models/photoofthedaycom.rb
index 724eae6..d66b778 100644
--- a/app/models/photoofthedaycom.rb
+++ b/app/models/photoofthedaycom.rb
@@ -1,30 +1,35 @@
class Photoofthedaycom < Content
+ def self.mylayout
+ "slideshow"
+ end
+
def self.parse_content(query = {})
content = Photoofthedaycom.new
content.name_human = "Photo of the Day"
+
year = Time.now.strftime("%Y")
# with leading zeros
month = Time.now.strftime("%m")
day = Time.now.strftime("%d")
content.create_xml_head
rawhtml = []
10.times.with_index do |x, index|
if index < 9
rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
else
rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
end
content.create_xml_body("image", rawhtml[index])
end
content.rawhtml = create_gallery(rawhtml)
content.save_me(query)
end
end
diff --git a/app/views/cnb/index.html.erb b/app/views/cnb/index.html.erb
deleted file mode 100644
index 8e86a56..0000000
--- a/app/views/cnb/index.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= @movies %>
diff --git a/app/views/cnb/index.rss.builder b/app/views/cnb/index.rss.builder
deleted file mode 100644
index 4ae04f1..0000000
--- a/app/views/cnb/index.rss.builder
+++ /dev/null
@@ -1,16 +0,0 @@
-xml.instruct! :xml, :version=>"1.0"
-xml.rss(:version=>"2.0"){
- xml.channel{
- xml.title("Petr Šigut | nové fotografie")
- xml.link("http://www.sigut.net/")
- xml.description("Fotogalerie.")
- xml.language('cs-cz')
- @movies.each do |a|
- xml.item do
- xml.title(a[1])
- xml.link(a[0])
- end
- end
- }
-}
-
diff --git a/app/views/exchange/index.html.erb b/app/views/exchange/index.html.erb
deleted file mode 100644
index 8e86a56..0000000
--- a/app/views/exchange/index.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= @movies %>
diff --git a/app/views/index.html.erb b/app/views/index.html.erb
deleted file mode 100644
index 6e225f0..0000000
--- a/app/views/index.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= debug(@movies) %>
diff --git a/app/views/movies/feed.rss.builder b/app/views/movies/feed.rss.builder
deleted file mode 100644
index 8eeae05..0000000
--- a/app/views/movies/feed.rss.builder
+++ /dev/null
@@ -1,15 +0,0 @@
-xml.instruct! :xml, :version=>"1.0"
-xml.rss(:version=>"2.0"){
- xml.channel{
- xml.title("Petr Šigut | nové fotografie")
- xml.link("http://www.sigut.net/")
- xml.description("Fotogalerie.")
- xml.language('cs-cz')
- for photo in @filmik
- xml.item do
- xml.title(photo.names)
- end
- end
- }
-}
-
diff --git a/app/views/movies/index.html.erb b/app/views/movies/index.html.erb
deleted file mode 100644
index 8e86a56..0000000
--- a/app/views/movies/index.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= @movies %>
diff --git a/app/views/movies/index.rss.builder b/app/views/movies/index.rss.builder
deleted file mode 100644
index e67997d..0000000
--- a/app/views/movies/index.rss.builder
+++ /dev/null
@@ -1,16 +0,0 @@
-xml.instruct! :xml, :version=>"1.0"
-xml.rss(:version=>"2.0"){
- xml.channel{
- xml.title("Petr Šigut | nové fotografie")
- xml.link("http://www.sigut.net/")
- xml.description("Fotogalerie.")
- xml.language('cs-cz')
- @odkazy.each do |a|
- xml.item do
- xml.title(a[1])
- xml.link(a[0])
- end
- end
- }
-}
-
diff --git a/app/views/pcfilmtydne/index.html.erb b/app/views/pcfilmtydne/index.html.erb
deleted file mode 100644
index 3a21e0e..0000000
--- a/app/views/pcfilmtydne/index.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-<%= @kml_doc %>
diff --git a/app/views/pcfilmtydne/show.html.erb b/app/views/pcfilmtydne/show.html.erb
deleted file mode 100644
index 65c64d5..0000000
--- a/app/views/pcfilmtydne/show.html.erb
+++ /dev/null
@@ -1,6 +0,0 @@
-<%= @doc %>
-
-<%= @label1 %>
-<%= @image1 %>
-<%= @label2 %>
-<%= @label3 %>
diff --git a/config/database.yml b/config/database.yml
index f6e2b32..5c87865 100644
--- a/config/database.yml
+++ b/config/database.yml
@@ -1,48 +1,48 @@
# MySQL. Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
# gem install mysql
# On Mac OS X:
# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
# On Mac OS X Leopard:
# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
# This sets the ARCHFLAGS environment variable to your native architecture
# On Windows:
# gem install mysql
# Choose the win32 build.
# Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: mysql
encoding: utf8
reconnect: false
- database: pcp_development
+ database: unico_development
pool: 5
username: petr
password: SQL_bubu78
socket: /var/run/mysqld/mysqld.sock
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: mysql
encoding: utf8
reconnect: false
- database: pcp_test
+ database: unico_test
pool: 5
username: root
password:
socket: /var/run/mysqld/mysqld.sock
production:
adapter: mysql
encoding: utf8
reconnect: false
- database: pcp_production
+ database: unico_production
pool: 5
username: root
password:
socket: /var/run/mysqld/mysqld.sock
diff --git a/config/deploy.rb b/config/deploy.rb
new file mode 100644
index 0000000..bb5f57e
--- /dev/null
+++ b/config/deploy.rb
@@ -0,0 +1,31 @@
+set :application, "unico"
+set :repository, "git://github.com/petrsigut/unico.git"
+set :scm, "git"
+default_run_options[:pty] = true
+set :branch, "master"
+
+role :web, "server3.railshosting.cz"
+role :app, "server3.railshosting.cz"
+role :db, "server3.railshosting.cz", :primary => true
+
+set :deploy_to, "/home/unico/app/"
+set :user, "unico"
+
+set :use_sudo, false
+
+task :after_update_code, :roles => [:app, :db] do
+ run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml"
+end
+
+
+namespace :deploy do
+ task :start, :roles => :app do
+ end
+end
+
+namespace :deploy do
+ desc "Restart Application"
+ task :restart, :roles => :app do
+ run "touch #{current_path}/tmp/restart.txt"
+ end
+end
diff --git a/config/environment.rb b/config/environment.rb
index a76e7e0..b5b1610 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,44 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
-RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
+# RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
PUSH_ENABLE = false
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb
index ff79076..05cbdd8 100644
--- a/config/initializers/session_store.rb
+++ b/config/initializers/session_store.rb
@@ -1,15 +1,15 @@
# Be sure to restart your server when you modify this file.
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
ActionController::Base.session = {
- :key => '_pcp_session',
+ :key => '_unico_session',
:secret => '5aa8b51704bb5e7126aff215b86795ffc646d1eaf88d5e4b7258446afea530c88d0c88aba7864f5bb6f51087367ddb97a342ff49980cfb971cbd33df9c4d6f56'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store
diff --git a/public/xml2html.xls b/public/xml2html.xsl
similarity index 100%
rename from public/xml2html.xls
rename to public/xml2html.xsl
|
petrsigut/unico | 2107709f2c04e3951a3c17aa3fd62954ecab78e5 | vyreseno query, predelano vic objektove | diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index f48f67b..0000478 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,79 +1,94 @@
class ContentsController < ApplicationController
layout :type_of_layout
protect_from_forgery :only => [:index]
def send_data
render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
end
render :nothing => true
end
-
def index
- @contents = Content.find(:all)
+ @contents = Content.find(:all, :order => "name")
@layout = "application"
end
def show
- @name = params[:id]
-
- if params[:query] =~ /^\w+$/i
- @query = params[:query]
+
+ name = params[:id]
+
+ query = {}
+ params.each do |param|
+ if (param[0] =~ /^\w+$/i and
+ param[1] =~ /^\w+$/i and
+ param[0] != "id" and
+ param[0] != "format" and
+ param[0] != "action" and
+ param[0] != "controller") then
+ query[param[0]] = param[1]
+ end
end
+ logger.fatal "Query"
+ logger.fatal query.inspect
+ logger.fatal "Query NIL?"
+ logger.fatal query.empty?
- # at nam pod to @name nepodstrci nejakou prasarnu!
+
+
+ # at nam pod to name nepodstrci nejakou zlou vec
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
- @name = @name.humanize
+ name = name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
- @content.each do |name|
- if @name == name.name
+ @content.each do |content_name|
+ if name == content_name.name
found_in_db = true
end
end
if found_in_db
- @content = Content.find_by_name(@name, :select => 'updated_at')
- if @content.updated_at < 10.seconds.ago # should be set by variable in content model
- (@name).constantize.parse_content
- end
- @content = Content.find_by_name(@name)
+ #@content = Content.find_by_name(@name, :select => 'updated_at')
+ #if @content.updated_at < 10.seconds.ago # should be set by variable in content model
+ @content = (name).constantize.parse_content(query)
+ logger.fatal "call parse_content"
+ #end
+ #@content = Content.find_by_name(@name)
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/.fiterminy.rb.swp b/app/models/.fiterminy.rb.swp
deleted file mode 100644
index d69b52e..0000000
Binary files a/app/models/.fiterminy.rb.swp and /dev/null differ
diff --git a/app/models/.pcfilmtydne.rb.swp b/app/models/.pcfilmtydne.rb.swp
deleted file mode 100644
index 11e9baa..0000000
Binary files a/app/models/.pcfilmtydne.rb.swp and /dev/null differ
diff --git a/app/models/capitolwords.rb b/app/models/capitolwords.rb
new file mode 100644
index 0000000..05d9e8e
--- /dev/null
+++ b/app/models/capitolwords.rb
@@ -0,0 +1,28 @@
+class Capitolwords < Content
+
+ def self.parse_content(query = {})
+ content = Capitolwords.new
+ content.name_human = "Top capitol words today"
+
+ if query["number"].nil?
+ url = "http://capitolwords.org/api/wod/latest/top10.xml"
+ else
+ url = "http://capitolwords.org/api/wod/latest/top#{query["number"]}.xml"
+ end
+
+ xml_data = Net::HTTP.get_response(URI.parse(url)).body
+ doc = REXML::Document.new(xml_data)
+
+ content.create_xml_head
+ doc.elements.each("xml/wordsofday/*") do |element|
+ word = element.attributes.get_attribute("word").value
+ word_count = element.attributes.get_attribute("word_count").value
+ content.create_xml_body("label", word+" "+word_count)
+ end
+
+
+
+ content.save_me(query)
+ end
+
+end
diff --git a/app/models/cnbkurzy.rb b/app/models/cnbkurzy.rb
index 121ef56..7798bd3 100644
--- a/app/models/cnbkurzy.rb
+++ b/app/models/cnbkurzy.rb
@@ -1,12 +1,17 @@
class Cnbkurzy < Content
- attr_accessor :name
- def self.parse_content
- @rawhtml = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
- @rawhtml = @rawhtml.at("//table[@class='kurzy_tisk']")
+ def self.parse_content(query = {})
+ content = Cnbkurzy.new
+ content.name_human = "Kurzy ÄNB"
+
+ rawhtml = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
+ rawhtml = rawhtml.at("//table[@class='kurzy_tisk']")
- save_me
+ content.rawhtml = rawhtml.to_s
+
+ content.save_me(query)
end
+
end
diff --git a/app/models/content.rb b/app/models/content.rb
index dbfe989..3eb482a 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,94 +1,133 @@
class Content < ActiveRecord::Base
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
+ # do decode html entities in html2txt
+# require 'rubygems'
+ # script/server needs restart after installing new gem
+ require 'htmlentities'
+
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
- def self.html2txt(html)
+ def html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
+
html = ActionController::Base.helpers.strip_tags(html)
+
+ coder = HTMLEntities.new
+ html = coder.decode(html)
+
+ # convert newlines from DOS to UNIX
+ html.gsub!(/[\n\r]+/, "\n")
+ html.gsub!(/^\s*/,'')
+ #ruby -ne 'BEGIN{$\="\n"}; print $_.chomp' <
+
# html = sanitize(html)
end
- def self.transform_xml2html(xml)
+ def transform_xml2html(xml)
xslt = XML::XSLT.new()
xslt.xml = xml.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xls"
xslt.serve()
end
- # private nebo tak neco?
- def self.create_xml_head
+ def create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
+ self.xml = @kml_doc
end
- def self.create_xml_body(entity_name, entity_text)
+ def create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
+ self.xml = @kml_doc.to_s
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
- def self.save_me
- # tohle až do konce můžu zoobecnit pro vÅ¡echny tÅÃdy...
- @content = Content.find_by_name(self.name) # udelat pres tridni promenou?
-
- if @content.nil?
- @content = Content.new
- @content.name = self.name
- end
+ # content.save_me - compare to old cached content in db and if we have newer
+ # data, save to database, automaticly trigger creation of plaintext etc.,
+ # and content.save at the end
+ def save_me(query)
+ content_old = Content.find_by_name(self.class.name)
+
+ #logger.info "The old content: "
+ #logger.info content_old
- @content.name_human = @name_human
-
- if @kml_doc.nil?
- @content.xml = nil
- else
- html_from_xml = transform_xml2html(@kml_doc)
- @content.xml = @kml_doc.to_s
- @content.xhtml = html_from_xml
+ #
+ # happens only at first run, when we call ModelName.parse_content - it
+ # creats just empty content_old so we can compare content to it
+ if content_old.nil?
+ content_old = Content.new
end
- logger.info "Entering HTML saving"
- if @rawhtml.nil?
- @content.rawhtml = nil
- else
- if PUSH_ENABLE and (@content.rawhtml != @rawhtml.to_s)
- unless @content.id.nil? # could be if it is first calling of new model
- Juggernaut.send_to_channel("location.reload();", [@content.id])
- logger.fatal "push happen"
- logger.fatal @content.name
+ if ((content_old.rawhtml != self.rawhtml) or (content_old.xml != self.xml) or (query.empty?))
+ # so we have newer content
+
+ # automagicly creates xhtml from xml
+ unless self.xml.nil?
+ html_from_xml = transform_xml2html(self.xml)
+ #self.xml = @kml_doc.to_s
+ self.xhtml = html_from_xml
+ end
+
+ logger.info "Entering rawhtml processing"
+ if not self.rawhtml.nil?
+ if (PUSH_ENABLE and (query.empty?))
+ Juggernaut.send_to_channel("location.reload();", [self.class.name])
+ logger.info "Pushing:"
+ logger.info self.class.name
end
+ end
+ logger.info "Leaving HTML processing"
+
+ # automagicly creates plain text from rawhtml or xhtml
+ if not self.rawhtml.nil?
+ txt = html2txt(self.rawhtml)
+ else
+ txt = html2txt(self.xhtml)
+ end
+
+ if txt.empty?
+ self.plaintext = nil
else
- logger.info "push NOT happen"
+ self.plaintext = txt
end
- @content.rawhtml = @rawhtml.to_s
- txt = html2txt(@rawhtml.to_s)
- @content.plaintext = txt
+
+
+ # Rails detect whether we change the content of record and if not,
+ # update_at will not be updated. But we want to update it every time we
+ # regenerete content
+ self.updated_at = Time.now
+ self.name = self.class.name
+
+ # we do not want do save/cache contents with user's query
+ if query.empty?
+ self.save
+ logger.fatal "Delete of content (if do not exist id will be NULL, it is OK)"
+ puts Content.delete(content_old.id)
+ end
+ logger.fatal "SAVE ME"
+ self
+ else
+ content_old
end
- logger.info "Leaving HTML saving"
-
- # Rails detect whether we change the content of record and if not,
- # update_at will not be updated. But we want to update it every time we
- # regenerete content
- @content.updated_at = Time.now
- @content.save
end
-
end
diff --git a/app/models/csfddokin.rb b/app/models/csfddokin.rb
index d3051a3..c3f290a 100644
--- a/app/models/csfddokin.rb
+++ b/app/models/csfddokin.rb
@@ -1,26 +1,36 @@
-# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
-# check_if_old?
class Csfddokin < Content
- def self.parse_content
- @name_human = "ÄSFD do kin"
+ def self.parse_content(query = {})
+ content = Csfddokin.new
+ content.name_human = "ÄSFD do kin"
- @rawhtml = Hpricot(open("http://www.csfd.cz/"))
- @rawhtml = @rawhtml.search("//body")
- @rawhtml = @rawhtml.to_s()
+ rawhtml = Hpricot(open("http://www.csfd.cz/"))
+ rawhtml = rawhtml.search("//body")
+ rawhtml = rawhtml.to_s()
- @rawhtml.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
- @rawhtml.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
- @rawhtml.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+ rawhtml.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
+ rawhtml.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
+ rawhtml.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+
+ rawhtml = Hpricot(rawhtml)
+ rawhtml = rawhtml.at("//table")
+
+ content.rawhtml = rawhtml.to_s
- @rawhtml = Hpricot(@rawhtml)
- @rawhtml = @rawhtml.at("//table")
# @movies = '<link rel="stylesheet" type="text/css" href="http://localhost/~phax/test.css" />' + @movies
- save_me
+ #logger.fatal "what returns save_me?"
+ content = content.save_me(query)
+ logger.fatal "content.name"
+ logger.fatal content.name
+ content
+
+
end
+
end
+
diff --git a/app/models/fiterminy.rb b/app/models/fiterminy.rb
index 02c4b9b..bf8b492 100644
--- a/app/models/fiterminy.rb
+++ b/app/models/fiterminy.rb
@@ -1,11 +1,15 @@
class Fiterminy < Content
- attr_accessor :name
- def self.parse_content
- @rawhtml = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
- @rawhtml = @rawhtml.at("//table")
+ def self.parse_content(query = {})
+ content = Fiterminy.new
+ content.name_human = "FI MUNI: aktuálnà termÃny"
+
+ rawhtml = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
+ rawhtml = rawhtml.at("//table")
- save_me
+ content.rawhtml = rawhtml.to_s
+
+ content.save_me(query)
end
end
diff --git a/app/models/googlepocasi.rb b/app/models/googlepocasi.rb
new file mode 100644
index 0000000..e8909db
--- /dev/null
+++ b/app/models/googlepocasi.rb
@@ -0,0 +1,46 @@
+class Googlepocasi < Content
+
+ def self.parse_content(query = {})
+
+ content = Googlepocasi.new
+ content.name_human = "Google poÄasÃ"
+
+ if query["city"].nil?
+ url="http://www.google.com/ig/api?weather=brno,czech+republic&hl=en"
+ else
+ url="http://www.google.com/ig/api?weather=#{query["city"]},czech+republic&hl=en"
+ end
+
+ xml_data = Net::HTTP.get_response(URI.parse(url)).body
+ doc = REXML::Document.new(xml_data)
+
+ content.create_xml_head
+ content.create_xml_body("label", query["city"])
+
+ url_base = "http://www.google.com"
+
+ doc.elements.each("xml_api_reply/weather/current_conditions/*") do |element|
+# element_data = (element.text)
+ logger.fatal "Element:"
+ element.attributes.each do |name, value|
+
+ element_data = value
+ extension = element_data.split('.').last
+ if (extension == "gif")
+ element_data = url_base + element_data
+ element_name = "image"
+ else
+ element_name = "label"
+ end
+
+ content.create_xml_body(element_name, element_data)
+ end
+ end
+
+
+ content.save_me(query)
+
+ end
+
+
+end
diff --git a/app/models/googlepocasibrno.rb b/app/models/googlepocasibrno.rb
deleted file mode 100644
index 1194f60..0000000
--- a/app/models/googlepocasibrno.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-class Googlepocasibrno < Content
- require 'rexml/document'
-
- attr_accessor :name
-
- def self.parse_content
- url="http://www.google.com/ig/api?weather=#{@query},czech+republic&hl=en"
- url="http://www.google.com/ig/api?weather=brno,czech+republic&hl=en"
- xml_data = Net::HTTP.get_response(URI.parse(url)).body
- doc = REXML::Document.new(xml_data)
-
- create_xml_head
-
- doc.elements.each("xml_api_reply/weather/current_conditions/*") do |element|
- create_xml_body("label", element.attributes.get_attribute("data"))
- end
-
-
- save_me
- end
-
-
-end
diff --git a/app/models/idsjmk.rb b/app/models/idsjmk.rb
new file mode 100644
index 0000000..7ae66a6
--- /dev/null
+++ b/app/models/idsjmk.rb
@@ -0,0 +1,20 @@
+class Idsjmk < Content
+
+ def self.parse_content(query = {})
+ content = Idsjmk.new
+ content.name_human = "IDS JMK odjezdy"
+
+ if (query["stopId"].nil? or query["poleId"].nil?)
+ url = "http://wap.aspone.cz/GetDepartures.ashx?stopId=1166&poleId=1"
+ else
+ url = "http://wap.aspone.cz/GetDepartures.ashx?stopId=#{query["stopId"]}&poleId=#{query["poleId"]}"
+ end
+
+
+ rawhtml = Hpricot(open(url))
+ content.rawhtml = rawhtml.to_s
+
+ content.save_me(query)
+ end
+
+end
diff --git a/app/models/pcfilmtydne.rb b/app/models/pcfilmtydne.rb
index 64d4da4..5e094d1 100644
--- a/app/models/pcfilmtydne.rb
+++ b/app/models/pcfilmtydne.rb
@@ -1,28 +1,30 @@
-# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
-# check_if_old?
class Pcfilmtydne < Content
- attr_accessor :name
- def self.parse_content
- @rawhtml = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
- @rawhtml = @rawhtml.at("//div[@class='frame red']")
+ def self.parse_content(query = {})
+ content = Pcfilmtydne.new
+ content.name_human = "Palace Cinemas: Film týdne"
- @label1 = @rawhtml.at("//h3")
- @label2 = @rawhtml.at("//h2")
- @image1 = @rawhtml.at("//img")
- @image1 = @image1.attributes['src']
- @label3 = @rawhtml.at("//p")
+ rawhtml = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
+ rawhtml = rawhtml.at("//div[@class='frame red']")
- create_xml_head
- create_xml_body("label", @label1)
- create_xml_body("label", @label2)
- create_xml_body("image", @image1)
- create_xml_body("label", @label3)
- create_xml_body("label", self.name)
+ label1 = rawhtml.at("//h3")
+ label2 = rawhtml.at("//h2")
+ image1 = rawhtml.at("//img")
+ image1 = image1.attributes['src']
+ label3 = rawhtml.at("//p").inner_text
- save_me
+ content.create_xml_head
+ content.create_xml_body("label", label1)
+ content.create_xml_body("label", label2)
+ content.create_xml_body("image", image1)
+ content.create_xml_body("label", label3)
+
+ content.rawhtml = rawhtml.to_s
+
+ # fix the UID - it changes everytime...
+ content.save_me(query)
end
end
diff --git a/app/models/photoofthedaycom.rb b/app/models/photoofthedaycom.rb
index 1c0cc00..724eae6 100644
--- a/app/models/photoofthedaycom.rb
+++ b/app/models/photoofthedaycom.rb
@@ -1,28 +1,30 @@
class Photoofthedaycom < Content
- attr_accessor :name
- def self.parse_content
+ def self.parse_content(query = {})
+ content = Photoofthedaycom.new
+ content.name_human = "Photo of the Day"
+
year = Time.now.strftime("%Y")
# with leading zeros
month = Time.now.strftime("%m")
day = Time.now.strftime("%d")
- create_xml_head
+ content.create_xml_head
- @rawhtml = []
+ rawhtml = []
10.times.with_index do |x, index|
if index < 9
- @rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
+ rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
else
- @rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
+ rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
end
- create_xml_body("image", @rawhtml[index])
+ content.create_xml_body("image", rawhtml[index])
end
- @rawhtml = create_gallery(@rawhtml)
+ content.rawhtml = create_gallery(rawhtml)
- save_me
+ content.save_me(query)
end
end
diff --git a/app/models/sablona.rb b/app/models/sablona.rb
index 8894d5a..4d4d6d2 100644
--- a/app/models/sablona.rb
+++ b/app/models/sablona.rb
@@ -1,14 +1,13 @@
class Model < Content
- attr_accessor :name
- def self.parse_raw_html
- @doc = Hpricot(open(""))
+ def self.parse_content(query = {})
+ content = Model.new
+ content.name_human = "Human name"
- save_me
- end
+ rawhtml = Hpricot(open(""))
+ content = rawhtml
- def self.parse_xml
- save_me
+ content.save_me(query)
end
end
diff --git a/app/models/timetest.rb b/app/models/timetest.rb
new file mode 100644
index 0000000..798e503
--- /dev/null
+++ b/app/models/timetest.rb
@@ -0,0 +1,11 @@
+class Timetest < Content
+
+ def self.parse_content(query = {})
+ content = Timetest.new
+
+ content.rawhtml = Time.now.to_s
+
+ content.save_me(query)
+ end
+
+end
diff --git a/app/models/youtube.rb b/app/models/youtube
similarity index 100%
rename from app/models/youtube.rb
rename to app/models/youtube
diff --git a/app/views/contents/index.html.erb b/app/views/contents/index.html.erb
index 4c834bb..19cdeec 100644
--- a/app/views/contents/index.html.erb
+++ b/app/views/contents/index.html.erb
@@ -1,20 +1,24 @@
<% for content in @contents %>
<div class="content">
<span><%=h content.name_human %></span>
<% unless content.rawhtml.nil? %>
<span><%= link_to "HTML", "/contents/show/"+content.name+".html" %></span>
<% end %>
<% unless content.xml.nil? %>
<span><%= link_to "XML", "/contents/show/"+content.name+".xml" %></span>
<span><%= link_to "XHTML", "/contents/show/"+content.name+".xhtml" %></span>
<% end %>
+ <% unless content.plaintext.nil? %>
+ <span><%= link_to "TXT", "/contents/show/"+content.name+".txt" %></span>
+ <% end %>
+
<% unless content.rawhtml.nil? %>
<%= content.rawhtml %>
<% else %>
<%= content.xhtml %>
<% end %>
</div>
<% end %>
diff --git a/app/views/contents/show.html.erb b/app/views/contents/show.html.erb
index 6765cb2..d8279e4 100644
--- a/app/views/contents/show.html.erb
+++ b/app/views/contents/show.html.erb
@@ -1,10 +1,9 @@
-<%= @query %>
<html>
<head>
- <%= render :partial => "juggernaut_head" %>
+ <%= if PUSH_ENABLE then render :partial => "juggernaut_head" end %>
</head>
<body>
<%= @content.rawhtml %>
- <%= render :partial => "juggernaut_body" %>
+ <%= if PUSH_ENABLE then render :partial => "juggernaut_body" end %>
</body>
</html>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index ba41e1a..eaf40ee 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,16 +1,16 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
- <%= stylesheet_link_tag 'style' %>
+ <%= stylesheet_link_tag 'index' %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>
diff --git a/config/environment.rb b/config/environment.rb
index 67662a2..a76e7e0 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,44 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
# Should we use Push funcionality?
-PUSH_ENABLE = true
+PUSH_ENABLE = false
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
diff --git a/lib/tasks/downloadall.rake b/lib/tasks/downloadall.rake
new file mode 100644
index 0000000..9540b59
--- /dev/null
+++ b/lib/tasks/downloadall.rake
@@ -0,0 +1,20 @@
+desc "Iterate thru all contents and download new content, if it differs from
+old, then push"
+task(:downloadall => :environment) do
+ # @contents = Content.find(:all)
+ # @contents.each do |content|
+ basedir = 'app/models/'
+ Dir.chdir(basedir)
+ files = Dir.glob("*.rb")
+ files.each do |model|
+ model.chomp!('.rb')
+ if (model != 'sablona' and model != 'content')
+ (model).humanize.constantize.parse_content
+ puts (model).humanize + " called parse_content"
+ end
+ end
+
+ # puts content.name
+ # puts "parsed"
+# end
+end
diff --git a/public/stylesheets/style.css b/public/stylesheets/index.css
similarity index 53%
rename from public/stylesheets/style.css
rename to public/stylesheets/index.css
index 82661e1..656f82e 100644
--- a/public/stylesheets/style.css
+++ b/public/stylesheets/index.css
@@ -1,7 +1,9 @@
div.content {
border: 1px solid gray;
width: 250px;
height: 200px;
- overflow:auto;
- float: right;
+ overflow: auto;
+ float: left;
+ margin: 20px;
+ padding: 12px;
}
|
petrsigut/unico | 1d8843633c64f7670d13b0099f080877564acd1e | push aktualizace | diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 51d791c..f48f67b 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,63 +1,79 @@
class ContentsController < ApplicationController
layout :type_of_layout
+ protect_from_forgery :only => [:index]
+
+ def send_data
+ render :juggernaut => {:channels => [params[:send_to_channel]], :type => :send_to_channels} do |page|
+ page.insert_html :top, 'chat_data', h(params[:chat_input])+"\n"
+ end
+ render :nothing => true
+ end
+
+
def index
@contents = Content.find(:all)
@layout = "application"
end
def show
@name = params[:id]
+
+ if params[:query] =~ /^\w+$/i
+ @query = params[:query]
+ end
+
+
# at nam pod to @name nepodstrci nejakou prasarnu!
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
# http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
@name = @name.humanize
@content = Content.find(:all, :select => 'name')
found_in_db = false
@content.each do |name|
if @name == name.name
found_in_db = true
end
end
if found_in_db
@content = Content.find_by_name(@name, :select => 'updated_at')
if @content.updated_at < 10.seconds.ago # should be set by variable in content model
(@name).constantize.parse_content
end
@content = Content.find_by_name(@name)
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
# udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
# http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
# Mime::Type.register "image/jpg", :jpg
Mime::Type.register "text/html", :xhtml
Mime::Type.register "text/plain", :txt
respond_to do |format|
format.html # show.html.erb
format.xhtml # show.xhtml.erb
format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/content.rb b/app/models/content.rb
index b16d8db..dbfe989 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,83 +1,94 @@
class Content < ActiveRecord::Base
require 'hpricot'
require 'open-uri'
require 'net/http'
require 'logger'
require "rexml/document"
# needed for XML XSLT
require 'xml/libxml'
require 'xml/libxslt'
def self.html2txt(html)
# http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
html = ActionController::Base.helpers.strip_tags(html)
# html = sanitize(html)
end
def self.transform_xml2html(xml)
xslt = XML::XSLT.new()
xslt.xml = xml.to_s
xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xls"
xslt.serve()
end
# private nebo tak neco?
def self.create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
end
def self.create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
end
def self.create_gallery(array_of_links)
html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
def self.save_me
# tohle až do konce můžu zoobecnit pro vÅ¡echny tÅÃdy...
@content = Content.find_by_name(self.name) # udelat pres tridni promenou?
if @content.nil?
@content = Content.new
@content.name = self.name
end
@content.name_human = @name_human
if @kml_doc.nil?
@content.xml = nil
else
html_from_xml = transform_xml2html(@kml_doc)
@content.xml = @kml_doc.to_s
@content.xhtml = html_from_xml
end
+ logger.info "Entering HTML saving"
if @rawhtml.nil?
@content.rawhtml = nil
else
+ if PUSH_ENABLE and (@content.rawhtml != @rawhtml.to_s)
+ unless @content.id.nil? # could be if it is first calling of new model
+ Juggernaut.send_to_channel("location.reload();", [@content.id])
+ logger.fatal "push happen"
+ logger.fatal @content.name
+ end
+ else
+ logger.info "push NOT happen"
+ end
@content.rawhtml = @rawhtml.to_s
txt = html2txt(@rawhtml.to_s)
@content.plaintext = txt
end
+ logger.info "Leaving HTML saving"
# Rails detect whether we change the content of record and if not,
# update_at will not be updated. But we want to update it every time we
# regenerete content
@content.updated_at = Time.now
@content.save
end
end
diff --git a/app/models/googlepocasibrno.rb b/app/models/googlepocasibrno.rb
index 97fd39d..1194f60 100644
--- a/app/models/googlepocasibrno.rb
+++ b/app/models/googlepocasibrno.rb
@@ -1,22 +1,23 @@
class Googlepocasibrno < Content
require 'rexml/document'
attr_accessor :name
def self.parse_content
+ url="http://www.google.com/ig/api?weather=#{@query},czech+republic&hl=en"
url="http://www.google.com/ig/api?weather=brno,czech+republic&hl=en"
xml_data = Net::HTTP.get_response(URI.parse(url)).body
doc = REXML::Document.new(xml_data)
create_xml_head
doc.elements.each("xml_api_reply/weather/current_conditions/*") do |element|
create_xml_body("label", element.attributes.get_attribute("data"))
end
save_me
end
end
diff --git a/app/views/contents/_juggernaut_body.html.erb b/app/views/contents/_juggernaut_body.html.erb
new file mode 100644
index 0000000..529ee6a
--- /dev/null
+++ b/app/views/contents/_juggernaut_body.html.erb
@@ -0,0 +1,6 @@
+<textarea id="console_text" style="width: 0px; height: 0px; visibility: hidden"></textarea>
+ <%=
+ # this will render the javascript that will 'cause listening to listen_to_channel channel
+ juggernaut(:channels => [@content.id], :client_id => request.session_options[:id])
+ %>
+
diff --git a/app/views/contents/_juggernaut_head.html.erb b/app/views/contents/_juggernaut_head.html.erb
new file mode 100644
index 0000000..9839687
--- /dev/null
+++ b/app/views/contents/_juggernaut_head.html.erb
@@ -0,0 +1,17 @@
+<%= javascript_include_tag :defaults, :juggernaut %>
+ <script>
+ // firebug console faker, for non-firefox browsers
+
+ window.console = {
+ firebug: '1.0',
+ log: function() {
+ $('console_text').innerHTML = arguments[0] + "\n" + $('console_text').innerHTML;
+ },
+ clear: function() {
+ $('console_text').innerHTML = '';
+ }
+ }
+
+ </script>
+ <%= juggernaut %>
+
diff --git a/app/views/contents/show.html.erb b/app/views/contents/show.html.erb
index 666fe49..6765cb2 100644
--- a/app/views/contents/show.html.erb
+++ b/app/views/contents/show.html.erb
@@ -1 +1,10 @@
-<%= @content.rawhtml %>
+<%= @query %>
+<html>
+ <head>
+ <%= render :partial => "juggernaut_head" %>
+ </head>
+ <body>
+ <%= @content.rawhtml %>
+ <%= render :partial => "juggernaut_body" %>
+ </body>
+</html>
diff --git a/config/environment.rb b/config/environment.rb
index ff450c7..67662a2 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,41 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
+# Should we use Push funcionality?
+PUSH_ENABLE = true
+
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
-end
\ No newline at end of file
+end
diff --git a/config/juggernaut_hosts.yml b/config/juggernaut_hosts.yml
new file mode 100644
index 0000000..36bf2fe
--- /dev/null
+++ b/config/juggernaut_hosts.yml
@@ -0,0 +1,18 @@
+# You should list any juggernaut hosts here.
+# You need only specify the secret key if you're using that type of authentication (see juggernaut.yml)
+#
+# Name: Mapping:
+# :port internal push server's port
+# :host internal push server's host/ip
+# :public_host public push server's host/ip (accessible from external clients)
+# :public_port public push server's port
+# :secret_key (optional) shared secret (should map to the key specified in the push server's config)
+# :environment (optional) limit host to a particular RAILS_ENV
+
+:hosts:
+ - :port: 5001
+ :host: 127.0.0.1
+ :public_host: 127.0.0.1
+ :public_port: 5001
+ # :secret_key: your_secret_key
+ # :environment: :development
\ No newline at end of file
diff --git a/juggernaut.yml b/juggernaut.yml
new file mode 100644
index 0000000..5baa598
--- /dev/null
+++ b/juggernaut.yml
@@ -0,0 +1,97 @@
+ # ======================
+ # Juggernaut Options
+ # ======================
+
+ # === Subscription authentication ===
+ # Leave all subscription options uncommented to allow anyone to subscribe.
+
+ # If specified, subscription_url is called everytime a client subscribes.
+ # Parameters passed are: session_id, client_id and an array of channels.
+ #
+ # The server should check that the session_id matches up to the client_id
+ # and that the client is allowed to access the specified channels.
+ #
+ # If a status code other than 200 is encountered, the subscription_request fails
+ # and the client is disconnected.
+ #
+ # :subscription_url: http://localhost:3000/sessions/juggernaut_subscription
+
+ # === Broadcast and query authentication ===
+ # Leave all broadcast/query options uncommented to allow anyone to broadcast/query.
+ #
+ # Broadcast authentication in a production environment is very importantant since broadcasters
+ # can execute JavaScript on subscribed clients, leaving you vulnerable to cross site scripting
+ # attacks if broadcasters aren't authenticated.
+
+ # 1) Via IP address
+ #
+ # If specified, if a client has an ip that is specified in allowed_ips, than it is automatically
+ # authenticated, even if a secret_key isn't provided.
+ #
+ # This is the recommended method for broadcast authentication.
+ #
+ :allowed_ips:
+ - 127.0.0.1
+ # - 192.168.0.1
+
+ # 2) Via HTTP request
+ #
+ # If specified, if a client attempts a broadcast/query, without a secret_key or using an IP
+ # no included in allowed_ips, then broadcast_query_login_url will be called.
+ # Parameters passed, if given, are: session_id, client_id, channels and type.
+ #
+ # The server should check that the session_id matches up to the client id, and the client
+ # is allowed to perform that particular type of broadcast/query.
+ #
+ # If a status code other than 200 is encountered, the broadcast_query_login_url fails
+ # and the client is disconnected.
+ #
+ # :broadcast_query_login_url: http://localhost:3000/sessions/juggernaut_broadcast
+
+ # 3) Via shared secret key
+ #
+ # This secret key must be sent with any query/broadcast commands.
+ # It must be the same as the one in the Rails config file.
+ #
+ # You shouldn't authenticate broadcasts from subscribed clients using this method
+ # since the secret_key will be easily visible in the page (and not so secret any more)!
+ #
+ # :secret_key: 21543b15acf4d5a8066cb7f913e3c6d31f7a57cb
+
+ # == Subscription Logout ==
+
+ # If specified, logout_connection_url is called everytime a specific connection from a subscribed client disconnects.
+ # Parameters passed are session_id, client_id and an array of channels specific to that connection.
+ #
+ # :logout_connection_url: http://localhost:3000/sessions/juggernaut_connection_logout
+
+ # Logout url is called when all connections from a subscribed client are closed.
+ # Parameters passed are session_id and client_id.
+ #
+ # :logout_url: http://localhost:3000/sessions/juggernaut_logout
+
+ # === Miscellaneous ===
+
+ # timeout defaults to 10. A timeout is the time between when a client closes a connection
+ # and a logout_request or logout_connection_request is made. The reason for this is that a client
+ # may only temporarily be disconnected, and may attempt a reconnect very soon.
+ #
+ # :timeout: 10
+
+ # store_messages defaults to false. If this option is true, messages send to connections will be stored.
+ # This is useful since a client can then receive broadcasted message that it has missed (perhaps it was disconnected).
+ #
+ # :store_messages: false
+
+ # === Server ===
+
+ # Host defaults to "0.0.0.0". You shouldn't need to change this.
+ # :host: 0.0.0.0
+
+ # Port is mandatory
+ :port: 5001
+
+ # Defaults to value of :port. If you are doing port forwarding you'll need to configure this to the same
+ # value as :public_port in the juggernaut_hosts.yml file
+ # :public_port: 5001
+
diff --git a/lib/tasks/push.rake b/lib/tasks/push.rake
new file mode 100644
index 0000000..f0ca5ed
--- /dev/null
+++ b/lib/tasks/push.rake
@@ -0,0 +1,10 @@
+desc "Iterate thru all contents and download new content, if it differs from
+old, then push"
+task(:push => :environment) do
+ @contents = Content.find(:all)
+ @contents.each do |content|
+ (content.name).constantize.parse_content
+ puts content.name
+ puts "parsed"
+ end
+end
diff --git a/public/javascripts/juggernaut/juggernaut.js b/public/javascripts/juggernaut/juggernaut.js
new file mode 100644
index 0000000..24df613
--- /dev/null
+++ b/public/javascripts/juggernaut/juggernaut.js
@@ -0,0 +1,204 @@
+/*
+Copyright (c) 2008 Alexander MacCaw
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+function Juggernaut(options) {
+ this.is_connected = false;
+ this.attempting_to_reconnect = false;
+ this.ever_been_connected = false;
+ this.hasLogger = "console" in window && "log" in window.console;
+ this.options = options;
+ this.bindToWindow();
+};
+
+Juggernaut.fn = Juggernaut.prototype;
+
+Juggernaut.fn.logger = function(msg) {
+ if (this.options.debug) {
+ msg = "Juggernaut: " + msg + " on " + this.options.host + ':' + this.options.port;
+ this.hasLogger ? console.log(msg) : alert(msg);
+ }
+};
+
+Juggernaut.fn.initialized = function(){
+ this.fire_event('initialized');
+ this.connect();
+};
+
+Juggernaut.fn.broadcast = function(body, type, client_ids, channels){
+ var msg = {command: 'broadcast', body: body, type: (type||'to_channels')};
+ if(channels) msg['channels'] = channels;
+ if(client_ids) msg['client_ids'] = client_ids;
+ this.sendData(Juggernaut.toJSON(msg));
+};
+
+Juggernaut.fn.sendData = function(data){
+ this.swf().sendData(escape(data));
+};
+
+Juggernaut.fn.connect = function(){
+ if(!this.is_connected){
+ this.fire_event('connect');
+ this.swf().connect(this.options.host, this.options.port);
+ }
+};
+
+Juggernaut.fn.disconnect = function(){
+ if(this.is_connected) {
+ this.swf().disconnect();
+ this.is_connected = false;
+ }
+};
+
+Juggernaut.fn.handshake = function() {
+ var handshake = {};
+ handshake['command'] = 'subscribe';
+ if(this.options.session_id) handshake['session_id'] = this.options.session_id;
+ if(this.options.client_id) handshake['client_id'] = this.options.client_id;
+ if(this.options.channels) handshake['channels'] = this.options.channels;
+ if(this.currentMsgId) {
+ handshake['last_msg_id'] = this.currentMsgId;
+ handshake['signature'] = this.currentSignature;
+ }
+
+ return handshake;
+};
+
+Juggernaut.fn.connected = function(e) {
+ var json = Juggernaut.toJSON(this.handshake());
+ this.sendData(json);
+ this.ever_been_connected = true;
+ this.is_connected = true;
+ var self = this;
+ setTimeout(function(){
+ if(self.is_connected) self.attempting_to_reconnect = false;
+ }, 1 * 1000);
+ this.logger('Connected');
+ this.fire_event('connected');
+};
+
+Juggernaut.fn.receiveData = function(e) {
+ var msg = Juggernaut.parseJSON(unescape(e.toString()));
+ this.currentMsgId = msg.id;
+ this.currentSignature = msg.signature;
+ this.logger("Received data:\n" + msg.body + "\n");
+ this.dispatchMessage(msg);
+};
+
+Juggernaut.fn.dispatchMessage = function(msg) {
+ eval(msg.body);
+}
+
+var juggernaut;
+
+// Prototype specific - override for other frameworks
+Juggernaut.fn.fire_event = function(fx_name) {
+ $(document).fire("juggernaut:" + fx_name);
+};
+
+Juggernaut.fn.bindToWindow = function() {
+ Event.observe(window, 'load', function() {
+ juggernaut = this;
+ this.appendFlashObject();
+ }.bind(this));
+};
+
+Juggernaut.toJSON = function(hash) {
+ return Object.toJSON(hash);
+};
+
+Juggernaut.parseJSON = function(string) {
+ return string.evalJSON();
+};
+
+Juggernaut.fn.swf = function(){
+ return $(this.options.swf_name);
+};
+
+Juggernaut.fn.appendElement = function() {
+ this.element = new Element('div', { id: 'juggernaut' });
+ $(document.body).insert({ bottom: this.element });
+};
+
+/*** END PROTOTYPE SPECIFIC ***/
+
+Juggernaut.fn.appendFlashObject = function(){
+ if(this.swf()) {
+ throw("Juggernaut error. 'swf_name' must be unique per juggernaut instance.");
+ }
+ Juggernaut.fn.appendElement();
+ swfobject.embedSWF(
+ this.options.swf_address,
+ 'juggernaut',
+ this.options.width,
+ this.options.height,
+ String(this.options.flash_version),
+ this.options.ei_swf_address,
+ {'bridgeName': this.options.bridge_name},
+ {},
+ {'id': this.options.swf_name, 'name': this.options.swf_name}
+ );
+};
+
+Juggernaut.fn.refreshFlashObject = function(){
+ this.swf().remove();
+ this.appendFlashObject();
+};
+
+Juggernaut.fn.errorConnecting = function(e) {
+ this.is_connected = false;
+ if(!this.attempting_to_reconnect) {
+ this.logger('There has been an error connecting');
+ this.fire_event('errorConnecting');
+ this.reconnect();
+ }
+};
+
+Juggernaut.fn.disconnected = function(e) {
+ this.is_connected = false;
+ if(!this.attempting_to_reconnect) {
+ this.logger('Connection has been lost');
+ this.fire_event('disconnected');
+ this.reconnect();
+ }
+};
+
+Juggernaut.fn.reconnect = function(){
+ if(this.options.reconnect_attempts){
+ this.attempting_to_reconnect = true;
+ this.fire_event('reconnect');
+ this.logger('Will attempt to reconnect ' + this.options.reconnect_attempts + ' times,\
+the first in ' + (this.options.reconnect_intervals || 3) + ' seconds');
+ for(var i=0; i < this.options.reconnect_attempts; i++){
+ setTimeout(function(){
+ if(!this.is_connected){
+ this.logger('Attempting reconnect');
+ if(!this.ever_been_connected){
+ this.refreshFlashObject();
+ } else {
+ this.connect();
+ }
+ }
+ }.bind(this), (this.options.reconnect_intervals || 3) * 1000 * (i + 1));
+ }
+ }
+};
\ No newline at end of file
diff --git a/public/javascripts/juggernaut/swfobject.js b/public/javascripts/juggernaut/swfobject.js
new file mode 100644
index 0000000..c383123
--- /dev/null
+++ b/public/javascripts/juggernaut/swfobject.js
@@ -0,0 +1,5 @@
+/* SWFObject v2.0 <http://code.google.com/p/swfobject/>
+ Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
+ This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
+*/
+var swfobject=function(){var Z="undefined",P="object",B="Shockwave Flash",h="ShockwaveFlash.ShockwaveFlash",W="application/x-shockwave-flash",K="SWFObjectExprInst",G=window,g=document,N=navigator,f=[],H=[],Q=null,L=null,T=null,S=false,C=false;var a=function(){var l=typeof g.getElementById!=Z&&typeof g.getElementsByTagName!=Z&&typeof g.createElement!=Z&&typeof g.appendChild!=Z&&typeof g.replaceChild!=Z&&typeof g.removeChild!=Z&&typeof g.cloneNode!=Z,t=[0,0,0],n=null;if(typeof N.plugins!=Z&&typeof N.plugins[B]==P){n=N.plugins[B].description;if(n){n=n.replace(/^.*\s+(\S+\s+\S+$)/,"$1");t[0]=parseInt(n.replace(/^(.*)\..*$/,"$1"),10);t[1]=parseInt(n.replace(/^.*\.(.*)\s.*$/,"$1"),10);t[2]=/r/.test(n)?parseInt(n.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof G.ActiveXObject!=Z){var o=null,s=false;try{o=new ActiveXObject(h+".7")}catch(k){try{o=new ActiveXObject(h+".6");t=[6,0,21];o.AllowScriptAccess="always"}catch(k){if(t[0]==6){s=true}}if(!s){try{o=new ActiveXObject(h)}catch(k){}}}if(!s&&o){try{n=o.GetVariable("$version");if(n){n=n.split(" ")[1].split(",");t=[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10)]}}catch(k){}}}}var v=N.userAgent.toLowerCase(),j=N.platform.toLowerCase(),r=/webkit/.test(v)?parseFloat(v.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,i=false,q=j?/win/.test(j):/win/.test(v),m=j?/mac/.test(j):/mac/.test(v);/*@cc_on i=true;@if(@_win32)q=true;@elif(@_mac)m=true;@end@*/return{w3cdom:l,pv:t,webkit:r,ie:i,win:q,mac:m}}();var e=function(){if(!a.w3cdom){return }J(I);if(a.ie&&a.win){try{g.write("<script id=__ie_ondomload defer=true src=//:><\/script>");var i=c("__ie_ondomload");if(i){i.onreadystatechange=function(){if(this.readyState=="complete"){this.parentNode.removeChild(this);V()}}}}catch(j){}}if(a.webkit&&typeof g.readyState!=Z){Q=setInterval(function(){if(/loaded|complete/.test(g.readyState)){V()}},10)}if(typeof g.addEventListener!=Z){g.addEventListener("DOMContentLoaded",V,null)}M(V)}();function V(){if(S){return }if(a.ie&&a.win){var m=Y("span");try{var l=g.getElementsByTagName("body")[0].appendChild(m);l.parentNode.removeChild(l)}catch(n){return }}S=true;if(Q){clearInterval(Q);Q=null}var j=f.length;for(var k=0;k<j;k++){f[k]()}}function J(i){if(S){i()}else{f[f.length]=i}}function M(j){if(typeof G.addEventListener!=Z){G.addEventListener("load",j,false)}else{if(typeof g.addEventListener!=Z){g.addEventListener("load",j,false)}else{if(typeof G.attachEvent!=Z){G.attachEvent("onload",j)}else{if(typeof G.onload=="function"){var i=G.onload;G.onload=function(){i();j()}}else{G.onload=j}}}}}function I(){var l=H.length;for(var j=0;j<l;j++){var m=H[j].id;if(a.pv[0]>0){var k=c(m);if(k){H[j].width=k.getAttribute("width")?k.getAttribute("width"):"0";H[j].height=k.getAttribute("height")?k.getAttribute("height"):"0";if(O(H[j].swfVersion)){if(a.webkit&&a.webkit<312){U(k)}X(m,true)}else{if(H[j].expressInstall&&!C&&O("6.0.65")&&(a.win||a.mac)){D(H[j])}else{d(k)}}}}else{X(m,true)}}}function U(m){var k=m.getElementsByTagName(P)[0];if(k){var p=Y("embed"),r=k.attributes;if(r){var o=r.length;for(var n=0;n<o;n++){if(r[n].nodeName.toLowerCase()=="data"){p.setAttribute("src",r[n].nodeValue)}else{p.setAttribute(r[n].nodeName,r[n].nodeValue)}}}var q=k.childNodes;if(q){var s=q.length;for(var l=0;l<s;l++){if(q[l].nodeType==1&&q[l].nodeName.toLowerCase()=="param"){p.setAttribute(q[l].getAttribute("name"),q[l].getAttribute("value"))}}}m.parentNode.replaceChild(p,m)}}function F(i){if(a.ie&&a.win&&O("8.0.0")){G.attachEvent("onunload",function(){var k=c(i);if(k){for(var j in k){if(typeof k[j]=="function"){k[j]=function(){}}}k.parentNode.removeChild(k)}})}}function D(j){C=true;var o=c(j.id);if(o){if(j.altContentId){var l=c(j.altContentId);if(l){L=l;T=j.altContentId}}else{L=b(o)}if(!(/%$/.test(j.width))&&parseInt(j.width,10)<310){j.width="310"}if(!(/%$/.test(j.height))&&parseInt(j.height,10)<137){j.height="137"}g.title=g.title.slice(0,47)+" - Flash Player Installation";var n=a.ie&&a.win?"ActiveX":"PlugIn",k=g.title,m="MMredirectURL="+G.location+"&MMplayerType="+n+"&MMdoctitle="+k,p=j.id;if(a.ie&&a.win&&o.readyState!=4){var i=Y("div");p+="SWFObjectNew";i.setAttribute("id",p);o.parentNode.insertBefore(i,o);o.style.display="none";G.attachEvent("onload",function(){o.parentNode.removeChild(o)})}R({data:j.expressInstall,id:K,width:j.width,height:j.height},{flashvars:m},p)}}function d(j){if(a.ie&&a.win&&j.readyState!=4){var i=Y("div");j.parentNode.insertBefore(i,j);i.parentNode.replaceChild(b(j),i);j.style.display="none";G.attachEvent("onload",function(){j.parentNode.removeChild(j)})}else{j.parentNode.replaceChild(b(j),j)}}function b(n){var m=Y("div");if(a.win&&a.ie){m.innerHTML=n.innerHTML}else{var k=n.getElementsByTagName(P)[0];if(k){var o=k.childNodes;if(o){var j=o.length;for(var l=0;l<j;l++){if(!(o[l].nodeType==1&&o[l].nodeName.toLowerCase()=="param")&&!(o[l].nodeType==8)){m.appendChild(o[l].cloneNode(true))}}}}}return m}function R(AE,AC,q){var p,t=c(q);if(typeof AE.id==Z){AE.id=q}if(a.ie&&a.win){var AD="";for(var z in AE){if(AE[z]!=Object.prototype[z]){if(z=="data"){AC.movie=AE[z]}else{if(z.toLowerCase()=="styleclass"){AD+=' class="'+AE[z]+'"'}else{if(z!="classid"){AD+=" "+z+'="'+AE[z]+'"'}}}}}var AB="";for(var y in AC){if(AC[y]!=Object.prototype[y]){AB+='<param name="'+y+'" value="'+AC[y]+'" />'}}t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AD+">"+AB+"</object>";F(AE.id);p=c(AE.id)}else{if(a.webkit&&a.webkit<312){var AA=Y("embed");AA.setAttribute("type",W);for(var x in AE){if(AE[x]!=Object.prototype[x]){if(x=="data"){AA.setAttribute("src",AE[x])}else{if(x.toLowerCase()=="styleclass"){AA.setAttribute("class",AE[x])}else{if(x!="classid"){AA.setAttribute(x,AE[x])}}}}}for(var w in AC){if(AC[w]!=Object.prototype[w]){if(w!="movie"){AA.setAttribute(w,AC[w])}}}t.parentNode.replaceChild(AA,t);p=AA}else{var s=Y(P);s.setAttribute("type",W);for(var v in AE){if(AE[v]!=Object.prototype[v]){if(v.toLowerCase()=="styleclass"){s.setAttribute("class",AE[v])}else{if(v!="classid"){s.setAttribute(v,AE[v])}}}}for(var u in AC){if(AC[u]!=Object.prototype[u]&&u!="movie"){E(s,u,AC[u])}}t.parentNode.replaceChild(s,t);p=s}}return p}function E(k,i,j){var l=Y("param");l.setAttribute("name",i);l.setAttribute("value",j);k.appendChild(l)}function c(i){return g.getElementById(i)}function Y(i){return g.createElement(i)}function O(k){var j=a.pv,i=k.split(".");i[0]=parseInt(i[0],10);i[1]=parseInt(i[1],10);i[2]=parseInt(i[2],10);return(j[0]>i[0]||(j[0]==i[0]&&j[1]>i[1])||(j[0]==i[0]&&j[1]==i[1]&&j[2]>=i[2]))?true:false}function A(m,j){if(a.ie&&a.mac){return }var l=g.getElementsByTagName("head")[0],k=Y("style");k.setAttribute("type","text/css");k.setAttribute("media","screen");if(!(a.ie&&a.win)&&typeof g.createTextNode!=Z){k.appendChild(g.createTextNode(m+" {"+j+"}"))}l.appendChild(k);if(a.ie&&a.win&&typeof g.styleSheets!=Z&&g.styleSheets.length>0){var i=g.styleSheets[g.styleSheets.length-1];if(typeof i.addRule==P){i.addRule(m,j)}}}function X(k,i){var j=i?"visible":"hidden";if(S){c(k).style.visibility=j}else{A("#"+k,"visibility:"+j)}}return{registerObject:function(l,i,k){if(!a.w3cdom||!l||!i){return }var j={};j.id=l;j.swfVersion=i;j.expressInstall=k?k:false;H[H.length]=j;X(l,false)},getObjectById:function(l){var i=null;if(a.w3cdom&&S){var j=c(l);if(j){var k=j.getElementsByTagName(P)[0];if(!k||(k&&typeof j.SetVariable!=Z)){i=j}else{if(typeof k.SetVariable!=Z){i=k}}}}return i},embedSWF:function(n,u,r,t,j,m,k,p,s){if(!a.w3cdom||!n||!u||!r||!t||!j){return }r+="";t+="";if(O(j)){X(u,false);var q=(typeof s==P)?s:{};q.data=n;q.width=r;q.height=t;var o=(typeof p==P)?p:{};if(typeof k==P){for(var l in k){if(k[l]!=Object.prototype[l]){if(typeof o.flashvars!=Z){o.flashvars+="&"+l+"="+k[l]}else{o.flashvars=l+"="+k[l]}}}}J(function(){R(q,o,u);if(q.id==u){X(u,true)}})}else{if(m&&!C&&O("6.0.65")&&(a.win||a.mac)){X(u,false);J(function(){var i={};i.id=i.altContentId=u;i.width=r;i.height=t;i.expressInstall=m;D(i)})}}},getFlashPlayerVersion:function(){return{major:a.pv[0],minor:a.pv[1],release:a.pv[2]}},hasFlashPlayerVersion:O,createSWF:function(k,j,i){if(a.w3cdom&&S){return R(k,j,i)}else{return undefined}},createCSS:function(j,i){if(a.w3cdom){A(j,i)}},addDomLoadEvent:J,addLoadEvent:M,getQueryParamValue:function(m){var l=g.location.search||g.location.hash;if(m==null){return l}if(l){var k=l.substring(1).split("&");for(var j=0;j<k.length;j++){if(k[j].substring(0,k[j].indexOf("="))==m){return k[j].substring((k[j].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(C&&L){var i=c(K);if(i){i.parentNode.replaceChild(L,i);if(T){X(T,true);if(a.ie&&a.win){L.style.display="block"}}L=null;T=null;C=false}}}}}();
\ No newline at end of file
diff --git a/public/juggernaut/expressinstall.swf b/public/juggernaut/expressinstall.swf
new file mode 100644
index 0000000..86958bf
Binary files /dev/null and b/public/juggernaut/expressinstall.swf differ
diff --git a/public/juggernaut/juggernaut.swf b/public/juggernaut/juggernaut.swf
new file mode 100644
index 0000000..525ea67
Binary files /dev/null and b/public/juggernaut/juggernaut.swf differ
diff --git a/vendor/plugins/juggernaut_plugin/LICENSE b/vendor/plugins/juggernaut_plugin/LICENSE
new file mode 100644
index 0000000..5dc86fd
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2005 Alexander MacCaw
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/vendor/plugins/juggernaut_plugin/README b/vendor/plugins/juggernaut_plugin/README
new file mode 100644
index 0000000..ea8bfeb
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/README
@@ -0,0 +1,233 @@
+Juggernaut
+===========
+
+=CONTACT DETAILS
+
+ Author: Alex MacCaw
+ E-Mail Address: [email protected]
+ License: MIT
+ Website: http://juggernaut.rubyforge.org
+ Blog: http://www.eribium.org
+
+=DESCRIPTION
+
+The Juggernaut plugin for Ruby on Rails aims to revolutionize your Rails app by letting the server initiate a connection and push data to the client. In other words your app can have a real time connection to the server with the advantage of instant updates. Although the obvious use of this is for chat, the most exciting prospect for me is collaborative cms and wikis.
+
+What Happens:
+
+ 1. Client A opens socket connection to the socket server
+ 2. Client B makes Ajax call to Rails
+ 3. Rails sends message to the socket server
+ 4. Socket server broadcasts message to clients
+
+Juggernaut Features:
+
+ * Allows a real time connection with a client - Rails can literally push javascript in real time to the client which is then evaluated.
+ * Push server - written in Ruby.
+ * Integrated, as a plugin, into Rails.
+ * Subscribers can subscribe to multiple channels, and broadcasters can broadcast to multiple channels.
+ * Subscribers can provide a 'unique_id' and broadcasters can send data to specific clients.
+ * Add and remove channels at runtime
+ * Uses Flash 8 - installed on more than 98% of computers.
+ * Supports all the major browsers (uses ExternalInterface): Firefox 1+, IE 6+ and Safari 2+.
+
+Requirements:
+
+ * Rails 2.0.2 or edge
+ * json gem (gem install json)
+ * EventMachine gem (gem install eventmachine)
+ * juggernaut gem (gem install juggernaut)
+
+
+===============================================
+INSTALLATION
+===============================================
+
+ 1. From your Rails Dir:
+ script/plugin install git://github.com/maccman/juggernaut_plugin.git
+ 2. Make sure to include the appropriate JavaScripts in your views/layouts
+ in the header of your views
+ <%= javascript_include_tag 'prototype', :juggernaut %>
+ 3. Add this to your view/layout head:
+ <%= juggernaut %>
+ 4. Make sure the juggernaut gem is installed (gem install maccman-juggernaut -s http://gems.github.com ) and run:
+ juggernaut -g juggernaut.yml
+ juggernaut -c juggernaut.yml
+ 5. Run script/server and visit the Jugged up page.
+ 6. Then, to send data to juggernaut, execute this in the console:
+ Juggernaut.send_to_all("alert('hi from juggernaut')")
+
+Usage
+
+To demonstrate Juggernaut I'll walk you through building a simple chat.
+
+Start the push server going by running:
+juggernaut -g juggernaut.yml
+juggernaut -c juggernaut.yml
+
+The chat controller:
+
+class ChatController < ApplicationController
+ def index
+ end
+
+ def send_data
+ render :juggernaut do |page|
+ page.insert_html :top, 'chat_data', "<li>#{h params[:chat_input]}</li>"
+ end
+ render :nothing => true
+ end
+end
+
+
+The index.html.erb
+
+ <html>
+ <head>
+ <%= javascript_include_tag :defaults, :juggernaut %>
+ <%= juggernaut %>
+ </head>
+ <body>
+ <%= form_remote_tag(
+ :url => { :action => :send_data },
+ :complete => "$('chat_input').value = ''" ) %>
+ <%= text_field_tag( 'chat_input', '', { :size => 20, :id => 'chat_input'} ) %>
+ <%= submit_tag "Add" %>
+ </form>
+ <ul id="chat_data" style="list-style:none">
+ </ul>
+ </body>
+ </html>
+
+Start the webserver going with:
+ruby script/server
+
+Try it and see what you think. If it doesn't work please visit the faq.
+
+Other ways of rendering to juggernaut:
+
+render :juggernaut do |page|
+ page.alert('hi')
+end
+
+render_juggernaut(:action => 'whatever')
+
+===============================================
+More usage information, examples and support
+===============================================
+
+=== Channel Usage ===
+
+<%= juggernaut(:channels => ['one', 'two', 'three']) %>
+render :juggernaut => {:type => :send_to_channels, :channels => ['one']} do |page|
+ page.alert('hi')
+end
+
+Client id usage:
+<%= juggernaut(:client_id => session[:user_id]) %>
+render :juggernaut => {:type => :send_to_clients, :client_ids => [1, 2, 3]} do |page|
+ page.alert('hi')
+end
+
+Other juggernaut render options:
+OPTION_TYPE PARAMS
+:send_to_all
+:send_to_channels :channels
+:send_to_channel :channel
+:send_to_client :client_id
+:send_to_clients :client_ids
+:send_to_client_on_channel :client_id, :channel
+:send_to_clients_on_channel :client_ids, :channel
+:send_to_client_on_channels :client_id, :channels
+:send_to_clients_on_channels :client_ids, :channels
+
+You can also call these methods directly on the Juggernaut class:
+Juggernaut.send_to_clients('data', [1,2,3])
+
+For authentication options and callbacks see the juggernaut.yml configuration file.
+
+Usage and examples: http://ncavig.com/blog/
+Support and forums: http://groups.google.com/group/Juggernaut-for-Rails?hl=en
+
+=== Getting remote clients to connect ===
+
+Firstly you will need to configure juggernaut_hosts.yml in your Rails app to point to the proper IP of the push server (rather than 127.0.0.1).
+For example:
+:hosts:
+ - :port: 5001
+ :host: 129.168.0.2
+ :environment: :production
+
+Ok, remote clients that visit pages on this server (once you restart it) will connect to the proper push server IP. BUT, if you're using IP based
+authentication (recommended) you'll find that the broadcast authentication fails.
+You'll need to add the Rails IP to juggernaut.yml, like so:
+
+:allowed_ips:
+ - 127.0.0.1
+ - 192.168.0.4 # IP of the Rails app
+
+===============================================
+Jquery
+===============================================
+
+To get Juggernaut working with Jquery (Prototype is used by default) follow the tutorial above with the following differences.
+
+>>Javascripts
+
+ You must have jquery.js (version 1.2.6 tested) and the jquery-json plugin (http://www.jdempster.com/wp-content/uploads/2007/08/jquery.json.js) in the /javascripts directory.
+
+ You need the jquerynaut.js file in the /javascripts/juggernaut directory (found in /lib in the media directory)
+
+
+>>The chat controller:
+
+ class ChatController < ApplicationController
+ def index
+ end
+
+ def send_data
+ render :juggernaut do |page|
+ page["#chat_data"].prepend "<li>#{h params[:chat_input]}</li>"
+ end
+ render :nothing => true
+ end
+
+ end
+
+
+>>The index.html.erb
+
+ <html>
+ <head>
+ <%= javascript_include_tag 'jquery', 'json', 'juggernaut/juggernaut', 'juggernaut/jquerynaut', 'juggernaut/swfobject' %>
+ <%= juggernaut %>
+ </head>
+ <body>
+ <form action="/chat/send_data" method="get">
+ <div style="margin:0;padding:0">
+ <input id="chat_input" name="chat_input" size="20" type="text" value="" />
+ <input name="commit" type="submit" value="Add" />
+ </form>
+
+ <script>
+ $(document).ready(function(){
+ $('form').submit(function(){
+ $.get('/chat/send_data', { chat_input: $('#chat_input').val() } )
+ return false;
+ })
+ })
+ </script>
+ <ul id="chat_data" style="list-style:none"></ul>
+ </body>
+ </html>
+
+
+
+===============================================
+Troubleshooting
+===============================================
+
+Check out the support forums on google groups:
+http://groups.google.com/group/Juggernaut-for-Rails
+
+
diff --git a/vendor/plugins/juggernaut_plugin/init.rb b/vendor/plugins/juggernaut_plugin/init.rb
new file mode 100644
index 0000000..58a12b6
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/init.rb
@@ -0,0 +1,18 @@
+require File.dirname(__FILE__) + '/lib/juggernaut'
+require File.dirname(__FILE__) + '/lib/juggernaut_helper'
+
+ActionView::Base.send(:include, Juggernaut::JuggernautHelper)
+
+ActionView::Helpers::AssetTagHelper.register_javascript_expansion :juggernaut => ['juggernaut/swfobject', 'juggernaut/juggernaut']
+
+ActionController::Base.class_eval do
+ alias_method :render_without_juggernaut, :render
+ include Juggernaut::RenderExtension
+ alias_method :render, :render_with_juggernaut
+end
+
+ActionView::Base.class_eval do
+ alias_method :render_without_juggernaut, :render
+ include Juggernaut::RenderExtension
+ alias_method :render, :render_with_juggernaut
+end
\ No newline at end of file
diff --git a/vendor/plugins/juggernaut_plugin/install.rb b/vendor/plugins/juggernaut_plugin/install.rb
new file mode 100644
index 0000000..86a5af7
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/install.rb
@@ -0,0 +1,18 @@
+require 'fileutils'
+
+here = File.dirname(__FILE__)
+there = defined?(RAILS_ROOT) ? RAILS_ROOT : "#{here}/../../.."
+
+FileUtils.mkdir_p("#{there}/public/javascripts/juggernaut/")
+FileUtils.mkdir_p("#{there}/public/juggernaut/")
+
+puts "Installing Juggernaut..."
+FileUtils.cp("#{here}/media/swfobject.js", "#{there}/public/javascripts/juggernaut/")
+FileUtils.cp("#{here}/media/juggernaut.js", "#{there}/public/javascripts/juggernaut/")
+FileUtils.cp("#{here}/media/juggernaut.swf", "#{there}/public/juggernaut/")
+FileUtils.cp("#{here}/media/expressinstall.swf", "#{there}/public/juggernaut/")
+
+FileUtils.cp("#{here}/media/juggernaut_hosts.yml", "#{there}/config/") unless File.exist?("#{there}/config/juggernaut_hosts.yml")
+puts "Juggernaut has been successfully installed."
+puts
+puts "Please refer to the readme file #{File.expand_path(here)}/README"
\ No newline at end of file
diff --git a/vendor/plugins/juggernaut_plugin/lib/juggernaut.rb b/vendor/plugins/juggernaut_plugin/lib/juggernaut.rb
new file mode 100644
index 0000000..427f644
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/lib/juggernaut.rb
@@ -0,0 +1,210 @@
+require "yaml"
+require "socket"
+
+module Juggernaut
+ CONFIG = YAML::load(ERB.new(IO.read("#{RAILS_ROOT}/config/juggernaut_hosts.yml")).result).freeze
+ CR = "\0"
+
+ class << self
+
+ def send_to_all(data)
+ fc = {
+ :command => :broadcast,
+ :body => data,
+ :type => :to_channels,
+ :channels => []
+ }
+ send_data(fc)
+ end
+
+ def send_to_channels(data, channels)
+ fc = {
+ :command => :broadcast,
+ :body => data,
+ :type => :to_channels,
+ :channels => channels
+ }
+ send_data(fc)
+ end
+ alias send_to_channel send_to_channels
+
+ def send_to_clients(data, client_ids)
+ fc = {
+ :command => :broadcast,
+ :body => data,
+ :type => :to_clients,
+ :client_ids => client_ids
+ }
+ send_data(fc)
+ end
+ alias send_to_client send_to_clients
+
+ def send_to_clients_on_channels(data, client_ids, channels)
+ fc = {
+ :command => :broadcast,
+ :body => data,
+ :type => :to_clients,
+ :client_ids => client_ids,
+ :channels => channels
+ }
+ send_data(fc)
+ end
+ alias send_to_clients_on_channel send_to_clients_on_channels
+ alias send_to_client_on_channels send_to_clients_on_channels
+
+ def remove_channels_from_clients(client_ids, channels)
+ fc = {
+ :command => :query,
+ :type => :remove_channels_from_client,
+ :client_ids => client_ids,
+ :channels => channels
+ }
+ send_data(fc)
+ end
+ alias remove_channel_from_client remove_channels_from_clients
+ alias remove_channels_from_client remove_channels_from_clients
+
+ def remove_all_channels(channels)
+ fc = {
+ :command => :query,
+ :type => :remove_all_channels,
+ :channels => channels
+ }
+ send_data(fc)
+ end
+
+ def show_clients
+ fc = {
+ :command => :query,
+ :type => :show_clients
+ }
+ send_data(fc, true).flatten
+ end
+
+ def show_client(client_id)
+ fc = {
+ :command => :query,
+ :type => :show_client,
+ :client_id => client_id
+ }
+ send_data(fc, true).flatten[0]
+ end
+
+ def show_clients_for_channels(channels)
+ fc = {
+ :command => :query,
+ :type => :show_clients_for_channels,
+ :channels => channels
+ }
+ send_data(fc, true).flatten
+ end
+ alias show_clients_for_channel show_clients_for_channels
+
+ def send_data(hash, response = false)
+ hash[:channels] = Array(hash[:channels]) if hash[:channels]
+ hash[:client_ids] = Array(hash[:client_ids]) if hash[:client_ids]
+
+ res = []
+ hosts.each do |address|
+ begin
+ hash[:secret_key] = address[:secret_key] if address[:secret_key]
+
+ @socket = TCPSocket.new(address[:host], address[:port])
+ # the \0 is to mirror flash
+ @socket.print(hash.to_json + CR)
+ @socket.flush
+ res << @socket.readline(CR) if response
+ ensure
+ @socket.close if @socket and [email protected]?
+ end
+ end
+ res.collect {|r| ActiveSupport::JSON.decode(r.chomp!(CR)) } if response
+ end
+
+ private
+
+ def hosts
+ CONFIG[:hosts].select {|h|
+ !h[:environment] or h[:environment].to_s == ENV['RAILS_ENV']
+ }
+ end
+
+ end
+
+ module RenderExtension
+ def self.included(base)
+ base.send :include, InstanceMethods
+ end
+
+ module InstanceMethods
+ # We can't protect these as ActionMailer complains
+
+ def render_with_juggernaut(options = nil, extra_options = {}, &block)
+ if options == :juggernaut or (options.is_a?(Hash) and options[:juggernaut])
+ begin
+ if @template.respond_to?(:_evaluate_assigns_and_ivars, true)
+ @template.send(:_evaluate_assigns_and_ivars)
+ else
+ @template.send(:evaluate_assigns)
+ end
+
+ generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(@template, &block)
+ render_for_juggernaut(generator.to_s, options.is_a?(Hash) ? options[:juggernaut] : nil)
+ ensure
+ erase_render_results
+ reset_variables_added_to_assigns
+ end
+ else
+ render_without_juggernaut(options, extra_options, &block)
+ end
+ end
+
+ def render_juggernaut(*args)
+ juggernaut_options = args.last.is_a?(Hash) ? args.pop : {}
+ render_for_juggernaut(render_to_string(*args), juggernaut_options)
+ end
+
+ def render_for_juggernaut(data, options = {})
+ if !options or !options.is_a?(Hash)
+ return Juggernaut.send_to_all(data)
+ end
+
+ case options[:type]
+ when :send_to_all
+ Juggernaut.send_to_all(data)
+ when :send_to_channels
+ juggernaut_needs options, :channels
+ Juggernaut.send_to_channels(data, options[:channels])
+ when :send_to_channel
+ juggernaut_needs options, :channel
+ Juggernaut.send_to_channel(data, options[:channel])
+ when :send_to_client
+ juggernaut_needs options, :client_id
+ Juggernaut.send_to_client(data, options[:client_id])
+ when :send_to_clients
+ juggernaut_needs options, :client_ids
+ Juggernaut.send_to_clients(data, options[:client_ids])
+ when :send_to_client_on_channel
+ juggernaut_needs options, :client_id, :channel
+ Juggernaut.send_to_clients_on_channel(data, options[:client_id], options[:channel])
+ when :send_to_clients_on_channel
+ juggernaut_needs options, :client_ids, :channel
+ Juggernaut.send_to_clients_on_channel(data, options[:client_ids], options[:channel])
+ when :send_to_client_on_channels
+ juggernaut_needs options, :client_ids, :channels
+ Juggernaut.send_to_clients_on_channel(data, options[:client_id], options[:channels])
+ when :send_to_clients_on_channels
+ juggernaut_needs options, :client_ids, :channels
+ Juggernaut.send_to_clients_on_channel(data, options[:client_ids], options[:channels])
+ end
+ end
+
+ def juggernaut_needs(options, *args)
+ args.each do |a|
+ raise "You must specify #{a}" unless options[a]
+ end
+ end
+
+ end
+ end
+end
diff --git a/vendor/plugins/juggernaut_plugin/lib/juggernaut_helper.rb b/vendor/plugins/juggernaut_plugin/lib/juggernaut_helper.rb
new file mode 100644
index 0000000..41e82bd
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/lib/juggernaut_helper.rb
@@ -0,0 +1,27 @@
+module Juggernaut # :nodoc:
+ module JuggernautHelper
+
+ def juggernaut(options = {})
+ hosts = Juggernaut::CONFIG[:hosts].select {|h| !h[:environment] or h[:environment] == ENV['RAILS_ENV'].to_sym }
+ random_host = hosts[rand(hosts.length)]
+ options = {
+ :host => (random_host[:public_host] || random_host[:host]),
+ :port => (random_host[:public_port] || random_host[:port]),
+ :width => '0px',
+ :height => '0px',
+ :session_id => request.session_options[:id],
+ :swf_address => "/juggernaut/juggernaut.swf",
+ :ei_swf_address => "/juggernaut/expressinstall.swf",
+ :flash_version => 8,
+ :flash_color => "#fff",
+ :swf_name => "juggernaut_flash",
+ :bridge_name => "juggernaut",
+ :debug => (RAILS_ENV == 'development'),
+ :reconnect_attempts => 3,
+ :reconnect_intervals => 3
+ }.merge(options)
+ javascript_tag "new Juggernaut(#{options.to_json});"
+ end
+
+ end
+end
diff --git a/vendor/plugins/juggernaut_plugin/media/expressinstall.swf b/vendor/plugins/juggernaut_plugin/media/expressinstall.swf
new file mode 100644
index 0000000..86958bf
Binary files /dev/null and b/vendor/plugins/juggernaut_plugin/media/expressinstall.swf differ
diff --git a/vendor/plugins/juggernaut_plugin/media/jquery.js b/vendor/plugins/juggernaut_plugin/media/jquery.js
new file mode 100755
index 0000000..74ffd51
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/jquery.js
@@ -0,0 +1,3549 @@
+(function(){
+/*
+ * jQuery 1.2.6 - New Wave Javascript
+ *
+ * Copyright (c) 2008 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
+ * $Rev: 5685 $
+ */
+
+// Map over jQuery in case of overwrite
+var _jQuery = window.jQuery,
+// Map over the $ in case of overwrite
+ _$ = window.$;
+
+var jQuery = window.jQuery = window.$ = function( selector, context ) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ return new jQuery.fn.init( selector, context );
+};
+
+// A simple way to check for HTML strings or ID strings
+// (both of which we optimize for)
+var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,
+
+// Is it a simple selector
+ isSimple = /^.[^:#\[\.]*$/,
+
+// Will speed up references to undefined, and allows munging its name.
+ undefined;
+
+jQuery.fn = jQuery.prototype = {
+ init: function( selector, context ) {
+ // Make sure that a selection was provided
+ selector = selector || document;
+
+ // Handle $(DOMElement)
+ if ( selector.nodeType ) {
+ this[0] = selector;
+ this.length = 1;
+ return this;
+ }
+ // Handle HTML strings
+ if ( typeof selector == "string" ) {
+ // Are we dealing with HTML string or an ID?
+ var match = quickExpr.exec( selector );
+
+ // Verify a match, and that no context was specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] )
+ selector = jQuery.clean( [ match[1] ], context );
+
+ // HANDLE: $("#id")
+ else {
+ var elem = document.getElementById( match[3] );
+
+ // Make sure an element was located
+ if ( elem ){
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id != match[3] )
+ return jQuery().find( selector );
+
+ // Otherwise, we inject the element directly into the jQuery object
+ return jQuery( elem );
+ }
+ selector = [];
+ }
+
+ // HANDLE: $(expr, [context])
+ // (which is just equivalent to: $(content).find(expr)
+ } else
+ return jQuery( context ).find( selector );
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) )
+ return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector );
+
+ return this.setArray(jQuery.makeArray(selector));
+ },
+
+ // The current version of jQuery being used
+ jquery: "1.2.6",
+
+ // The number of elements contained in the matched element set
+ size: function() {
+ return this.length;
+ },
+
+ // The number of elements contained in the matched element set
+ length: 0,
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num == undefined ?
+
+ // Return a 'clean' array
+ jQuery.makeArray( this ) :
+
+ // Return just the object
+ this[ num ];
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems ) {
+ // Build a new jQuery matched element set
+ var ret = jQuery( elems );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Force the current matched set of elements to become
+ // the specified array of elements (destroying the stack in the process)
+ // You should use pushStack() in order to do this, but maintain the stack
+ setArray: function( elems ) {
+ // Resetting the length to 0, then using the native Array push
+ // is a super-fast way to populate an object with array-like properties
+ this.length = 0;
+ Array.prototype.push.apply( this, elems );
+
+ return this;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+ var ret = -1;
+
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem && elem.jquery ? elem[0] : elem
+ , this );
+ },
+
+ attr: function( name, value, type ) {
+ var options = name;
+
+ // Look for the case where we're accessing a style value
+ if ( name.constructor == String )
+ if ( value === undefined )
+ return this[0] && jQuery[ type || "attr" ]( this[0], name );
+
+ else {
+ options = {};
+ options[ name ] = value;
+ }
+
+ // Check to see if we're setting style values
+ return this.each(function(i){
+ // Set all the styles
+ for ( name in options )
+ jQuery.attr(
+ type ?
+ this.style :
+ this,
+ name, jQuery.prop( this, options[ name ], type, i, name )
+ );
+ });
+ },
+
+ css: function( key, value ) {
+ // ignore negative width and height values
+ if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
+ value = undefined;
+ return this.attr( key, value, "curCSS" );
+ },
+
+ text: function( text ) {
+ if ( typeof text != "object" && text != null )
+ return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+
+ var ret = "";
+
+ jQuery.each( text || this, function(){
+ jQuery.each( this.childNodes, function(){
+ if ( this.nodeType != 8 )
+ ret += this.nodeType != 1 ?
+ this.nodeValue :
+ jQuery.fn.text( [ this ] );
+ });
+ });
+
+ return ret;
+ },
+
+ wrapAll: function( html ) {
+ if ( this[0] )
+ // The elements to wrap the target around
+ jQuery( html, this[0].ownerDocument )
+ .clone()
+ .insertBefore( this[0] )
+ .map(function(){
+ var elem = this;
+
+ while ( elem.firstChild )
+ elem = elem.firstChild;
+
+ return elem;
+ })
+ .append(this);
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ return this.each(function(){
+ jQuery( this ).contents().wrapAll( html );
+ });
+ },
+
+ wrap: function( html ) {
+ return this.each(function(){
+ jQuery( this ).wrapAll( html );
+ });
+ },
+
+ append: function() {
+ return this.domManip(arguments, true, false, function(elem){
+ if (this.nodeType == 1)
+ this.appendChild( elem );
+ });
+ },
+
+ prepend: function() {
+ return this.domManip(arguments, true, true, function(elem){
+ if (this.nodeType == 1)
+ this.insertBefore( elem, this.firstChild );
+ });
+ },
+
+ before: function() {
+ return this.domManip(arguments, false, false, function(elem){
+ this.parentNode.insertBefore( elem, this );
+ });
+ },
+
+ after: function() {
+ return this.domManip(arguments, false, true, function(elem){
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ });
+ },
+
+ end: function() {
+ return this.prevObject || jQuery( [] );
+ },
+
+ find: function( selector ) {
+ var elems = jQuery.map(this, function(elem){
+ return jQuery.find( selector, elem );
+ });
+
+ return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ?
+ jQuery.unique( elems ) :
+ elems );
+ },
+
+ clone: function( events ) {
+ // Do the clone
+ var ret = this.map(function(){
+ if ( jQuery.browser.msie && !jQuery.isXMLDoc(this) ) {
+ // IE copies events bound via attachEvent when
+ // using cloneNode. Calling detachEvent on the
+ // clone will also remove the events from the orignal
+ // In order to get around this, we use innerHTML.
+ // Unfortunately, this means some modifications to
+ // attributes in IE that are actually only stored
+ // as properties will not be copied (such as the
+ // the name attribute on an input).
+ var clone = this.cloneNode(true),
+ container = document.createElement("div");
+ container.appendChild(clone);
+ return jQuery.clean([container.innerHTML])[0];
+ } else
+ return this.cloneNode(true);
+ });
+
+ // Need to set the expando to null on the cloned set if it exists
+ // removeData doesn't work here, IE removes it from the original as well
+ // this is primarily for IE but the data expando shouldn't be copied over in any browser
+ var clone = ret.find("*").andSelf().each(function(){
+ if ( this[ expando ] != undefined )
+ this[ expando ] = null;
+ });
+
+ // Copy the events from the original to the clone
+ if ( events === true )
+ this.find("*").andSelf().each(function(i){
+ if (this.nodeType == 3)
+ return;
+ var events = jQuery.data( this, "events" );
+
+ for ( var type in events )
+ for ( var handler in events[ type ] )
+ jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
+ });
+
+ // Return the cloned set
+ return ret;
+ },
+
+ filter: function( selector ) {
+ return this.pushStack(
+ jQuery.isFunction( selector ) &&
+ jQuery.grep(this, function(elem, i){
+ return selector.call( elem, i );
+ }) ||
+
+ jQuery.multiFilter( selector, this ) );
+ },
+
+ not: function( selector ) {
+ if ( selector.constructor == String )
+ // test special case where just one selector is passed in
+ if ( isSimple.test( selector ) )
+ return this.pushStack( jQuery.multiFilter( selector, this, true ) );
+ else
+ selector = jQuery.multiFilter( selector, this );
+
+ var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
+ return this.filter(function() {
+ return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
+ });
+ },
+
+ add: function( selector ) {
+ return this.pushStack( jQuery.unique( jQuery.merge(
+ this.get(),
+ typeof selector == 'string' ?
+ jQuery( selector ) :
+ jQuery.makeArray( selector )
+ )));
+ },
+
+ is: function( selector ) {
+ return !!selector && jQuery.multiFilter( selector, this ).length > 0;
+ },
+
+ hasClass: function( selector ) {
+ return this.is( "." + selector );
+ },
+
+ val: function( value ) {
+ if ( value == undefined ) {
+
+ if ( this.length ) {
+ var elem = this[0];
+
+ // We need to handle select boxes special
+ if ( jQuery.nodeName( elem, "select" ) ) {
+ var index = elem.selectedIndex,
+ values = [],
+ options = elem.options,
+ one = elem.type == "select-one";
+
+ // Nothing was selected
+ if ( index < 0 )
+ return null;
+
+ // Loop through all the selected options
+ for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+ var option = options[ i ];
+
+ if ( option.selected ) {
+ // Get the specifc value for the option
+ value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;
+
+ // We don't need an array for one selects
+ if ( one )
+ return value;
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+
+ // Everything else, we just grab the value
+ } else
+ return (this[0].value || "").replace(/\r/g, "");
+
+ }
+
+ return undefined;
+ }
+
+ if( value.constructor == Number )
+ value += '';
+
+ return this.each(function(){
+ if ( this.nodeType != 1 )
+ return;
+
+ if ( value.constructor == Array && /radio|checkbox/.test( this.type ) )
+ this.checked = (jQuery.inArray(this.value, value) >= 0 ||
+ jQuery.inArray(this.name, value) >= 0);
+
+ else if ( jQuery.nodeName( this, "select" ) ) {
+ var values = jQuery.makeArray(value);
+
+ jQuery( "option", this ).each(function(){
+ this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
+ jQuery.inArray( this.text, values ) >= 0);
+ });
+
+ if ( !values.length )
+ this.selectedIndex = -1;
+
+ } else
+ this.value = value;
+ });
+ },
+
+ html: function( value ) {
+ return value == undefined ?
+ (this[0] ?
+ this[0].innerHTML :
+ null) :
+ this.empty().append( value );
+ },
+
+ replaceWith: function( value ) {
+ return this.after( value ).remove();
+ },
+
+ eq: function( i ) {
+ return this.slice( i, i + 1 );
+ },
+
+ slice: function() {
+ return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function(elem, i){
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ andSelf: function() {
+ return this.add( this.prevObject );
+ },
+
+ data: function( key, value ){
+ var parts = key.split(".");
+ parts[1] = parts[1] ? "." + parts[1] : "";
+
+ if ( value === undefined ) {
+ var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+ if ( data === undefined && this.length )
+ data = jQuery.data( this[0], key );
+
+ return data === undefined && parts[1] ?
+ this.data( parts[0] ) :
+ data;
+ } else
+ return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
+ jQuery.data( this, key, value );
+ });
+ },
+
+ removeData: function( key ){
+ return this.each(function(){
+ jQuery.removeData( this, key );
+ });
+ },
+
+ domManip: function( args, table, reverse, callback ) {
+ var clone = this.length > 1, elems;
+
+ return this.each(function(){
+ if ( !elems ) {
+ elems = jQuery.clean( args, this.ownerDocument );
+
+ if ( reverse )
+ elems.reverse();
+ }
+
+ var obj = this;
+
+ if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) )
+ obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") );
+
+ var scripts = jQuery( [] );
+
+ jQuery.each(elems, function(){
+ var elem = clone ?
+ jQuery( this ).clone( true )[0] :
+ this;
+
+ // execute all scripts after the elements have been injected
+ if ( jQuery.nodeName( elem, "script" ) )
+ scripts = scripts.add( elem );
+ else {
+ // Remove any inner scripts for later evaluation
+ if ( elem.nodeType == 1 )
+ scripts = scripts.add( jQuery( "script", elem ).remove() );
+
+ // Inject the elements into the document
+ callback.call( obj, elem );
+ }
+ });
+
+ scripts.each( evalScript );
+ });
+ }
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+function evalScript( i, elem ) {
+ if ( elem.src )
+ jQuery.ajax({
+ url: elem.src,
+ async: false,
+ dataType: "script"
+ });
+
+ else
+ jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
+
+ if ( elem.parentNode )
+ elem.parentNode.removeChild( elem );
+}
+
+function now(){
+ return +new Date;
+}
+
+jQuery.extend = jQuery.fn.extend = function() {
+ // copy reference to target object
+ var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
+
+ // Handle a deep copy situation
+ if ( target.constructor == Boolean ) {
+ deep = target;
+ target = arguments[1] || {};
+ // skip the boolean and the target
+ i = 2;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target != "object" && typeof target != "function" )
+ target = {};
+
+ // extend jQuery itself if only one argument is passed
+ if ( length == i ) {
+ target = this;
+ --i;
+ }
+
+ for ( ; i < length; i++ )
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null )
+ // Extend the base object
+ for ( var name in options ) {
+ var src = target[ name ], copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy )
+ continue;
+
+ // Recurse if we're merging object values
+ if ( deep && copy && typeof copy == "object" && !copy.nodeType )
+ target[ name ] = jQuery.extend( deep,
+ // Never move original objects, clone them
+ src || ( copy.length != null ? [ ] : { } )
+ , copy );
+
+ // Don't bring in undefined values
+ else if ( copy !== undefined )
+ target[ name ] = copy;
+
+ }
+
+ // Return the modified object
+ return target;
+};
+
+var expando = "jQuery" + now(), uuid = 0, windowData = {},
+ // exclude the following css properties to add px
+ exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
+ // cache defaultView
+ defaultView = document.defaultView || {};
+
+jQuery.extend({
+ noConflict: function( deep ) {
+ window.$ = _$;
+
+ if ( deep )
+ window.jQuery = _jQuery;
+
+ return jQuery;
+ },
+
+ // See test/unit/core.js for details concerning this function.
+ isFunction: function( fn ) {
+ return !!fn && typeof fn != "string" && !fn.nodeName &&
+ fn.constructor != Array && /^[\s[]?function/.test( fn + "" );
+ },
+
+ // check if an element is in a (or is an) XML document
+ isXMLDoc: function( elem ) {
+ return elem.documentElement && !elem.body ||
+ elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
+ },
+
+ // Evalulates a script in a global context
+ globalEval: function( data ) {
+ data = jQuery.trim( data );
+
+ if ( data ) {
+ // Inspired by code by Andrea Giammarchi
+ // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+ var head = document.getElementsByTagName("head")[0] || document.documentElement,
+ script = document.createElement("script");
+
+ script.type = "text/javascript";
+ if ( jQuery.browser.msie )
+ script.text = data;
+ else
+ script.appendChild( document.createTextNode( data ) );
+
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709).
+ head.insertBefore( script, head.firstChild );
+ head.removeChild( script );
+ }
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
+ },
+
+ cache: {},
+
+ data: function( elem, name, data ) {
+ elem = elem == window ?
+ windowData :
+ elem;
+
+ var id = elem[ expando ];
+
+ // Compute a unique ID for the element
+ if ( !id )
+ id = elem[ expando ] = ++uuid;
+
+ // Only generate the data cache if we're
+ // trying to access or manipulate it
+ if ( name && !jQuery.cache[ id ] )
+ jQuery.cache[ id ] = {};
+
+ // Prevent overriding the named cache with undefined values
+ if ( data !== undefined )
+ jQuery.cache[ id ][ name ] = data;
+
+ // Return the named cache data, or the ID for the element
+ return name ?
+ jQuery.cache[ id ][ name ] :
+ id;
+ },
+
+ removeData: function( elem, name ) {
+ elem = elem == window ?
+ windowData :
+ elem;
+
+ var id = elem[ expando ];
+
+ // If we want to remove a specific section of the element's data
+ if ( name ) {
+ if ( jQuery.cache[ id ] ) {
+ // Remove the section of cache data
+ delete jQuery.cache[ id ][ name ];
+
+ // If we've removed all the data, remove the element's cache
+ name = "";
+
+ for ( name in jQuery.cache[ id ] )
+ break;
+
+ if ( !name )
+ jQuery.removeData( elem );
+ }
+
+ // Otherwise, we want to remove all of the element's data
+ } else {
+ // Clean up the element expando
+ try {
+ delete elem[ expando ];
+ } catch(e){
+ // IE has trouble directly removing the expando
+ // but it's ok with using removeAttribute
+ if ( elem.removeAttribute )
+ elem.removeAttribute( expando );
+ }
+
+ // Completely remove the data cache
+ delete jQuery.cache[ id ];
+ }
+ },
+
+ // args is for internal usage only
+ each: function( object, callback, args ) {
+ var name, i = 0, length = object.length;
+
+ if ( args ) {
+ if ( length == undefined ) {
+ for ( name in object )
+ if ( callback.apply( object[ name ], args ) === false )
+ break;
+ } else
+ for ( ; i < length; )
+ if ( callback.apply( object[ i++ ], args ) === false )
+ break;
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( length == undefined ) {
+ for ( name in object )
+ if ( callback.call( object[ name ], name, object[ name ] ) === false )
+ break;
+ } else
+ for ( var value = object[0];
+ i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
+ }
+
+ return object;
+ },
+
+ prop: function( elem, value, type, i, name ) {
+ // Handle executable functions
+ if ( jQuery.isFunction( value ) )
+ value = value.call( elem, i );
+
+ // Handle passing in a number to a CSS property
+ return value && value.constructor == Number && type == "curCSS" && !exclude.test( name ) ?
+ value + "px" :
+ value;
+ },
+
+ className: {
+ // internal only, use addClass("class")
+ add: function( elem, classNames ) {
+ jQuery.each((classNames || "").split(/\s+/), function(i, className){
+ if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
+ elem.className += (elem.className ? " " : "") + className;
+ });
+ },
+
+ // internal only, use removeClass("class")
+ remove: function( elem, classNames ) {
+ if (elem.nodeType == 1)
+ elem.className = classNames != undefined ?
+ jQuery.grep(elem.className.split(/\s+/), function(className){
+ return !jQuery.className.has( classNames, className );
+ }).join(" ") :
+ "";
+ },
+
+ // internal only, use hasClass("class")
+ has: function( elem, className ) {
+ return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
+ }
+ },
+
+ // A method for quickly swapping in/out CSS properties to get correct calculations
+ swap: function( elem, options, callback ) {
+ var old = {};
+ // Remember the old values, and insert the new ones
+ for ( var name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ callback.call( elem );
+
+ // Revert the old values
+ for ( var name in options )
+ elem.style[ name ] = old[ name ];
+ },
+
+ css: function( elem, name, force ) {
+ if ( name == "width" || name == "height" ) {
+ var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
+
+ function getWH() {
+ val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
+ var padding = 0, border = 0;
+ jQuery.each( which, function() {
+ padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
+ border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
+ });
+ val -= Math.round(padding + border);
+ }
+
+ if ( jQuery(elem).is(":visible") )
+ getWH();
+ else
+ jQuery.swap( elem, props, getWH );
+
+ return Math.max(0, val);
+ }
+
+ return jQuery.curCSS( elem, name, force );
+ },
+
+ curCSS: function( elem, name, force ) {
+ var ret, style = elem.style;
+
+ // A helper method for determining if an element's values are broken
+ function color( elem ) {
+ if ( !jQuery.browser.safari )
+ return false;
+
+ // defaultView is cached
+ var ret = defaultView.getComputedStyle( elem, null );
+ return !ret || ret.getPropertyValue("color") == "";
+ }
+
+ // We need to handle opacity special in IE
+ if ( name == "opacity" && jQuery.browser.msie ) {
+ ret = jQuery.attr( style, "opacity" );
+
+ return ret == "" ?
+ "1" :
+ ret;
+ }
+ // Opera sometimes will give the wrong display answer, this fixes it, see #2037
+ if ( jQuery.browser.opera && name == "display" ) {
+ var save = style.outline;
+ style.outline = "0 solid black";
+ style.outline = save;
+ }
+
+ // Make sure we're using the right name for getting the float value
+ if ( name.match( /float/i ) )
+ name = styleFloat;
+
+ if ( !force && style && style[ name ] )
+ ret = style[ name ];
+
+ else if ( defaultView.getComputedStyle ) {
+
+ // Only "float" is needed here
+ if ( name.match( /float/i ) )
+ name = "float";
+
+ name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
+
+ var computedStyle = defaultView.getComputedStyle( elem, null );
+
+ if ( computedStyle && !color( elem ) )
+ ret = computedStyle.getPropertyValue( name );
+
+ // If the element isn't reporting its values properly in Safari
+ // then some display: none elements are involved
+ else {
+ var swap = [], stack = [], a = elem, i = 0;
+
+ // Locate all of the parent display: none elements
+ for ( ; a && color(a); a = a.parentNode )
+ stack.unshift(a);
+
+ // Go through and make them visible, but in reverse
+ // (It would be better if we knew the exact display type that they had)
+ for ( ; i < stack.length; i++ )
+ if ( color( stack[ i ] ) ) {
+ swap[ i ] = stack[ i ].style.display;
+ stack[ i ].style.display = "block";
+ }
+
+ // Since we flip the display style, we have to handle that
+ // one special, otherwise get the value
+ ret = name == "display" && swap[ stack.length - 1 ] != null ?
+ "none" :
+ ( computedStyle && computedStyle.getPropertyValue( name ) ) || "";
+
+ // Finally, revert the display styles back
+ for ( i = 0; i < swap.length; i++ )
+ if ( swap[ i ] != null )
+ stack[ i ].style.display = swap[ i ];
+ }
+
+ // We should always get a number back from opacity
+ if ( name == "opacity" && ret == "" )
+ ret = "1";
+
+ } else if ( elem.currentStyle ) {
+ var camelCase = name.replace(/\-(\w)/g, function(all, letter){
+ return letter.toUpperCase();
+ });
+
+ ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
+
+ // From the awesome hack by Dean Edwards
+ // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+ // If we're not dealing with a regular pixel number
+ // but a number that has a weird ending, we need to convert it to pixels
+ if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
+ // Remember the original values
+ var left = style.left, rsLeft = elem.runtimeStyle.left;
+
+ // Put in the new values to get a computed value out
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ style.left = ret || 0;
+ ret = style.pixelLeft + "px";
+
+ // Revert the changed values
+ style.left = left;
+ elem.runtimeStyle.left = rsLeft;
+ }
+ }
+
+ return ret;
+ },
+
+ clean: function( elems, context ) {
+ var ret = [];
+ context = context || document;
+ // !context.createElement fails in IE with an error but returns typeof 'object'
+ if (typeof context.createElement == 'undefined')
+ context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+
+ jQuery.each(elems, function(i, elem){
+ if ( !elem )
+ return;
+
+ if ( elem.constructor == Number )
+ elem += '';
+
+ // Convert html string into DOM nodes
+ if ( typeof elem == "string" ) {
+ // Fix "XHTML"-style tags in all browsers
+ elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
+ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
+ all :
+ front + "></" + tag + ">";
+ });
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div");
+
+ var wrap =
+ // option or optgroup
+ !tags.indexOf("<opt") &&
+ [ 1, "<select multiple='multiple'>", "</select>" ] ||
+
+ !tags.indexOf("<leg") &&
+ [ 1, "<fieldset>", "</fieldset>" ] ||
+
+ tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
+ [ 1, "<table>", "</table>" ] ||
+
+ !tags.indexOf("<tr") &&
+ [ 2, "<table><tbody>", "</tbody></table>" ] ||
+
+ // <thead> matched above
+ (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
+ [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
+
+ !tags.indexOf("<col") &&
+ [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
+
+ // IE can't serialize <link> and <script> tags normally
+ jQuery.browser.msie &&
+ [ 1, "div<div>", "</div>" ] ||
+
+ [ 0, "", "" ];
+
+ // Go to html and back, then peel off extra wrappers
+ div.innerHTML = wrap[1] + elem + wrap[2];
+
+ // Move to the right depth
+ while ( wrap[0]-- )
+ div = div.lastChild;
+
+ // Remove IE's autoinserted <tbody> from table fragments
+ if ( jQuery.browser.msie ) {
+
+ // String was a <table>, *may* have spurious <tbody>
+ var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
+ div.firstChild && div.firstChild.childNodes :
+
+ // String was a bare <thead> or <tfoot>
+ wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
+ div.childNodes :
+ [];
+
+ for ( var j = tbody.length - 1; j >= 0 ; --j )
+ if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
+ tbody[ j ].parentNode.removeChild( tbody[ j ] );
+
+ // IE completely kills leading whitespace when innerHTML is used
+ if ( /^\s/.test( elem ) )
+ div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
+
+ }
+
+ elem = jQuery.makeArray( div.childNodes );
+ }
+
+ if ( elem.length === 0 && (!jQuery.nodeName( elem, "form" ) && !jQuery.nodeName( elem, "select" )) )
+ return;
+
+ if ( elem[0] == undefined || jQuery.nodeName( elem, "form" ) || elem.options )
+ ret.push( elem );
+
+ else
+ ret = jQuery.merge( ret, elem );
+
+ });
+
+ return ret;
+ },
+
+ attr: function( elem, name, value ) {
+ // don't set attributes on text and comment nodes
+ if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
+ return undefined;
+
+ var notxml = !jQuery.isXMLDoc( elem ),
+ // Whether we are setting (or getting)
+ set = value !== undefined,
+ msie = jQuery.browser.msie;
+
+ // Try to normalize/fix the name
+ name = notxml && jQuery.props[ name ] || name;
+
+ // Only do all the following if this is a node (faster for style)
+ // IE elem.getAttribute passes even for style
+ if ( elem.tagName ) {
+
+ // These attributes require special treatment
+ var special = /href|src|style/.test( name );
+
+ // Safari mis-reports the default selected property of a hidden option
+ // Accessing the parent's selectedIndex property fixes it
+ if ( name == "selected" && jQuery.browser.safari )
+ elem.parentNode.selectedIndex;
+
+ // If applicable, access the attribute via the DOM 0 way
+ if ( name in elem && notxml && !special ) {
+ if ( set ){
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
+ throw "type property can't be changed";
+
+ elem[ name ] = value;
+ }
+
+ // browsers index elements by id/name on forms, give priority to attributes.
+ if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
+ return elem.getAttributeNode( name ).nodeValue;
+
+ return elem[ name ];
+ }
+
+ if ( msie && notxml && name == "style" )
+ return jQuery.attr( elem.style, "cssText", value );
+
+ if ( set )
+ // convert the value to a string (all browsers do this but IE) see #1070
+ elem.setAttribute( name, "" + value );
+
+ var attr = msie && notxml && special
+ // Some attributes require a special call on IE
+ ? elem.getAttribute( name, 2 )
+ : elem.getAttribute( name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return attr === null ? undefined : attr;
+ }
+
+ // elem is actually elem.style ... set the style
+
+ // IE uses filters for opacity
+ if ( msie && name == "opacity" ) {
+ if ( set ) {
+ // IE has trouble with opacity if it does not have layout
+ // Force it by setting the zoom level
+ elem.zoom = 1;
+
+ // Set the alpha filter to set the opacity
+ elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
+ (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
+ }
+
+ return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
+ (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
+ "";
+ }
+
+ name = name.replace(/-([a-z])/ig, function(all, letter){
+ return letter.toUpperCase();
+ });
+
+ if ( set )
+ elem[ name ] = value;
+
+ return elem[ name ];
+ },
+
+ trim: function( text ) {
+ return (text || "").replace( /^\s+|\s+$/g, "" );
+ },
+
+ makeArray: function( array ) {
+ var ret = [];
+
+ if( array != null ){
+ var i = array.length;
+ //the window, strings and functions also have 'length'
+ if( i == null || array.split || array.setInterval || array.call )
+ ret[0] = array;
+ else
+ while( i )
+ ret[--i] = array[i];
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, array ) {
+ for ( var i = 0, length = array.length; i < length; i++ )
+ // Use === because on IE, window == document
+ if ( array[ i ] === elem )
+ return i;
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ // We have to loop this way because IE & Opera overwrite the length
+ // expando of getElementsByTagName
+ var i = 0, elem, pos = first.length;
+ // Also, we need to make sure that the correct elements are being returned
+ // (IE returns comment nodes in a '*' query)
+ if ( jQuery.browser.msie ) {
+ while ( elem = second[ i++ ] )
+ if ( elem.nodeType != 8 )
+ first[ pos++ ] = elem;
+
+ } else
+ while ( elem = second[ i++ ] )
+ first[ pos++ ] = elem;
+
+ return first;
+ },
+
+ unique: function( array ) {
+ var ret = [], done = {};
+
+ try {
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ var id = jQuery.data( array[ i ] );
+
+ if ( !done[ id ] ) {
+ done[ id ] = true;
+ ret.push( array[ i ] );
+ }
+ }
+
+ } catch( e ) {
+ ret = array;
+ }
+
+ return ret;
+ },
+
+ grep: function( elems, callback, inv ) {
+ var ret = [];
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, length = elems.length; i < length; i++ )
+ if ( !inv != !callback( elems[ i ], i ) )
+ ret.push( elems[ i ] );
+
+ return ret;
+ },
+
+ map: function( elems, callback ) {
+ var ret = [];
+
+ // Go through the array, translating each of the items to their
+ // new value (or values).
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ var value = callback( elems[ i ], i );
+
+ if ( value != null )
+ ret[ ret.length ] = value;
+ }
+
+ return ret.concat.apply( [], ret );
+ }
+});
+
+var userAgent = navigator.userAgent.toLowerCase();
+
+// Figure out what browser is being used
+jQuery.browser = {
+ version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
+ safari: /webkit/.test( userAgent ),
+ opera: /opera/.test( userAgent ),
+ msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
+ mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
+};
+
+var styleFloat = jQuery.browser.msie ?
+ "styleFloat" :
+ "cssFloat";
+
+jQuery.extend({
+ // Check to see if the W3C box model is being used
+ boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",
+
+ props: {
+ "for": "htmlFor",
+ "class": "className",
+ "float": styleFloat,
+ cssFloat: styleFloat,
+ styleFloat: styleFloat,
+ readonly: "readOnly",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing"
+ }
+});
+
+jQuery.each({
+ parent: function(elem){return elem.parentNode;},
+ parents: function(elem){return jQuery.dir(elem,"parentNode");},
+ next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
+ prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
+ nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
+ prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
+ siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
+ children: function(elem){return jQuery.sibling(elem.firstChild);},
+ contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
+}, function(name, fn){
+ jQuery.fn[ name ] = function( selector ) {
+ var ret = jQuery.map( this, fn );
+
+ if ( selector && typeof selector == "string" )
+ ret = jQuery.multiFilter( selector, ret );
+
+ return this.pushStack( jQuery.unique( ret ) );
+ };
+});
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function(name, original){
+ jQuery.fn[ name ] = function() {
+ var args = arguments;
+
+ return this.each(function(){
+ for ( var i = 0, length = args.length; i < length; i++ )
+ jQuery( args[ i ] )[ original ]( this );
+ });
+ };
+});
+
+jQuery.each({
+ removeAttr: function( name ) {
+ jQuery.attr( this, name, "" );
+ if (this.nodeType == 1)
+ this.removeAttribute( name );
+ },
+
+ addClass: function( classNames ) {
+ jQuery.className.add( this, classNames );
+ },
+
+ removeClass: function( classNames ) {
+ jQuery.className.remove( this, classNames );
+ },
+
+ toggleClass: function( classNames ) {
+ jQuery.className[ jQuery.className.has( this, classNames ) ? "remove" : "add" ]( this, classNames );
+ },
+
+ remove: function( selector ) {
+ if ( !selector || jQuery.filter( selector, [ this ] ).r.length ) {
+ // Prevent memory leaks
+ jQuery( "*", this ).add(this).each(function(){
+ jQuery.event.remove(this);
+ jQuery.removeData(this);
+ });
+ if (this.parentNode)
+ this.parentNode.removeChild( this );
+ }
+ },
+
+ empty: function() {
+ // Remove element nodes and prevent memory leaks
+ jQuery( ">*", this ).remove();
+
+ // Remove any remaining nodes
+ while ( this.firstChild )
+ this.removeChild( this.firstChild );
+ }
+}, function(name, fn){
+ jQuery.fn[ name ] = function(){
+ return this.each( fn, arguments );
+ };
+});
+
+jQuery.each([ "Height", "Width" ], function(i, name){
+ var type = name.toLowerCase();
+
+ jQuery.fn[ type ] = function( size ) {
+ // Get window width or height
+ return this[0] == window ?
+ // Opera reports document.body.client[Width/Height] properly in both quirks and standards
+ jQuery.browser.opera && document.body[ "client" + name ] ||
+
+ // Safari reports inner[Width/Height] just fine (Mozilla and Opera include scroll bar widths)
+ jQuery.browser.safari && window[ "inner" + name ] ||
+
+ // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+ document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] :
+
+ // Get document width or height
+ this[0] == document ?
+ // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+ Math.max(
+ Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
+ Math.max(document.body["offset" + name], document.documentElement["offset" + name])
+ ) :
+
+ // Get or set width or height on the element
+ size == undefined ?
+ // Get width or height on the element
+ (this.length ? jQuery.css( this[0], type ) : null) :
+
+ // Set the width or height on the element (default to pixels if value is unitless)
+ this.css( type, size.constructor == String ? size : size + "px" );
+ };
+});
+
+// Helper function used by the dimensions and offset modules
+function num(elem, prop) {
+ return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
+}var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
+ "(?:[\\w*_-]|\\\\.)" :
+ "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
+ quickChild = new RegExp("^>\\s*(" + chars + "+)"),
+ quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
+ quickClass = new RegExp("^([#.]?)(" + chars + "*)");
+
+jQuery.extend({
+ expr: {
+ "": function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},
+ "#": function(a,i,m){return a.getAttribute("id")==m[2];},
+ ":": {
+ // Position Checks
+ lt: function(a,i,m){return i<m[3]-0;},
+ gt: function(a,i,m){return i>m[3]-0;},
+ nth: function(a,i,m){return m[3]-0==i;},
+ eq: function(a,i,m){return m[3]-0==i;},
+ first: function(a,i){return i==0;},
+ last: function(a,i,m,r){return i==r.length-1;},
+ even: function(a,i){return i%2==0;},
+ odd: function(a,i){return i%2;},
+
+ // Child Checks
+ "first-child": function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},
+ "last-child": function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},
+ "only-child": function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},
+
+ // Parent Checks
+ parent: function(a){return a.firstChild;},
+ empty: function(a){return !a.firstChild;},
+
+ // Text Check
+ contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},
+
+ // Visibility
+ visible: function(a){return "hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},
+ hidden: function(a){return "hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},
+
+ // Form attributes
+ enabled: function(a){return !a.disabled;},
+ disabled: function(a){return a.disabled;},
+ checked: function(a){return a.checked;},
+ selected: function(a){return a.selected||jQuery.attr(a,"selected");},
+
+ // Form elements
+ text: function(a){return "text"==a.type;},
+ radio: function(a){return "radio"==a.type;},
+ checkbox: function(a){return "checkbox"==a.type;},
+ file: function(a){return "file"==a.type;},
+ password: function(a){return "password"==a.type;},
+ submit: function(a){return "submit"==a.type;},
+ image: function(a){return "image"==a.type;},
+ reset: function(a){return "reset"==a.type;},
+ button: function(a){return "button"==a.type||jQuery.nodeName(a,"button");},
+ input: function(a){return /input|select|textarea|button/i.test(a.nodeName);},
+
+ // :has()
+ has: function(a,i,m){return jQuery.find(m[3],a).length;},
+
+ // :header
+ header: function(a){return /h\d/i.test(a.nodeName);},
+
+ // :animated
+ animated: function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}
+ }
+ },
+
+ // The regular expressions that power the parsing engine
+ parse: [
+ // Match: [@value='test'], [@foo]
+ /^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,
+
+ // Match: :contains('foo')
+ /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
+
+ // Match: :even, :last-child, #id, .class
+ new RegExp("^([:.#]*)(" + chars + "+)")
+ ],
+
+ multiFilter: function( expr, elems, not ) {
+ var old, cur = [];
+
+ while ( expr && expr != old ) {
+ old = expr;
+ var f = jQuery.filter( expr, elems, not );
+ expr = f.t.replace(/^\s*,\s*/, "" );
+ cur = not ? elems = f.r : jQuery.merge( cur, f.r );
+ }
+
+ return cur;
+ },
+
+ find: function( t, context ) {
+ // Quickly handle non-string expressions
+ if ( typeof t != "string" )
+ return [ t ];
+
+ // check to make sure context is a DOM element or a document
+ if ( context && context.nodeType != 1 && context.nodeType != 9)
+ return [ ];
+
+ // Set the correct context (if none is provided)
+ context = context || document;
+
+ // Initialize the search
+ var ret = [context], done = [], last, nodeName;
+
+ // Continue while a selector expression exists, and while
+ // we're no longer looping upon ourselves
+ while ( t && last != t ) {
+ var r = [];
+ last = t;
+
+ t = jQuery.trim(t);
+
+ var foundToken = false,
+
+ // An attempt at speeding up child selectors that
+ // point to a specific element tag
+ re = quickChild,
+
+ m = re.exec(t);
+
+ if ( m ) {
+ nodeName = m[1].toUpperCase();
+
+ // Perform our own iteration and filter
+ for ( var i = 0; ret[i]; i++ )
+ for ( var c = ret[i].firstChild; c; c = c.nextSibling )
+ if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
+ r.push( c );
+
+ ret = r;
+ t = t.replace( re, "" );
+ if ( t.indexOf(" ") == 0 ) continue;
+ foundToken = true;
+ } else {
+ re = /^([>+~])\s*(\w*)/i;
+
+ if ( (m = re.exec(t)) != null ) {
+ r = [];
+
+ var merge = {};
+ nodeName = m[2].toUpperCase();
+ m = m[1];
+
+ for ( var j = 0, rl = ret.length; j < rl; j++ ) {
+ var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
+ for ( ; n; n = n.nextSibling )
+ if ( n.nodeType == 1 ) {
+ var id = jQuery.data(n);
+
+ if ( m == "~" && merge[id] ) break;
+
+ if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
+ if ( m == "~" ) merge[id] = true;
+ r.push( n );
+ }
+
+ if ( m == "+" ) break;
+ }
+ }
+
+ ret = r;
+
+ // And remove the token
+ t = jQuery.trim( t.replace( re, "" ) );
+ foundToken = true;
+ }
+ }
+
+ // See if there's still an expression, and that we haven't already
+ // matched a token
+ if ( t && !foundToken ) {
+ // Handle multiple expressions
+ if ( !t.indexOf(",") ) {
+ // Clean the result set
+ if ( context == ret[0] ) ret.shift();
+
+ // Merge the result sets
+ done = jQuery.merge( done, ret );
+
+ // Reset the context
+ r = ret = [context];
+
+ // Touch up the selector string
+ t = " " + t.substr(1,t.length);
+
+ } else {
+ // Optimize for the case nodeName#idName
+ var re2 = quickID;
+ var m = re2.exec(t);
+
+ // Re-organize the results, so that they're consistent
+ if ( m ) {
+ m = [ 0, m[2], m[3], m[1] ];
+
+ } else {
+ // Otherwise, do a traditional filter check for
+ // ID, class, and element selectors
+ re2 = quickClass;
+ m = re2.exec(t);
+ }
+
+ m[2] = m[2].replace(/\\/g, "");
+
+ var elem = ret[ret.length-1];
+
+ // Try to do a global search by ID, where we can
+ if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
+ // Optimization for HTML document case
+ var oid = elem.getElementById(m[2]);
+
+ // Do a quick check for the existence of the actual ID attribute
+ // to avoid selecting by the name attribute in IE
+ // also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
+ if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
+ oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
+
+ // Do a quick check for node name (where applicable) so
+ // that div#foo searches will be really fast
+ ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
+ } else {
+ // We need to find all descendant elements
+ for ( var i = 0; ret[i]; i++ ) {
+ // Grab the tag name being searched for
+ var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];
+
+ // Handle IE7 being really dumb about <object>s
+ if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
+ tag = "param";
+
+ r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
+ }
+
+ // It's faster to filter by class and be done with it
+ if ( m[1] == "." )
+ r = jQuery.classFilter( r, m[2] );
+
+ // Same with ID filtering
+ if ( m[1] == "#" ) {
+ var tmp = [];
+
+ // Try to find the element with the ID
+ for ( var i = 0; r[i]; i++ )
+ if ( r[i].getAttribute("id") == m[2] ) {
+ tmp = [ r[i] ];
+ break;
+ }
+
+ r = tmp;
+ }
+
+ ret = r;
+ }
+
+ t = t.replace( re2, "" );
+ }
+
+ }
+
+ // If a selector string still exists
+ if ( t ) {
+ // Attempt to filter it
+ var val = jQuery.filter(t,r);
+ ret = r = val.r;
+ t = jQuery.trim(val.t);
+ }
+ }
+
+ // An error occurred with the selector;
+ // just return an empty set instead
+ if ( t )
+ ret = [];
+
+ // Remove the root context
+ if ( ret && context == ret[0] )
+ ret.shift();
+
+ // And combine the results
+ done = jQuery.merge( done, ret );
+
+ return done;
+ },
+
+ classFilter: function(r,m,not){
+ m = " " + m + " ";
+ var tmp = [];
+ for ( var i = 0; r[i]; i++ ) {
+ var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
+ if ( !not && pass || not && !pass )
+ tmp.push( r[i] );
+ }
+ return tmp;
+ },
+
+ filter: function(t,r,not) {
+ var last;
+
+ // Look for common filter expressions
+ while ( t && t != last ) {
+ last = t;
+
+ var p = jQuery.parse, m;
+
+ for ( var i = 0; p[i]; i++ ) {
+ m = p[i].exec( t );
+
+ if ( m ) {
+ // Remove what we just matched
+ t = t.substring( m[0].length );
+
+ m[2] = m[2].replace(/\\/g, "");
+ break;
+ }
+ }
+
+ if ( !m )
+ break;
+
+ // :not() is a special case that can be optimized by
+ // keeping it out of the expression list
+ if ( m[1] == ":" && m[2] == "not" )
+ // optimize if only one selector found (most common case)
+ r = isSimple.test( m[3] ) ?
+ jQuery.filter(m[3], r, true).r :
+ jQuery( r ).not( m[3] );
+
+ // We can get a big speed boost by filtering by class here
+ else if ( m[1] == "." )
+ r = jQuery.classFilter(r, m[2], not);
+
+ else if ( m[1] == "[" ) {
+ var tmp = [], type = m[3];
+
+ for ( var i = 0, rl = r.length; i < rl; i++ ) {
+ var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];
+
+ if ( z == null || /href|src|selected/.test(m[2]) )
+ z = jQuery.attr(a,m[2]) || '';
+
+ if ( (type == "" && !!z ||
+ type == "=" && z == m[5] ||
+ type == "!=" && z != m[5] ||
+ type == "^=" && z && !z.indexOf(m[5]) ||
+ type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
+ (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
+ tmp.push( a );
+ }
+
+ r = tmp;
+
+ // We can get a speed boost by handling nth-child here
+ } else if ( m[1] == ":" && m[2] == "nth-child" ) {
+ var merge = {}, tmp = [],
+ // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+ test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+ m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
+ !/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
+ // calculate the numbers (first)n+(last) including if they are negative
+ first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;
+
+ // loop through all the elements left in the jQuery object
+ for ( var i = 0, rl = r.length; i < rl; i++ ) {
+ var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);
+
+ if ( !merge[id] ) {
+ var c = 1;
+
+ for ( var n = parentNode.firstChild; n; n = n.nextSibling )
+ if ( n.nodeType == 1 )
+ n.nodeIndex = c++;
+
+ merge[id] = true;
+ }
+
+ var add = false;
+
+ if ( first == 0 ) {
+ if ( node.nodeIndex == last )
+ add = true;
+ } else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
+ add = true;
+
+ if ( add ^ not )
+ tmp.push( node );
+ }
+
+ r = tmp;
+
+ // Otherwise, find the expression to execute
+ } else {
+ var fn = jQuery.expr[ m[1] ];
+ if ( typeof fn == "object" )
+ fn = fn[ m[2] ];
+
+ if ( typeof fn == "string" )
+ fn = eval("false||function(a,i){return " + fn + ";}");
+
+ // Execute it against the current filter
+ r = jQuery.grep( r, function(elem, i){
+ return fn(elem, i, m, r);
+ }, not );
+ }
+ }
+
+ // Return an array of filtered elements (r)
+ // and the modified expression string (t)
+ return { r: r, t: t };
+ },
+
+ dir: function( elem, dir ){
+ var matched = [],
+ cur = elem[dir];
+ while ( cur && cur != document ) {
+ if ( cur.nodeType == 1 )
+ matched.push( cur );
+ cur = cur[dir];
+ }
+ return matched;
+ },
+
+ nth: function(cur,result,dir,elem){
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] )
+ if ( cur.nodeType == 1 && ++num == result )
+ break;
+
+ return cur;
+ },
+
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType == 1 && n != elem )
+ r.push( n );
+ }
+
+ return r;
+ }
+});
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code orignated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function(elem, types, handler, data) {
+ if ( elem.nodeType == 3 || elem.nodeType == 8 )
+ return;
+
+ // For whatever reason, IE has trouble passing the window object
+ // around, causing it to be cloned in the process
+ if ( jQuery.browser.msie && elem.setInterval )
+ elem = window;
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid )
+ handler.guid = this.guid++;
+
+ // if data is passed, bind to handler
+ if( data != undefined ) {
+ // Create temporary function pointer to original handler
+ var fn = handler;
+
+ // Create unique handler function, wrapped around original handler
+ handler = this.proxy( fn, function() {
+ // Pass arguments and context to original handler
+ return fn.apply(this, arguments);
+ });
+
+ // Store data in unique handler
+ handler.data = data;
+ }
+
+ // Init the element's event structure
+ var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
+ handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
+ // Handle the second event of a trigger and when
+ // an event is called after a page has unloaded
+ if ( typeof jQuery != "undefined" && !jQuery.event.triggered )
+ return jQuery.event.handle.apply(arguments.callee.elem, arguments);
+ });
+ // Add elem as a property of the handle function
+ // This is to prevent a memory leak with non-native
+ // event in IE.
+ handle.elem = elem;
+
+ // Handle multiple events separated by a space
+ // jQuery(...).bind("mouseover mouseout", fn);
+ jQuery.each(types.split(/\s+/), function(index, type) {
+ // Namespaced event handlers
+ var parts = type.split(".");
+ type = parts[0];
+ handler.type = parts[1];
+
+ // Get the current list of functions bound to this event
+ var handlers = events[type];
+
+ // Init the event handler queue
+ if (!handlers) {
+ handlers = events[type] = {};
+
+ // Check for a special event handler
+ // Only use addEventListener/attachEvent if the special
+ // events handler returns false
+ if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
+ // Bind the global event handler to the element
+ if (elem.addEventListener)
+ elem.addEventListener(type, handle, false);
+ else if (elem.attachEvent)
+ elem.attachEvent("on" + type, handle);
+ }
+ }
+
+ // Add the function to the element's handler list
+ handlers[handler.guid] = handler;
+
+ // Keep track of which events have been used, for global triggering
+ jQuery.event.global[type] = true;
+ });
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ guid: 1,
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function(elem, types, handler) {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType == 3 || elem.nodeType == 8 )
+ return;
+
+ var events = jQuery.data(elem, "events"), ret, index;
+
+ if ( events ) {
+ // Unbind all events for the element
+ if ( types == undefined || (typeof types == "string" && types.charAt(0) == ".") )
+ for ( var type in events )
+ this.remove( elem, type + (types || "") );
+ else {
+ // types is actually an event object here
+ if ( types.type ) {
+ handler = types.handler;
+ types = types.type;
+ }
+
+ // Handle multiple events seperated by a space
+ // jQuery(...).unbind("mouseover mouseout", fn);
+ jQuery.each(types.split(/\s+/), function(index, type){
+ // Namespaced event handlers
+ var parts = type.split(".");
+ type = parts[0];
+
+ if ( events[type] ) {
+ // remove the given handler for the given type
+ if ( handler )
+ delete events[type][handler.guid];
+
+ // remove all handlers for the given type
+ else
+ for ( handler in events[type] )
+ // Handle the removal of namespaced events
+ if ( !parts[1] || events[type][handler].type == parts[1] )
+ delete events[type][handler];
+
+ // remove generic event handler if no more handlers exist
+ for ( ret in events[type] ) break;
+ if ( !ret ) {
+ if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
+ if (elem.removeEventListener)
+ elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
+ else if (elem.detachEvent)
+ elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
+ }
+ ret = null;
+ delete events[type];
+ }
+ }
+ });
+ }
+
+ // Remove the expando if it's no longer used
+ for ( ret in events ) break;
+ if ( !ret ) {
+ var handle = jQuery.data( elem, "handle" );
+ if ( handle ) handle.elem = null;
+ jQuery.removeData( elem, "events" );
+ jQuery.removeData( elem, "handle" );
+ }
+ }
+ },
+
+ trigger: function(type, data, elem, donative, extra) {
+ // Clone the incoming data, if any
+ data = jQuery.makeArray(data);
+
+ if ( type.indexOf("!") >= 0 ) {
+ type = type.slice(0, -1);
+ var exclusive = true;
+ }
+
+ // Handle a global trigger
+ if ( !elem ) {
+ // Only trigger if we've ever bound an event for it
+ if ( this.global[type] )
+ jQuery("*").add([window, document]).trigger(type, data);
+
+ // Handle triggering a single element
+ } else {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType == 3 || elem.nodeType == 8 )
+ return undefined;
+
+ var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
+ // Check to see if we need to provide a fake event, or not
+ event = !data[0] || !data[0].preventDefault;
+
+ // Pass along a fake event
+ if ( event ) {
+ data.unshift({
+ type: type,
+ target: elem,
+ preventDefault: function(){},
+ stopPropagation: function(){},
+ timeStamp: now()
+ });
+ data[0][expando] = true; // no need to fix fake event
+ }
+
+ // Enforce the right trigger type
+ data[0].type = type;
+ if ( exclusive )
+ data[0].exclusive = true;
+
+ // Trigger the event, it is assumed that "handle" is a function
+ var handle = jQuery.data(elem, "handle");
+ if ( handle )
+ val = handle.apply( elem, data );
+
+ // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
+ if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
+ val = false;
+
+ // Extra functions don't get the custom event object
+ if ( event )
+ data.shift();
+
+ // Handle triggering of extra function
+ if ( extra && jQuery.isFunction( extra ) ) {
+ // call the extra function and tack the current return value on the end for possible inspection
+ ret = extra.apply( elem, val == null ? data : data.concat( val ) );
+ // if anything is returned, give it precedence and have it overwrite the previous value
+ if (ret !== undefined)
+ val = ret;
+ }
+
+ // Trigger the native events (except for clicks on links)
+ if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
+ this.triggered = true;
+ try {
+ elem[ type ]();
+ // prevent IE from throwing an error for some hidden elements
+ } catch (e) {}
+ }
+
+ this.triggered = false;
+ }
+
+ return val;
+ },
+
+ handle: function(event) {
+ // returned undefined or false
+ var val, ret, namespace, all, handlers;
+
+ event = arguments[0] = jQuery.event.fix( event || window.event );
+
+ // Namespaced event handlers
+ namespace = event.type.split(".");
+ event.type = namespace[0];
+ namespace = namespace[1];
+ // Cache this now, all = true means, any handler
+ all = !namespace && !event.exclusive;
+
+ handlers = ( jQuery.data(this, "events") || {} )[event.type];
+
+ for ( var j in handlers ) {
+ var handler = handlers[j];
+
+ // Filter the functions by class
+ if ( all || handler.type == namespace ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ event.handler = handler;
+ event.data = handler.data;
+
+ ret = handler.apply( this, arguments );
+
+ if ( val !== false )
+ val = ret;
+
+ if ( ret === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+ }
+
+ return val;
+ },
+
+ fix: function(event) {
+ if ( event[expando] == true )
+ return event;
+
+ // store a copy of the original event object
+ // and "clone" to set read-only properties
+ var originalEvent = event;
+ event = { originalEvent: originalEvent };
+ var props = "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");
+ for ( var i=props.length; i; i-- )
+ event[ props[i] ] = originalEvent[ props[i] ];
+
+ // Mark it as fixed
+ event[expando] = true;
+
+ // add preventDefault and stopPropagation since
+ // they will not work on the clone
+ event.preventDefault = function() {
+ // if preventDefault exists run it on the original event
+ if (originalEvent.preventDefault)
+ originalEvent.preventDefault();
+ // otherwise set the returnValue property of the original event to false (IE)
+ originalEvent.returnValue = false;
+ };
+ event.stopPropagation = function() {
+ // if stopPropagation exists run it on the original event
+ if (originalEvent.stopPropagation)
+ originalEvent.stopPropagation();
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ originalEvent.cancelBubble = true;
+ };
+
+ // Fix timeStamp
+ event.timeStamp = event.timeStamp || now();
+
+ // Fix target property, if necessary
+ if ( !event.target )
+ event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
+
+ // check if target is a textnode (safari)
+ if ( event.target.nodeType == 3 )
+ event.target = event.target.parentNode;
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement )
+ event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var doc = document.documentElement, body = document.body;
+ event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
+ event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
+ }
+
+ // Add which for key events
+ if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
+ event.which = event.charCode || event.keyCode;
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey )
+ event.metaKey = event.ctrlKey;
+
+ // Add which for click: 1 == left; 2 == middle; 3 == right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button )
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+
+ return event;
+ },
+
+ proxy: function( fn, proxy ){
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
+ // So proxy can be declared as an argument
+ return proxy;
+ },
+
+ special: {
+ ready: {
+ setup: function() {
+ // Make sure the ready event is setup
+ bindReady();
+ return;
+ },
+
+ teardown: function() { return; }
+ },
+
+ mouseenter: {
+ setup: function() {
+ if ( jQuery.browser.msie ) return false;
+ jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
+ return true;
+ },
+
+ teardown: function() {
+ if ( jQuery.browser.msie ) return false;
+ jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
+ return true;
+ },
+
+ handler: function(event) {
+ // If we actually just moused on to a sub-element, ignore it
+ if ( withinElement(event, this) ) return true;
+ // Execute the right handlers by setting the event type to mouseenter
+ event.type = "mouseenter";
+ return jQuery.event.handle.apply(this, arguments);
+ }
+ },
+
+ mouseleave: {
+ setup: function() {
+ if ( jQuery.browser.msie ) return false;
+ jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
+ return true;
+ },
+
+ teardown: function() {
+ if ( jQuery.browser.msie ) return false;
+ jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
+ return true;
+ },
+
+ handler: function(event) {
+ // If we actually just moused on to a sub-element, ignore it
+ if ( withinElement(event, this) ) return true;
+ // Execute the right handlers by setting the event type to mouseleave
+ event.type = "mouseleave";
+ return jQuery.event.handle.apply(this, arguments);
+ }
+ }
+ }
+};
+
+jQuery.fn.extend({
+ bind: function( type, data, fn ) {
+ return type == "unload" ? this.one(type, data, fn) : this.each(function(){
+ jQuery.event.add( this, type, fn || data, fn && data );
+ });
+ },
+
+ one: function( type, data, fn ) {
+ var one = jQuery.event.proxy( fn || data, function(event) {
+ jQuery(this).unbind(event, one);
+ return (fn || data).apply( this, arguments );
+ });
+ return this.each(function(){
+ jQuery.event.add( this, type, one, fn && data);
+ });
+ },
+
+ unbind: function( type, fn ) {
+ return this.each(function(){
+ jQuery.event.remove( this, type, fn );
+ });
+ },
+
+ trigger: function( type, data, fn ) {
+ return this.each(function(){
+ jQuery.event.trigger( type, data, this, true, fn );
+ });
+ },
+
+ triggerHandler: function( type, data, fn ) {
+ return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
+ },
+
+ toggle: function( fn ) {
+ // Save reference to arguments for access in closure
+ var args = arguments, i = 1;
+
+ // link all the functions, so any of them can unbind this click handler
+ while( i < args.length )
+ jQuery.event.proxy( fn, args[i++] );
+
+ return this.click( jQuery.event.proxy( fn, function(event) {
+ // Figure out which function to execute
+ this.lastToggle = ( this.lastToggle || 0 ) % i;
+
+ // Make sure that clicks stop
+ event.preventDefault();
+
+ // and execute the function
+ return args[ this.lastToggle++ ].apply( this, arguments ) || false;
+ }));
+ },
+
+ hover: function(fnOver, fnOut) {
+ return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
+ },
+
+ ready: function(fn) {
+ // Attach the listeners
+ bindReady();
+
+ // If the DOM is already ready
+ if ( jQuery.isReady )
+ // Execute the function immediately
+ fn.call( document, jQuery );
+
+ // Otherwise, remember the function for later
+ else
+ // Add the function to the wait list
+ jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
+
+ return this;
+ }
+});
+
+jQuery.extend({
+ isReady: false,
+ readyList: [],
+ // Handle when the DOM is ready
+ ready: function() {
+ // Make sure that the DOM is not already loaded
+ if ( !jQuery.isReady ) {
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If there are functions bound, to execute
+ if ( jQuery.readyList ) {
+ // Execute all of them
+ jQuery.each( jQuery.readyList, function(){
+ this.call( document );
+ });
+
+ // Reset the list of functions
+ jQuery.readyList = null;
+ }
+
+ // Trigger any bound ready events
+ jQuery(document).triggerHandler("ready");
+ }
+ }
+});
+
+var readyBound = false;
+
+function bindReady(){
+ if ( readyBound ) return;
+ readyBound = true;
+
+ // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
+ if ( document.addEventListener && !jQuery.browser.opera)
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
+
+ // If IE is used and is not in a frame
+ // Continually check to see if the document is ready
+ if ( jQuery.browser.msie && window == top ) (function(){
+ if (jQuery.isReady) return;
+ try {
+ // If IE is used, use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ document.documentElement.doScroll("left");
+ } catch( error ) {
+ setTimeout( arguments.callee, 0 );
+ return;
+ }
+ // and execute any waiting functions
+ jQuery.ready();
+ })();
+
+ if ( jQuery.browser.opera )
+ document.addEventListener( "DOMContentLoaded", function () {
+ if (jQuery.isReady) return;
+ for (var i = 0; i < document.styleSheets.length; i++)
+ if (document.styleSheets[i].disabled) {
+ setTimeout( arguments.callee, 0 );
+ return;
+ }
+ // and execute any waiting functions
+ jQuery.ready();
+ }, false);
+
+ if ( jQuery.browser.safari ) {
+ var numStyles;
+ (function(){
+ if (jQuery.isReady) return;
+ if ( document.readyState != "loaded" && document.readyState != "complete" ) {
+ setTimeout( arguments.callee, 0 );
+ return;
+ }
+ if ( numStyles === undefined )
+ numStyles = jQuery("style, link[rel=stylesheet]").length;
+ if ( document.styleSheets.length != numStyles ) {
+ setTimeout( arguments.callee, 0 );
+ return;
+ }
+ // and execute any waiting functions
+ jQuery.ready();
+ })();
+ }
+
+ // A fallback to window.onload, that will always work
+ jQuery.event.add( window, "load", jQuery.ready );
+}
+
+jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
+ "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
+ "submit,keydown,keypress,keyup,error").split(","), function(i, name){
+
+ // Handle event binding
+ jQuery.fn[name] = function(fn){
+ return fn ? this.bind(name, fn) : this.trigger(name);
+ };
+});
+
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function(event, elem) {
+ // Check if mouse(over|out) are still within the same parent element
+ var parent = event.relatedTarget;
+ // Traverse up the tree
+ while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
+ // Return true if we actually just moused on to a sub-element
+ return parent == elem;
+};
+
+// Prevent memory leaks in IE
+// And prevent errors on refresh with events like mouseover in other browsers
+// Window isn't included so as not to unbind existing unload events
+jQuery(window).bind("unload", function() {
+ jQuery("*").add(document).unbind();
+});
+jQuery.fn.extend({
+ // Keep a copy of the old load
+ _load: jQuery.fn.load,
+
+ load: function( url, params, callback ) {
+ if ( typeof url != 'string' )
+ return this._load( url );
+
+ var off = url.indexOf(" ");
+ if ( off >= 0 ) {
+ var selector = url.slice(off, url.length);
+ url = url.slice(0, off);
+ }
+
+ callback = callback || function(){};
+
+ // Default to a GET request
+ var type = "GET";
+
+ // If the second parameter was provided
+ if ( params )
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+ // We assume that it's the callback
+ callback = params;
+ params = null;
+
+ // Otherwise, build a param string
+ } else {
+ params = jQuery.param( params );
+ type = "POST";
+ }
+
+ var self = this;
+
+ // Request the remote document
+ jQuery.ajax({
+ url: url,
+ type: type,
+ dataType: "html",
+ data: params,
+ complete: function(res, status){
+ // If successful, inject the HTML into all the matched elements
+ if ( status == "success" || status == "notmodified" )
+ // See if a selector was specified
+ self.html( selector ?
+ // Create a dummy div to hold the results
+ jQuery("<div/>")
+ // inject the contents of the document in, removing the scripts
+ // to avoid any 'Permission Denied' errors in IE
+ .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
+
+ // Locate the specified elements
+ .find(selector) :
+
+ // If not, just inject the full result
+ res.responseText );
+
+ self.each( callback, [res.responseText, status, res] );
+ }
+ });
+ return this;
+ },
+
+ serialize: function() {
+ return jQuery.param(this.serializeArray());
+ },
+ serializeArray: function() {
+ return this.map(function(){
+ return jQuery.nodeName(this, "form") ?
+ jQuery.makeArray(this.elements) : this;
+ })
+ .filter(function(){
+ return this.name && !this.disabled &&
+ (this.checked || /select|textarea/i.test(this.nodeName) ||
+ /text|hidden|password/i.test(this.type));
+ })
+ .map(function(i, elem){
+ var val = jQuery(this).val();
+ return val == null ? null :
+ val.constructor == Array ?
+ jQuery.map( val, function(val, i){
+ return {name: elem.name, value: val};
+ }) :
+ {name: elem.name, value: val};
+ }).get();
+ }
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
+ jQuery.fn[o] = function(f){
+ return this.bind(o, f);
+ };
+});
+
+var jsc = now();
+
+jQuery.extend({
+ get: function( url, data, callback, type ) {
+ // shift arguments if data argument was ommited
+ if ( jQuery.isFunction( data ) ) {
+ callback = data;
+ data = null;
+ }
+
+ return jQuery.ajax({
+ type: "GET",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ },
+
+ getScript: function( url, callback ) {
+ return jQuery.get(url, null, callback, "script");
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get(url, data, callback, "json");
+ },
+
+ post: function( url, data, callback, type ) {
+ if ( jQuery.isFunction( data ) ) {
+ callback = data;
+ data = {};
+ }
+
+ return jQuery.ajax({
+ type: "POST",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ },
+
+ ajaxSetup: function( settings ) {
+ jQuery.extend( jQuery.ajaxSettings, settings );
+ },
+
+ ajaxSettings: {
+ url: location.href,
+ global: true,
+ type: "GET",
+ timeout: 0,
+ contentType: "application/x-www-form-urlencoded",
+ processData: true,
+ async: true,
+ data: null,
+ username: null,
+ password: null,
+ accepts: {
+ xml: "application/xml, text/xml",
+ html: "text/html",
+ script: "text/javascript, application/javascript",
+ json: "application/json, text/javascript",
+ text: "text/plain",
+ _default: "*/*"
+ }
+ },
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+
+ ajax: function( s ) {
+ // Extend the settings, but re-extend 's' so that it can be
+ // checked again later (in the test suite, specifically)
+ s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
+
+ var jsonp, jsre = /=\?(&|$)/g, status, data,
+ type = s.type.toUpperCase();
+
+ // convert data if not already a string
+ if ( s.data && s.processData && typeof s.data != "string" )
+ s.data = jQuery.param(s.data);
+
+ // Handle JSONP Parameter Callbacks
+ if ( s.dataType == "jsonp" ) {
+ if ( type == "GET" ) {
+ if ( !s.url.match(jsre) )
+ s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
+ } else if ( !s.data || !s.data.match(jsre) )
+ s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
+ s.dataType = "json";
+ }
+
+ // Build temporary JSONP function
+ if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
+ jsonp = "jsonp" + jsc++;
+
+ // Replace the =? sequence both in the query string and the data
+ if ( s.data )
+ s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+ s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+
+ // We need to make sure
+ // that a JSONP style response is executed properly
+ s.dataType = "script";
+
+ // Handle JSONP-style loading
+ window[ jsonp ] = function(tmp){
+ data = tmp;
+ success();
+ complete();
+ // Garbage collect
+ window[ jsonp ] = undefined;
+ try{ delete window[ jsonp ]; } catch(e){}
+ if ( head )
+ head.removeChild( script );
+ };
+ }
+
+ if ( s.dataType == "script" && s.cache == null )
+ s.cache = false;
+
+ if ( s.cache === false && type == "GET" ) {
+ var ts = now();
+ // try replacing _= if it is there
+ var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
+ // if nothing was replaced, add timestamp to the end
+ s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
+ }
+
+ // If data is available, append data to url for get requests
+ if ( s.data && type == "GET" ) {
+ s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
+
+ // IE likes to send both get and post data, prevent this
+ s.data = null;
+ }
+
+ // Watch for a new set of requests
+ if ( s.global && ! jQuery.active++ )
+ jQuery.event.trigger( "ajaxStart" );
+
+ // Matches an absolute URL, and saves the domain
+ var remote = /^(?:\w+:)?\/\/([^\/?#]+)/;
+
+ // If we're requesting a remote document
+ // and trying to load JSON or Script with a GET
+ if ( s.dataType == "script" && type == "GET"
+ && remote.test(s.url) && remote.exec(s.url)[1] != location.host ){
+ var head = document.getElementsByTagName("head")[0];
+ var script = document.createElement("script");
+ script.src = s.url;
+ if (s.scriptCharset)
+ script.charset = s.scriptCharset;
+
+ // Handle Script loading
+ if ( !jsonp ) {
+ var done = false;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function(){
+ if ( !done && (!this.readyState ||
+ this.readyState == "loaded" || this.readyState == "complete") ) {
+ done = true;
+ success();
+ complete();
+ head.removeChild( script );
+ }
+ };
+ }
+
+ head.appendChild(script);
+
+ // We handle everything using the script element injection
+ return undefined;
+ }
+
+ var requestDone = false;
+
+ // Create the request object; Microsoft failed to properly
+ // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
+ var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
+
+ // Open the socket
+ // Passing null username, generates a login popup on Opera (#2865)
+ if( s.username )
+ xhr.open(type, s.url, s.async, s.username, s.password);
+ else
+ xhr.open(type, s.url, s.async);
+ // console.log(s.url) // JF
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ // Set the correct header, if data is being sent
+ if ( s.data )
+ xhr.setRequestHeader("Content-Type", s.contentType);
+
+ // Set the If-Modified-Since header, if ifModified mode.
+ if ( s.ifModified )
+ xhr.setRequestHeader("If-Modified-Since",
+ jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
+
+ // Set header so the called script knows that it's an XMLHttpRequest
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+
+ // Set the Accepts header for the server, depending on the dataType
+ xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
+ s.accepts[ s.dataType ] + ", */*" :
+ s.accepts._default );
+ } catch(e){}
+
+ // Allow custom headers/mimetypes
+ if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
+ // cleanup active request counter
+ s.global && jQuery.active--;
+ // close opended socket
+ xhr.abort();
+ return false;
+ }
+
+ if ( s.global )
+ jQuery.event.trigger("ajaxSend", [xhr, s]);
+
+ // Wait for a response to come back
+ var onreadystatechange = function(isTimeout){
+ // The transfer is complete and the data is available, or the request timed out
+ if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
+ requestDone = true;
+
+ // clear poll interval
+ if (ival) {
+ clearInterval(ival);
+ ival = null;
+ }
+
+ status = isTimeout == "timeout" && "timeout" ||
+ !jQuery.httpSuccess( xhr ) && "error" ||
+ s.ifModified && jQuery.httpNotModified( xhr, s.url ) && "notmodified" ||
+ "success";
+
+ if ( status == "success" ) {
+ // Watch for, and catch, XML document parse errors
+ try {
+ // process the data (runs the xml through httpData regardless of callback)
+ data = jQuery.httpData( xhr, s.dataType, s.dataFilter );
+ } catch(e) {
+ status = "parsererror";
+ }
+ }
+
+ // Make sure that the request was successful or notmodified
+ if ( status == "success" ) {
+ // Cache Last-Modified header, if ifModified mode.
+ var modRes;
+ try {
+ modRes = xhr.getResponseHeader("Last-Modified");
+ } catch(e) {} // swallow exception thrown by FF if header is not available
+
+ if ( s.ifModified && modRes )
+ jQuery.lastModified[s.url] = modRes;
+
+ // JSONP handles its own success callback
+ if ( !jsonp )
+ success();
+ } else
+ jQuery.handleError(s, xhr, status);
+
+ // Fire the complete handlers
+ complete();
+
+ // Stop memory leaks
+ if ( s.async )
+ xhr = null;
+ }
+ };
+
+ if ( s.async ) {
+ // don't attach the handler to the request, just poll it instead
+ var ival = setInterval(onreadystatechange, 13);
+
+ // Timeout checker
+ if ( s.timeout > 0 )
+ setTimeout(function(){
+ // Check to see if the request is still happening
+ if ( xhr ) {
+ // Cancel the request
+ xhr.abort();
+
+ if( !requestDone )
+ onreadystatechange( "timeout" );
+ }
+ }, s.timeout);
+ }
+
+ // Send the data
+ try {
+ xhr.send(s.data);
+ } catch(e) {
+ jQuery.handleError(s, xhr, null, e);
+ }
+
+ // firefox 1.5 doesn't fire statechange for sync requests
+ if ( !s.async )
+ onreadystatechange();
+
+ function success(){
+ // If a local callback was specified, fire it and pass it the data
+ if ( s.success )
+ s.success( data, status );
+
+ // Fire the global callback
+ if ( s.global )
+ jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
+ }
+
+ function complete(){
+ // Process result
+ if ( s.complete )
+ s.complete(xhr, status);
+
+ // The request was completed
+ if ( s.global )
+ jQuery.event.trigger( "ajaxComplete", [xhr, s] );
+
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active )
+ jQuery.event.trigger( "ajaxStop" );
+ }
+
+ // return XMLHttpRequest to allow aborting the request etc.
+ return xhr;
+ },
+
+ handleError: function( s, xhr, status, e ) {
+ // If a local callback was specified, fire it
+ if ( s.error ) s.error( xhr, status, e );
+
+ // Fire the global callback
+ if ( s.global )
+ jQuery.event.trigger( "ajaxError", [xhr, s, e] );
+ },
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Determines if an XMLHttpRequest was successful or not
+ httpSuccess: function( xhr ) {
+ try {
+ // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
+ return !xhr.status && location.protocol == "file:" ||
+ ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223 ||
+ jQuery.browser.safari && xhr.status == undefined;
+ } catch(e){}
+ return false;
+ },
+
+ // Determines if an XMLHttpRequest returns NotModified
+ httpNotModified: function( xhr, url ) {
+ try {
+ var xhrRes = xhr.getResponseHeader("Last-Modified");
+
+ // Firefox always returns 200. check Last-Modified date
+ return xhr.status == 304 || xhrRes == jQuery.lastModified[url] ||
+ jQuery.browser.safari && xhr.status == undefined;
+ } catch(e){}
+ return false;
+ },
+
+ httpData: function( xhr, type, filter ) {
+ var ct = xhr.getResponseHeader("content-type"),
+ xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
+ data = xml ? xhr.responseXML : xhr.responseText;
+
+ if ( xml && data.documentElement.tagName == "parsererror" )
+ throw "parsererror";
+
+ // Allow a pre-filtering function to sanitize the response
+ if( filter )
+ data = filter( data, type );
+
+ // If the type is "script", eval it in global context
+ if ( type == "script" )
+ jQuery.globalEval( data );
+
+ // Get the JavaScript object, if JSON is used.
+ if ( type == "json" )
+ data = eval("(" + data + ")");
+
+ return data;
+ },
+
+ // Serialize an array of form elements or a set of
+ // key/values into a query string
+ param: function( a ) {
+ var s = [];
+
+ // If an array was passed in, assume that it is an array
+ // of form elements
+ if ( a.constructor == Array || a.jquery )
+ // Serialize the form elements
+ jQuery.each( a, function(){
+ s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
+ });
+
+ // Otherwise, assume that it's an object of key/value pairs
+ else
+ // Serialize the key/values
+ for ( var j in a )
+ // If the value is an array then the key names need to be repeated
+ if ( a[j] && a[j].constructor == Array )
+ jQuery.each( a[j], function(){
+ s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
+ });
+ else
+ s.push( encodeURIComponent(j) + "=" + encodeURIComponent( jQuery.isFunction(a[j]) ? a[j]() : a[j] ) );
+
+ // Return the resulting serialization
+ return s.join("&").replace(/%20/g, "+");
+ }
+
+});
+jQuery.fn.extend({
+ show: function(speed,callback){
+ return speed ?
+ this.animate({
+ height: "show", width: "show", opacity: "show"
+ }, speed, callback) :
+
+ this.filter(":hidden").each(function(){
+ this.style.display = this.oldblock || "";
+ if ( jQuery.css(this,"display") == "none" ) {
+ var elem = jQuery("<" + this.tagName + " />").appendTo("body");
+ this.style.display = elem.css("display");
+ // handle an edge condition where css is - div { display:none; } or similar
+ if (this.style.display == "none")
+ this.style.display = "block";
+ elem.remove();
+ }
+ }).end();
+ },
+
+ hide: function(speed,callback){
+ return speed ?
+ this.animate({
+ height: "hide", width: "hide", opacity: "hide"
+ }, speed, callback) :
+
+ this.filter(":visible").each(function(){
+ this.oldblock = this.oldblock || jQuery.css(this,"display");
+ this.style.display = "none";
+ }).end();
+ },
+
+ // Save the old toggle function
+ _toggle: jQuery.fn.toggle,
+
+ toggle: function( fn, fn2 ){
+ return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
+ this._toggle.apply( this, arguments ) :
+ fn ?
+ this.animate({
+ height: "toggle", width: "toggle", opacity: "toggle"
+ }, fn, fn2) :
+ this.each(function(){
+ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
+ });
+ },
+
+ slideDown: function(speed,callback){
+ return this.animate({height: "show"}, speed, callback);
+ },
+
+ slideUp: function(speed,callback){
+ return this.animate({height: "hide"}, speed, callback);
+ },
+
+ slideToggle: function(speed, callback){
+ return this.animate({height: "toggle"}, speed, callback);
+ },
+
+ fadeIn: function(speed, callback){
+ return this.animate({opacity: "show"}, speed, callback);
+ },
+
+ fadeOut: function(speed, callback){
+ return this.animate({opacity: "hide"}, speed, callback);
+ },
+
+ fadeTo: function(speed,to,callback){
+ return this.animate({opacity: to}, speed, callback);
+ },
+
+ animate: function( prop, speed, easing, callback ) {
+ var optall = jQuery.speed(speed, easing, callback);
+
+ return this[ optall.queue === false ? "each" : "queue" ](function(){
+ if ( this.nodeType != 1)
+ return false;
+
+ var opt = jQuery.extend({}, optall), p,
+ hidden = jQuery(this).is(":hidden"), self = this;
+
+ for ( p in prop ) {
+ if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
+ return opt.complete.call(this);
+
+ if ( p == "height" || p == "width" ) {
+ // Store display property
+ opt.display = jQuery.css(this, "display");
+
+ // Make sure that nothing sneaks out
+ opt.overflow = this.style.overflow;
+ }
+ }
+
+ if ( opt.overflow != null )
+ this.style.overflow = "hidden";
+
+ opt.curAnim = jQuery.extend({}, prop);
+
+ jQuery.each( prop, function(name, val){
+ var e = new jQuery.fx( self, opt, name );
+
+ if ( /toggle|show|hide/.test(val) )
+ e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+ else {
+ var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
+ start = e.cur(true) || 0;
+
+ if ( parts ) {
+ var end = parseFloat(parts[2]),
+ unit = parts[3] || "px";
+
+ // We need to compute starting value
+ if ( unit != "px" ) {
+ self.style[ name ] = (end || 1) + unit;
+ start = ((end || 1) / e.cur(true)) * start;
+ self.style[ name ] = start + unit;
+ }
+
+ // If a +=/-= token was provided, we're doing a relative animation
+ if ( parts[1] )
+ end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
+
+ e.custom( start, end, unit );
+ } else
+ e.custom( start, val, "" );
+ }
+ });
+
+ // For JS strict compliance
+ return true;
+ });
+ },
+
+ queue: function(type, fn){
+ if ( jQuery.isFunction(type) || ( type && type.constructor == Array )) {
+ fn = type;
+ type = "fx";
+ }
+
+ if ( !type || (typeof type == "string" && !fn) )
+ return queue( this[0], type );
+
+ return this.each(function(){
+ if ( fn.constructor == Array )
+ queue(this, type, fn);
+ else {
+ queue(this, type).push( fn );
+
+ if ( queue(this, type).length == 1 )
+ fn.call(this);
+ }
+ });
+ },
+
+ stop: function(clearQueue, gotoEnd){
+ var timers = jQuery.timers;
+
+ if (clearQueue)
+ this.queue([]);
+
+ this.each(function(){
+ // go in reverse order so anything added to the queue during the loop is ignored
+ for ( var i = timers.length - 1; i >= 0; i-- )
+ if ( timers[i].elem == this ) {
+ if (gotoEnd)
+ // force the next step to be the last
+ timers[i](true);
+ timers.splice(i, 1);
+ }
+ });
+
+ // start the next in the queue if the last step wasn't forced
+ if (!gotoEnd)
+ this.dequeue();
+
+ return this;
+ }
+
+});
+
+var queue = function( elem, type, array ) {
+ if ( elem ){
+
+ type = type || "fx";
+
+ var q = jQuery.data( elem, type + "queue" );
+
+ if ( !q || array )
+ q = jQuery.data( elem, type + "queue", jQuery.makeArray(array) );
+
+ }
+ return q;
+};
+
+jQuery.fn.dequeue = function(type){
+ type = type || "fx";
+
+ return this.each(function(){
+ var q = queue(this, type);
+
+ q.shift();
+
+ if ( q.length )
+ q[0].call( this );
+ });
+};
+
+jQuery.extend({
+
+ speed: function(speed, easing, fn) {
+ var opt = speed && speed.constructor == Object ? speed : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && easing.constructor != Function && easing
+ };
+
+ opt.duration = (opt.duration && opt.duration.constructor == Number ?
+ opt.duration :
+ jQuery.fx.speeds[opt.duration]) || jQuery.fx.speeds.def;
+
+ // Queueing
+ opt.old = opt.complete;
+ opt.complete = function(){
+ if ( opt.queue !== false )
+ jQuery(this).dequeue();
+ if ( jQuery.isFunction( opt.old ) )
+ opt.old.call( this );
+ };
+
+ return opt;
+ },
+
+ easing: {
+ linear: function( p, n, firstNum, diff ) {
+ return firstNum + diff * p;
+ },
+ swing: function( p, n, firstNum, diff ) {
+ return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+ }
+ },
+
+ timers: [],
+ timerId: null,
+
+ fx: function( elem, options, prop ){
+ this.options = options;
+ this.elem = elem;
+ this.prop = prop;
+
+ if ( !options.orig )
+ options.orig = {};
+ }
+
+});
+
+jQuery.fx.prototype = {
+
+ // Simple function for setting a style value
+ update: function(){
+ if ( this.options.step )
+ this.options.step.call( this.elem, this.now, this );
+
+ (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+
+ // Set display property to block for height/width animations
+ if ( this.prop == "height" || this.prop == "width" )
+ this.elem.style.display = "block";
+ },
+
+ // Get the current size
+ cur: function(force){
+ if ( this.elem[this.prop] != null && this.elem.style[this.prop] == null )
+ return this.elem[ this.prop ];
+
+ var r = parseFloat(jQuery.css(this.elem, this.prop, force));
+ return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
+ },
+
+ // Start an animation from one number to another
+ custom: function(from, to, unit){
+ this.startTime = now();
+ this.start = from;
+ this.end = to;
+ this.unit = unit || this.unit || "px";
+ this.now = this.start;
+ this.pos = this.state = 0;
+ this.update();
+
+ var self = this;
+ function t(gotoEnd){
+ return self.step(gotoEnd);
+ }
+
+ t.elem = this.elem;
+
+ jQuery.timers.push(t);
+
+ if ( jQuery.timerId == null ) {
+ jQuery.timerId = setInterval(function(){
+ var timers = jQuery.timers;
+
+ for ( var i = 0; i < timers.length; i++ )
+ if ( !timers[i]() )
+ timers.splice(i--, 1);
+
+ if ( !timers.length ) {
+ clearInterval( jQuery.timerId );
+ jQuery.timerId = null;
+ }
+ }, 13);
+ }
+ },
+
+ // Simple 'show' function
+ show: function(){
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+ this.options.show = true;
+
+ // Begin the animation
+ this.custom(0, this.cur());
+
+ // Make sure that we start at a small width/height to avoid any
+ // flash of content
+ if ( this.prop == "width" || this.prop == "height" )
+ this.elem.style[this.prop] = "1px";
+
+ // Start by showing the element
+ jQuery(this.elem).show();
+ },
+
+ // Simple 'hide' function
+ hide: function(){
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+ this.options.hide = true;
+
+ // Begin the animation
+ this.custom(this.cur(), 0);
+ },
+
+ // Each step of an animation
+ step: function(gotoEnd){
+ var t = now();
+
+ if ( gotoEnd || t > this.options.duration + this.startTime ) {
+ this.now = this.end;
+ this.pos = this.state = 1;
+ this.update();
+
+ this.options.curAnim[ this.prop ] = true;
+
+ var done = true;
+ for ( var i in this.options.curAnim )
+ if ( this.options.curAnim[i] !== true )
+ done = false;
+
+ if ( done ) {
+ if ( this.options.display != null ) {
+ // Reset the overflow
+ this.elem.style.overflow = this.options.overflow;
+
+ // Reset the display
+ this.elem.style.display = this.options.display;
+ if ( jQuery.css(this.elem, "display") == "none" )
+ this.elem.style.display = "block";
+ }
+
+ // Hide the element if the "hide" operation was done
+ if ( this.options.hide )
+ this.elem.style.display = "none";
+
+ // Reset the properties, if the item has been hidden or shown
+ if ( this.options.hide || this.options.show )
+ for ( var p in this.options.curAnim )
+ jQuery.attr(this.elem.style, p, this.options.orig[p]);
+ }
+
+ if ( done )
+ // Execute the complete function
+ this.options.complete.call( this.elem );
+
+ return false;
+ } else {
+ var n = t - this.startTime;
+ this.state = n / this.options.duration;
+
+ // Perform the easing function, defaults to swing
+ this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
+ this.now = this.start + ((this.end - this.start) * this.pos);
+
+ // Perform the next step of the animation
+ this.update();
+ }
+
+ return true;
+ }
+
+};
+
+jQuery.extend( jQuery.fx, {
+ speeds:{
+ slow: 600,
+ fast: 200,
+ // Default speed
+ def: 400
+ },
+ step: {
+ scrollLeft: function(fx){
+ fx.elem.scrollLeft = fx.now;
+ },
+
+ scrollTop: function(fx){
+ fx.elem.scrollTop = fx.now;
+ },
+
+ opacity: function(fx){
+ jQuery.attr(fx.elem.style, "opacity", fx.now);
+ },
+
+ _default: function(fx){
+ fx.elem.style[ fx.prop ] = fx.now + fx.unit;
+ }
+ }
+});
+// The Offset Method
+// Originally By Brandon Aaron, part of the Dimension Plugin
+// http://jquery.com/plugins/project/dimensions
+jQuery.fn.offset = function() {
+ var left = 0, top = 0, elem = this[0], results;
+
+ if ( elem ) with ( jQuery.browser ) {
+ var parent = elem.parentNode,
+ offsetChild = elem,
+ offsetParent = elem.offsetParent,
+ doc = elem.ownerDocument,
+ safari2 = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),
+ css = jQuery.curCSS,
+ fixed = css(elem, "position") == "fixed";
+
+ // Use getBoundingClientRect if available
+ if ( elem.getBoundingClientRect ) {
+ var box = elem.getBoundingClientRect();
+
+ // Add the document scroll offsets
+ add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
+ box.top + Math.max(doc.documentElement.scrollTop, doc.body.scrollTop));
+
+ // IE adds the HTML element's border, by default it is medium which is 2px
+ // IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }
+ // IE 7 standards mode, the border is always 2px
+ // This border/offset is typically represented by the clientLeft and clientTop properties
+ // However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS
+ // Therefore this method will be off by 2px in IE while in quirksmode
+ add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );
+
+ // Otherwise loop through the offsetParents and parentNodes
+ } else {
+
+ // Initial element offsets
+ add( elem.offsetLeft, elem.offsetTop );
+
+ // Get parent offsets
+ while ( offsetParent ) {
+ // Add offsetParent offsets
+ add( offsetParent.offsetLeft, offsetParent.offsetTop );
+
+ // Mozilla and Safari > 2 does not include the border on offset parents
+ // However Mozilla adds the border for table or table cells
+ if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )
+ border( offsetParent );
+
+ // Add the document scroll offsets if position is fixed on any offsetParent
+ if ( !fixed && css(offsetParent, "position") == "fixed" )
+ fixed = true;
+
+ // Set offsetChild to previous offsetParent unless it is the body element
+ offsetChild = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;
+ // Get next offsetParent
+ offsetParent = offsetParent.offsetParent;
+ }
+
+ // Get parent scroll offsets
+ while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {
+ // Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug
+ if ( !/^inline|table.*$/i.test(css(parent, "display")) )
+ // Subtract parent scroll offsets
+ add( -parent.scrollLeft, -parent.scrollTop );
+
+ // Mozilla does not add the border for a parent that has overflow != visible
+ if ( mozilla && css(parent, "overflow") != "visible" )
+ border( parent );
+
+ // Get next parent
+ parent = parent.parentNode;
+ }
+
+ // Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild
+ // Mozilla doubles body offsets with a non-absolutely positioned offsetChild
+ if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) ||
+ (mozilla && css(offsetChild, "position") != "absolute") )
+ add( -doc.body.offsetLeft, -doc.body.offsetTop );
+
+ // Add the document scroll offsets if position is fixed
+ if ( fixed )
+ add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
+ Math.max(doc.documentElement.scrollTop, doc.body.scrollTop));
+ }
+
+ // Return an object with top and left properties
+ results = { top: top, left: left };
+ }
+
+ function border(elem) {
+ add( jQuery.curCSS(elem, "borderLeftWidth", true), jQuery.curCSS(elem, "borderTopWidth", true) );
+ }
+
+ function add(l, t) {
+ left += parseInt(l, 10) || 0;
+ top += parseInt(t, 10) || 0;
+ }
+
+ return results;
+};
+
+
+jQuery.fn.extend({
+ position: function() {
+ var left = 0, top = 0, results;
+
+ if ( this[0] ) {
+ // Get *real* offsetParent
+ var offsetParent = this.offsetParent(),
+
+ // Get correct offsets
+ offset = this.offset(),
+ parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+ // Subtract element margins
+ // note: when an element has margin: auto the offsetLeft and marginLeft
+ // are the same in Safari causing offset.left to incorrectly be 0
+ offset.top -= num( this, 'marginTop' );
+ offset.left -= num( this, 'marginLeft' );
+
+ // Add offsetParent borders
+ parentOffset.top += num( offsetParent, 'borderTopWidth' );
+ parentOffset.left += num( offsetParent, 'borderLeftWidth' );
+
+ // Subtract the two offsets
+ results = {
+ top: offset.top - parentOffset.top,
+ left: offset.left - parentOffset.left
+ };
+ }
+
+ return results;
+ },
+
+ offsetParent: function() {
+ var offsetParent = this[0].offsetParent;
+ while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
+ offsetParent = offsetParent.offsetParent;
+ return jQuery(offsetParent);
+ }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ['Left', 'Top'], function(i, name) {
+ var method = 'scroll' + name;
+
+ jQuery.fn[ method ] = function(val) {
+ if (!this[0]) return;
+
+ return val != undefined ?
+
+ // Set the scroll offset
+ this.each(function() {
+ this == window || this == document ?
+ window.scrollTo(
+ !i ? val : jQuery(window).scrollLeft(),
+ i ? val : jQuery(window).scrollTop()
+ ) :
+ this[ method ] = val;
+ }) :
+
+ // Return the scroll offset
+ this[0] == window || this[0] == document ?
+ self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
+ jQuery.boxModel && document.documentElement[ method ] ||
+ document.body[ method ] :
+ this[0][ method ];
+ };
+});
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function(i, name){
+
+ var tl = i ? "Left" : "Top", // top or left
+ br = i ? "Right" : "Bottom"; // bottom or right
+
+ // innerHeight and innerWidth
+ jQuery.fn["inner" + name] = function(){
+ return this[ name.toLowerCase() ]() +
+ num(this, "padding" + tl) +
+ num(this, "padding" + br);
+ };
+
+ // outerHeight and outerWidth
+ jQuery.fn["outer" + name] = function(margin) {
+ return this["inner" + name]() +
+ num(this, "border" + tl + "Width") +
+ num(this, "border" + br + "Width") +
+ (margin ?
+ num(this, "margin" + tl) + num(this, "margin" + br) : 0);
+ };
+
+});})();
diff --git a/vendor/plugins/juggernaut_plugin/media/jquerynaut.js b/vendor/plugins/juggernaut_plugin/media/jquerynaut.js
new file mode 100644
index 0000000..a038528
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/jquerynaut.js
@@ -0,0 +1,57 @@
+// Simply overwrites prototype specific functions
+// with jquery specific versions
+
+Juggernaut.fn.fire_event = function(fx_name) {
+ $(document).trigger("juggernaut:" + fx_name);
+ };
+
+Juggernaut.fn.bindToWindow = function() {
+ $(window).bind("load", this, function(e) {
+ juggernaut = e.data;
+ e.data.appendFlashObject();
+ });
+ };
+
+Juggernaut.toJSON = function(hash) {
+ return $.toJSON(hash) ;
+ };
+
+Juggernaut.parseJSON = function(string) {
+ return $.parseJSON(string);
+ };
+
+Juggernaut.fn.swf = function(){
+ return $('#' + this.options.swf_name)[0];
+ };
+
+Juggernaut.fn.appendElement = function() {
+ this.element = $('<div id=juggernaut>');
+ $("body").append(this.element);
+ };
+
+Juggernaut.fn.refreshFlashObject = function(){
+ $(this.swf()).remove();
+ this.appendFlashObject();
+ };
+
+Juggernaut.fn.reconnect = function(){
+ if(this.options.reconnect_attempts){
+ this.attempting_to_reconnect = true;
+ this.fire_event('reconnect');
+ this.logger('Will attempt to reconnect ' + this.options.reconnect_attempts + ' times, the first in ' + (this.options.reconnect_intervals || 3) + ' seconds');
+ var self = this;
+ for(var i=0; i < this.options.reconnect_attempts; i++){
+ setTimeout(function(){
+ if(!self.is_connected){
+ self.logger('Attempting reconnect');
+ if(!self.ever_been_connected){
+ self.refreshFlashObject();
+ } else {
+ self.connect();
+ }
+ }
+ }, (this.options.reconnect_intervals || 3) * 1000 * (i + 1));
+
+ }
+ }
+ };
diff --git a/vendor/plugins/juggernaut_plugin/media/json.js b/vendor/plugins/juggernaut_plugin/media/json.js
new file mode 100644
index 0000000..6222784
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/json.js
@@ -0,0 +1,97 @@
+(function ($) {
+ var m = {
+ '\b': '\\b',
+ '\t': '\\t',
+ '\n': '\\n',
+ '\f': '\\f',
+ '\r': '\\r',
+ '"' : '\\"',
+ '\\': '\\\\'
+ },
+ s = {
+ 'array': function (x) {
+ var a = ['['], b, f, i, l = x.length, v;
+ for (i = 0; i < l; i += 1) {
+ v = x[i];
+ f = s[typeof v];
+ if (f) {
+ v = f(v);
+ if (typeof v == 'string') {
+ if (b) {
+ a[a.length] = ',';
+ }
+ a[a.length] = v;
+ b = true;
+ }
+ }
+ }
+ a[a.length] = ']';
+ return a.join('');
+ },
+ 'boolean': function (x) {
+ return String(x);
+ },
+ 'null': function (x) {
+ return "null";
+ },
+ 'number': function (x) {
+ return isFinite(x) ? String(x) : 'null';
+ },
+ 'object': function (x) {
+ if (x) {
+ if (x instanceof Array) {
+ return s.array(x);
+ }
+ var a = ['{'], b, f, i, v;
+ for (i in x) {
+ v = x[i];
+ f = s[typeof v];
+ if (f) {
+ v = f(v);
+ if (typeof v == 'string') {
+ if (b) {
+ a[a.length] = ',';
+ }
+ a.push(s.string(i), ':', v);
+ b = true;
+ }
+ }
+ }
+ a[a.length] = '}';
+ return a.join('');
+ }
+ return 'null';
+ },
+ 'string': function (x) {
+ if (/["\\\x00-\x1f]/.test(x)) {
+ x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
+ var c = m[b];
+ if (c) {
+ return c;
+ }
+ c = b.charCodeAt();
+ return '\\u00' +
+ Math.floor(c / 16).toString(16) +
+ (c % 16).toString(16);
+ });
+ }
+ return '"' + x + '"';
+ }
+ };
+
+ $.toJSON = function(v) {
+ var f = isNaN(v) ? s[typeof v] : s['number'];
+ if (f) return f(v);
+ };
+
+ $.parseJSON = function(v, safe) {
+ if (safe === undefined) safe = $.parseJSON.safe;
+ if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
+ return undefined;
+ return eval('('+v+')');
+ };
+
+ $.parseJSON.safe = false;
+
+})(jQuery);
+
diff --git a/vendor/plugins/juggernaut_plugin/media/juggernaut.as b/vendor/plugins/juggernaut_plugin/media/juggernaut.as
new file mode 100644
index 0000000..9ca96c9
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/juggernaut.as
@@ -0,0 +1,79 @@
+/*
+Copyright (c) 2007 Alexander MacCaw
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+/*
+ Compile using MTACS (http://www.mtasc.org/)
+ mtasc -version 8 -header 1:1:1 -main -swf juggernaut.swf juggernaut.as
+*/
+
+import flash.external.ExternalInterface;
+
+class SocketServer {
+
+ static var socket : XMLSocket;
+
+ static function connect(host:String, port:Number) {
+ // The following line was causing crashes on Leopard
+ // System.security.loadPolicyFile('xmlsocket://' + host + ':' + port);
+
+ socket = new XMLSocket();
+ socket.onData = onData;
+ socket.onConnect = onConnect;
+ socket.onClose = onDisconnect;
+ socket.connect(host, port);
+ }
+
+ static function disconnect(){
+ socket.close();
+ }
+
+ static function onConnect(success:Boolean) {
+ if(success){
+ ExternalInterface.call("juggernaut.connected");
+ } else {
+ ExternalInterface.call("juggernaut.errorConnecting");
+ }
+ }
+
+ static function sendData(data:String){
+ socket.send(unescape(data));
+ }
+
+ static function onDisconnect() {
+ ExternalInterface.call("juggernaut.disconnected");
+ }
+
+ static function onData(data:String) {
+ ExternalInterface.call("juggernaut.receiveData", escape(data));
+ }
+
+ static function main() {
+ ExternalInterface.addCallback("connect", null, connect);
+ ExternalInterface.addCallback("sendData", null, sendData);
+ ExternalInterface.addCallback("disconnect", null, disconnect);
+
+ ExternalInterface.call("juggernaut.initialized");
+ }
+
+}
+
diff --git a/vendor/plugins/juggernaut_plugin/media/juggernaut.js b/vendor/plugins/juggernaut_plugin/media/juggernaut.js
new file mode 100644
index 0000000..24df613
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/juggernaut.js
@@ -0,0 +1,204 @@
+/*
+Copyright (c) 2008 Alexander MacCaw
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+function Juggernaut(options) {
+ this.is_connected = false;
+ this.attempting_to_reconnect = false;
+ this.ever_been_connected = false;
+ this.hasLogger = "console" in window && "log" in window.console;
+ this.options = options;
+ this.bindToWindow();
+};
+
+Juggernaut.fn = Juggernaut.prototype;
+
+Juggernaut.fn.logger = function(msg) {
+ if (this.options.debug) {
+ msg = "Juggernaut: " + msg + " on " + this.options.host + ':' + this.options.port;
+ this.hasLogger ? console.log(msg) : alert(msg);
+ }
+};
+
+Juggernaut.fn.initialized = function(){
+ this.fire_event('initialized');
+ this.connect();
+};
+
+Juggernaut.fn.broadcast = function(body, type, client_ids, channels){
+ var msg = {command: 'broadcast', body: body, type: (type||'to_channels')};
+ if(channels) msg['channels'] = channels;
+ if(client_ids) msg['client_ids'] = client_ids;
+ this.sendData(Juggernaut.toJSON(msg));
+};
+
+Juggernaut.fn.sendData = function(data){
+ this.swf().sendData(escape(data));
+};
+
+Juggernaut.fn.connect = function(){
+ if(!this.is_connected){
+ this.fire_event('connect');
+ this.swf().connect(this.options.host, this.options.port);
+ }
+};
+
+Juggernaut.fn.disconnect = function(){
+ if(this.is_connected) {
+ this.swf().disconnect();
+ this.is_connected = false;
+ }
+};
+
+Juggernaut.fn.handshake = function() {
+ var handshake = {};
+ handshake['command'] = 'subscribe';
+ if(this.options.session_id) handshake['session_id'] = this.options.session_id;
+ if(this.options.client_id) handshake['client_id'] = this.options.client_id;
+ if(this.options.channels) handshake['channels'] = this.options.channels;
+ if(this.currentMsgId) {
+ handshake['last_msg_id'] = this.currentMsgId;
+ handshake['signature'] = this.currentSignature;
+ }
+
+ return handshake;
+};
+
+Juggernaut.fn.connected = function(e) {
+ var json = Juggernaut.toJSON(this.handshake());
+ this.sendData(json);
+ this.ever_been_connected = true;
+ this.is_connected = true;
+ var self = this;
+ setTimeout(function(){
+ if(self.is_connected) self.attempting_to_reconnect = false;
+ }, 1 * 1000);
+ this.logger('Connected');
+ this.fire_event('connected');
+};
+
+Juggernaut.fn.receiveData = function(e) {
+ var msg = Juggernaut.parseJSON(unescape(e.toString()));
+ this.currentMsgId = msg.id;
+ this.currentSignature = msg.signature;
+ this.logger("Received data:\n" + msg.body + "\n");
+ this.dispatchMessage(msg);
+};
+
+Juggernaut.fn.dispatchMessage = function(msg) {
+ eval(msg.body);
+}
+
+var juggernaut;
+
+// Prototype specific - override for other frameworks
+Juggernaut.fn.fire_event = function(fx_name) {
+ $(document).fire("juggernaut:" + fx_name);
+};
+
+Juggernaut.fn.bindToWindow = function() {
+ Event.observe(window, 'load', function() {
+ juggernaut = this;
+ this.appendFlashObject();
+ }.bind(this));
+};
+
+Juggernaut.toJSON = function(hash) {
+ return Object.toJSON(hash);
+};
+
+Juggernaut.parseJSON = function(string) {
+ return string.evalJSON();
+};
+
+Juggernaut.fn.swf = function(){
+ return $(this.options.swf_name);
+};
+
+Juggernaut.fn.appendElement = function() {
+ this.element = new Element('div', { id: 'juggernaut' });
+ $(document.body).insert({ bottom: this.element });
+};
+
+/*** END PROTOTYPE SPECIFIC ***/
+
+Juggernaut.fn.appendFlashObject = function(){
+ if(this.swf()) {
+ throw("Juggernaut error. 'swf_name' must be unique per juggernaut instance.");
+ }
+ Juggernaut.fn.appendElement();
+ swfobject.embedSWF(
+ this.options.swf_address,
+ 'juggernaut',
+ this.options.width,
+ this.options.height,
+ String(this.options.flash_version),
+ this.options.ei_swf_address,
+ {'bridgeName': this.options.bridge_name},
+ {},
+ {'id': this.options.swf_name, 'name': this.options.swf_name}
+ );
+};
+
+Juggernaut.fn.refreshFlashObject = function(){
+ this.swf().remove();
+ this.appendFlashObject();
+};
+
+Juggernaut.fn.errorConnecting = function(e) {
+ this.is_connected = false;
+ if(!this.attempting_to_reconnect) {
+ this.logger('There has been an error connecting');
+ this.fire_event('errorConnecting');
+ this.reconnect();
+ }
+};
+
+Juggernaut.fn.disconnected = function(e) {
+ this.is_connected = false;
+ if(!this.attempting_to_reconnect) {
+ this.logger('Connection has been lost');
+ this.fire_event('disconnected');
+ this.reconnect();
+ }
+};
+
+Juggernaut.fn.reconnect = function(){
+ if(this.options.reconnect_attempts){
+ this.attempting_to_reconnect = true;
+ this.fire_event('reconnect');
+ this.logger('Will attempt to reconnect ' + this.options.reconnect_attempts + ' times,\
+the first in ' + (this.options.reconnect_intervals || 3) + ' seconds');
+ for(var i=0; i < this.options.reconnect_attempts; i++){
+ setTimeout(function(){
+ if(!this.is_connected){
+ this.logger('Attempting reconnect');
+ if(!this.ever_been_connected){
+ this.refreshFlashObject();
+ } else {
+ this.connect();
+ }
+ }
+ }.bind(this), (this.options.reconnect_intervals || 3) * 1000 * (i + 1));
+ }
+ }
+};
\ No newline at end of file
diff --git a/vendor/plugins/juggernaut_plugin/media/juggernaut.swf b/vendor/plugins/juggernaut_plugin/media/juggernaut.swf
new file mode 100644
index 0000000..525ea67
Binary files /dev/null and b/vendor/plugins/juggernaut_plugin/media/juggernaut.swf differ
diff --git a/vendor/plugins/juggernaut_plugin/media/juggernaut.yml b/vendor/plugins/juggernaut_plugin/media/juggernaut.yml
new file mode 100644
index 0000000..0e114e3
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/juggernaut.yml
@@ -0,0 +1,93 @@
+ # ======================
+ # Juggernaut Options
+ # ======================
+
+ # === Subscription authentication ===
+ # Leave all subscription options uncommented to allow anyone to subscribe.
+
+ # If specified, subscription_url is called everytime a client subscribes.
+ # Parameters passed are: session_id, client_id and an array of channels.
+ #
+ # The server should check that the session_id matches up to the client_id
+ # and that the client is allowed to access the specified channels.
+ #
+ # If a status code other than 200 is encountered, the subscription_request fails
+ # and the client is disconnected.
+ #
+ # :subscription_url: http://localhost:3000/sessions/juggernaut_subscription
+
+ # === Broadcast and query authentication ===
+ # Leave all broadcast/query options uncommented to allow anyone to broadcast/query.
+ #
+ # Broadcast authentication in a production environment is very importantant since broadcasters
+ # can execute JavaScript on subscribed clients, leaving you vulnerable to cross site scripting
+ # attacks if broadcasters aren't authenticated.
+
+ # 1) Via IP address
+ #
+ # If specified, if a client has an ip that is specified in allowed_ips, than it is automatically
+ # authenticated, even if a secret_key isn't provided.
+ #
+ # This is the recommended method for broadcast authentication.
+ #
+ :allowed_ips:
+ - 127.0.0.1
+ # - 192.168.0.1
+
+ # 2) Via HTTP request
+ #
+ # If specified, if a client attempts a broadcast/query, without a secret_key or using an IP
+ # no included in allowed_ips, then broadcast_query_login_url will be called.
+ # Parameters passed, if given, are: session_id, client_id, channels and type.
+ #
+ # The server should check that the session_id matches up to the client id, and the client
+ # is allowed to perform that particular type of broadcast/query.
+ #
+ # If a status code other than 200 is encountered, the broadcast_query_login_url fails
+ # and the client is disconnected.
+ #
+ # :broadcast_query_login_url: http://localhost:3000/sessions/juggernaut_broadcast
+
+ # 3) Via shared secret key
+ #
+ # This secret key must be sent with any query/broadcast commands.
+ # It must be the same as the one in the Rails config file.
+ #
+ # You shouldn't authenticate broadcasts from subscribed clients using this method
+ # since the secret_key will be easily visible in the page (and not so secret any more)!
+ #
+ # :secret_key: 8a01f4941eac46fcb36354c62487ef04d113cdbe
+
+ # == Subscription Logout ==
+
+ # If specified, logout_connection_url is called everytime a specific connection from a subscribed client disconnects.
+ # Parameters passed are session_id, client_id and an array of channels specific to that connection.
+ #
+ # :logout_connection_url: http://localhost:3000/sessions/juggernaut_connection_logout
+
+ # Logout url is called when all connections from a subscribed client are closed.
+ # Parameters passed are session_id and client_id.
+ #
+ # :logout_url: http://localhost:3000/sessions/juggernaut_logout
+
+ # === Miscellaneous ===
+
+ # timeout defaults to 10. A timeout is the time between when a client closes a connection
+ # and a logout_request or logout_connection_request is made. The reason for this is that a client
+ # may only temporarily be disconnected, and may attempt a reconnect very soon.
+ #
+ # :timeout: 10
+
+ # store_messages defaults to false. If this option is true, messages send to connections will be stored.
+ # This is useful since a client can then receive broadcasted message that it has missed (perhaps it was disconnected).
+ #
+ # :store_messages: false
+
+ # === Server ===
+
+ # Host defaults to "0.0.0.0". You shouldn't need to change this.
+ # :host: 0.0.0.0
+
+ # Port is mandatory
+ :port: 5001
+
diff --git a/vendor/plugins/juggernaut_plugin/media/juggernaut_hosts.yml b/vendor/plugins/juggernaut_plugin/media/juggernaut_hosts.yml
new file mode 100644
index 0000000..36bf2fe
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/juggernaut_hosts.yml
@@ -0,0 +1,18 @@
+# You should list any juggernaut hosts here.
+# You need only specify the secret key if you're using that type of authentication (see juggernaut.yml)
+#
+# Name: Mapping:
+# :port internal push server's port
+# :host internal push server's host/ip
+# :public_host public push server's host/ip (accessible from external clients)
+# :public_port public push server's port
+# :secret_key (optional) shared secret (should map to the key specified in the push server's config)
+# :environment (optional) limit host to a particular RAILS_ENV
+
+:hosts:
+ - :port: 5001
+ :host: 127.0.0.1
+ :public_host: 127.0.0.1
+ :public_port: 5001
+ # :secret_key: your_secret_key
+ # :environment: :development
\ No newline at end of file
diff --git a/vendor/plugins/juggernaut_plugin/media/log/juggernaut.log b/vendor/plugins/juggernaut_plugin/media/log/juggernaut.log
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/plugins/juggernaut_plugin/media/swfobject.js b/vendor/plugins/juggernaut_plugin/media/swfobject.js
new file mode 100644
index 0000000..c383123
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/media/swfobject.js
@@ -0,0 +1,5 @@
+/* SWFObject v2.0 <http://code.google.com/p/swfobject/>
+ Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
+ This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
+*/
+var swfobject=function(){var Z="undefined",P="object",B="Shockwave Flash",h="ShockwaveFlash.ShockwaveFlash",W="application/x-shockwave-flash",K="SWFObjectExprInst",G=window,g=document,N=navigator,f=[],H=[],Q=null,L=null,T=null,S=false,C=false;var a=function(){var l=typeof g.getElementById!=Z&&typeof g.getElementsByTagName!=Z&&typeof g.createElement!=Z&&typeof g.appendChild!=Z&&typeof g.replaceChild!=Z&&typeof g.removeChild!=Z&&typeof g.cloneNode!=Z,t=[0,0,0],n=null;if(typeof N.plugins!=Z&&typeof N.plugins[B]==P){n=N.plugins[B].description;if(n){n=n.replace(/^.*\s+(\S+\s+\S+$)/,"$1");t[0]=parseInt(n.replace(/^(.*)\..*$/,"$1"),10);t[1]=parseInt(n.replace(/^.*\.(.*)\s.*$/,"$1"),10);t[2]=/r/.test(n)?parseInt(n.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof G.ActiveXObject!=Z){var o=null,s=false;try{o=new ActiveXObject(h+".7")}catch(k){try{o=new ActiveXObject(h+".6");t=[6,0,21];o.AllowScriptAccess="always"}catch(k){if(t[0]==6){s=true}}if(!s){try{o=new ActiveXObject(h)}catch(k){}}}if(!s&&o){try{n=o.GetVariable("$version");if(n){n=n.split(" ")[1].split(",");t=[parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10)]}}catch(k){}}}}var v=N.userAgent.toLowerCase(),j=N.platform.toLowerCase(),r=/webkit/.test(v)?parseFloat(v.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,i=false,q=j?/win/.test(j):/win/.test(v),m=j?/mac/.test(j):/mac/.test(v);/*@cc_on i=true;@if(@_win32)q=true;@elif(@_mac)m=true;@end@*/return{w3cdom:l,pv:t,webkit:r,ie:i,win:q,mac:m}}();var e=function(){if(!a.w3cdom){return }J(I);if(a.ie&&a.win){try{g.write("<script id=__ie_ondomload defer=true src=//:><\/script>");var i=c("__ie_ondomload");if(i){i.onreadystatechange=function(){if(this.readyState=="complete"){this.parentNode.removeChild(this);V()}}}}catch(j){}}if(a.webkit&&typeof g.readyState!=Z){Q=setInterval(function(){if(/loaded|complete/.test(g.readyState)){V()}},10)}if(typeof g.addEventListener!=Z){g.addEventListener("DOMContentLoaded",V,null)}M(V)}();function V(){if(S){return }if(a.ie&&a.win){var m=Y("span");try{var l=g.getElementsByTagName("body")[0].appendChild(m);l.parentNode.removeChild(l)}catch(n){return }}S=true;if(Q){clearInterval(Q);Q=null}var j=f.length;for(var k=0;k<j;k++){f[k]()}}function J(i){if(S){i()}else{f[f.length]=i}}function M(j){if(typeof G.addEventListener!=Z){G.addEventListener("load",j,false)}else{if(typeof g.addEventListener!=Z){g.addEventListener("load",j,false)}else{if(typeof G.attachEvent!=Z){G.attachEvent("onload",j)}else{if(typeof G.onload=="function"){var i=G.onload;G.onload=function(){i();j()}}else{G.onload=j}}}}}function I(){var l=H.length;for(var j=0;j<l;j++){var m=H[j].id;if(a.pv[0]>0){var k=c(m);if(k){H[j].width=k.getAttribute("width")?k.getAttribute("width"):"0";H[j].height=k.getAttribute("height")?k.getAttribute("height"):"0";if(O(H[j].swfVersion)){if(a.webkit&&a.webkit<312){U(k)}X(m,true)}else{if(H[j].expressInstall&&!C&&O("6.0.65")&&(a.win||a.mac)){D(H[j])}else{d(k)}}}}else{X(m,true)}}}function U(m){var k=m.getElementsByTagName(P)[0];if(k){var p=Y("embed"),r=k.attributes;if(r){var o=r.length;for(var n=0;n<o;n++){if(r[n].nodeName.toLowerCase()=="data"){p.setAttribute("src",r[n].nodeValue)}else{p.setAttribute(r[n].nodeName,r[n].nodeValue)}}}var q=k.childNodes;if(q){var s=q.length;for(var l=0;l<s;l++){if(q[l].nodeType==1&&q[l].nodeName.toLowerCase()=="param"){p.setAttribute(q[l].getAttribute("name"),q[l].getAttribute("value"))}}}m.parentNode.replaceChild(p,m)}}function F(i){if(a.ie&&a.win&&O("8.0.0")){G.attachEvent("onunload",function(){var k=c(i);if(k){for(var j in k){if(typeof k[j]=="function"){k[j]=function(){}}}k.parentNode.removeChild(k)}})}}function D(j){C=true;var o=c(j.id);if(o){if(j.altContentId){var l=c(j.altContentId);if(l){L=l;T=j.altContentId}}else{L=b(o)}if(!(/%$/.test(j.width))&&parseInt(j.width,10)<310){j.width="310"}if(!(/%$/.test(j.height))&&parseInt(j.height,10)<137){j.height="137"}g.title=g.title.slice(0,47)+" - Flash Player Installation";var n=a.ie&&a.win?"ActiveX":"PlugIn",k=g.title,m="MMredirectURL="+G.location+"&MMplayerType="+n+"&MMdoctitle="+k,p=j.id;if(a.ie&&a.win&&o.readyState!=4){var i=Y("div");p+="SWFObjectNew";i.setAttribute("id",p);o.parentNode.insertBefore(i,o);o.style.display="none";G.attachEvent("onload",function(){o.parentNode.removeChild(o)})}R({data:j.expressInstall,id:K,width:j.width,height:j.height},{flashvars:m},p)}}function d(j){if(a.ie&&a.win&&j.readyState!=4){var i=Y("div");j.parentNode.insertBefore(i,j);i.parentNode.replaceChild(b(j),i);j.style.display="none";G.attachEvent("onload",function(){j.parentNode.removeChild(j)})}else{j.parentNode.replaceChild(b(j),j)}}function b(n){var m=Y("div");if(a.win&&a.ie){m.innerHTML=n.innerHTML}else{var k=n.getElementsByTagName(P)[0];if(k){var o=k.childNodes;if(o){var j=o.length;for(var l=0;l<j;l++){if(!(o[l].nodeType==1&&o[l].nodeName.toLowerCase()=="param")&&!(o[l].nodeType==8)){m.appendChild(o[l].cloneNode(true))}}}}}return m}function R(AE,AC,q){var p,t=c(q);if(typeof AE.id==Z){AE.id=q}if(a.ie&&a.win){var AD="";for(var z in AE){if(AE[z]!=Object.prototype[z]){if(z=="data"){AC.movie=AE[z]}else{if(z.toLowerCase()=="styleclass"){AD+=' class="'+AE[z]+'"'}else{if(z!="classid"){AD+=" "+z+'="'+AE[z]+'"'}}}}}var AB="";for(var y in AC){if(AC[y]!=Object.prototype[y]){AB+='<param name="'+y+'" value="'+AC[y]+'" />'}}t.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AD+">"+AB+"</object>";F(AE.id);p=c(AE.id)}else{if(a.webkit&&a.webkit<312){var AA=Y("embed");AA.setAttribute("type",W);for(var x in AE){if(AE[x]!=Object.prototype[x]){if(x=="data"){AA.setAttribute("src",AE[x])}else{if(x.toLowerCase()=="styleclass"){AA.setAttribute("class",AE[x])}else{if(x!="classid"){AA.setAttribute(x,AE[x])}}}}}for(var w in AC){if(AC[w]!=Object.prototype[w]){if(w!="movie"){AA.setAttribute(w,AC[w])}}}t.parentNode.replaceChild(AA,t);p=AA}else{var s=Y(P);s.setAttribute("type",W);for(var v in AE){if(AE[v]!=Object.prototype[v]){if(v.toLowerCase()=="styleclass"){s.setAttribute("class",AE[v])}else{if(v!="classid"){s.setAttribute(v,AE[v])}}}}for(var u in AC){if(AC[u]!=Object.prototype[u]&&u!="movie"){E(s,u,AC[u])}}t.parentNode.replaceChild(s,t);p=s}}return p}function E(k,i,j){var l=Y("param");l.setAttribute("name",i);l.setAttribute("value",j);k.appendChild(l)}function c(i){return g.getElementById(i)}function Y(i){return g.createElement(i)}function O(k){var j=a.pv,i=k.split(".");i[0]=parseInt(i[0],10);i[1]=parseInt(i[1],10);i[2]=parseInt(i[2],10);return(j[0]>i[0]||(j[0]==i[0]&&j[1]>i[1])||(j[0]==i[0]&&j[1]==i[1]&&j[2]>=i[2]))?true:false}function A(m,j){if(a.ie&&a.mac){return }var l=g.getElementsByTagName("head")[0],k=Y("style");k.setAttribute("type","text/css");k.setAttribute("media","screen");if(!(a.ie&&a.win)&&typeof g.createTextNode!=Z){k.appendChild(g.createTextNode(m+" {"+j+"}"))}l.appendChild(k);if(a.ie&&a.win&&typeof g.styleSheets!=Z&&g.styleSheets.length>0){var i=g.styleSheets[g.styleSheets.length-1];if(typeof i.addRule==P){i.addRule(m,j)}}}function X(k,i){var j=i?"visible":"hidden";if(S){c(k).style.visibility=j}else{A("#"+k,"visibility:"+j)}}return{registerObject:function(l,i,k){if(!a.w3cdom||!l||!i){return }var j={};j.id=l;j.swfVersion=i;j.expressInstall=k?k:false;H[H.length]=j;X(l,false)},getObjectById:function(l){var i=null;if(a.w3cdom&&S){var j=c(l);if(j){var k=j.getElementsByTagName(P)[0];if(!k||(k&&typeof j.SetVariable!=Z)){i=j}else{if(typeof k.SetVariable!=Z){i=k}}}}return i},embedSWF:function(n,u,r,t,j,m,k,p,s){if(!a.w3cdom||!n||!u||!r||!t||!j){return }r+="";t+="";if(O(j)){X(u,false);var q=(typeof s==P)?s:{};q.data=n;q.width=r;q.height=t;var o=(typeof p==P)?p:{};if(typeof k==P){for(var l in k){if(k[l]!=Object.prototype[l]){if(typeof o.flashvars!=Z){o.flashvars+="&"+l+"="+k[l]}else{o.flashvars=l+"="+k[l]}}}}J(function(){R(q,o,u);if(q.id==u){X(u,true)}})}else{if(m&&!C&&O("6.0.65")&&(a.win||a.mac)){X(u,false);J(function(){var i={};i.id=i.altContentId=u;i.width=r;i.height=t;i.expressInstall=m;D(i)})}}},getFlashPlayerVersion:function(){return{major:a.pv[0],minor:a.pv[1],release:a.pv[2]}},hasFlashPlayerVersion:O,createSWF:function(k,j,i){if(a.w3cdom&&S){return R(k,j,i)}else{return undefined}},createCSS:function(j,i){if(a.w3cdom){A(j,i)}},addDomLoadEvent:J,addLoadEvent:M,getQueryParamValue:function(m){var l=g.location.search||g.location.hash;if(m==null){return l}if(l){var k=l.substring(1).split("&");for(var j=0;j<k.length;j++){if(k[j].substring(0,k[j].indexOf("="))==m){return k[j].substring((k[j].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(C&&L){var i=c(K);if(i){i.parentNode.replaceChild(L,i);if(T){X(T,true);if(a.ie&&a.win){L.style.display="block"}}L=null;T=null;C=false}}}}}();
\ No newline at end of file
diff --git a/vendor/plugins/juggernaut_plugin/tasks/juggernaut.rake b/vendor/plugins/juggernaut_plugin/tasks/juggernaut.rake
new file mode 100644
index 0000000..c0c024f
--- /dev/null
+++ b/vendor/plugins/juggernaut_plugin/tasks/juggernaut.rake
@@ -0,0 +1,13 @@
+namespace :juggernaut do
+ desc "Reinstall the Juggernaut js and swf files"
+ task :reinstall do
+ load "#{File.dirname(__FILE__)}/../install.rb"
+ end
+end
+
+namespace :juggernaut do
+ desc 'Compile the juggernaut flash file'
+ task :compile_flash do
+ `mtasc -version 8 -header 1:1:1 -main -swf media/juggernaut.swf media/juggernaut.as`
+ end
+end
|
petrsigut/unico | e0c8791e9a2836ce99c1eef1a658eaa51356b9b8 | better index, xml transform, plain text | diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 8c76556..51d791c 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,47 +1,63 @@
class ContentsController < ApplicationController
layout :type_of_layout
def index
@contents = Content.find(:all)
+ @layout = "application"
end
def show
@name = params[:id]
# at nam pod to @name nepodstrci nejakou prasarnu!
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
- case @name
- when "pcfilmtydne"
- Pcfilmtydne.parse_raw_html
- Pcfilmtydne.parse_xml
- when "csfddokin"
- Csfddokin.parse_raw_html
- Csfddokin.parse_xml
- when "cnbkurzy"
- Cnbkurzy.parse_raw_html
- Cnbkurzy.parse_xml
- when "photoofthedaycom"
- Photoofthedaycom.parse_raw_html
- Photoofthedaycom.parse_xml
- @layout = "slideshow"
+ # http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/
+
+ @name = @name.humanize
+ @content = Content.find(:all, :select => 'name')
+
+ found_in_db = false
+ @content.each do |name|
+ if @name == name.name
+ found_in_db = true
+ end
+ end
+
+ if found_in_db
+ @content = Content.find_by_name(@name, :select => 'updated_at')
+ if @content.updated_at < 10.seconds.ago # should be set by variable in content model
+ (@name).constantize.parse_content
+ end
+ @content = Content.find_by_name(@name)
+ else
+ render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return
end
- @content = Content.find_by_name(@name) # udelat pres tridni promenou?
+
+ # udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
-
+
+ # http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb
+ # Mime::Type.register "image/jpg", :jpg
+ Mime::Type.register "text/html", :xhtml
+ Mime::Type.register "text/plain", :txt
+
+
respond_to do |format|
format.html # show.html.erb
+ format.xhtml # show.xhtml.erb
+ format.txt # show.txt.erb
format.xml { render :xml => @content.xml }
end
end
private
def type_of_layout
@layout
end
end
diff --git a/app/models/.fiterminy.rb.swp b/app/models/.fiterminy.rb.swp
new file mode 100644
index 0000000..d69b52e
Binary files /dev/null and b/app/models/.fiterminy.rb.swp differ
diff --git a/app/models/.pcfilmtydne.rb.swp b/app/models/.pcfilmtydne.rb.swp
new file mode 100644
index 0000000..11e9baa
Binary files /dev/null and b/app/models/.pcfilmtydne.rb.swp differ
diff --git a/app/models/cnbkurzy.rb b/app/models/cnbkurzy.rb
index 193003c..121ef56 100644
--- a/app/models/cnbkurzy.rb
+++ b/app/models/cnbkurzy.rb
@@ -1,26 +1,12 @@
class Cnbkurzy < Content
attr_accessor :name
- def self.parse_raw_html
- @doc = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
- @doc = @doc.search("//table[@class='kurzy_tisk']")
-
-
-# @kurzy = {}
-# (@movies/"//table//tr").each do |row|
-# (row/"//td").each do |cell|
-# logger.fatal cell.inner_html
-# end
-# logger.fatal "XXX"
-# end
-
-
+ def self.parse_content
+ @rawhtml = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
+ @rawhtml = @rawhtml.at("//table[@class='kurzy_tisk']")
save_me
end
- def self.parse_xml
- save_me
- end
end
diff --git a/app/models/content.rb b/app/models/content.rb
index ec32765..b16d8db 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,48 +1,83 @@
class Content < ActiveRecord::Base
require 'hpricot'
require 'open-uri'
require 'net/http'
+ require 'logger'
require "rexml/document"
+
+ # needed for XML XSLT
+ require 'xml/libxml'
+ require 'xml/libxslt'
+
+ def self.html2txt(html)
+ # http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/strip_tags
+ html = ActionController::Base.helpers.strip_tags(html)
+# html = sanitize(html)
+ end
+
+ def self.transform_xml2html(xml)
+ xslt = XML::XSLT.new()
+ xslt.xml = xml.to_s
+ xslt.xsl = "#{RAILS_ROOT}/public/xml2html.xls"
+ xslt.serve()
+ end
# private nebo tak neco?
def self.create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
end
def self.create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
end
def self.create_gallery(array_of_links)
- html_chunk = '<div id="slideshow">'
- html_chunk += "<img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" class=\"active\" />\n"
+ html_chunk = "<a href=\"#\" class=\"show\" ><img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" rel=\"fdsafa\" /></a>\n"
array_of_links.each_with_index do |link, index|
- html_chunk += "<img src=\"#{array_of_links[index]}\" alt=\"Slideshow Image 1\" />\n"
+ html_chunk += "<a href=\"#\"><img src=\"#{array_of_links[index]}\" alt=\"Slideshow Image 1\" /></a>\n"
end
html_chunk += '</div>'
end
def self.save_me
# tohle až do konce můžu zoobecnit pro vÅ¡echny tÅÃdy...
@content = Content.find_by_name(self.name) # udelat pres tridni promenou?
if @content.nil?
@content = Content.new
+ @content.name = self.name
end
- @content.name = self.name
- @content.xml = @kml_doc.to_s
- @content.rawhtml = @doc.to_s
- @content.save
-
+ @content.name_human = @name_human
+
+ if @kml_doc.nil?
+ @content.xml = nil
+ else
+ html_from_xml = transform_xml2html(@kml_doc)
+ @content.xml = @kml_doc.to_s
+ @content.xhtml = html_from_xml
+ end
+ if @rawhtml.nil?
+ @content.rawhtml = nil
+ else
+ @content.rawhtml = @rawhtml.to_s
+ txt = html2txt(@rawhtml.to_s)
+ @content.plaintext = txt
+ end
+
+ # Rails detect whether we change the content of record and if not,
+ # update_at will not be updated. But we want to update it every time we
+ # regenerete content
+ @content.updated_at = Time.now
+ @content.save
end
end
diff --git a/app/models/csfddokin.rb b/app/models/csfddokin.rb
index 89afcdf..d3051a3 100644
--- a/app/models/csfddokin.rb
+++ b/app/models/csfddokin.rb
@@ -1,29 +1,26 @@
# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
# check_if_old?
class Csfddokin < Content
- attr_accessor :name
- def self.parse_raw_html
- @doc = Hpricot(open("http://www.csfd.cz/"))
- @doc = @doc.search("//body")
- @doc = @doc.to_s()
+ def self.parse_content
+ @name_human = "ÄSFD do kin"
- @doc.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
- @doc.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
- @doc.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+ @rawhtml = Hpricot(open("http://www.csfd.cz/"))
+ @rawhtml = @rawhtml.search("//body")
+ @rawhtml = @rawhtml.to_s()
- @doc = Hpricot(@doc)
- @doc = @doc.at("//table")
+ @rawhtml.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
+ @rawhtml.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
+ @rawhtml.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+
+ @rawhtml = Hpricot(@rawhtml)
+ @rawhtml = @rawhtml.at("//table")
# @movies = '<link rel="stylesheet" type="text/css" href="http://localhost/~phax/test.css" />' + @movies
save_me
end
- def self.parse_xml
- save_me
- end
-
end
diff --git a/app/models/fiterminy.rb b/app/models/fiterminy.rb
index 080d95f..02c4b9b 100644
--- a/app/models/fiterminy.rb
+++ b/app/models/fiterminy.rb
@@ -1,15 +1,11 @@
class Fiterminy < Content
attr_accessor :name
- def self.parse_raw_html
- @doc = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
- @doc = @doc.at("//table")
+ def self.parse_content
+ @rawhtml = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
+ @rawhtml = @rawhtml.at("//table")
save_me
end
- def self.parse_xml
- save_me
- end
-
end
diff --git a/app/models/googlepocasibrno.rb b/app/models/googlepocasibrno.rb
new file mode 100644
index 0000000..97fd39d
--- /dev/null
+++ b/app/models/googlepocasibrno.rb
@@ -0,0 +1,22 @@
+class Googlepocasibrno < Content
+ require 'rexml/document'
+
+ attr_accessor :name
+
+ def self.parse_content
+ url="http://www.google.com/ig/api?weather=brno,czech+republic&hl=en"
+ xml_data = Net::HTTP.get_response(URI.parse(url)).body
+ doc = REXML::Document.new(xml_data)
+
+ create_xml_head
+
+ doc.elements.each("xml_api_reply/weather/current_conditions/*") do |element|
+ create_xml_body("label", element.attributes.get_attribute("data"))
+ end
+
+
+ save_me
+ end
+
+
+end
diff --git a/app/models/movie.rb b/app/models/movie.rb
deleted file mode 100644
index bc4c3af..0000000
--- a/app/models/movie.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-class Movie
- attr_accessor :name
-
- def parse_raw_html
- end
-end
diff --git a/app/models/pcfilmtydne.rb b/app/models/pcfilmtydne.rb
index 93a88ec..64d4da4 100644
--- a/app/models/pcfilmtydne.rb
+++ b/app/models/pcfilmtydne.rb
@@ -1,34 +1,28 @@
# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
# check_if_old?
class Pcfilmtydne < Content
attr_accessor :name
- def self.parse_raw_html
- @doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
- @doc = @doc.search("//div[@class='frame red']")
- save_me
- end
-
- def self.parse_xml
- @doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
- @doc = @doc.search("//div[@class='frame red']")
+ def self.parse_content
+ @rawhtml = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
+ @rawhtml = @rawhtml.at("//div[@class='frame red']")
- @label1 = @doc.at("//h3")
- @label2 = @doc.at("//h2")
- @image1 = @doc.at("//img")
+ @label1 = @rawhtml.at("//h3")
+ @label2 = @rawhtml.at("//h2")
+ @image1 = @rawhtml.at("//img")
@image1 = @image1.attributes['src']
- @label3 = @doc.at("//p")
+ @label3 = @rawhtml.at("//p")
create_xml_head
create_xml_body("label", @label1)
create_xml_body("label", @label2)
create_xml_body("image", @image1)
create_xml_body("label", @label3)
create_xml_body("label", self.name)
save_me
end
end
diff --git a/app/models/photoofthedaycom.rb b/app/models/photoofthedaycom.rb
index 060dffb..1c0cc00 100644
--- a/app/models/photoofthedaycom.rb
+++ b/app/models/photoofthedaycom.rb
@@ -1,30 +1,28 @@
class Photoofthedaycom < Content
attr_accessor :name
- def self.parse_raw_html
+ def self.parse_content
year = Time.now.strftime("%Y")
# with leading zeros
month = Time.now.strftime("%m")
day = Time.now.strftime("%d")
- @doc = []
+ create_xml_head
+
+ @rawhtml = []
10.times.with_index do |x, index|
if index < 9
- @doc << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
+ @rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
else
- @doc << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
+ @rawhtml << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
end
+ create_xml_body("image", @rawhtml[index])
end
- @doc = create_gallery(@doc)
- logger.fatal "Logujem"
- logger.fatal @doc
+ @rawhtml = create_gallery(@rawhtml)
save_me
end
- def self.parse_xml
- save_me
- end
end
diff --git a/app/models/sablona b/app/models/sablona.rb
similarity index 100%
rename from app/models/sablona
rename to app/models/sablona.rb
diff --git a/app/models/youtube.rb b/app/models/youtube.rb
new file mode 100644
index 0000000..2043742
--- /dev/null
+++ b/app/models/youtube.rb
@@ -0,0 +1,15 @@
+class Youtube < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open(""))
+
+ save_me
+ end
+
+ def self.parse_xml
+ #http://www.youtube.com/get_video?video_id=v_4-zRVFLnY&t=vjVQa1PpcFMoUet4DvWYTUuw
+ save_me
+ end
+
+end
diff --git a/app/views/contents/.show.txt.erb.swp b/app/views/contents/.show.txt.erb.swp
new file mode 100644
index 0000000..c7481ac
Binary files /dev/null and b/app/views/contents/.show.txt.erb.swp differ
diff --git a/app/views/contents/index.html.erb b/app/views/contents/index.html.erb
index d32fc10..4c834bb 100644
--- a/app/views/contents/index.html.erb
+++ b/app/views/contents/index.html.erb
@@ -1,6 +1,20 @@
<% for content in @contents %>
- <div class="content">
- <%=h content.name %>
- <%= content.rawhtml %>
+ <div class="content">
+ <span><%=h content.name_human %></span>
+
+ <% unless content.rawhtml.nil? %>
+ <span><%= link_to "HTML", "/contents/show/"+content.name+".html" %></span>
+ <% end %>
+
+ <% unless content.xml.nil? %>
+ <span><%= link_to "XML", "/contents/show/"+content.name+".xml" %></span>
+ <span><%= link_to "XHTML", "/contents/show/"+content.name+".xhtml" %></span>
+ <% end %>
+
+ <% unless content.rawhtml.nil? %>
+ <%= content.rawhtml %>
+ <% else %>
+ <%= content.xhtml %>
+ <% end %>
</div>
<% end %>
diff --git a/app/views/contents/show.txt.erb b/app/views/contents/show.txt.erb
new file mode 100644
index 0000000..b606be8
--- /dev/null
+++ b/app/views/contents/show.txt.erb
@@ -0,0 +1 @@
+<%= @content.plaintext %>
diff --git a/app/views/contents/show.xhtml.erb b/app/views/contents/show.xhtml.erb
new file mode 100644
index 0000000..10613e5
--- /dev/null
+++ b/app/views/contents/show.xhtml.erb
@@ -0,0 +1 @@
+<%= @content.xhtml %>
diff --git a/app/views/layouts/slideshow.html.erb b/app/views/layouts/slideshow.html.erb
index 9d6b3e6..81c6825 100644
--- a/app/views/layouts/slideshow.html.erb
+++ b/app/views/layouts/slideshow.html.erb
@@ -1,85 +1,147 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
- <%= stylesheet_link_tag 'style' %>
-<!-- tady budu muset nacpat absolutni cestu? To ale nejde... poresit -->
- <%= javascript_include_tag 'jquery.js' %>
-<script type="text/javascript">
-
-/***
- Simple jQuery Slideshow Script
- Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc. Please link out to me if you like it :)
-***/
-
-function slideSwitch() {
- var $active = $('#slideshow IMG.active');
-
- if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
-
- // use this to pull the images in the order they appear in the markup
- var $next = $active.next().length ? $active.next()
- : $('#slideshow IMG:first');
-
- // uncomment the 3 lines below to pull the images in random order
-
- // var $sibs = $active.siblings();
- // var rndNum = Math.floor(Math.random() * $sibs.length );
- // var $next = $( $sibs[ rndNum ] );
-
-
- $active.addClass('last-active');
-
- $next.css({opacity: 0.0})
- .addClass('active')
- .animate({opacity: 1.0}, 1000, function() {
- $active.removeClass('active last-active');
- });
-}
-
-$(function() {
- setInterval( "slideSwitch()", 1000 );
-});
-
-</script>
-
-<style type="text/css">
-
-/*** set the width and height to match your images **/
-
-#slideshow {
- position:relative;
- height:650px;
-}
-
-#slideshow IMG {
- position:absolute;
- top:0;
- left:0;
- z-index:8;
- opacity:0.0;
-}
-
-#slideshow IMG.active {
- z-index:10;
- opacity:1.0;
-}
-
-#slideshow IMG.last-active {
- z-index:9;
-}
-
-</style>
-</head>
-
-
-<body>
-
-<p style="color: green"><%= flash[:notice] %></p>
-
-<%= yield %>
-
-</body>
-</html>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<title>JQuery Photo Slider with Semi Transparent Caption</title>
+
+<%= javascript_include_tag 'jquery.js' %>
+<script type="text/javascript">
+
+$(document).ready(function() {
+
+ //Execute the slideShow
+ slideShow();
+
+});
+
+function slideShow() {
+
+ //Set the opacity of all images to 0
+ // $('#gallery a').css({opacity: 0.0});
+ $('#gallery a').css("display","none");
+
+ //Get the first image and display it (set it to full opacity)
+ //$('#gallery a:first').css({opacity: 1.0});
+ $('#gallery a:first').css("display", "block" );
+
+ //Set the caption background to semi-transparent
+ $('#gallery .caption').css({opacity: 0.7});
+
+ //Resize the width of the caption according to the image width
+ $('#gallery .caption').css({width: $('#gallery a').find('img').css('width')});
+
+ //Get the caption of the first image from REL attribute and display it
+ $('#gallery .content').html($('#gallery a:first').find('img').attr('rel'))
+ .animate({opacity: 0.7}, 400);
+
+ //Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
+ setInterval('gallery()',6000);
+
+}
+
+function gallery() {
+
+ //if no IMGs have the show class, grab the first image
+ var current = ($('#gallery a.show')? $('#gallery a.show') : $('#gallery a:first'));
+
+ //Get next image, if it reached the end of the slideshow, rotate it back to the first image
+ var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#gallery a:first') :current.next()) : $('#gallery a:first'));
+
+ //Get next image caption
+ var caption = next.find('img').attr('rel');
+
+ //Set the fade in effect for the next image, show class has higher z-index
+ next.css({
+ display: 'block',
+ opacity: 0.0
+ })
+ .addClass('show')
+ .animate({opacity: 1.0}, 1000);
+
+// next.css({opacity: 0.0})
+// .addClass('show')
+// .animate({opacity: 1.0}, 1000);
+
+ //Hide the current image
+ //current.animate({opacity: 0.0}, 1000)
+ //.removeClass('show');
+ current.animate({opacity: 0.0}, 1000)
+ .css({display: 'none'})
+ .removeClass('show');
+
+ //Set the opacity to 0 and height to 1px
+ $('#gallery .caption').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '1px'}, { queue:true, duration:300 });
+
+ //Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect
+ $('#gallery .caption').animate({opacity: 0.7},100 ).animate({height: '100px'},500 );
+
+ //Display the content
+ $('#gallery .content').html(caption);
+
+
+}
+
+</script>
+<style type="text/css">
+body{
+ font-family:arial
+}
+
+.clear {
+ clear:both
+}
+
+#gallery {
+ position:relative;
+ height:360px
+}
+ #gallery a {
+ float:left;
+ position:absolute;
+ }
+
+ #gallery a img {
+ border:none;
+ }
+
+ #gallery a.show {
+ z-index:500
+ }
+
+ #gallery .caption {
+ z-index:600;
+ background-color:#000;
+ color:#ffffff;
+ height:100px;
+ width:100%;
+ position:absolute;
+ bottom:0;
+ }
+
+ #gallery .caption .content {
+ margin:5px
+ }
+
+ #gallery .caption .content h3 {
+ margin:0;
+ padding:0;
+ color:#1DCCEF;
+ }
+
+
+</style>
+</head>
+<body>
+<div id="gallery">
+
+<%= yield %>
+
+<div class="caption"><div class="content"></div></div>
+</div>
+<div class="clear"></div>
+
+<br/><br/>
+<div style="font-size:10px;color:#ccc">Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License.</div>
+
+
+</body>
+</html>
diff --git a/app/views/layouts/slideshow_old.html.erb b/app/views/layouts/slideshow_old.html.erb
new file mode 100644
index 0000000..9d6b3e6
--- /dev/null
+++ b/app/views/layouts/slideshow_old.html.erb
@@ -0,0 +1,85 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
+ <%= stylesheet_link_tag 'style' %>
+<!-- tady budu muset nacpat absolutni cestu? To ale nejde... poresit -->
+ <%= javascript_include_tag 'jquery.js' %>
+<script type="text/javascript">
+
+/***
+ Simple jQuery Slideshow Script
+ Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc. Please link out to me if you like it :)
+***/
+
+function slideSwitch() {
+ var $active = $('#slideshow IMG.active');
+
+ if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
+
+ // use this to pull the images in the order they appear in the markup
+ var $next = $active.next().length ? $active.next()
+ : $('#slideshow IMG:first');
+
+ // uncomment the 3 lines below to pull the images in random order
+
+ // var $sibs = $active.siblings();
+ // var rndNum = Math.floor(Math.random() * $sibs.length );
+ // var $next = $( $sibs[ rndNum ] );
+
+
+ $active.addClass('last-active');
+
+ $next.css({opacity: 0.0})
+ .addClass('active')
+ .animate({opacity: 1.0}, 1000, function() {
+ $active.removeClass('active last-active');
+ });
+}
+
+$(function() {
+ setInterval( "slideSwitch()", 1000 );
+});
+
+</script>
+
+<style type="text/css">
+
+/*** set the width and height to match your images **/
+
+#slideshow {
+ position:relative;
+ height:650px;
+}
+
+#slideshow IMG {
+ position:absolute;
+ top:0;
+ left:0;
+ z-index:8;
+ opacity:0.0;
+}
+
+#slideshow IMG.active {
+ z-index:10;
+ opacity:1.0;
+}
+
+#slideshow IMG.last-active {
+ z-index:9;
+}
+
+</style>
+</head>
+
+
+<body>
+
+<p style="color: green"><%= flash[:notice] %></p>
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/db/migrate/20091031100608_add_name_human_to_contents.rb b/db/migrate/20091031100608_add_name_human_to_contents.rb
new file mode 100644
index 0000000..371cfbf
--- /dev/null
+++ b/db/migrate/20091031100608_add_name_human_to_contents.rb
@@ -0,0 +1,9 @@
+class AddNameHumanToContents < ActiveRecord::Migration
+ def self.up
+ add_column :contents, :name_human, :string
+ end
+
+ def self.down
+ remove_column :contents, :name_human
+ end
+end
diff --git a/db/migrate/20091031104431_add_html_from_xml_to_contents.rb b/db/migrate/20091031104431_add_html_from_xml_to_contents.rb
new file mode 100644
index 0000000..30ad9f6
--- /dev/null
+++ b/db/migrate/20091031104431_add_html_from_xml_to_contents.rb
@@ -0,0 +1,9 @@
+class AddHtmlFromXmlToContents < ActiveRecord::Migration
+ def self.up
+ add_column :contents, :xhtml, :text
+ end
+
+ def self.down
+ remove_column :contents, :xhtml
+ end
+end
diff --git a/db/migrate/20091031120615_add_plaintext_to_contents.rb b/db/migrate/20091031120615_add_plaintext_to_contents.rb
new file mode 100644
index 0000000..06ac69a
--- /dev/null
+++ b/db/migrate/20091031120615_add_plaintext_to_contents.rb
@@ -0,0 +1,9 @@
+class AddPlaintextToContents < ActiveRecord::Migration
+ def self.up
+ add_column :contents, :plaintext, :text
+ end
+
+ def self.down
+ remove_column :contents, :plaintext
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 541f4af..d9bd60e 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,22 +1,25 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20091010135514) do
+ActiveRecord::Schema.define(:version => 20091031120615) do
create_table "contents", :force => true do |t|
t.string "name"
t.text "rawhtml"
t.text "xml"
t.datetime "created_at"
t.datetime "updated_at"
+ t.string "name_human"
+ t.text "xhtml"
+ t.text "plaintext"
end
end
diff --git a/public/images/html.png b/public/images/html.png
new file mode 100644
index 0000000..a9a9d2e
Binary files /dev/null and b/public/images/html.png differ
diff --git a/public/images/xml.png b/public/images/xml.png
new file mode 100644
index 0000000..4d9a9dc
Binary files /dev/null and b/public/images/xml.png differ
diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css
index 6897636..82661e1 100644
--- a/public/stylesheets/style.css
+++ b/public/stylesheets/style.css
@@ -1,6 +1,7 @@
div.content {
- border: 1px solid red;
- width: 200px;
+ border: 1px solid gray;
+ width: 250px;
height: 200px;
overflow:auto;
+ float: right;
}
diff --git a/public/xml2html.xls b/public/xml2html.xls
new file mode 100644
index 0000000..f33c59f
--- /dev/null
+++ b/public/xml2html.xls
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
+
+ <head></head>
+ <body>
+
+ <xsl:for-each select="document/*">
+ <xsl:choose>
+ <xsl:when test="name()='label'">
+ <p><xsl:value-of select="."/></p>
+ </xsl:when>
+ <xsl:when test="name()='image'">
+ <xsl:element name="img">
+ <xsl:attribute name="src">
+ <xsl:value-of select="."/>
+ </xsl:attribute>
+ </xsl:element>
+ </xsl:when>
+ </xsl:choose>
+ </xsl:for-each>
+
+
+
+
+</body>
+</html>
|
petrsigut/unico | e4ba5c1a005db7d26cb70526f89941b08cb5b3b5 | prace na Photoofthedaycom pokracuji... | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
deleted file mode 100644
index 180af03..0000000
Binary files a/app/controllers/.contents_controller.rb.swp and /dev/null differ
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
deleted file mode 100644
index a7d7585..0000000
Binary files a/app/models/.content.rb.swp and /dev/null differ
diff --git a/app/models/.photoofthedaycom.rb.swp b/app/models/.photoofthedaycom.rb.swp
deleted file mode 100644
index 26739fe..0000000
Binary files a/app/models/.photoofthedaycom.rb.swp and /dev/null differ
diff --git a/app/models/content.rb b/app/models/content.rb
index 6165595..ec32765 100644
--- a/app/models/content.rb
+++ b/app/models/content.rb
@@ -1,37 +1,48 @@
class Content < ActiveRecord::Base
require 'hpricot'
require 'open-uri'
require 'net/http'
require "rexml/document"
# private nebo tak neco?
def self.create_xml_head
@xml = REXML::Document.new
@kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
@kml_doc = @kml.add_element 'document'
end
def self.create_xml_body(entity_name, entity_text)
(@kml_doc.add_element entity_name).text = entity_text
#(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
end
+ def self.create_gallery(array_of_links)
+ html_chunk = '<div id="slideshow">'
+ html_chunk += "<img src=\"#{array_of_links[0]}\" alt=\"Slideshow Image 1\" class=\"active\" />\n"
+ array_of_links.each_with_index do |link, index|
+ html_chunk += "<img src=\"#{array_of_links[index]}\" alt=\"Slideshow Image 1\" />\n"
+ end
+
+ html_chunk += '</div>'
+
+ end
+
def self.save_me
# tohle až do konce můžu zoobecnit pro vÅ¡echny tÅÃdy...
@content = Content.find_by_name(self.name) # udelat pres tridni promenou?
if @content.nil?
@content = Content.new
end
@content.name = self.name
@content.xml = @kml_doc.to_s
@content.rawhtml = @doc.to_s
@content.save
end
end
diff --git a/app/models/photoofthedaycom.rb b/app/models/photoofthedaycom.rb
index 4e715aa..060dffb 100644
--- a/app/models/photoofthedaycom.rb
+++ b/app/models/photoofthedaycom.rb
@@ -1,14 +1,30 @@
class Photoofthedaycom < Content
attr_accessor :name
def self.parse_raw_html
- @doc = Hpricot(open("http://www.cocoa.de/news2/2009/03/photos/10/photo005.htm"))
+ year = Time.now.strftime("%Y")
+ # with leading zeros
+ month = Time.now.strftime("%m")
+ day = Time.now.strftime("%d")
+
+ @doc = []
+ 10.times.with_index do |x, index|
+ if index < 9
+ @doc << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo00#{index+1}.jpg"
+ else
+ @doc << "http://www.cocoa.de/news2/#{year}/#{month}/photos/#{day}/photo0#{index+1}.jpg"
+ end
+ end
+
+ @doc = create_gallery(@doc)
+ logger.fatal "Logujem"
+ logger.fatal @doc
save_me
end
def self.parse_xml
save_me
end
end
diff --git a/app/views/layouts/.slideshow.html.erb.swp b/app/views/layouts/.slideshow.html.erb.swp
deleted file mode 100644
index d0b243a..0000000
Binary files a/app/views/layouts/.slideshow.html.erb.swp and /dev/null differ
diff --git a/app/views/layouts/slideshow.html.erb b/app/views/layouts/slideshow.html.erb
index 2bc5f96..9d6b3e6 100644
--- a/app/views/layouts/slideshow.html.erb
+++ b/app/views/layouts/slideshow.html.erb
@@ -1,85 +1,85 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<%= stylesheet_link_tag 'style' %>
<!-- tady budu muset nacpat absolutni cestu? To ale nejde... poresit -->
<%= javascript_include_tag 'jquery.js' %>
<script type="text/javascript">
/***
Simple jQuery Slideshow Script
Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc. Please link out to me if you like it :)
***/
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
// use this to pull the images in the order they appear in the markup
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
// uncomment the 3 lines below to pull the images in random order
// var $sibs = $active.siblings();
// var rndNum = Math.floor(Math.random() * $sibs.length );
// var $next = $( $sibs[ rndNum ] );
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
- setInterval( "slideSwitch()", 5000 );
+ setInterval( "slideSwitch()", 1000 );
});
</script>
<style type="text/css">
/*** set the width and height to match your images **/
#slideshow {
position:relative;
- height:350px;
+ height:650px;
}
#slideshow IMG {
position:absolute;
top:0;
left:0;
z-index:8;
opacity:0.0;
}
#slideshow IMG.active {
z-index:10;
opacity:1.0;
}
#slideshow IMG.last-active {
z-index:9;
}
</style>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= yield %>
</body>
</html>
|
petrsigut/unico | 566b577005a148c531ec01dc68fb2dd8066d1d34 | pridavani Photoofthedaycom a reseni layoutu | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
index 2150516..180af03 100644
Binary files a/app/controllers/.contents_controller.rb.swp and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index 2811835..8c76556 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,32 +1,47 @@
class ContentsController < ApplicationController
+ layout :type_of_layout
+
+ def index
+ @contents = Content.find(:all)
+ end
+
def show
@name = params[:id]
# at nam pod to @name nepodstrci nejakou prasarnu!
# zautomatizovat to a udelat automaticky generovany index s prehledem...
# (nahledem html v ramecku? to by bylo huste...)
case @name
when "pcfilmtydne"
Pcfilmtydne.parse_raw_html
Pcfilmtydne.parse_xml
when "csfddokin"
Csfddokin.parse_raw_html
Csfddokin.parse_xml
when "cnbkurzy"
Cnbkurzy.parse_raw_html
Cnbkurzy.parse_xml
+ when "photoofthedaycom"
+ Photoofthedaycom.parse_raw_html
+ Photoofthedaycom.parse_xml
+ @layout = "slideshow"
end
@content = Content.find_by_name(@name) # udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @content.xml }
end
end
+
+ private
+ def type_of_layout
+ @layout
+ end
end
diff --git a/app/models/.cnbkurzy.rb.swp b/app/models/.content.rb.swp
similarity index 74%
rename from app/models/.cnbkurzy.rb.swp
rename to app/models/.content.rb.swp
index 37ed869..a7d7585 100644
Binary files a/app/models/.cnbkurzy.rb.swp and b/app/models/.content.rb.swp differ
diff --git a/app/models/.csfddokin.rb.swp b/app/models/.photoofthedaycom.rb.swp
similarity index 91%
rename from app/models/.csfddokin.rb.swp
rename to app/models/.photoofthedaycom.rb.swp
index cddbfa9..26739fe 100644
Binary files a/app/models/.csfddokin.rb.swp and b/app/models/.photoofthedaycom.rb.swp differ
diff --git a/app/models/csfddokin.rb b/app/models/csfddokin.rb
index e0a4756..89afcdf 100644
--- a/app/models/csfddokin.rb
+++ b/app/models/csfddokin.rb
@@ -1,27 +1,29 @@
# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
# check_if_old?
class Csfddokin < Content
attr_accessor :name
def self.parse_raw_html
@doc = Hpricot(open("http://www.csfd.cz/"))
- @movies = @doc.search("//body")
- @movies = @movies.to_s()
+ @doc = @doc.search("//body")
+ @doc = @doc.to_s()
- @movies.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
- @movies.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
- @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+ @doc.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
+ @doc.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
+ @doc.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+
+ @doc = Hpricot(@doc)
+ @doc = @doc.at("//table")
- @movies = '<link rel="stylesheet" type="text/css" href="http://localhost/~phax/test.css" />' + @movies
+# @movies = '<link rel="stylesheet" type="text/css" href="http://localhost/~phax/test.css" />' + @movies
- @doc = @movies
save_me
end
def self.parse_xml
save_me
end
end
diff --git a/app/models/fiterminy.rb b/app/models/fiterminy.rb
new file mode 100644
index 0000000..080d95f
--- /dev/null
+++ b/app/models/fiterminy.rb
@@ -0,0 +1,15 @@
+class Fiterminy < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open("http://www.fi.muni.cz/studies/dates.xhtml"))
+ @doc = @doc.at("//table")
+
+ save_me
+ end
+
+ def self.parse_xml
+ save_me
+ end
+
+end
diff --git a/app/models/photoofthedaycom.rb b/app/models/photoofthedaycom.rb
new file mode 100644
index 0000000..4e715aa
--- /dev/null
+++ b/app/models/photoofthedaycom.rb
@@ -0,0 +1,14 @@
+class Photoofthedaycom < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open("http://www.cocoa.de/news2/2009/03/photos/10/photo005.htm"))
+
+ save_me
+ end
+
+ def self.parse_xml
+ save_me
+ end
+
+end
diff --git a/app/views/contents/index.html.erb b/app/views/contents/index.html.erb
new file mode 100644
index 0000000..d32fc10
--- /dev/null
+++ b/app/views/contents/index.html.erb
@@ -0,0 +1,6 @@
+<% for content in @contents %>
+ <div class="content">
+ <%=h content.name %>
+ <%= content.rawhtml %>
+ </div>
+<% end %>
diff --git a/app/controllers/.cnb_controller.rb.swp b/app/views/layouts/.slideshow.html.erb.swp
similarity index 78%
rename from app/controllers/.cnb_controller.rb.swp
rename to app/views/layouts/.slideshow.html.erb.swp
index 02c1734..d0b243a 100644
Binary files a/app/controllers/.cnb_controller.rb.swp and b/app/views/layouts/.slideshow.html.erb.swp differ
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
new file mode 100644
index 0000000..ba41e1a
--- /dev/null
+++ b/app/views/layouts/application.html.erb
@@ -0,0 +1,16 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
+ <%= stylesheet_link_tag 'style' %>
+</head>
+<body>
+
+<p style="color: green"><%= flash[:notice] %></p>
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/app/views/layouts/slideshow.html.erb b/app/views/layouts/slideshow.html.erb
new file mode 100644
index 0000000..2bc5f96
--- /dev/null
+++ b/app/views/layouts/slideshow.html.erb
@@ -0,0 +1,85 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
+ <%= stylesheet_link_tag 'style' %>
+<!-- tady budu muset nacpat absolutni cestu? To ale nejde... poresit -->
+ <%= javascript_include_tag 'jquery.js' %>
+<script type="text/javascript">
+
+/***
+ Simple jQuery Slideshow Script
+ Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc. Please link out to me if you like it :)
+***/
+
+function slideSwitch() {
+ var $active = $('#slideshow IMG.active');
+
+ if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
+
+ // use this to pull the images in the order they appear in the markup
+ var $next = $active.next().length ? $active.next()
+ : $('#slideshow IMG:first');
+
+ // uncomment the 3 lines below to pull the images in random order
+
+ // var $sibs = $active.siblings();
+ // var rndNum = Math.floor(Math.random() * $sibs.length );
+ // var $next = $( $sibs[ rndNum ] );
+
+
+ $active.addClass('last-active');
+
+ $next.css({opacity: 0.0})
+ .addClass('active')
+ .animate({opacity: 1.0}, 1000, function() {
+ $active.removeClass('active last-active');
+ });
+}
+
+$(function() {
+ setInterval( "slideSwitch()", 5000 );
+});
+
+</script>
+
+<style type="text/css">
+
+/*** set the width and height to match your images **/
+
+#slideshow {
+ position:relative;
+ height:350px;
+}
+
+#slideshow IMG {
+ position:absolute;
+ top:0;
+ left:0;
+ z-index:8;
+ opacity:0.0;
+}
+
+#slideshow IMG.active {
+ z-index:10;
+ opacity:1.0;
+}
+
+#slideshow IMG.last-active {
+ z-index:9;
+}
+
+</style>
+</head>
+
+
+<body>
+
+<p style="color: green"><%= flash[:notice] %></p>
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/public/javascripts/jquery.js b/public/javascripts/jquery.js
new file mode 100644
index 0000000..b1ae21d
--- /dev/null
+++ b/public/javascripts/jquery.js
@@ -0,0 +1,19 @@
+/*
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
+/*
+ * Sizzle CSS Selector Engine - v0.9.3
+ * Copyright 2009, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
\ No newline at end of file
diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css
new file mode 100644
index 0000000..6897636
--- /dev/null
+++ b/public/stylesheets/style.css
@@ -0,0 +1,6 @@
+div.content {
+ border: 1px solid red;
+ width: 200px;
+ height: 200px;
+ overflow:auto;
+}
|
petrsigut/unico | e755edbb43411c7a796f150e7506a4a71e6e30b8 | predelane vsechny kontrolery na modely | diff --git a/app/controllers/.cnb_controller.rb.swp b/app/controllers/.cnb_controller.rb.swp
index 6709ca2..02c1734 100644
Binary files a/app/controllers/.cnb_controller.rb.swp and b/app/controllers/.cnb_controller.rb.swp differ
diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
index 5b910e2..2150516 100644
Binary files a/app/controllers/.contents_controller.rb.swp and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/controllers/.movies_controller.rb.swp b/app/controllers/.movies_controller.rb.swp
deleted file mode 100644
index c8b66d0..0000000
Binary files a/app/controllers/.movies_controller.rb.swp and /dev/null differ
diff --git a/app/controllers/.pcfilmtydne_controller.rb.swp b/app/controllers/.pcfilmtydne_controller.rb.swp
deleted file mode 100644
index bfe172d..0000000
Binary files a/app/controllers/.pcfilmtydne_controller.rb.swp and /dev/null differ
diff --git a/app/controllers/cnb_controller.rb b/app/controllers/cnb_controller.rb
index d293644..1ac42fc 100644
--- a/app/controllers/cnb_controller.rb
+++ b/app/controllers/cnb_controller.rb
@@ -1,36 +1,34 @@
class CnbController < ApplicationController
require 'hpricot'
# na otvirani urlek
require 'open-uri'
def index
# tady tahaji z imdb:
# http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
@doc = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
- #doc = doc.to_s()
- #@movies = @doc.at("//table/#kurzy_tisk").xpath
- @movies = @doc.search("//table[@class='kurzy_tisk']")
+ @doc = @doc.search("//table[@class='kurzy_tisk']")
- @movies = @movies.to_s()
+ @doc = @doc.to_s()
# @movies.gsub!(/[\n\r]/, "")
# /m nam zajisti ze neresi newlines
# http://www.regular-expressions.info/ruby.html
# @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
# @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
- @movies = Hpricot(@movies)
+ # @movies = Hpricot(@movies)
- @kurzy = {}
- (@movies/"//table//tr").each do |row|
- (row/"//td").each do |cell|
- logger.fatal cell.inner_html
- end
- logger.fatal "XXX"
- end
+ #@kurzy = {}
+# (@movies/"//table//tr").each do |row|
+# (row/"//td").each do |cell|
+# logger.fatal cell.inner_html
+# end
+# logger.fatal "XXX"
+# end
end
end
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
index a71f6a7..2811835 100644
--- a/app/controllers/contents_controller.rb
+++ b/app/controllers/contents_controller.rb
@@ -1,18 +1,32 @@
class ContentsController < ApplicationController
def show
@name = params[:id]
- Pcfilmtydne.parse_raw_html
- Pcfilmtydne.parse_xml
+
+ # at nam pod to @name nepodstrci nejakou prasarnu!
+
+ # zautomatizovat to a udelat automaticky generovany index s prehledem...
+ # (nahledem html v ramecku? to by bylo huste...)
+ case @name
+ when "pcfilmtydne"
+ Pcfilmtydne.parse_raw_html
+ Pcfilmtydne.parse_xml
+ when "csfddokin"
+ Csfddokin.parse_raw_html
+ Csfddokin.parse_xml
+ when "cnbkurzy"
+ Cnbkurzy.parse_raw_html
+ Cnbkurzy.parse_xml
+ end
@content = Content.find_by_name(@name) # udelat pres tridni promenou?
# a pak v tom modelu aby si moh programator vybrat jestli se to obali
# standardni HTML hlavickou a tak nebo ne...
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @content.xml }
end
end
end
diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb
index 68761f8..cd3a6d2 100644
--- a/app/controllers/movies_controller.rb
+++ b/app/controllers/movies_controller.rb
@@ -1,25 +1,24 @@
class MoviesController < ApplicationController
require 'hpricot'
# na otvirani urlek
require 'open-uri'
def index
# tady tahaji z imdb:
# http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
@doc = Hpricot(open("http://www.csfd.cz/"))
- #doc = doc.to_s()
@movies = @doc.search("//body")
@movies = @movies.to_s()
# @movies.gsub!(/[\n\r]/, "")
# /m nam zajisti ze neresi newlines
# http://www.regular-expressions.info/ruby.html
@movies.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
@movies.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
@movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
@movies = Hpricot(@movies)
end
end
diff --git a/app/models/.content.rb.swp b/app/models/.cnbkurzy.rb.swp
similarity index 89%
rename from app/models/.content.rb.swp
rename to app/models/.cnbkurzy.rb.swp
index cb441be..37ed869 100644
Binary files a/app/models/.content.rb.swp and b/app/models/.cnbkurzy.rb.swp differ
diff --git a/app/views/contents/.show.html.erb.swp b/app/models/.csfddokin.rb.swp
similarity index 91%
rename from app/views/contents/.show.html.erb.swp
rename to app/models/.csfddokin.rb.swp
index 60e7b5d..cddbfa9 100644
Binary files a/app/views/contents/.show.html.erb.swp and b/app/models/.csfddokin.rb.swp differ
diff --git a/app/models/.pcfilmtydne.rb.swp b/app/models/.pcfilmtydne.rb.swp
deleted file mode 100644
index 5fb9a7d..0000000
Binary files a/app/models/.pcfilmtydne.rb.swp and /dev/null differ
diff --git a/app/models/cnbkurzy.rb b/app/models/cnbkurzy.rb
new file mode 100644
index 0000000..193003c
--- /dev/null
+++ b/app/models/cnbkurzy.rb
@@ -0,0 +1,26 @@
+class Cnbkurzy < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
+ @doc = @doc.search("//table[@class='kurzy_tisk']")
+
+
+# @kurzy = {}
+# (@movies/"//table//tr").each do |row|
+# (row/"//td").each do |cell|
+# logger.fatal cell.inner_html
+# end
+# logger.fatal "XXX"
+# end
+
+
+
+ save_me
+ end
+
+ def self.parse_xml
+ save_me
+ end
+
+end
diff --git a/app/models/csfddokin.rb b/app/models/csfddokin.rb
new file mode 100644
index 0000000..e0a4756
--- /dev/null
+++ b/app/models/csfddokin.rb
@@ -0,0 +1,27 @@
+# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
+# check_if_old?
+class Csfddokin < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open("http://www.csfd.cz/"))
+ @movies = @doc.search("//body")
+ @movies = @movies.to_s()
+
+ @movies.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
+ @movies.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
+ @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+
+ @movies = '<link rel="stylesheet" type="text/css" href="http://localhost/~phax/test.css" />' + @movies
+
+ @doc = @movies
+
+ save_me
+ end
+
+ def self.parse_xml
+ save_me
+ end
+
+
+end
diff --git a/app/models/sablona b/app/models/sablona
new file mode 100644
index 0000000..8894d5a
--- /dev/null
+++ b/app/models/sablona
@@ -0,0 +1,14 @@
+class Model < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open(""))
+
+ save_me
+ end
+
+ def self.parse_xml
+ save_me
+ end
+
+end
diff --git a/app/views/contents/.show.xml.erb.swp b/app/views/contents/.show.xml.erb.swp
deleted file mode 100644
index 97cc983..0000000
Binary files a/app/views/contents/.show.xml.erb.swp and /dev/null differ
|
petrsigut/unico | 4c88553d98ff5a2a1cef8ede4b076e0c9654b01c | kompletene predelana struktura, controler content a parsovani budou v modelech ktere dedi content | diff --git a/app/controllers/.contents_controller.rb.swp b/app/controllers/.contents_controller.rb.swp
new file mode 100644
index 0000000..5b910e2
Binary files /dev/null and b/app/controllers/.contents_controller.rb.swp differ
diff --git a/app/controllers/.movies_controller.rb.swp b/app/controllers/.movies_controller.rb.swp
new file mode 100644
index 0000000..c8b66d0
Binary files /dev/null and b/app/controllers/.movies_controller.rb.swp differ
diff --git a/app/controllers/contents_controller.rb b/app/controllers/contents_controller.rb
new file mode 100644
index 0000000..a71f6a7
--- /dev/null
+++ b/app/controllers/contents_controller.rb
@@ -0,0 +1,18 @@
+class ContentsController < ApplicationController
+ def show
+ @name = params[:id]
+ Pcfilmtydne.parse_raw_html
+ Pcfilmtydne.parse_xml
+
+ @content = Content.find_by_name(@name) # udelat pres tridni promenou?
+ # a pak v tom modelu aby si moh programator vybrat jestli se to obali
+ # standardni HTML hlavickou a tak nebo ne...
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml => @content.xml }
+ end
+
+ end
+
+end
diff --git a/app/models/.content.rb.swp b/app/models/.content.rb.swp
new file mode 100644
index 0000000..cb441be
Binary files /dev/null and b/app/models/.content.rb.swp differ
diff --git a/app/models/.pcfilmtydne.rb.swp b/app/models/.pcfilmtydne.rb.swp
new file mode 100644
index 0000000..5fb9a7d
Binary files /dev/null and b/app/models/.pcfilmtydne.rb.swp differ
diff --git a/app/models/content.rb b/app/models/content.rb
new file mode 100644
index 0000000..6165595
--- /dev/null
+++ b/app/models/content.rb
@@ -0,0 +1,37 @@
+class Content < ActiveRecord::Base
+ require 'hpricot'
+ require 'open-uri'
+ require 'net/http'
+ require "rexml/document"
+
+ # private nebo tak neco?
+ def self.create_xml_head
+ @xml = REXML::Document.new
+ @kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
+ @kml_doc = @kml.add_element 'document'
+ end
+
+ def self.create_xml_body(entity_name, entity_text)
+ (@kml_doc.add_element entity_name).text = entity_text
+ #(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
+ end
+
+ def self.save_me
+ # tohle až do konce můžu zoobecnit pro vÅ¡echny tÅÃdy...
+ @content = Content.find_by_name(self.name) # udelat pres tridni promenou?
+
+ if @content.nil?
+ @content = Content.new
+ end
+
+ @content.name = self.name
+ @content.xml = @kml_doc.to_s
+ @content.rawhtml = @doc.to_s
+ @content.save
+
+
+ end
+
+
+
+end
diff --git a/app/models/movie.rb b/app/models/movie.rb
index 2f0c950..bc4c3af 100644
--- a/app/models/movie.rb
+++ b/app/models/movie.rb
@@ -1,3 +1,6 @@
class Movie
attr_accessor :name
+
+ def parse_raw_html
+ end
end
diff --git a/app/models/pcfilmtydne.rb b/app/models/pcfilmtydne.rb
new file mode 100644
index 0000000..93a88ec
--- /dev/null
+++ b/app/models/pcfilmtydne.rb
@@ -0,0 +1,34 @@
+# a tohle zdedime z nejake nadrtidy abychom meli obecne funkce show_txt a
+# check_if_old?
+class Pcfilmtydne < Content
+ attr_accessor :name
+
+ def self.parse_raw_html
+ @doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
+ @doc = @doc.search("//div[@class='frame red']")
+ save_me
+ end
+
+ def self.parse_xml
+ @doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1"))
+ @doc = @doc.search("//div[@class='frame red']")
+
+ @label1 = @doc.at("//h3")
+ @label2 = @doc.at("//h2")
+ @image1 = @doc.at("//img")
+ @image1 = @image1.attributes['src']
+ @label3 = @doc.at("//p")
+
+ create_xml_head
+ create_xml_body("label", @label1)
+ create_xml_body("label", @label2)
+ create_xml_body("image", @image1)
+ create_xml_body("label", @label3)
+ create_xml_body("label", self.name)
+
+ save_me
+
+ end
+
+
+end
diff --git a/app/views/contents/.show.html.erb.swp b/app/views/contents/.show.html.erb.swp
new file mode 100644
index 0000000..60e7b5d
Binary files /dev/null and b/app/views/contents/.show.html.erb.swp differ
diff --git a/app/views/contents/.show.xml.erb.swp b/app/views/contents/.show.xml.erb.swp
new file mode 100644
index 0000000..97cc983
Binary files /dev/null and b/app/views/contents/.show.xml.erb.swp differ
diff --git a/app/views/contents/show.html.erb b/app/views/contents/show.html.erb
new file mode 100644
index 0000000..666fe49
--- /dev/null
+++ b/app/views/contents/show.html.erb
@@ -0,0 +1 @@
+<%= @content.rawhtml %>
diff --git a/app/views/contents/show.xml.erb b/app/views/contents/show.xml.erb
new file mode 100644
index 0000000..dc55d84
--- /dev/null
+++ b/app/views/contents/show.xml.erb
@@ -0,0 +1 @@
+<%= @content.xml %>
diff --git a/db/migrate/20091010135514_contents.rb b/db/migrate/20091010135514_contents.rb
new file mode 100644
index 0000000..9fc431b
--- /dev/null
+++ b/db/migrate/20091010135514_contents.rb
@@ -0,0 +1,15 @@
+class Contents < ActiveRecord::Migration
+ def self.up
+ create_table :contents do |t|
+ t.string :name
+ t.text :rawhtml
+ t.text :xml
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :contents
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index b81ae5a..541f4af 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,14 +1,22 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 0) do
+ActiveRecord::Schema.define(:version => 20091010135514) do
+
+ create_table "contents", :force => true do |t|
+ t.string "name"
+ t.text "rawhtml"
+ t.text "xml"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
end
|
petrsigut/unico | 5dac06b2eb783a68ec1132e7570907cfe4ed3806 | pred celkovym rozhodnutim jak budou kontrolery a tak | diff --git a/config/.routes.rb.swp b/app/controllers/.cnb_controller.rb.swp
similarity index 78%
rename from config/.routes.rb.swp
rename to app/controllers/.cnb_controller.rb.swp
index ce72575..6709ca2 100644
Binary files a/config/.routes.rb.swp and b/app/controllers/.cnb_controller.rb.swp differ
diff --git a/app/controllers/.pcfilmtydne_controller.rb.swp b/app/controllers/.pcfilmtydne_controller.rb.swp
new file mode 100644
index 0000000..bfe172d
Binary files /dev/null and b/app/controllers/.pcfilmtydne_controller.rb.swp differ
diff --git a/app/controllers/pcfilmtydne_controller.rb b/app/controllers/pcfilmtydne_controller.rb
index 872f62f..1e74c20 100644
--- a/app/controllers/pcfilmtydne_controller.rb
+++ b/app/controllers/pcfilmtydne_controller.rb
@@ -1,29 +1,78 @@
class PcfilmtydneController < ApplicationController
require 'hpricot'
# na otvirani urlek
require 'open-uri'
+ require 'net/http'
+ # require 'builder'
+ require "rexml/document"
+
def index
# tady tahaji z imdb:
# http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
# film tydne ve Spalicku
@doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1&cin=411&td=2008-09-21&id=0&uid=7c18c3c1b38f4081e601bf2d5eb63b73"))
#doc = doc.to_s()
#@movies = @doc.at("//table/#kurzy_tisk").xpath
- @movies = @doc.search("//div[@class='frame red']")
+ @doc = @doc.search("//div[@class='frame red']")
- @movies = @movies.to_s()
+ #@movies = @movies.to_s()
# @movies.gsub!(/[\n\r]/, "")
# /m nam zajisti ze neresi newlines
# http://www.regular-expressions.info/ruby.html
# @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
# @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
- @movies = Hpricot(@movies)
+ #@movies = Hpricot(@movies)
+
+
+ @label1 = @doc.search("//h3")
+ @label2 = @doc.search("//h2")
+ @image1 = @doc.at("//img")
+ @image1 = @image1.attributes['src']
+ @label3 = @doc.at("//p")
+
+# @x = Builder::XmlMarkup.new
+# @x.instruct!
+# @x.label @label1
+
+ @xml = REXML::Document.new
+ @kml = @xml.add_element 'kml', {'xmlns' => 'http://kml.ns.cz'}
+ @kml_doc = @kml.add_element 'document'
+ (@kml_doc.add_element 'label').text = @label1
+ (@kml_doc.add_element 'label').text = @label2
+ (@kml_doc.add_element 'image').text = @image1
+ (@kml_doc.add_element 'label').text = @label3
+ #(@kml_doc.add_element 'video').text = "http://tinyvid.tv/vfe/big_buck_bunny.mp4"
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.xml { render :xml }
+ end
+
+#<label>obsah labelu1</label>
+ #
+
+
+ # ted musime nejak kesovat ten obrazek, takhle?
+ # http://www.ruby-forum.com/topic/133981
+ #
+
+#--------------------------------------------------
+# Net::HTTP.start( 'www.sigut.net' ) { |http|
+# resp = http.get( '/fotky/_obr300.jpg' )
+# open( '/tmp/ror_vs_c_asm.jpg', 'wb' ) { |file|
+# file.write(resp.body)
+# }
+# }
+#
+#--------------------------------------------------
+
+
end
end
diff --git a/app/views/pcfilmtydne/index.html.erb b/app/views/pcfilmtydne/index.html.erb
index 8e86a56..3a21e0e 100644
--- a/app/views/pcfilmtydne/index.html.erb
+++ b/app/views/pcfilmtydne/index.html.erb
@@ -1 +1 @@
-<%= @movies %>
+<%= @kml_doc %>
diff --git a/app/views/pcfilmtydne/show.html.erb b/app/views/pcfilmtydne/show.html.erb
new file mode 100644
index 0000000..65c64d5
--- /dev/null
+++ b/app/views/pcfilmtydne/show.html.erb
@@ -0,0 +1,6 @@
+<%= @doc %>
+
+<%= @label1 %>
+<%= @image1 %>
+<%= @label2 %>
+<%= @label3 %>
diff --git a/config/routes.rb b/config/routes.rb
index 9b6a19d..13424a5 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,46 +1,49 @@
ActionController::Routing::Routes.draw do |map|
map.connect 'movies/feed.:format', :controller => 'movies', :action => 'index'
- map.connect 'cnb/feed.:format', :controller => 'cnb', :action => 'index'
+
+ #map.connect 'cnb/feed.:format', :controller => 'cnb', :action => 'index'
+
+ map.resources :pcfilmtydne
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
|
petrsigut/unico | 85a4c7275ff80e23835de4a6f9d58da670202137 | pred novou koncepci raw html a XML | diff --git a/app/controllers/cnb_controller.rb b/app/controllers/cnb_controller.rb
new file mode 100644
index 0000000..d293644
--- /dev/null
+++ b/app/controllers/cnb_controller.rb
@@ -0,0 +1,36 @@
+class CnbController < ApplicationController
+ require 'hpricot'
+ # na otvirani urlek
+ require 'open-uri'
+
+ def index
+ # tady tahaji z imdb:
+ # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
+
+ @doc = Hpricot(open("http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.jsp"))
+ #doc = doc.to_s()
+ #@movies = @doc.at("//table/#kurzy_tisk").xpath
+ @movies = @doc.search("//table[@class='kurzy_tisk']")
+
+ @movies = @movies.to_s()
+
+
+ # @movies.gsub!(/[\n\r]/, "")
+ # /m nam zajisti ze neresi newlines
+ # http://www.regular-expressions.info/ruby.html
+# @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
+ # @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
+# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+ @movies = Hpricot(@movies)
+
+ @kurzy = {}
+ (@movies/"//table//tr").each do |row|
+ (row/"//td").each do |cell|
+ logger.fatal cell.inner_html
+ end
+ logger.fatal "XXX"
+ end
+
+
+ end
+end
diff --git a/app/controllers/exchange_controller.rb b/app/controllers/exchange_controller.rb
new file mode 100644
index 0000000..b6d945a
--- /dev/null
+++ b/app/controllers/exchange_controller.rb
@@ -0,0 +1,24 @@
+class ExchangeController < ApplicationController
+ require 'hpricot'
+ # na otvirani urlek
+ require 'open-uri'
+
+ def index
+ # tady tahaji z imdb:
+ # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
+
+ @doc = Hpricot(open("http://www.kurzy.cz/kurzy-men/"))
+ #doc = doc.to_s()
+ @movies = @doc.search("//body")
+ @movies = @movies.to_s()
+
+
+ # @movies.gsub!(/[\n\r]/, "")
+ # /m nam zajisti ze neresi newlines
+ # http://www.regular-expressions.info/ruby.html
+ @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
+ @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
+# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+ @movies = Hpricot(@movies)
+ end
+end
diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb
index fb06146..68761f8 100644
--- a/app/controllers/movies_controller.rb
+++ b/app/controllers/movies_controller.rb
@@ -1,55 +1,25 @@
class MoviesController < ApplicationController
require 'hpricot'
# na otvirani urlek
require 'open-uri'
def index
-# doc = Hpricot("<p>A simple <b>tesxxt</b> string.</p>")
- #
- # tady tahaji z imdb:
- # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
- #@doc = Hpricot(open("http://www.csfd.cz/"))
- @doc = Hpricot(open("http://localhost/~phax/csfd/"))
+ # tady tahaji z imdb:
+ # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
+
+ @doc = Hpricot(open("http://www.csfd.cz/"))
#doc = doc.to_s()
@movies = @doc.search("//body")
@movies = @movies.to_s()
+
-# @movies.gsub!(/[\n\r]/, "")
+ # @movies.gsub!(/[\n\r]/, "")
# /m nam zajisti ze neresi newlines
# http://www.regular-expressions.info/ruby.html
@movies.gsub!(/(.)*Filmové novinky v kinech/m, "") #=> "sa st"
@movies.gsub!(/Tento mÄsÃc vycházà na DVD(.)*/m, "") #=> "sa st"
@movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
@movies = Hpricot(@movies)
- @odkazy = {}
- (@movies/"table//td//a").each do |obj|
- @odkazy[obj.attributes['href']] = obj.inner_text
- end
-
- @filmik = Movie.new
- @filmik.name = ["Moje jmeno", "Neco jineho"]
-
- # tak ted mame odkazy na ty filmy a vytahneme z toho obrazky
- #
- # (doc/"p/a/img").each do |img|
- # puts img.attributes['class']
- # end
- #
-
-# words.gsub!("?", " ")
-
- #@movies = doc
-
-# @movies = doc.search("//table//td")
-# string = "fdsffdas asdf this is a string"
-# string.slice!(2)
- # doc.to_s
- #doc.slice!(/(.)*kino premiery/) #=> "sa st"
-
- #@movies = doc
-# @movies = Photo.find(:all, :include => :section)
end
-
-
end
diff --git a/app/controllers/pcfilmtydne_controller.rb b/app/controllers/pcfilmtydne_controller.rb
new file mode 100644
index 0000000..872f62f
--- /dev/null
+++ b/app/controllers/pcfilmtydne_controller.rb
@@ -0,0 +1,29 @@
+class PcfilmtydneController < ApplicationController
+ require 'hpricot'
+ # na otvirani urlek
+ require 'open-uri'
+
+ def index
+ # tady tahaji z imdb:
+ # http://www.weheartcode.com/2007/04/03/scraping-imdb-with-ruby-and-hpricot/
+
+ # film tydne ve Spalicku
+ @doc = Hpricot(open("http://www.palacecinemas.cz/Default.asp?city=1&cin=411&td=2008-09-21&id=0&uid=7c18c3c1b38f4081e601bf2d5eb63b73"))
+ #doc = doc.to_s()
+ #@movies = @doc.at("//table/#kurzy_tisk").xpath
+ @movies = @doc.search("//div[@class='frame red']")
+
+ @movies = @movies.to_s()
+
+ # @movies.gsub!(/[\n\r]/, "")
+ # /m nam zajisti ze neresi newlines
+ # http://www.regular-expressions.info/ruby.html
+# @movies.gsub!(/(.)*<!-- Begin kurzak CNB -->/m, "") #=> "sa st"
+ # @movies.gsub!(/<!-- End kurzak CNB -->(.)*/m, "") #=> "sa st"
+# @movies.gsub!(/tento mesic vychazi na DVD(.)*/m, "") #=> "sa st"
+ @movies = Hpricot(@movies)
+
+
+
+ end
+end
diff --git a/app/views/cnb/index.html.erb b/app/views/cnb/index.html.erb
new file mode 100644
index 0000000..8e86a56
--- /dev/null
+++ b/app/views/cnb/index.html.erb
@@ -0,0 +1 @@
+<%= @movies %>
diff --git a/app/views/cnb/index.rss.builder b/app/views/cnb/index.rss.builder
new file mode 100644
index 0000000..4ae04f1
--- /dev/null
+++ b/app/views/cnb/index.rss.builder
@@ -0,0 +1,16 @@
+xml.instruct! :xml, :version=>"1.0"
+xml.rss(:version=>"2.0"){
+ xml.channel{
+ xml.title("Petr Šigut | nové fotografie")
+ xml.link("http://www.sigut.net/")
+ xml.description("Fotogalerie.")
+ xml.language('cs-cz')
+ @movies.each do |a|
+ xml.item do
+ xml.title(a[1])
+ xml.link(a[0])
+ end
+ end
+ }
+}
+
diff --git a/app/views/exchange/index.html.erb b/app/views/exchange/index.html.erb
new file mode 100644
index 0000000..8e86a56
--- /dev/null
+++ b/app/views/exchange/index.html.erb
@@ -0,0 +1 @@
+<%= @movies %>
diff --git a/app/views/pcfilmtydne/index.html.erb b/app/views/pcfilmtydne/index.html.erb
new file mode 100644
index 0000000..8e86a56
--- /dev/null
+++ b/app/views/pcfilmtydne/index.html.erb
@@ -0,0 +1 @@
+<%= @movies %>
diff --git a/app/controllers/.movies_controller.rb.swp b/config/.routes.rb.swp
similarity index 78%
rename from app/controllers/.movies_controller.rb.swp
rename to config/.routes.rb.swp
index 08e1e28..ce72575 100644
Binary files a/app/controllers/.movies_controller.rb.swp and b/config/.routes.rb.swp differ
diff --git a/config/routes.rb b/config/routes.rb
index fb1fa5f..9b6a19d 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,45 +1,46 @@
ActionController::Routing::Routes.draw do |map|
map.connect 'movies/feed.:format', :controller => 'movies', :action => 'index'
+ map.connect 'cnb/feed.:format', :controller => 'cnb', :action => 'index'
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
|
jtrupiano/techcrawleast | 5f01b98bae6d9496e6a9542e1a2955bae3ad815b | Cache bust the stylesheet | diff --git a/presenters.html b/presenters.html
index acfa88c..8a0a43d 100644
--- a/presenters.html
+++ b/presenters.html
@@ -1,132 +1,132 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
-<link href="css/styles.css" rel="stylesheet" type="text/css" />
+<link href="css/styles.css?1" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_presenters">
<div class="container_wide" id="intro_presenters">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Tech Crawl East Presenting Companies</h2>
</div>
</div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<table>
<tr>
<td><a target="_blank" href="http://mailVU.com">A2Stream Inc.</a></td>
<td><a target="_blank" href="http://www.klaggle.com">Klaggle</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.actionreactionlabs.com/">Action = Reaction Labs LLC</a></td>
<td><a target="_blank" href="http://localist.com">Localist</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.biofortis.com">BioFortis</a></td>
<td><a target="_blank" href="http://www.mobilereactor.com">Mobile Reactor</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.bloominescence.com">Bloominescence LLC</a></td>
<td><a target="_blank" href="http://www.NV3tech.com">NV3 Technologies LLC</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.cityryde.com">CityRyde LLC</a></td>
<td><a target="_blank" href="http://floridawebdevelopers.com/owv/investor.php">One World Virtual</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.cloudspree.com">CloudSpree Inc.</a></td>
<td><a target="_blank" href="http://www.prestosports.com">PrestoSports</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.commoncurriculum.com">Common Curriculum</a></td>
<td><a target="_blank" href="http://www.printedpiece.com">PrintedPiece</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.coolcadelectronics.com">CoolCAD Electronics LLC</a></td>
<td><a target="_blank" href="http://www.razoron.com">Razoron Health Innovations</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.csamedical.com">CSA Medical</a></td>
<td><a target="_blank" href="http://www.REMcloud.com">REMcloud</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://deconstructmedia.com">Deconstruct Media</a></td>
<td><a target="_blank" href="http://www.rentjungle.com">Rent Jungle, LLC.</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.deepwebtech.com">Deep Web Technologies</a></td>
<td><a target="_blank" href="http://www.ringio.com">Ringio</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.shapeshot.com">Direct Dimensions, Inc.</a></td>
<td><a target="_blank" href="http://www.ppmroadmap.com/">Roadmap</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.docdep.com">Document Depository Corp</a></td>
<td><a target="_blank" href="http://roomtag.com">Roomtag</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.e-isg.com">E-ISG</a></td>
<td><a target="_blank" href="http://www.socialtoaster.com">SocialToaster, LLC</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://goodzer.com">Goodzer Inc</a></td>
<td><a target="_blank" href="http://www.usermover.com">UserMover</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.hopstop.com">HopStop</a></td>
<td><a target="_blank" href="http://www.viaplace.com">viaPlace</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.IMLeagues.com">IMLeagues.com</a></td>
<td><a target="_blank" href="http://vigilantmedical.net">Vigilant Medical</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://www.interbots.com/">Interbots LLC</a></td>
<td><a target="_blank" href="http://www.centerofmath.com">Worldwide Center of Mathematics</a></td>
</tr>
<tr>
<td><a target="_blank" href="http://ipiqi.com">ipiqi</a></td>
<td><a target="_blank" href="http://www.ClickTube.com">www.ClickTube.com</a></td>
</tr>
</table>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 198f571801d851f06fc7439b8da04d0b4caa13c4 | List presenting companies | diff --git a/css/styles.css b/css/styles.css
index 345246c..6a93d01 100644
--- a/css/styles.css
+++ b/css/styles.css
@@ -1,550 +1,568 @@
/* CSS RESET */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* tags
----------------------------------------------- */
body {
background-color: #00222e;
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
font-size: 18px;
line-height: 24px;
}
h1, h2, h3, h4, h5, h6 {
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
text-shadow: 1px 1px 0px #fff;
}
h1 {
}
h2 {
font-size:21px;
font-weight:bold;
}
h3 {
padding-bottom:8px;
font-size:24px;
line-height:24px;
/*font-style:italic;*/
color:#00222e;
text-shadow: 1px 1px 0px #fff;
}
h4 {
padding-bottom:5px;
font-size:21px;
line-height:21px;
}
/*a:link, a:visited, a:focus {
text-decoration: none;
border-bottom: 1px solid #000;
color:#000;
}*/
a:link, a:visited, a:focus {
color:#0066cc;
text-decoration:none;
font-weight:normal;
border:none;
}
a:hover {
color:#0066cc;
color:#00ccff;
border-bottom:1px solid #0066cc;
border:none;
}
/* layout
----------------------------------------------- */
#content {
}
.container_wide {
padding:30px 0 30px 0;
width:100%;
background-color:#e4e4e4;
border-bottom: 1px dashed #666;
border-top: 1px dashed #fff;
}
.container_fixed {
width:960px;
margin: 0 auto 0 auto;
}
/* head
----------------------------------------------- */
#head {
margin:0;
padding: 10px 0 10px 0;
position:fixed;
top:0px;
left:0px;
height: auto;
width: 100%;
background-color:#00222e;
border-bottom: 1px solid black;
z-index: 1000;
}
#logo {
padding: 0 0 0 15px;
position:relative;
float:left;
}
#logo h2 {
font-size:18px;
font-weight:bold;
text-shadow:none;
}
#logo h2 a:link, #logo h2 a:visited, #logo h2 a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#logo h2 a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav {
position:relative;
float:left;
}
#nav a:link, #nav a:visited, #nav a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#nav a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav ul, #social_media ul {
font-size:16px;
}
#nav ul li {
margin:0 0 0 20px;
position:relative;
float:left;
}
#nav .register {
position:relative;
float:right;
}
#social_media {
padding-right:25px;
float:right;
}
#social_media li#twitter {
padding-left:25px;
background: url(../img/icon_twitter.png) no-repeat center left;
}
#social_media a:link, #social_media a:visited, #social_media a:focus {
color:#499ff3;
}
#social_media a:hover {
color:#fff;
}
/* intro
----------------------------------------------- */
#intro {
margin-top:45px;
padding-top:70px;
padding-bottom:60px;
text-align: center;
border:none;
background-color:#0461c0;
background-image: url(../img/background_round_wave.png);
background-repeat: no-repeat;
background-position: center center;
}
#intro h1 {
padding:0;
margin:0;
}
/* call-to-action
----------------------------------------------- */
#intro_action {
background-color:#fdfee0;
}
.call_to_action {
margin: 0 10px 0 10px;
font-size:28px;
line-height:28px;
text-align:center;
}
.call_to_action h2 {
padding-bottom:10px;
font-size:36px !important;
line-height:36px;
}
.call_to_action h3 {
padding-bottom:0;
font-size:26px !important;
line-height:26px;
font-weight:normal;
text-transform:none;
}
.call_to_action a:link, .call_to_action a:visited, .call_to_action a:focus {
color:#ff4439;
border-bottom:1px solid #ff4439;
}
.call_to_action a:hover {
color:#499ff3;
border-bottom:1px solid #499ff3;
}
/* summary
----------------------------------------------- */
#summary {
background-color:#fff;
font-size:18px;
line-height:24px;
}
#summary h3 {
font-size:28px;
line-height:28px;
}
#summary h4 {
font-style:italic;
}
#companies, #attendees {
margin:0 10px 0 10px;
position:relative;
float:left;
width:460px;
text-align:center;
}
/* details
----------------------------------------------- */
#details {
border-bottom:none;
padding-bottom:0;
}
#details_text {
border-top:none;
}
#map, #venue, #event_links {
margin:0 10px 0 10px;
width:298px;
position:relative;
float:left;
border:1px solid #aaa;
background-color:#fff;
}
#event_links {
width:300px;
border:none;
background:none;
}
#map {
width:618px;
}
#venue {
}
#map iframe, #venue img {
padding:9px;
}
#event_links ul {
margin-top:5px;
border-top:1px solid #ccc;
border-bottom:1px solid #efefef;
}
#event_links li {
/*padding:8px 0 8px 25px;*/
padding:8px 0 8px 0;
font-size: 18px;
border-bottom: 1px solid #ccc;
border-top:1px solid #efefef;
background-repeat: no-repeat;
background-position: left center;
}
/*li#map_link_car {
background-image: url(../img/icon_car.png);
}
li#map_link_train {
background-image: url(../img/icon_train.png);
}
li#map_link_plane {
background-image: url(../img/icon_plane.png);
}
li#map_link_hotel {
background-image: url(../img/icon_hotel.png);
}
/* faqs
----------------------------------------------- */
.column_headline, .column_text {
position:relative;
float:left;
}
.column_headline {
padding:0 10px 0 10px;
width:300px;
}
.column_text {
padding:0 10px 0 10px;
width:620px;
}
.column_headline h3, .column_text h3 {
font-size:24px;
line-height:24px;
}
/* register
----------------------------------------------- */
#register {
background-color:#fdfee0;
text-align:center;
}
#register h3 {
font-size:28px;
line-height:28px;
padding:30px 0 30px 0;
border:1px solid #666;
background-color:#fff;
}
#register h3 a {
color:#ff4439;
border:none;
}
/* register PAGE
----------------------------------------------- */
#content_register {
margin-top:45px;
}
#content_register #intro_register {
border-top:none;
}
#register_form {
background-color:#fff;
border-bottom:none;
}
form {
margin-right:auto;
margin-left:auto;
width: 700px;
}
label {
width: 250px;
padding: 0 10px 0 0;
text-align: right;
position: relative;
float: left;
}
.form_row {
padding:0 0 15px 0;
}
.form_row p {
width:250px;
float:left;
text-align:right;
font-size:12px;
line-height:normal;
}
.form_row span {
padding-left:2px;
color:red;
}
#form-message {
color:#393;
font-size:21px;
line-height:28px;
padding-top:35px;
padding-bottom:15px;
text-align:center;
}
form button {
margin-left:260px;
}
input, textarea {
float:left;
font-size:16px;
}
#terms {
margin-top:30px;
margin-left:260px;
font-size:12px;
line-height:normal;
}
button {
font-size:18px;
padding:10px;
}
/* information for presenters PAGE
----------------------------------------------- */
#content_information {
margin-top:45px;
}
#content_information #intro_information {
border-top:none;
}
#information_container {
background-color:#fff;
border-bottom:none;
padding-left: 10%;
padding-right: 10%;
width: 80%;
}
#information_container #information {
float: left;
width: 56%;
margin-right: 5%;
}
#information_container #information h3 {
margin-top: 10px;
}
#information_container #information li, #information_container #information p {
margin-right: 0px;
font-size: 14px;
margin-bottom: 10px;
}
#information_container #information ul.indent {
margin-left: 10px;
margin-bottom: 10px;
}
#information_container #information ul.indent li {
margin-left: 20px;
list-style-type: disc;
margin-bottom: 0px;
}
#information_container #photos {
float: left;
width: 38%;
}
#information_container #photos .caption {
font-size: 12px;
}
/* organizers PAGE
----------------------------------------------- */
#content_organizers {
margin-top:45px;
}
#content_organizers #intro_organizers {
border-top:none;
}
#content_organizers img {
float: left;
padding-right: 8px;
}
.container_wide_last {
border-bottom: 0;
}
+/* presenters PAGE
+----------------------------------------------- */
+
+#content_presenters {
+ margin-top:45px;
+}
+#content_presenters #intro_presenters {
+ border-top:none;
+}
+
+#content_presenters table {
+ margin: 0px auto;
+}
+
+#content_presenters table td {
+ padding: 2px 15px;
+}
+
/* sponsors
----------------------------------------------- */
#sponsors {
text-align:center;
background-color:#fff;
border:none;
}
#sponsors h3 {
font-size:18px;
}
#sponsors p {
font-size:12px;
}
.sponsor_box {
margin:15px 10px 15px 10px;
position:relative;
float:left;
/*height:125px;*/
width:300px;
text-align:center;/*border:1px dashed #000;*/
}
/* foot
----------------------------------------------- */
#foot {
background-color:#00222e;
padding:30px 0 30px 0;
color:#ccc;
font-size:14px;
text-align:center;
}
a.sig:link, a.sig:visited, a.sig:focus {
color:#ccc;
text-decoration:underline;
}
a.sig:hover {
color:#fff;
}
/* float clearing
----------------------------------------------- */
/* float clearing for IE6 */
* html .clear {
height: 1%;
overflow: visible;
}
/* float clearing for IE7 */
*+html .clear {
min-height: 1%;
}
/* float clearing for everyone else */
.clear:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
.clear {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
diff --git a/index.html b/index.html
index 82cc066..bc5ea02 100644
--- a/index.html
+++ b/index.html
@@ -1,157 +1,158 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('sponsors')">Sponsors</a></li>
+ <li><a href="presenters.html">Presenting Companies</a></li>
<li><a href="organizers.html">Organizers</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=Thames+St+and+S+Caroline+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><h3>Premier Sponsor</h3></div>
<div class="sponsor_box"><a href="http://www.greaterbaltimore.org/" target="_blank"><img src="./img/img_sponsor_eagb.jpg" alt="Economic Alliance of Greater Baltimore" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"><a href="http://www.redstartcreative.com" target="_blank"><img src="./img/img_sponsor_redstart.gif" alt="Redstart Creative" height="70" /></a></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" height="80" /></a></div>
<div class="sponsor_box"><a href="http://www.vircity.us/" target="_blank"><img src="./img/img_sponsor_vircity.jpg" alt="Vircity" height="60" /></a></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
diff --git a/presenters.html b/presenters.html
new file mode 100644
index 0000000..acfa88c
--- /dev/null
+++ b/presenters.html
@@ -0,0 +1,132 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Tech Crawl East</title>
+<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
+<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
+<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
+<link href="css/styles.css" rel="stylesheet" type="text/css" />
+</head>
+<body id="body">
+<div id="head">
+ <div id="logo">
+ <h2><a href="index.html">« Return to Homepage</a></h2>
+ </div>
+ <div id="social_media">
+ <ul>
+ <li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
+ </ul>
+ </div>
+ <div class="clear"></div>
+</div>
+<div id="content_presenters">
+ <div class="container_wide" id="intro_presenters">
+ <div class="container_fixed">
+ <div>
+ <div class="call_to_action">
+ <h2>Tech Crawl East Presenting Companies</h2>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <table>
+ <tr>
+ <td><a target="_blank" href="http://mailVU.com">A2Stream Inc.</a></td>
+ <td><a target="_blank" href="http://www.klaggle.com">Klaggle</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.actionreactionlabs.com/">Action = Reaction Labs LLC</a></td>
+ <td><a target="_blank" href="http://localist.com">Localist</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.biofortis.com">BioFortis</a></td>
+ <td><a target="_blank" href="http://www.mobilereactor.com">Mobile Reactor</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.bloominescence.com">Bloominescence LLC</a></td>
+ <td><a target="_blank" href="http://www.NV3tech.com">NV3 Technologies LLC</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.cityryde.com">CityRyde LLC</a></td>
+ <td><a target="_blank" href="http://floridawebdevelopers.com/owv/investor.php">One World Virtual</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.cloudspree.com">CloudSpree Inc.</a></td>
+ <td><a target="_blank" href="http://www.prestosports.com">PrestoSports</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.commoncurriculum.com">Common Curriculum</a></td>
+ <td><a target="_blank" href="http://www.printedpiece.com">PrintedPiece</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.coolcadelectronics.com">CoolCAD Electronics LLC</a></td>
+ <td><a target="_blank" href="http://www.razoron.com">Razoron Health Innovations</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.csamedical.com">CSA Medical</a></td>
+ <td><a target="_blank" href="http://www.REMcloud.com">REMcloud</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://deconstructmedia.com">Deconstruct Media</a></td>
+ <td><a target="_blank" href="http://www.rentjungle.com">Rent Jungle, LLC.</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.deepwebtech.com">Deep Web Technologies</a></td>
+ <td><a target="_blank" href="http://www.ringio.com">Ringio</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.shapeshot.com">Direct Dimensions, Inc.</a></td>
+ <td><a target="_blank" href="http://www.ppmroadmap.com/">Roadmap</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.docdep.com">Document Depository Corp</a></td>
+ <td><a target="_blank" href="http://roomtag.com">Roomtag</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.e-isg.com">E-ISG</a></td>
+ <td><a target="_blank" href="http://www.socialtoaster.com">SocialToaster, LLC</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://goodzer.com">Goodzer Inc</a></td>
+ <td><a target="_blank" href="http://www.usermover.com">UserMover</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.hopstop.com">HopStop</a></td>
+ <td><a target="_blank" href="http://www.viaplace.com">viaPlace</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.IMLeagues.com">IMLeagues.com</a></td>
+ <td><a target="_blank" href="http://vigilantmedical.net">Vigilant Medical</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://www.interbots.com/">Interbots LLC</a></td>
+ <td><a target="_blank" href="http://www.centerofmath.com">Worldwide Center of Mathematics</a></td>
+ </tr>
+ <tr>
+ <td><a target="_blank" href="http://ipiqi.com">ipiqi</a></td>
+ <td><a target="_blank" href="http://www.ClickTube.com">www.ClickTube.com</a></td>
+ </tr>
+ </table>
+ </div>
+ </div>
+</div>
+<div id="foot">
+ <div class="container_fixed">
+ <p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
+ </div>
+</div>
+<script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-11671914-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>
+</body>
+</html>
|
jtrupiano/techcrawleast | c4f656e17c587b48269697e49498188f175bde49 | Add timers | diff --git a/information-for-presenters.html b/information-for-presenters.html
index 3bf7cf5..0dbf3a2 100644
--- a/information-for-presenters.html
+++ b/information-for-presenters.html
@@ -1,90 +1,91 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_information">
<div class="container_wide" id="intro_information">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Information for Tech Crawl East</h2>
</div>
</div>
</div>
</div>
<div class="container_wide" id="information_container">
<div id="information">
<h3>What do I need to do?</h3>
<ul>
<li><strong>Register as a Presenter</strong> by completing our <a href="https://spreadsheets0.google.com/viewform?hl=en&formkey=dEpUdXRhNEc2cWIwSmhNQWp4UkR1ZHc6MQ#gid=0" target="_blank">Presenter Intake Form</a>.</li>
<li><strong>Upload your logo</strong> to <a href="http://drop.io/TechCrawlEast" target="_blank">drop.io</a>. Click the "Add" link and name the file with the same company name that you submitted.</li>
<li><strong>Pay the Presenter Fee</strong> by signing up for this <a href="http://tcepresenter.eventbrite.com/" target="_blank">EventBrite event</a>.</li>
<li><strong>Prepare your Pitch</strong>: each table will have a "home base" set up for attendees to step on to hear your pitch. Whenever anyone steps up, you should be prepared to give your 60-second pitch that answers these questions:
<ul class="indent">
<li>What is exciting about your company or product?</li>
<li>Who are you selling to?</li>
<li>How does your customer benefit from your product?</li>
<li>Are you seeking investment and how will you use it?</li>
</ul>
</li>
<li><strong>Show off your product!</strong> this is a show and tell event. Attendees want to be able to experience your technology.</li>
<li><strong>Compile your marketing materials</strong>: each presenter will have a booth not all that dissimilar from a trade show. Bring your standard set of marketing posters, take-homes and business cards.</li>
<li><strong>Get pumped!</strong> this is an event to showcase you! Bring a load of energy and take advantage of the community coming to see you.</li>
</ul>
<h3>What is being provided to me?</h3>
<p>Tech Crawl East will provide each presenter with the following:</p>
<ul class="indent">
<li>a 2 1/2 ft x 6 ft table with a skirt and tablecloth</li>
<li>a "home base" for attendees to step on to hear your pitch</li>
+ <li>a 60-second timer</li>
<li>power and wifi</li>
<li>we will be recording your pitch and posting it online after the event</li>
</ul>
<h3>Is there an agenda?</h3>
<p>Yes, of course. Doors open at 5PM with food and beverages immediately available. The Crawl will begin at 5:30PM and run until 8:30PM. During the Crawl attendees will be voting for the best pitch. Award for the best pitch will be announced at 8:30PM. Presenters are encouraged to arrive at Morgan Stanley between 3:00PM and 3:30PM to begin setting up their tables. If your particular setup requires more time, feel free to arrive earlier than that.</p>
</div>
<div id="photos">
<img src="./img/img_information_empty_booth_small.jpg" alt="Empty Booth" width="400" height="300" />
<p class="caption">A sample booth setup. We are providing a table, skirt, cloth and base.</p>
<img src="./img/img_information_presenters_at_booth_small.jpg" alt="Presenters at booth" width="400" height="300" />
<p class="caption">Each presenter will be best served by having at least two people at the booth. At any given time, one person should be prepared to pitch to anyone who steps up to the plate, and the other should be there to talk casually to attendees and hand out marketing material.</p>
</div>
<div class="clear" />
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | aad82160413a168e0b8326f9aded635f2865da07 | Add Paul to organizers | diff --git a/img/img_paul.png b/img/img_paul.png
new file mode 100644
index 0000000..a375ea3
Binary files /dev/null and b/img/img_paul.png differ
diff --git a/organizers.html b/organizers.html
index 97a3a1e..9737112 100644
--- a/organizers.html
+++ b/organizers.html
@@ -1,95 +1,95 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_organizers">
<div class="container_wide" id="intro_organizers">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Tech Crawl East Organizers</h2>
</div>
</div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_john.jpg" alt="John" height="200" width="200" />
<h3>John Trupiano</h3>
<p>John is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_heather.jpg" alt="Heather" height="200" />
<h3>Heather Sarkissian</h3>
<p>Heather is a Baltimore entrepreneur running <a href="http://mp3car.com">mp3car.com</a> and an active supporter of the local tech community. She organizes <a href="http://betascape.org">Betascape</a> and is a co-organizer of <a href="http://ignitebaltimore.com">Ignite Baltimore</a>.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_fulya.jpg" alt="Fulya" height="200" width="200" />
<h3>Fulya Gursel</h3>
<p>As one of the co-founders of Tech Crawl East, Fulya Gursel works at <a href="http://etcbaltimore.com">Emerging Technology Centers</a> (ETC) as Director of Marketing. At ETC, she provides business advisory services to ETC clients in the areas of marketing and communications, and provides direct assistance in the areas of market research, market strategy and business data collection and organization. She also is responsible for maintaining ETCâs portfolio of client resource materials like guidelines, impact studies, production reports, marketing collateral and making these materials available to clients when needed.
</p>
<div class="clear"></div>
</div>
</div>
- <div class="container_wide container_wide_last">
+ <div class="container_wide">
<div class="container_fixed">
<img src="./img/img_brian.jpg" alt="Brian" height="200" width="200" />
<h3>Brian Sierakowski</h3>
<p>Brian Sierakowski is an enthusiastic advocate for the tech and entrepreneurial communities. He's currently the Managing Editor of the <a href="http://thestartupdigest.com/" target="_blank">Baltimore Startup Digest</a>, and is in the early stages of launching his startup Cahoots.
</p>
<div class="clear"></div>
</div>
</div>
- <!-- <div class="container_wide container_wide_last">
+ <div class="container_wide container_wide_last">
<div class="container_fixed">
- <img src="./img/img_paul.jpg" alt="Paul" height="200" width="200" />
+ <img src="./img/img_paul.png" alt="Paul" height="200" width="200" />
<h3>Paul Capestany</h3>
- <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ <p>Paul Capestany stays immersed in all things startup, given he has his own web startup. Having seen firsthand the success of events like TechCrunch 50 and SXSW in connecting people, Paul is excited to help bring the same kind of energy to Tech Crawl East.
</p>
<div class="clear"></div>
</div>
- </div> -->
+ </div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 9148d0c9e054a37438ec39674589a63cc4b1cf88 | Heather's photo | diff --git a/img/img_heather.jpg b/img/img_heather.jpg
new file mode 100644
index 0000000..e650002
Binary files /dev/null and b/img/img_heather.jpg differ
|
jtrupiano/techcrawleast | 5b73ec1ac9904429c9b9de78696f816ee3595c4d | Add organizers page | diff --git a/index.html b/index.html
index 3ac8b55..82cc066 100644
--- a/index.html
+++ b/index.html
@@ -1,157 +1,157 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
- <li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
- <li><a href="register.html">Apply To Present</a></li>
+ <li><a href="javascript:void(0)" onclick="goToByScroll('sponsors')">Sponsors</a></li>
+ <li><a href="organizers.html">Organizers</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=Thames+St+and+S+Caroline+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><h3>Premier Sponsor</h3></div>
<div class="sponsor_box"><a href="http://www.greaterbaltimore.org/" target="_blank"><img src="./img/img_sponsor_eagb.jpg" alt="Economic Alliance of Greater Baltimore" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"><a href="http://www.redstartcreative.com" target="_blank"><img src="./img/img_sponsor_redstart.gif" alt="Redstart Creative" height="70" /></a></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" height="80" /></a></div>
<div class="sponsor_box"><a href="http://www.vircity.us/" target="_blank"><img src="./img/img_sponsor_vircity.jpg" alt="Vircity" height="60" /></a></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
diff --git a/organizers.html b/organizers.html
index 8a94985..97a3a1e 100644
--- a/organizers.html
+++ b/organizers.html
@@ -1,95 +1,95 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_organizers">
<div class="container_wide" id="intro_organizers">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Tech Crawl East Organizers</h2>
</div>
</div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_john.jpg" alt="John" height="200" width="200" />
<h3>John Trupiano</h3>
- <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ <p>John is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
- <img src="./img/img_heather.jpg" alt="Heather" height="200" width="200" />
+ <img src="./img/img_heather.jpg" alt="Heather" height="200" />
<h3>Heather Sarkissian</h3>
- <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ <p>Heather is a Baltimore entrepreneur running <a href="http://mp3car.com">mp3car.com</a> and an active supporter of the local tech community. She organizes <a href="http://betascape.org">Betascape</a> and is a co-organizer of <a href="http://ignitebaltimore.com">Ignite Baltimore</a>.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_fulya.jpg" alt="Fulya" height="200" width="200" />
<h3>Fulya Gursel</h3>
<p>As one of the co-founders of Tech Crawl East, Fulya Gursel works at <a href="http://etcbaltimore.com">Emerging Technology Centers</a> (ETC) as Director of Marketing. At ETC, she provides business advisory services to ETC clients in the areas of marketing and communications, and provides direct assistance in the areas of market research, market strategy and business data collection and organization. She also is responsible for maintaining ETCâs portfolio of client resource materials like guidelines, impact studies, production reports, marketing collateral and making these materials available to clients when needed.
</p>
<div class="clear"></div>
</div>
</div>
- <div class="container_wide">
+ <div class="container_wide container_wide_last">
<div class="container_fixed">
<img src="./img/img_brian.jpg" alt="Brian" height="200" width="200" />
<h3>Brian Sierakowski</h3>
<p>Brian Sierakowski is an enthusiastic advocate for the tech and entrepreneurial communities. He's currently the Managing Editor of the <a href="http://thestartupdigest.com/" target="_blank">Baltimore Startup Digest</a>, and is in the early stages of launching his startup Cahoots.
</p>
<div class="clear"></div>
</div>
</div>
- <div class="container_wide container_wide_last">
+ <!-- <div class="container_wide container_wide_last">
<div class="container_fixed">
<img src="./img/img_paul.jpg" alt="Paul" height="200" width="200" />
<h3>Paul Capestany</h3>
<p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
</p>
<div class="clear"></div>
</div>
- </div>
+ </div> -->
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 5dafd153695eb66db0eab810c3bd4e66e5610c53 | Add Redstart and Vircity as sponsors | diff --git a/img/img_sponsor_redstart.gif b/img/img_sponsor_redstart.gif
new file mode 100644
index 0000000..23ff9fc
Binary files /dev/null and b/img/img_sponsor_redstart.gif differ
diff --git a/img/img_sponsor_vircity.jpg b/img/img_sponsor_vircity.jpg
new file mode 100644
index 0000000..fadcb0a
Binary files /dev/null and b/img/img_sponsor_vircity.jpg differ
diff --git a/index.html b/index.html
index fb6560e..3ac8b55 100644
--- a/index.html
+++ b/index.html
@@ -1,157 +1,157 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=Thames+St+and+S+Caroline+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><h3>Premier Sponsor</h3></div>
<div class="sponsor_box"><a href="http://www.greaterbaltimore.org/" target="_blank"><img src="./img/img_sponsor_eagb.jpg" alt="Economic Alliance of Greater Baltimore" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
- <div class="sponsor_box"></div>
+ <div class="sponsor_box"><a href="http://www.redstartcreative.com" target="_blank"><img src="./img/img_sponsor_redstart.gif" alt="Redstart Creative" height="70" /></a></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" height="80" /></a></div>
- <div class="sponsor_box"></div>
+ <div class="sponsor_box"><a href="http://www.vircity.us/" target="_blank"><img src="./img/img_sponsor_vircity.jpg" alt="Vircity" height="60" /></a></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | f5452f5b884efcf1e703e42e05b49dffdb20503a | Premier Sponsor | diff --git a/index.html b/index.html
index 8b53940..fb6560e 100644
--- a/index.html
+++ b/index.html
@@ -1,157 +1,157 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=Thames+St+and+S+Caroline+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
- <div class="sponsor_box"></div>
+ <div class="sponsor_box"><h3>Premier Sponsor</h3></div>
<div class="sponsor_box"><a href="http://www.greaterbaltimore.org/" target="_blank"><img src="./img/img_sponsor_eagb.jpg" alt="Economic Alliance of Greater Baltimore" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" height="80" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 3450ffa3c53399a59f45cc70419926833b82e107 | Add Economic Alliance as sponsor | diff --git a/img/img_sponsor_eagb.jpg b/img/img_sponsor_eagb.jpg
new file mode 100644
index 0000000..77278df
Binary files /dev/null and b/img/img_sponsor_eagb.jpg differ
diff --git a/index.html b/index.html
index 76d47ad..8b53940 100644
--- a/index.html
+++ b/index.html
@@ -1,153 +1,157 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=Thames+St+and+S+Caroline+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
+ <div class="sponsor_box"></div>
+ <div class="sponsor_box"><a href="http://www.greaterbaltimore.org/" target="_blank"><img src="./img/img_sponsor_eagb.jpg" alt="Economic Alliance of Greater Baltimore" /></a></div>
+ <div class="sponsor_box"></div>
+ <div class="clear"></div>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"></div>
- <div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" /></a></div>
+ <div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" height="80" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 1bbc36f72635b519bdfbcc27dfe6ec087a1bd653 | Link to Presenter Intake Form. | diff --git a/information-for-presenters.html b/information-for-presenters.html
index c5f6912..d91d78b 100644
--- a/information-for-presenters.html
+++ b/information-for-presenters.html
@@ -1,89 +1,89 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_information">
<div class="container_wide" id="intro_information">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Information for Tech Crawl East</h2>
</div>
</div>
</div>
</div>
<div class="container_wide" id="information_container">
<div id="information">
<h3>What do I need to do?</h3>
<ul>
- <li><strong>Register as a Presenter</strong> by completing this Google Form.</li>
- <li><strong>Upload your logo</strong> to this <a href="http://drop.io/TechCrawlEast" target="_blank">drop.io drop</a>. Click the "Add" link and name the file with the same company name that you submitted.</li>
+ <li><strong>Register as a Presenter</strong> by completing our <a href="https://spreadsheets0.google.com/viewform?hl=en&formkey=dEpUdXRhNEc2cWIwSmhNQWp4UkR1ZHc6MQ#gid=0" target="_blank">Presenter Intake Form</a>.</li>
+ <li><strong>Upload your logo</strong> to <a href="http://drop.io/TechCrawlEast" target="_blank">drop.io</a>. Click the "Add" link and name the file with the same company name that you submitted.</li>
<li><strong>Pay the Presenter Fee</strong> by signing up for this <a href="http://tcepresenter.eventbrite.com/" target="_blank">EventBrite event</a>.</li>
<li><strong>Prepare your Pitch</strong>: each table will have a "home base" set up for attendees to step on to hear your pitch. Whenever anyone steps up, you should be prepared to give your 60-second pitch that answers these questions:
<ul class="indent">
<li>What is exciting about your company or product?</li>
<li>Who are you selling to?</li>
<li>How does your customer benefit from your product?</li>
<li>Are you seeking investment and how will you use it?</li>
</ul>
</li>
<li><strong>Show off your product!</strong> this is a show and tell event. Attendees want to be able to experience your technology.</li>
<li><strong>Compile your marketing materials</strong>: each presenter will have a booth not all that dissimilar from a trade show. Bring your standard set of marketing posters, take-homes and business cards.</li>
<li><strong>Get pumped!</strong> this is an event to showcase you! Bring a load of energy and take advantage of the community coming to see you.</li>
</ul>
<h3>What is being provided to me?</h3>
<p>Tech Crawl East will provide each presenter with the following:</p>
<ul class="indent">
<li>a 2 1/2 ft x 5 ft table with a skirt and tablecloth</li>
<li>power and/or wifi (by request)</li>
<li>we will be recording your pitch and posting it online after the event</li>
</ul>
<h3>Is there an agenda?</h3>
<p>Yes, of course. Doors open at 5PM with food and beverages immediately available. The Crawl will begin at 5:30PM and run until 7:30PM. Award for the best pitch will be announced at 8:00PM. Presenters are encouraged to arrive at Morgan Stanley between 3:00PM and 3:30PM to begin setting up their tables. If your particular setup requires more time, feel free to arrive earlier than that.</p>
</div>
<div id="photos">
<img src="./img/img_information_empty_booth_small.jpg" alt="Empty Booth" width="400" height="300" />
<p class="caption">A sample booth setup. We are providing a table, skirt, cloth and base.</p>
<img src="./img/img_information_presenters_at_booth_small.jpg" alt="Presenters at booth" width="400" height="300" />
<p class="caption">Each presenter will be best served by having at least two people at the booth. At any given time, one person should be prepared to pitch to anyone who steps up to the plate, and the other should be there to talk casually to attendees and hand out marketing material.</p>
</div>
<div class="clear" />
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 2711c0cfa92483603bfffd1f91e6662813a59898 | Add Brian and Fulya to organizers | diff --git a/img/img_brian.jpg b/img/img_brian.jpg
new file mode 100644
index 0000000..61cc77e
Binary files /dev/null and b/img/img_brian.jpg differ
diff --git a/img/img_fulya.jpg b/img/img_fulya.jpg
new file mode 100644
index 0000000..8f35cca
Binary files /dev/null and b/img/img_fulya.jpg differ
diff --git a/organizers.html b/organizers.html
index 9a19f9f..8a94985 100644
--- a/organizers.html
+++ b/organizers.html
@@ -1,95 +1,95 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_organizers">
<div class="container_wide" id="intro_organizers">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Tech Crawl East Organizers</h2>
</div>
</div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_john.jpg" alt="John" height="200" width="200" />
<h3>John Trupiano</h3>
<p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_heather.jpg" alt="Heather" height="200" width="200" />
<h3>Heather Sarkissian</h3>
<p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_fulya.jpg" alt="Fulya" height="200" width="200" />
<h3>Fulya Gursel</h3>
- <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ <p>As one of the co-founders of Tech Crawl East, Fulya Gursel works at <a href="http://etcbaltimore.com">Emerging Technology Centers</a> (ETC) as Director of Marketing. At ETC, she provides business advisory services to ETC clients in the areas of marketing and communications, and provides direct assistance in the areas of market research, market strategy and business data collection and organization. She also is responsible for maintaining ETCâs portfolio of client resource materials like guidelines, impact studies, production reports, marketing collateral and making these materials available to clients when needed.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<img src="./img/img_brian.jpg" alt="Brian" height="200" width="200" />
<h3>Brian Sierakowski</h3>
- <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ <p>Brian Sierakowski is an enthusiastic advocate for the tech and entrepreneurial communities. He's currently the Managing Editor of the <a href="http://thestartupdigest.com/" target="_blank">Baltimore Startup Digest</a>, and is in the early stages of launching his startup Cahoots.
</p>
<div class="clear"></div>
</div>
</div>
<div class="container_wide container_wide_last">
<div class="container_fixed">
<img src="./img/img_paul.jpg" alt="Paul" height="200" width="200" />
<h3>Paul Capestany</h3>
<p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
</p>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 5cd00c5d6a0eacb461289ca806cb95f27f724b56 | target="_blank" | diff --git a/information-for-presenters.html b/information-for-presenters.html
index 5af3940..c5f6912 100644
--- a/information-for-presenters.html
+++ b/information-for-presenters.html
@@ -1,89 +1,89 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_information">
<div class="container_wide" id="intro_information">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Information for Tech Crawl East</h2>
</div>
</div>
</div>
</div>
<div class="container_wide" id="information_container">
<div id="information">
<h3>What do I need to do?</h3>
<ul>
<li><strong>Register as a Presenter</strong> by completing this Google Form.</li>
- <li><strong>Upload your logo</strong> to this <a href="http://drop.io/TechCrawlEast">drop.io drop</a>. Click the "Add" link and name the file with the same company name that you submitted.</li>
- <li><strong>Pay the Presenter Fee</strong> by signing up for this <a href="http://tcepresenter.eventbrite.com/">EventBrite event</a>.</li>
+ <li><strong>Upload your logo</strong> to this <a href="http://drop.io/TechCrawlEast" target="_blank">drop.io drop</a>. Click the "Add" link and name the file with the same company name that you submitted.</li>
+ <li><strong>Pay the Presenter Fee</strong> by signing up for this <a href="http://tcepresenter.eventbrite.com/" target="_blank">EventBrite event</a>.</li>
<li><strong>Prepare your Pitch</strong>: each table will have a "home base" set up for attendees to step on to hear your pitch. Whenever anyone steps up, you should be prepared to give your 60-second pitch that answers these questions:
<ul class="indent">
<li>What is exciting about your company or product?</li>
<li>Who are you selling to?</li>
<li>How does your customer benefit from your product?</li>
<li>Are you seeking investment and how will you use it?</li>
</ul>
</li>
<li><strong>Show off your product!</strong> this is a show and tell event. Attendees want to be able to experience your technology.</li>
<li><strong>Compile your marketing materials</strong>: each presenter will have a booth not all that dissimilar from a trade show. Bring your standard set of marketing posters, take-homes and business cards.</li>
<li><strong>Get pumped!</strong> this is an event to showcase you! Bring a load of energy and take advantage of the community coming to see you.</li>
</ul>
<h3>What is being provided to me?</h3>
<p>Tech Crawl East will provide each presenter with the following:</p>
<ul class="indent">
<li>a 2 1/2 ft x 5 ft table with a skirt and tablecloth</li>
<li>power and/or wifi (by request)</li>
<li>we will be recording your pitch and posting it online after the event</li>
</ul>
<h3>Is there an agenda?</h3>
<p>Yes, of course. Doors open at 5PM with food and beverages immediately available. The Crawl will begin at 5:30PM and run until 7:30PM. Award for the best pitch will be announced at 8:00PM. Presenters are encouraged to arrive at Morgan Stanley between 3:00PM and 3:30PM to begin setting up their tables. If your particular setup requires more time, feel free to arrive earlier than that.</p>
</div>
<div id="photos">
<img src="./img/img_information_empty_booth_small.jpg" alt="Empty Booth" width="400" height="300" />
<p class="caption">A sample booth setup. We are providing a table, skirt, cloth and base.</p>
<img src="./img/img_information_presenters_at_booth_small.jpg" alt="Presenters at booth" width="400" height="300" />
<p class="caption">Each presenter will be best served by having at least two people at the booth. At any given time, one person should be prepared to pitch to anyone who steps up to the plate, and the other should be there to talk casually to attendees and hand out marketing material.</p>
</div>
<div class="clear" />
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | ec3d499493626c1d9fb8383fe46929eb40dd346b | Organizers page, placeholders for everyone but John | diff --git a/css/styles.css b/css/styles.css
index dda9e3e..345246c 100644
--- a/css/styles.css
+++ b/css/styles.css
@@ -1,532 +1,550 @@
/* CSS RESET */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* tags
----------------------------------------------- */
body {
background-color: #00222e;
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
font-size: 18px;
line-height: 24px;
}
h1, h2, h3, h4, h5, h6 {
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
text-shadow: 1px 1px 0px #fff;
}
h1 {
}
h2 {
font-size:21px;
font-weight:bold;
}
h3 {
padding-bottom:8px;
font-size:24px;
line-height:24px;
/*font-style:italic;*/
color:#00222e;
text-shadow: 1px 1px 0px #fff;
}
h4 {
padding-bottom:5px;
font-size:21px;
line-height:21px;
}
/*a:link, a:visited, a:focus {
text-decoration: none;
border-bottom: 1px solid #000;
color:#000;
}*/
a:link, a:visited, a:focus {
color:#0066cc;
text-decoration:none;
font-weight:normal;
border:none;
}
a:hover {
color:#0066cc;
color:#00ccff;
border-bottom:1px solid #0066cc;
border:none;
}
/* layout
----------------------------------------------- */
#content {
}
.container_wide {
padding:30px 0 30px 0;
width:100%;
background-color:#e4e4e4;
border-bottom: 1px dashed #666;
border-top: 1px dashed #fff;
}
.container_fixed {
width:960px;
margin: 0 auto 0 auto;
}
/* head
----------------------------------------------- */
#head {
margin:0;
padding: 10px 0 10px 0;
position:fixed;
top:0px;
left:0px;
height: auto;
width: 100%;
background-color:#00222e;
border-bottom: 1px solid black;
z-index: 1000;
}
#logo {
padding: 0 0 0 15px;
position:relative;
float:left;
}
#logo h2 {
font-size:18px;
font-weight:bold;
text-shadow:none;
}
#logo h2 a:link, #logo h2 a:visited, #logo h2 a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#logo h2 a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav {
position:relative;
float:left;
}
#nav a:link, #nav a:visited, #nav a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#nav a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav ul, #social_media ul {
font-size:16px;
}
#nav ul li {
margin:0 0 0 20px;
position:relative;
float:left;
}
#nav .register {
position:relative;
float:right;
}
#social_media {
padding-right:25px;
float:right;
}
#social_media li#twitter {
padding-left:25px;
background: url(../img/icon_twitter.png) no-repeat center left;
}
#social_media a:link, #social_media a:visited, #social_media a:focus {
color:#499ff3;
}
#social_media a:hover {
color:#fff;
}
/* intro
----------------------------------------------- */
#intro {
margin-top:45px;
padding-top:70px;
padding-bottom:60px;
text-align: center;
border:none;
background-color:#0461c0;
background-image: url(../img/background_round_wave.png);
background-repeat: no-repeat;
background-position: center center;
}
#intro h1 {
padding:0;
margin:0;
}
/* call-to-action
----------------------------------------------- */
#intro_action {
background-color:#fdfee0;
}
.call_to_action {
margin: 0 10px 0 10px;
font-size:28px;
line-height:28px;
text-align:center;
}
.call_to_action h2 {
padding-bottom:10px;
font-size:36px !important;
line-height:36px;
}
.call_to_action h3 {
padding-bottom:0;
font-size:26px !important;
line-height:26px;
font-weight:normal;
text-transform:none;
}
.call_to_action a:link, .call_to_action a:visited, .call_to_action a:focus {
color:#ff4439;
border-bottom:1px solid #ff4439;
}
.call_to_action a:hover {
color:#499ff3;
border-bottom:1px solid #499ff3;
}
/* summary
----------------------------------------------- */
#summary {
background-color:#fff;
font-size:18px;
line-height:24px;
}
#summary h3 {
font-size:28px;
line-height:28px;
}
#summary h4 {
font-style:italic;
}
#companies, #attendees {
margin:0 10px 0 10px;
position:relative;
float:left;
width:460px;
text-align:center;
}
/* details
----------------------------------------------- */
#details {
border-bottom:none;
padding-bottom:0;
}
#details_text {
border-top:none;
}
#map, #venue, #event_links {
margin:0 10px 0 10px;
width:298px;
position:relative;
float:left;
border:1px solid #aaa;
background-color:#fff;
}
#event_links {
width:300px;
border:none;
background:none;
}
#map {
width:618px;
}
#venue {
}
#map iframe, #venue img {
padding:9px;
}
#event_links ul {
margin-top:5px;
border-top:1px solid #ccc;
border-bottom:1px solid #efefef;
}
#event_links li {
/*padding:8px 0 8px 25px;*/
padding:8px 0 8px 0;
font-size: 18px;
border-bottom: 1px solid #ccc;
border-top:1px solid #efefef;
background-repeat: no-repeat;
background-position: left center;
}
/*li#map_link_car {
background-image: url(../img/icon_car.png);
}
li#map_link_train {
background-image: url(../img/icon_train.png);
}
li#map_link_plane {
background-image: url(../img/icon_plane.png);
}
li#map_link_hotel {
background-image: url(../img/icon_hotel.png);
}
/* faqs
----------------------------------------------- */
.column_headline, .column_text {
position:relative;
float:left;
}
.column_headline {
padding:0 10px 0 10px;
width:300px;
}
.column_text {
padding:0 10px 0 10px;
width:620px;
}
.column_headline h3, .column_text h3 {
font-size:24px;
line-height:24px;
}
/* register
----------------------------------------------- */
#register {
background-color:#fdfee0;
text-align:center;
}
#register h3 {
font-size:28px;
line-height:28px;
padding:30px 0 30px 0;
border:1px solid #666;
background-color:#fff;
}
#register h3 a {
color:#ff4439;
border:none;
}
/* register PAGE
----------------------------------------------- */
#content_register {
margin-top:45px;
}
#content_register #intro_register {
border-top:none;
}
#register_form {
background-color:#fff;
border-bottom:none;
}
form {
margin-right:auto;
margin-left:auto;
width: 700px;
}
label {
width: 250px;
padding: 0 10px 0 0;
text-align: right;
position: relative;
float: left;
}
.form_row {
padding:0 0 15px 0;
}
.form_row p {
width:250px;
float:left;
text-align:right;
font-size:12px;
line-height:normal;
}
.form_row span {
padding-left:2px;
color:red;
}
#form-message {
color:#393;
font-size:21px;
line-height:28px;
padding-top:35px;
padding-bottom:15px;
text-align:center;
}
form button {
margin-left:260px;
}
input, textarea {
float:left;
font-size:16px;
}
#terms {
margin-top:30px;
margin-left:260px;
font-size:12px;
line-height:normal;
}
button {
font-size:18px;
padding:10px;
}
/* information for presenters PAGE
----------------------------------------------- */
#content_information {
margin-top:45px;
}
#content_information #intro_information {
border-top:none;
}
#information_container {
background-color:#fff;
border-bottom:none;
padding-left: 10%;
padding-right: 10%;
width: 80%;
}
#information_container #information {
float: left;
width: 56%;
margin-right: 5%;
}
#information_container #information h3 {
margin-top: 10px;
}
#information_container #information li, #information_container #information p {
margin-right: 0px;
font-size: 14px;
margin-bottom: 10px;
}
#information_container #information ul.indent {
margin-left: 10px;
margin-bottom: 10px;
}
#information_container #information ul.indent li {
margin-left: 20px;
list-style-type: disc;
margin-bottom: 0px;
}
#information_container #photos {
float: left;
width: 38%;
}
#information_container #photos .caption {
font-size: 12px;
}
+/* organizers PAGE
+----------------------------------------------- */
+
+#content_organizers {
+ margin-top:45px;
+}
+#content_organizers #intro_organizers {
+ border-top:none;
+}
+
+#content_organizers img {
+ float: left;
+ padding-right: 8px;
+}
+
+.container_wide_last {
+ border-bottom: 0;
+}
/* sponsors
----------------------------------------------- */
#sponsors {
text-align:center;
background-color:#fff;
border:none;
}
#sponsors h3 {
font-size:18px;
}
#sponsors p {
font-size:12px;
}
.sponsor_box {
margin:15px 10px 15px 10px;
position:relative;
float:left;
/*height:125px;*/
width:300px;
text-align:center;/*border:1px dashed #000;*/
}
/* foot
----------------------------------------------- */
#foot {
background-color:#00222e;
padding:30px 0 30px 0;
color:#ccc;
font-size:14px;
text-align:center;
}
a.sig:link, a.sig:visited, a.sig:focus {
color:#ccc;
text-decoration:underline;
}
a.sig:hover {
color:#fff;
}
/* float clearing
----------------------------------------------- */
/* float clearing for IE6 */
* html .clear {
height: 1%;
overflow: visible;
}
/* float clearing for IE7 */
*+html .clear {
min-height: 1%;
}
/* float clearing for everyone else */
.clear:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
.clear {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
diff --git a/img/img_john.jpg b/img/img_john.jpg
new file mode 100644
index 0000000..d3ed2be
Binary files /dev/null and b/img/img_john.jpg differ
diff --git a/organizers.html b/organizers.html
new file mode 100644
index 0000000..9a19f9f
--- /dev/null
+++ b/organizers.html
@@ -0,0 +1,95 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Tech Crawl East</title>
+<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
+<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
+<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
+<link href="css/styles.css" rel="stylesheet" type="text/css" />
+</head>
+<body id="body">
+<div id="head">
+ <div id="logo">
+ <h2><a href="index.html">« Return to Homepage</a></h2>
+ </div>
+ <div id="social_media">
+ <ul>
+ <li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
+ </ul>
+ </div>
+ <div class="clear"></div>
+</div>
+<div id="content_organizers">
+ <div class="container_wide" id="intro_organizers">
+ <div class="container_fixed">
+ <div>
+ <div class="call_to_action">
+ <h2>Tech Crawl East Organizers</h2>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <img src="./img/img_john.jpg" alt="John" height="200" width="200" />
+ <h3>John Trupiano</h3>
+ <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ </p>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <img src="./img/img_heather.jpg" alt="Heather" height="200" width="200" />
+ <h3>Heather Sarkissian</h3>
+ <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ </p>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <img src="./img/img_fulya.jpg" alt="Fulya" height="200" width="200" />
+ <h3>Fulya Gursel</h3>
+ <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ </p>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <img src="./img/img_brian.jpg" alt="Brian" height="200" width="200" />
+ <h3>Brian Sierakowski</h3>
+ <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ </p>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide container_wide_last">
+ <div class="container_fixed">
+ <img src="./img/img_paul.jpg" alt="Paul" height="200" width="200" />
+ <h3>Paul Capestany</h3>
+ <p>John co-founded the Tech Crawl in 2009 with Heather. He is the president of <a href="http://smartlogicsolutions.com">SmartLogic Solutions</a>, a technology consulting and software development firm based in Baltimore. He is a very active member in the local business and technology communities. He co-organizes <a href="http://bmoreonrails.org">B'more on Rails</a> and is involved with other initiatives like <a href="http://betascape.org">Betascape</a>, <a href="http://ignitebaltimore.com">Ignite Baltimore</a>, <a href="http://bohconf.com">BohConf</a> and <a href="http://baltimorecocoa.com">Baltimore Cocoa</a>.
+ </p>
+ <div class="clear"></div>
+ </div>
+ </div>
+</div>
+<div id="foot">
+ <div class="container_fixed">
+ <p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
+ </div>
+</div>
+<script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-11671914-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>
+</body>
+</html>
|
jtrupiano/techcrawleast | 15cf249383d2a96d34667eada423d34036366425 | Change hopstop link | diff --git a/index.html b/index.html
index feb371a..76d47ad 100644
--- a/index.html
+++ b/index.html
@@ -1,153 +1,153 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
- <li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=1300+Thames+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
+ <li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=Thames+St+and+S+Caroline+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | fe746be05b7eecc6c56f1aeaaccd95d1c15b0630 | 1300, not 1200 | diff --git a/index.html b/index.html
index 193549e..feb371a 100644
--- a/index.html
+++ b/index.html
@@ -1,153 +1,153 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
- <li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=1200+Thames+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
+ <li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=1300+Thames+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 78da14522d2cf0e58f283eb9cab4c06c5c01bc35 | Drop the pin on the map at 1300 Thames St. | diff --git a/index.html b/index.html
index f524982..193549e 100644
--- a/index.html
+++ b/index.html
@@ -1,153 +1,153 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
- <iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=901+South+Bond+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
+ <iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=1300+Thames+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=1300+Thames+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=1200+Thames+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<div class="sponsor_box"></div>
<div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" /></a></div>
<div class="sponsor_box"></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | e0d338a4d0038dcc781aa5bef85a1b2d064314e2 | Presenter information page | diff --git a/css/styles.css b/css/styles.css
index dfbbc41..dda9e3e 100644
--- a/css/styles.css
+++ b/css/styles.css
@@ -1,479 +1,532 @@
/* CSS RESET */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* tags
----------------------------------------------- */
body {
background-color: #00222e;
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
font-size: 18px;
line-height: 24px;
}
h1, h2, h3, h4, h5, h6 {
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
text-shadow: 1px 1px 0px #fff;
}
h1 {
}
h2 {
font-size:21px;
font-weight:bold;
}
h3 {
padding-bottom:8px;
font-size:24px;
line-height:24px;
/*font-style:italic;*/
color:#00222e;
text-shadow: 1px 1px 0px #fff;
}
h4 {
padding-bottom:5px;
font-size:21px;
line-height:21px;
}
/*a:link, a:visited, a:focus {
text-decoration: none;
border-bottom: 1px solid #000;
color:#000;
}*/
a:link, a:visited, a:focus {
color:#0066cc;
text-decoration:none;
font-weight:normal;
border:none;
}
a:hover {
color:#0066cc;
color:#00ccff;
border-bottom:1px solid #0066cc;
border:none;
}
/* layout
----------------------------------------------- */
#content {
}
.container_wide {
padding:30px 0 30px 0;
width:100%;
background-color:#e4e4e4;
border-bottom: 1px dashed #666;
border-top: 1px dashed #fff;
}
.container_fixed {
width:960px;
margin: 0 auto 0 auto;
}
/* head
----------------------------------------------- */
#head {
margin:0;
padding: 10px 0 10px 0;
position:fixed;
top:0px;
left:0px;
height: auto;
width: 100%;
background-color:#00222e;
border-bottom: 1px solid black;
z-index: 1000;
}
#logo {
padding: 0 0 0 15px;
position:relative;
float:left;
}
#logo h2 {
font-size:18px;
font-weight:bold;
text-shadow:none;
}
#logo h2 a:link, #logo h2 a:visited, #logo h2 a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#logo h2 a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav {
position:relative;
float:left;
}
#nav a:link, #nav a:visited, #nav a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#nav a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav ul, #social_media ul {
font-size:16px;
}
#nav ul li {
margin:0 0 0 20px;
position:relative;
float:left;
}
#nav .register {
position:relative;
float:right;
}
#social_media {
padding-right:25px;
float:right;
}
#social_media li#twitter {
padding-left:25px;
background: url(../img/icon_twitter.png) no-repeat center left;
}
#social_media a:link, #social_media a:visited, #social_media a:focus {
color:#499ff3;
}
#social_media a:hover {
color:#fff;
}
/* intro
----------------------------------------------- */
#intro {
margin-top:45px;
padding-top:70px;
padding-bottom:60px;
text-align: center;
border:none;
background-color:#0461c0;
background-image: url(../img/background_round_wave.png);
background-repeat: no-repeat;
background-position: center center;
}
#intro h1 {
padding:0;
margin:0;
}
/* call-to-action
----------------------------------------------- */
#intro_action {
background-color:#fdfee0;
}
.call_to_action {
margin: 0 10px 0 10px;
font-size:28px;
line-height:28px;
text-align:center;
}
.call_to_action h2 {
padding-bottom:10px;
font-size:36px !important;
line-height:36px;
}
.call_to_action h3 {
padding-bottom:0;
font-size:26px !important;
line-height:26px;
font-weight:normal;
text-transform:none;
}
.call_to_action a:link, .call_to_action a:visited, .call_to_action a:focus {
color:#ff4439;
border-bottom:1px solid #ff4439;
}
.call_to_action a:hover {
color:#499ff3;
border-bottom:1px solid #499ff3;
}
/* summary
----------------------------------------------- */
#summary {
background-color:#fff;
font-size:18px;
line-height:24px;
}
#summary h3 {
font-size:28px;
line-height:28px;
}
#summary h4 {
font-style:italic;
}
#companies, #attendees {
margin:0 10px 0 10px;
position:relative;
float:left;
width:460px;
text-align:center;
}
/* details
----------------------------------------------- */
#details {
border-bottom:none;
padding-bottom:0;
}
#details_text {
border-top:none;
}
#map, #venue, #event_links {
margin:0 10px 0 10px;
width:298px;
position:relative;
float:left;
border:1px solid #aaa;
background-color:#fff;
}
#event_links {
width:300px;
border:none;
background:none;
}
#map {
width:618px;
}
#venue {
}
#map iframe, #venue img {
padding:9px;
}
#event_links ul {
margin-top:5px;
border-top:1px solid #ccc;
border-bottom:1px solid #efefef;
}
#event_links li {
/*padding:8px 0 8px 25px;*/
padding:8px 0 8px 0;
font-size: 18px;
border-bottom: 1px solid #ccc;
border-top:1px solid #efefef;
background-repeat: no-repeat;
background-position: left center;
}
/*li#map_link_car {
background-image: url(../img/icon_car.png);
}
li#map_link_train {
background-image: url(../img/icon_train.png);
}
li#map_link_plane {
background-image: url(../img/icon_plane.png);
}
li#map_link_hotel {
background-image: url(../img/icon_hotel.png);
}
/* faqs
----------------------------------------------- */
.column_headline, .column_text {
position:relative;
float:left;
}
.column_headline {
padding:0 10px 0 10px;
width:300px;
}
.column_text {
padding:0 10px 0 10px;
width:620px;
}
.column_headline h3, .column_text h3 {
font-size:24px;
line-height:24px;
}
/* register
----------------------------------------------- */
#register {
background-color:#fdfee0;
text-align:center;
}
#register h3 {
font-size:28px;
line-height:28px;
padding:30px 0 30px 0;
border:1px solid #666;
background-color:#fff;
}
#register h3 a {
color:#ff4439;
border:none;
}
/* register PAGE
----------------------------------------------- */
#content_register {
margin-top:45px;
}
#content_register #intro_register {
border-top:none;
}
#register_form {
background-color:#fff;
border-bottom:none;
}
form {
margin-right:auto;
margin-left:auto;
width: 700px;
}
label {
width: 250px;
padding: 0 10px 0 0;
text-align: right;
position: relative;
float: left;
}
.form_row {
padding:0 0 15px 0;
}
.form_row p {
width:250px;
float:left;
text-align:right;
font-size:12px;
line-height:normal;
}
.form_row span {
padding-left:2px;
color:red;
}
#form-message {
color:#393;
font-size:21px;
line-height:28px;
padding-top:35px;
padding-bottom:15px;
text-align:center;
}
form button {
margin-left:260px;
}
input, textarea {
float:left;
font-size:16px;
}
#terms {
margin-top:30px;
margin-left:260px;
font-size:12px;
line-height:normal;
}
button {
font-size:18px;
padding:10px;
}
+/* information for presenters PAGE
+----------------------------------------------- */
+
+#content_information {
+ margin-top:45px;
+}
+#content_information #intro_information {
+ border-top:none;
+}
+#information_container {
+ background-color:#fff;
+ border-bottom:none;
+ padding-left: 10%;
+ padding-right: 10%;
+ width: 80%;
+}
+
+#information_container #information {
+ float: left;
+ width: 56%;
+ margin-right: 5%;
+}
+
+#information_container #information h3 {
+ margin-top: 10px;
+}
+
+#information_container #information li, #information_container #information p {
+ margin-right: 0px;
+ font-size: 14px;
+ margin-bottom: 10px;
+}
+
+#information_container #information ul.indent {
+ margin-left: 10px;
+ margin-bottom: 10px;
+}
+#information_container #information ul.indent li {
+ margin-left: 20px;
+ list-style-type: disc;
+ margin-bottom: 0px;
+}
+
+#information_container #photos {
+ float: left;
+ width: 38%;
+}
+
+#information_container #photos .caption {
+ font-size: 12px;
+}
+
+
/* sponsors
----------------------------------------------- */
#sponsors {
text-align:center;
background-color:#fff;
border:none;
}
#sponsors h3 {
font-size:18px;
}
#sponsors p {
font-size:12px;
}
.sponsor_box {
margin:15px 10px 15px 10px;
position:relative;
float:left;
/*height:125px;*/
width:300px;
text-align:center;/*border:1px dashed #000;*/
}
/* foot
----------------------------------------------- */
#foot {
background-color:#00222e;
padding:30px 0 30px 0;
color:#ccc;
font-size:14px;
text-align:center;
}
a.sig:link, a.sig:visited, a.sig:focus {
color:#ccc;
text-decoration:underline;
}
a.sig:hover {
color:#fff;
}
/* float clearing
----------------------------------------------- */
/* float clearing for IE6 */
* html .clear {
height: 1%;
overflow: visible;
}
/* float clearing for IE7 */
*+html .clear {
min-height: 1%;
}
/* float clearing for everyone else */
.clear:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
.clear {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
diff --git a/img/img_information_empty_booth_small.jpg b/img/img_information_empty_booth_small.jpg
new file mode 100644
index 0000000..f2f5c17
Binary files /dev/null and b/img/img_information_empty_booth_small.jpg differ
diff --git a/img/img_information_presenters_at_booth_small.jpg b/img/img_information_presenters_at_booth_small.jpg
new file mode 100644
index 0000000..45a396e
Binary files /dev/null and b/img/img_information_presenters_at_booth_small.jpg differ
diff --git a/information-for-presenters.html b/information-for-presenters.html
new file mode 100644
index 0000000..c9c54a2
--- /dev/null
+++ b/information-for-presenters.html
@@ -0,0 +1,88 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Tech Crawl East</title>
+<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
+<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
+<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
+<link href="css/styles.css" rel="stylesheet" type="text/css" />
+</head>
+<body id="body">
+<div id="head">
+ <div id="logo">
+ <h2><a href="index.html">« Return to Homepage</a></h2>
+ </div>
+ <div id="social_media">
+ <ul>
+ <li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
+ </ul>
+ </div>
+ <div class="clear"></div>
+</div>
+<div id="content_information">
+ <div class="container_wide" id="intro_information">
+ <div class="container_fixed">
+ <div>
+ <div class="call_to_action">
+ <h2>Presenter Information for Tech Crawl East</h2>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="container_wide" id="information_container">
+ <div id="information">
+ <h3>What do I need to do?</h3>
+ <ul>
+ <li><strong>Register as a Presenter</strong>: complete this Google Form.</li>
+ <li><strong>Pay the Presenter Fee</strong>: link to EventBrite.</li>
+ <li><strong>Prepare your Pitch</strong>: each table will have a "home base" set up for attendees to step on to hear your pitch. Whenever anyone steps up, you should be prepared to give your 60-second pitch that answers these questions:
+ <ul class="indent">
+ <li>What is exciting about your company or product?</li>
+ <li>Who are you selling to?</li>
+ <li>How does your customer benefit from your product?</li>
+ <li>Are you seeking investment and how will you use it?</li>
+ </ul>
+ </li>
+ <li><strong>Show off your product!</strong> this is a show and tell event. Attendees want to be able to experience your technology.</li>
+ <li><strong>Compile your marketing materials</strong>: each presenter will have a booth not all that dissimilar from a trade show. Bring your standard set of marketing posters, take-homes and business cards.</li>
+ <li><strong>Get pumped!</strong> this is an event to showcase you! Bring a load of energy and take advantage of the community coming to see you.</li>
+ </ul>
+
+ <h3>What is being provided to me?</h3>
+ <p>Tech Crawl East will provide each presenter with the following:</p>
+ <ul class="indent">
+ <li>a 2 1/2 ft x 5 ft table with a skirt and tablecloth</li>
+ <li>power and/or wifi (by request)</li>
+ <li>we will be recording your pitch and posting it online after the event</li>
+ </ul>
+
+ <h3>Is there an agenda?</h3>
+ <p>Yes, of course. Doors open at 5PM with food and beverages immediately available. The Crawl will begin at 5:30PM and run until 7:30PM. Award for the best pitch will be announced at 8:00PM. Presenters are encouraged to arrive at Morgan Stanley between 3:00PM and 3:30PM to begin setting up their tables. If your particular setup requires more time, feel free to arrive earlier than that.</p>
+ </div>
+ <div id="photos">
+ <img src="./img/img_information_empty_booth_small.jpg" alt="Empty Booth" width="400" height="300" />
+ <p class="caption">A sample booth setup. We are providing a table, skirt, cloth and base.</p>
+ <img src="./img/img_information_presenters_at_booth_small.jpg" alt="Presenters at booth" width="400" height="300" />
+ <p class="caption">Each presenter will be best served by having at least two people at the booth. At any given time, one person should be prepared to pitch to anyone who steps up to the plate, and the other should be there to talk casually to attendees and hand out marketing material.</p>
+ </div>
+ <div class="clear" />
+ </div>
+</div>
+<div id="foot">
+ <div class="container_fixed">
+ <p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
+ </div>
+</div>
+<script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-11671914-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>
+</body>
+</html>
|
jtrupiano/techcrawleast | 8e1ce5e86eee47dc3fef7dee8709c6c55a10c9a8 | Add clarification note about the $100 fee | diff --git a/register.html b/register.html
index a4aec09..13dca74 100644
--- a/register.html
+++ b/register.html
@@ -1,128 +1,128 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete each required field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
- <p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
+ <p>The $100 presenter fee is necessary to help offset the cost of organizing this event. The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
<p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_description">Your Pitch</label>
<textarea id="pitch_description" name="entry.7.single" rows="10" cols="40"></textarea>
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Video (optional)</label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 60ffde3d4c4a3114e231c6c20e178eda08748428 | Add Vmeals as sponsor, add "Get Transit Directions" via HopStop | diff --git a/img/img_sponsor_vmeals.jpg b/img/img_sponsor_vmeals.jpg
new file mode 100644
index 0000000..0af4cdd
Binary files /dev/null and b/img/img_sponsor_vmeals.jpg differ
diff --git a/index.html b/index.html
index 05ac876..f524982 100644
--- a/index.html
+++ b/index.html
@@ -1,148 +1,153 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=901+South+Bond+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
- <li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=901+S+Bond+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
+ <li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=1300+Thames+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
+ <li id="map_link_transit"><a href="http://www.hopstop.com/route?city2=Baltimore&county2=baltimore%2c+md&address2=1200+Thames+St&mode=a&city1=Baltimore" target="_blank">Get Transit Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
+ <div class="sponsor_box"></div>
+ <div class="sponsor_box"><a href="http://www.vmeals.com/" target="_blank"><img src="./img/img_sponsor_vmeals.jpg" alt="Vmeals" /></a></div>
+ <div class="sponsor_box"></div>
+ <div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | d8058ef33ddfeafa0c3c9f8160000847e932fb7b | Make the video more optional | diff --git a/register.html b/register.html
index d98f32f..a4aec09 100644
--- a/register.html
+++ b/register.html
@@ -1,131 +1,128 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete each required field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
<p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
- <span>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site. If you are unable to record a video, then please write out your pitch in the textarea beneath. Strong preference will be given to those who submit a video.</span>
- </div>
- <div class="form_row">
- <label for="pitch_link">Link to 60 Second Pitch Video</label>
- <input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
+ <label for="pitch_description">Your Pitch</label>
+ <textarea id="pitch_description" name="entry.7.single" rows="10" cols="40"></textarea>
<div class="clear"></div>
</div>
<div class="form_row">
- <label for="pitch_description">Your Pitch</label>
- <textarea id="pitch_description" name="entry.7.single" rows="10" cols="40"></textarea>
+ <label for="pitch_link">Link to 60 Second Pitch Video (optional)</label>
+ <input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 8b2fcab47d867e5100301bbba18ed427c44a9f20 | Change validation alert message | diff --git a/register.html b/register.html
index b850199..d98f32f 100644
--- a/register.html
+++ b/register.html
@@ -1,131 +1,131 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
- alert("Please complete every field");
+ alert("Please complete each required field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
<p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<span>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site. If you are unable to record a video, then please write out your pitch in the textarea beneath. Strong preference will be given to those who submit a video.</span>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Video</label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_description">Your Pitch</label>
<textarea id="pitch_description" name="entry.7.single" rows="10" cols="40"></textarea>
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | e35a2399200998731c37d5706f555f24f9febd98 | Don't require a pitch link | diff --git a/register.html b/register.html
index 0f7afad..b850199 100644
--- a/register.html
+++ b/register.html
@@ -1,131 +1,131 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
- var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location", "pitch_link"];
+ var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete every field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
<p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<span>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site. If you are unable to record a video, then please write out your pitch in the textarea beneath. Strong preference will be given to those who submit a video.</span>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Video</label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_description">Your Pitch</label>
<textarea id="pitch_description" name="entry.7.single" rows="10" cols="40"></textarea>
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 22a8896c3eb7831dc9a61d1506a8f3b662e7d28e | Tweak video upload | diff --git a/register.html b/register.html
index 6f1a032..0f7afad 100644
--- a/register.html
+++ b/register.html
@@ -1,130 +1,131 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location", "pitch_link"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete every field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
<p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
- <label for="pitch_link">Link to 60 Second Pitch Demo</label>
+ <span>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site. If you are unable to record a video, then please write out your pitch in the textarea beneath. Strong preference will be given to those who submit a video.</span>
+ </div>
+ <div class="form_row">
+ <label for="pitch_link">Link to 60 Second Pitch Video</label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
- <p>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site. Preference will be given to those who submit a video.</p>
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_description">Your Pitch</label>
- <textarea id="pitch_description" name="entry.7.single" rows="10" cols="30"></textarea>
- <p>Only fill out your pitch if you have not submitted a video. It is highly encouraged to submit a video of your pitch rather than typing it out here!</p>
+ <textarea id="pitch_description" name="entry.7.single" rows="10" cols="40"></textarea>
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | f27197e33845ab5185ff94005662901a4dcc7a76 | Make video optional, allow written pitch. | diff --git a/register.html b/register.html
index 3086271..6f1a032 100644
--- a/register.html
+++ b/register.html
@@ -1,124 +1,130 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location", "pitch_link"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete every field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
<p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
- <label for="pitch_link">Link to 60 Second Pitch Demo<span class="required">*</span></label>
+ <label for="pitch_link">Link to 60 Second Pitch Demo</label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
- <p>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site.</p>
+ <p>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site. Preference will be given to those who submit a video.</p>
+ <div class="clear"></div>
+ </div>
+ <div class="form_row">
+ <label for="pitch_description">Your Pitch</label>
+ <textarea id="pitch_description" name="entry.7.single" rows="10" cols="30"></textarea>
+ <p>Only fill out your pitch if you have not submitted a video. It is highly encouraged to submit a video of your pitch rather than typing it out here!</p>
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 25bc83a5b404f02556af3f4e5cd426ffdd67c87f | Fix language | diff --git a/index.html b/index.html
index b90e72f..05ac876 100644
--- a/index.html
+++ b/index.html
@@ -1,148 +1,148 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=901+South+Bond+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=901+S+Bond+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
- <p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is intended as an annual event where, year after year, companies will return with new and exiting products and services to demo. </p>
+ <p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is an annual event where, year after year, companies will return with new and exciting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 3641a3147d606cebf874f12ba477bf26e705279b | Link to last year's videos | diff --git a/index.html b/index.html
index ea07557..b90e72f 100644
--- a/index.html
+++ b/index.html
@@ -1,148 +1,148 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=901+South+Bond+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=901+S+Bond+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
- <p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful MD Tech Crawl (<a href="http://www.mdtechcrawl.com" target="_blank">mdtechcrawl.com</a>), where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. This year we aim to more than double the number of businesses present as well as attendees.</p>
+ <p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful <a href="http://www.mdtechcrawl.com" target="_blank">MD Tech Crawl</a>, where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. Check out videos of our <a href="http://www.youtube.com/watch?v=XrFoG2aJfg4" target="_blank">first place winner Direct Dimensions</a> and one of our runners up <a href="http://www.youtube.com/watch?v=Ft0tGFcmctI" target="_blank">Juxtopia</a>.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is intended as an annual event where, year after year, companies will return with new and exiting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 08db3866db12793ea8fe4df18786207bf5391a3f | Add note about deadline to presenter application form | diff --git a/register.html b/register.html
index ae25155..3086271 100644
--- a/register.html
+++ b/register.html
@@ -1,122 +1,124 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location", "pitch_link"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete every field");
return false;
}
}
return true;
}
</script>
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
+ <p>The deadline for submitting your application is September 1. Presenters will be notified of selection by September 3.</p>
+ <p> </p>
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Demo<span class="required">*</span></label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
<p>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site.</p>
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 97c6b00eed1d348ed07d303b73ce1fd4434b53b2 | Added favicon | diff --git a/img/favicon.ico b/img/favicon.ico
new file mode 100644
index 0000000..20f23d3
Binary files /dev/null and b/img/favicon.ico differ
diff --git a/index.html b/index.html
index ac7d6ec..ea07557 100644
--- a/index.html
+++ b/index.html
@@ -1,147 +1,148 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East: One Night, One Place, Top East-Coast Tech Companies</title>
<meta name="robots" content="all" />
<meta name="keywords" content="startup, startups, pitch, speed pitch, funding, seed funding, entrepreneurs, angel investor, angel investors, investors, investment, venture capital"/>
<meta http-equiv="Description" content="In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products." />
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
+<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
</div>
<div id="nav">
<ul>
<li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
<li><a href="javascript:void(0)" onclick="goToByScroll('details')">Event Details</a></li>
<li><a href="register.html">Apply To Present</a></li>
<li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register To Attend</a></li>
</ul>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content">
<div class="container_wide" id="intro">
<div class="container_fixed">
<div>
<h1><img src="./img/text_tech_crawl_east_lrg.png" alt="Tech Crawl East" /></h1>
</div>
</div>
</div>
<div id="intro_action" class="container_wide">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>One Night, One Place, Top East-Coast Tech Companies</h2>
<h3>Thursday, September 16th, 5-9PM, Baltimore, MD » <a href="register.html">Present</a> or <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Attend</a></h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="summary">
<div class="container_fixed">
<div id="companies">
<!--<h3>Companies</h3>-->
<h4>Pitch in 60 Seconds to Investors and Peers</h4>
<p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with important investor, partner and media contacts.<br />
<a href="register.html">Apply to present »</a></p>
</div>
<div id="attendees">
<!--<h3>Attendees</h3>-->
<h4>See Who's Hot on the East Coast</h4>
<p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products.<br />
<a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register to attend for free »</a></p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details">
<div class="container_fixed">
<div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
<div id="map">
<iframe width="600" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=901+South+Bond+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="details_text">
<div class="container_fixed">
<div id="event_links">
<h3>Event Details</h3>
<ul>
<li id="map_link_car"><a href="http://www.google.com/maps?f=d&source=s_d&saddr=&daddr=901+S+Bond+St,+Baltimore,+Maryland+21231&hl=en&geocode=&mra=ls&sll=39.280902,-76.594362&sspn=0.012756,0.026178&ie=UTF8&ll=39.280686,-76.594362&spn=0.013171,0.026178&z=16&iwloc=ddw1" target="_blank">Get Driving Directions</a></li>
<li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
<li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
<li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
</ul>
</div>
<div class="column_text">
<p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful MD Tech Crawl (<a href="http://www.mdtechcrawl.com" target="_blank">mdtechcrawl.com</a>), where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. This year we aim to more than double the number of businesses present as well as attendees.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>What is a Tech Crawl?</h3>
</div>
<div class="column_text">
<p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is intended as an annual event where, year after year, companies will return with new and exiting products and services to demo. </p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide">
<div class="container_fixed">
<div class="column_headline">
<h3>Why the 60 Second Pitch?</h3>
</div>
<div class="column_text">
<p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="container_wide" id="sponsors">
<div class="container_fixed">
<div>
<h3>Please Support Our Sponsors</h3>
<div class="sponsor_box"><a href="http://www.etcbaltimore.com/" target="_blank"><img src="./img/img_sponsor_etc_logo.jpg" alt="ETC" /></a></div>
<div class="sponsor_box"><a href="http://www.fundinguniverse.com/" target="_blank"><img src="./img/img_sponsor_funding_universe.jpg" alt="Funding Universe" /></a></div>
<div class="sponsor_box"><a href="http://thestartupdigest.com/" target="_blank"><img src="./img/img_sponsor_startup_digest.jpg" alt="Startup Digest" /></a></div>
<div class="clear"></div>
<p><a href="mailto:[email protected]">Become a sponsor »</a></p>
</div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
diff --git a/register.html b/register.html
index 47b6b20..ae25155 100644
--- a/register.html
+++ b/register.html
@@ -1,121 +1,122 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
function showThankYou() {
document.getElementById("form-message").style.display="";
document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
}
function formCompleted() {
var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location", "pitch_link"];
var elem;
for (elem in elems) {
if (document.getElementById(elems[elem]).value === "") {
alert("Please complete every field");
return false;
}
}
return true;
}
</script>
+<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
<input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
<input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
<input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
<input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
<input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
<input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Demo<span class="required">*</span></label>
<input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
<p>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site.</p>
<div class="clear"></div>
</div>
</div>
<button type="submit" id="submit_button">Submit Application</button>
<div style="display:none;" id="form-message"></div>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
<iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | b36581df1aa65ef5ee3f2fb9e476ce4aff24b1f8 | styled thank you message on register page | diff --git a/css/styles.css b/css/styles.css
index ac6e813..dfbbc41 100644
--- a/css/styles.css
+++ b/css/styles.css
@@ -1,473 +1,479 @@
/* CSS RESET */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* tags
----------------------------------------------- */
body {
background-color: #00222e;
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
font-size: 18px;
line-height: 24px;
}
h1, h2, h3, h4, h5, h6 {
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
text-shadow: 1px 1px 0px #fff;
}
h1 {
}
h2 {
font-size:21px;
font-weight:bold;
}
h3 {
padding-bottom:8px;
font-size:24px;
line-height:24px;
/*font-style:italic;*/
color:#00222e;
text-shadow: 1px 1px 0px #fff;
}
h4 {
padding-bottom:5px;
font-size:21px;
line-height:21px;
}
/*a:link, a:visited, a:focus {
text-decoration: none;
border-bottom: 1px solid #000;
color:#000;
}*/
a:link, a:visited, a:focus {
color:#0066cc;
text-decoration:none;
font-weight:normal;
border:none;
}
a:hover {
color:#0066cc;
color:#00ccff;
border-bottom:1px solid #0066cc;
border:none;
}
/* layout
----------------------------------------------- */
#content {
}
.container_wide {
padding:30px 0 30px 0;
width:100%;
background-color:#e4e4e4;
border-bottom: 1px dashed #666;
border-top: 1px dashed #fff;
}
.container_fixed {
width:960px;
margin: 0 auto 0 auto;
}
/* head
----------------------------------------------- */
#head {
margin:0;
padding: 10px 0 10px 0;
position:fixed;
top:0px;
left:0px;
height: auto;
width: 100%;
background-color:#00222e;
border-bottom: 1px solid black;
z-index: 1000;
}
#logo {
padding: 0 0 0 15px;
position:relative;
float:left;
}
#logo h2 {
font-size:18px;
font-weight:bold;
text-shadow:none;
}
#logo h2 a:link, #logo h2 a:visited, #logo h2 a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#logo h2 a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav {
position:relative;
float:left;
}
#nav a:link, #nav a:visited, #nav a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#nav a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav ul, #social_media ul {
font-size:16px;
}
#nav ul li {
margin:0 0 0 20px;
position:relative;
float:left;
}
#nav .register {
position:relative;
float:right;
}
#social_media {
padding-right:25px;
float:right;
}
#social_media li#twitter {
padding-left:25px;
background: url(../img/icon_twitter.png) no-repeat center left;
}
#social_media a:link, #social_media a:visited, #social_media a:focus {
color:#499ff3;
}
#social_media a:hover {
color:#fff;
}
/* intro
----------------------------------------------- */
#intro {
margin-top:45px;
padding-top:70px;
padding-bottom:60px;
text-align: center;
border:none;
background-color:#0461c0;
background-image: url(../img/background_round_wave.png);
background-repeat: no-repeat;
background-position: center center;
}
#intro h1 {
padding:0;
margin:0;
}
/* call-to-action
----------------------------------------------- */
#intro_action {
background-color:#fdfee0;
}
.call_to_action {
margin: 0 10px 0 10px;
font-size:28px;
line-height:28px;
text-align:center;
}
.call_to_action h2 {
padding-bottom:10px;
font-size:36px !important;
line-height:36px;
}
.call_to_action h3 {
padding-bottom:0;
font-size:26px !important;
line-height:26px;
font-weight:normal;
text-transform:none;
}
.call_to_action a:link, .call_to_action a:visited, .call_to_action a:focus {
color:#ff4439;
border-bottom:1px solid #ff4439;
}
.call_to_action a:hover {
color:#499ff3;
border-bottom:1px solid #499ff3;
}
/* summary
----------------------------------------------- */
#summary {
background-color:#fff;
font-size:18px;
line-height:24px;
}
#summary h3 {
font-size:28px;
line-height:28px;
}
#summary h4 {
font-style:italic;
}
#companies, #attendees {
margin:0 10px 0 10px;
position:relative;
float:left;
width:460px;
text-align:center;
}
/* details
----------------------------------------------- */
#details {
border-bottom:none;
padding-bottom:0;
}
#details_text {
border-top:none;
}
#map, #venue, #event_links {
margin:0 10px 0 10px;
width:298px;
position:relative;
float:left;
border:1px solid #aaa;
background-color:#fff;
}
#event_links {
width:300px;
border:none;
background:none;
}
#map {
width:618px;
}
#venue {
}
#map iframe, #venue img {
padding:9px;
}
#event_links ul {
margin-top:5px;
border-top:1px solid #ccc;
border-bottom:1px solid #efefef;
}
#event_links li {
/*padding:8px 0 8px 25px;*/
padding:8px 0 8px 0;
font-size: 18px;
border-bottom: 1px solid #ccc;
border-top:1px solid #efefef;
background-repeat: no-repeat;
background-position: left center;
}
/*li#map_link_car {
background-image: url(../img/icon_car.png);
}
li#map_link_train {
background-image: url(../img/icon_train.png);
}
li#map_link_plane {
background-image: url(../img/icon_plane.png);
}
li#map_link_hotel {
background-image: url(../img/icon_hotel.png);
}
/* faqs
----------------------------------------------- */
.column_headline, .column_text {
position:relative;
float:left;
}
.column_headline {
padding:0 10px 0 10px;
width:300px;
}
.column_text {
padding:0 10px 0 10px;
width:620px;
}
.column_headline h3, .column_text h3 {
font-size:24px;
line-height:24px;
}
/* register
----------------------------------------------- */
#register {
background-color:#fdfee0;
text-align:center;
}
#register h3 {
font-size:28px;
line-height:28px;
padding:30px 0 30px 0;
border:1px solid #666;
background-color:#fff;
}
#register h3 a {
color:#ff4439;
border:none;
}
/* register PAGE
----------------------------------------------- */
#content_register {
margin-top:45px;
}
-
#content_register #intro_register {
border-top:none;
}
-
#register_form {
background-color:#fff;
border-bottom:none;
}
form {
margin-right:auto;
margin-left:auto;
width: 700px;
}
label {
width: 250px;
padding: 0 10px 0 0;
text-align: right;
position: relative;
float: left;
}
.form_row {
padding:0 0 15px 0;
}
.form_row p {
width:250px;
float:left;
text-align:right;
font-size:12px;
line-height:normal;
}
.form_row span {
padding-left:2px;
color:red;
}
+#form-message {
+ color:#393;
+ font-size:21px;
+ line-height:28px;
+ padding-top:35px;
+ padding-bottom:15px;
+ text-align:center;
+}
form button {
margin-left:260px;
}
input, textarea {
float:left;
font-size:16px;
}
#terms {
margin-top:30px;
margin-left:260px;
font-size:12px;
line-height:normal;
}
button {
font-size:18px;
padding:10px;
}
/* sponsors
----------------------------------------------- */
#sponsors {
text-align:center;
background-color:#fff;
border:none;
}
#sponsors h3 {
font-size:18px;
}
#sponsors p {
font-size:12px;
}
.sponsor_box {
margin:15px 10px 15px 10px;
position:relative;
float:left;
/*height:125px;*/
width:300px;
text-align:center;/*border:1px dashed #000;*/
}
/* foot
----------------------------------------------- */
#foot {
background-color:#00222e;
padding:30px 0 30px 0;
color:#ccc;
font-size:14px;
text-align:center;
}
a.sig:link, a.sig:visited, a.sig:focus {
color:#ccc;
text-decoration:underline;
}
a.sig:hover {
color:#fff;
}
/* float clearing
----------------------------------------------- */
/* float clearing for IE6 */
* html .clear {
height: 1%;
overflow: visible;
}
/* float clearing for IE7 */
*+html .clear {
min-height: 1%;
}
/* float clearing for everyone else */
.clear:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
.clear {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
|
jtrupiano/techcrawleast | 186427c4515b833f3272249a396a4d2ca2cce651 | Hook up the Google Form, requires polish from Charles | diff --git a/register.html b/register.html
index 671be8b..47b6b20 100644
--- a/register.html
+++ b/register.html
@@ -1,100 +1,121 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
+<script type="text/javascript">
+ function showThankYou() {
+ document.getElementById("form-message").style.display="";
+ document.getElementById("form-message").innerHTML="<p>Thanks for submitting your application! We will contact you by email to let you know if you've been selected.</p>";
+ }
+
+ function formCompleted() {
+ var elems = ["company_name", "contact_name", "email", "phone", "company_website", "location", "pitch_link"];
+ var elem;
+ for (elem in elems) {
+ if (document.getElementById(elems[elem]).value === "") {
+ alert("Please complete every field");
+ return false;
+ }
+ }
+ return true;
+ }
+</script>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
- <form action="" method="get">
+ <form id="application" action="" method="post" target="fake-target" onsubmit="if (formCompleted()) { this.action='http://spreadsheets.google.com/formResponse?formkey=dDJrV05leVRlYUpBS0hTYjZsRy1GcGc6MQ'; showThankYou(); return true; } else { return false; }">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
- <input id="company_name" name="" size="30" type="text" value="" disabled="disabled" />
+ <input id="company_name" name="entry.0.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
- <input id="contact_name" name="" size="30" type="text" value="" disabled="disabled" />
+ <input id="contact_name" name="entry.1.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
- <input id="email" name="" size="30" type="text" value="" disabled="disabled" />
+ <input id="email" name="entry.2.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
- <input id="phone" name="" size="30" type="text" value="" disabled="disabled" />
+ <input id="phone" name="entry.3.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
- <input id="company_website" name="" size="30" type="text" value="" disabled="disabled" />
+ <input id="company_website" name="entry.4.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
- <input id="location" name="" size="30" type="text" value="" disabled="disabled" />
+ <input id="location" name="entry.5.single" size="30" type="text" value="" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Demo<span class="required">*</span></label>
- <input id="pitch_link" name="" size="30" type="text" value="" disabled="disabled" />
- <p>Please record a 30 second clip of your best pitch, and upload to your preferred video hosting site.</p>
+ <input id="pitch_link" name="entry.6.single" size="30" type="text" value="" />
+ <p>Please record a 60 second clip of your best pitch, and upload to your preferred video hosting site.</p>
<div class="clear"></div>
</div>
</div>
- <button type="button">Registration Will Open Next Week</button>
+ <button type="submit" id="submit_button">Submit Application</button>
+ <div style="display:none;" id="form-message"></div>
+
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
+ <iframe id="fake-target" name="fake-target" style="width:0px; height:0px; border:0px;"></iframe>
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 9a5134cba969c40c5099b580e5f78894af66b439 | Fixed visual bugs, disabled form input elements until form is functional | diff --git a/css/styles.css b/css/styles.css
index b6b6425..ac6e813 100644
--- a/css/styles.css
+++ b/css/styles.css
@@ -1,468 +1,473 @@
/* CSS RESET */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
/* remember to highlight inserts somehow! */
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: collapse;
border-spacing: 0;
}
/* tags
----------------------------------------------- */
body {
background-color: #00222e;
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
font-size: 18px;
line-height: 24px;
}
h1, h2, h3, h4, h5, h6 {
font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
text-shadow: 1px 1px 0px #fff;
}
h1 {
}
h2 {
font-size:21px;
font-weight:bold;
}
h3 {
padding-bottom:8px;
font-size:24px;
line-height:24px;
/*font-style:italic;*/
color:#00222e;
text-shadow: 1px 1px 0px #fff;
}
h4 {
padding-bottom:5px;
font-size:21px;
line-height:21px;
}
/*a:link, a:visited, a:focus {
text-decoration: none;
border-bottom: 1px solid #000;
color:#000;
}*/
a:link, a:visited, a:focus {
color:#0066cc;
text-decoration:none;
font-weight:normal;
border:none;
}
a:hover {
color:#0066cc;
color:#00ccff;
border-bottom:1px solid #0066cc;
border:none;
}
/* layout
----------------------------------------------- */
#content {
}
.container_wide {
padding:30px 0 30px 0;
width:100%;
background-color:#e4e4e4;
border-bottom: 1px dashed #666;
border-top: 1px dashed #fff;
}
.container_fixed {
width:960px;
margin: 0 auto 0 auto;
}
/* head
----------------------------------------------- */
#head {
margin:0;
padding: 10px 0 10px 0;
position:fixed;
top:0px;
left:0px;
height: auto;
width: 100%;
background-color:#00222e;
border-bottom: 1px solid black;
z-index: 1000;
}
#logo {
padding: 0 0 0 15px;
position:relative;
float:left;
}
#logo h2 {
font-size:18px;
font-weight:bold;
text-shadow:none;
}
#logo h2 a:link, #logo h2 a:visited, #logo h2 a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#logo h2 a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav {
position:relative;
float:left;
}
#nav a:link, #nav a:visited, #nav a:focus {
text-decoration:none;
color:#fff;
border:none;
}
#nav a:hover {
text-decoration:none;
border-bottom: 1px solid #fff;
}
#nav ul, #social_media ul {
font-size:16px;
}
#nav ul li {
margin:0 0 0 20px;
position:relative;
float:left;
}
#nav .register {
position:relative;
float:right;
}
#social_media {
padding-right:25px;
float:right;
}
#social_media li#twitter {
padding-left:25px;
background: url(../img/icon_twitter.png) no-repeat center left;
}
#social_media a:link, #social_media a:visited, #social_media a:focus {
color:#499ff3;
}
#social_media a:hover {
color:#fff;
}
/* intro
----------------------------------------------- */
#intro {
margin-top:45px;
padding-top:70px;
padding-bottom:60px;
text-align: center;
border:none;
- background-color:#0090f2;
+ background-color:#0461c0;
background-image: url(../img/background_round_wave.png);
background-repeat: no-repeat;
background-position: center center;
}
#intro h1 {
padding:0;
margin:0;
}
/* call-to-action
----------------------------------------------- */
#intro_action {
background-color:#fdfee0;
}
.call_to_action {
margin: 0 10px 0 10px;
font-size:28px;
line-height:28px;
text-align:center;
}
.call_to_action h2 {
padding-bottom:10px;
font-size:36px !important;
line-height:36px;
}
.call_to_action h3 {
padding-bottom:0;
font-size:26px !important;
line-height:26px;
font-weight:normal;
text-transform:none;
}
.call_to_action a:link, .call_to_action a:visited, .call_to_action a:focus {
color:#ff4439;
border-bottom:1px solid #ff4439;
}
.call_to_action a:hover {
color:#499ff3;
border-bottom:1px solid #499ff3;
}
/* summary
----------------------------------------------- */
#summary {
background-color:#fff;
font-size:18px;
line-height:24px;
}
#summary h3 {
font-size:28px;
line-height:28px;
}
#summary h4 {
font-style:italic;
}
#companies, #attendees {
margin:0 10px 0 10px;
position:relative;
float:left;
width:460px;
text-align:center;
}
/* details
----------------------------------------------- */
#details {
border-bottom:none;
padding-bottom:0;
}
#details_text {
border-top:none;
}
#map, #venue, #event_links {
margin:0 10px 0 10px;
width:298px;
position:relative;
float:left;
border:1px solid #aaa;
background-color:#fff;
}
#event_links {
width:300px;
border:none;
background:none;
}
#map {
width:618px;
}
#venue {
}
#map iframe, #venue img {
padding:9px;
}
#event_links ul {
margin-top:5px;
border-top:1px solid #ccc;
border-bottom:1px solid #efefef;
}
#event_links li {
/*padding:8px 0 8px 25px;*/
padding:8px 0 8px 0;
font-size: 18px;
border-bottom: 1px solid #ccc;
border-top:1px solid #efefef;
background-repeat: no-repeat;
background-position: left center;
}
/*li#map_link_car {
background-image: url(../img/icon_car.png);
}
li#map_link_train {
background-image: url(../img/icon_train.png);
}
li#map_link_plane {
background-image: url(../img/icon_plane.png);
}
li#map_link_hotel {
background-image: url(../img/icon_hotel.png);
}
/* faqs
----------------------------------------------- */
.column_headline, .column_text {
position:relative;
float:left;
}
.column_headline {
padding:0 10px 0 10px;
width:300px;
}
.column_text {
padding:0 10px 0 10px;
width:620px;
}
.column_headline h3, .column_text h3 {
font-size:24px;
line-height:24px;
}
/* register
----------------------------------------------- */
#register {
background-color:#fdfee0;
text-align:center;
}
#register h3 {
font-size:28px;
line-height:28px;
padding:30px 0 30px 0;
border:1px solid #666;
background-color:#fff;
}
#register h3 a {
color:#ff4439;
border:none;
}
/* register PAGE
----------------------------------------------- */
#content_register {
margin-top:45px;
}
+
+#content_register #intro_register {
+ border-top:none;
+}
+
#register_form {
background-color:#fff;
border-bottom:none;
}
form {
margin-right:auto;
margin-left:auto;
width: 700px;
}
label {
width: 250px;
padding: 0 10px 0 0;
text-align: right;
position: relative;
float: left;
}
.form_row {
padding:0 0 15px 0;
}
.form_row p {
width:250px;
float:left;
text-align:right;
font-size:12px;
line-height:normal;
}
.form_row span {
padding-left:2px;
color:red;
}
form button {
margin-left:260px;
}
input, textarea {
float:left;
font-size:16px;
}
#terms {
margin-top:30px;
margin-left:260px;
font-size:12px;
line-height:normal;
}
button {
font-size:18px;
padding:10px;
}
/* sponsors
----------------------------------------------- */
#sponsors {
text-align:center;
background-color:#fff;
border:none;
}
#sponsors h3 {
font-size:18px;
}
#sponsors p {
font-size:12px;
}
.sponsor_box {
margin:15px 10px 15px 10px;
position:relative;
float:left;
/*height:125px;*/
width:300px;
text-align:center;/*border:1px dashed #000;*/
}
/* foot
----------------------------------------------- */
#foot {
background-color:#00222e;
padding:30px 0 30px 0;
color:#ccc;
font-size:14px;
text-align:center;
}
a.sig:link, a.sig:visited, a.sig:focus {
color:#ccc;
text-decoration:underline;
}
a.sig:hover {
color:#fff;
}
/* float clearing
----------------------------------------------- */
/* float clearing for IE6 */
* html .clear {
height: 1%;
overflow: visible;
}
/* float clearing for IE7 */
*+html .clear {
min-height: 1%;
}
/* float clearing for everyone else */
.clear:after {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
.clear {
clear: both;
content: ".";
display: block;
height: 0;
visibility: hidden;
}
diff --git a/register.html b/register.html
index ce3c439..671be8b 100644
--- a/register.html
+++ b/register.html
@@ -1,100 +1,100 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tech Crawl East</title>
<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body id="body">
<div id="head">
<div id="logo">
<h2><a href="index.html">« Return to Homepage</a></h2>
</div>
<div id="social_media">
<ul>
<li id="twitter"><a href="http://www.twitter.com/techcrawleast" target="_blank">Follow Us on Twitter</a></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div id="content_register">
<div class="container_wide" id="intro_register">
<div class="container_fixed">
<div>
<div class="call_to_action">
<h2>Presenter Application for Tech Crawl East</h2>
<h3>If your application is approved, the presentation fee will be <strong>$100</strong>.</h3>
</div>
</div>
</div>
</div>
<div class="container_wide" id="register_form">
<div class="container_fixed">
<form action="" method="get">
<div class="form_subgroup">
<div class="form_row">
<label for="company_name">Company Name<span class="required">*</span></label>
- <input id="company_name" name="" size="30" type="text" value="" />
+ <input id="company_name" name="" size="30" type="text" value="" disabled="disabled" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="contact_name">Contact Name<span class="required">*</span></label>
- <input id="contact_name" name="" size="30" type="text" value="" />
+ <input id="contact_name" name="" size="30" type="text" value="" disabled="disabled" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="email">Email<span class="required">*</span></label>
- <input id="email" name="" size="30" type="text" value="" />
+ <input id="email" name="" size="30" type="text" value="" disabled="disabled" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="phone">Phone Number<span class="required">*</span></label>
- <input id="phone" name="" size="30" type="text" value="" />
+ <input id="phone" name="" size="30" type="text" value="" disabled="disabled" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="company_website">Company Website<span class="required">*</span></label>
- <input id="company_website" name="" size="30" type="text" value="" />
+ <input id="company_website" name="" size="30" type="text" value="" disabled="disabled" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="location">Location<span class="required">*</span></label>
- <input id="location" name="" size="30" type="text" value="" />
+ <input id="location" name="" size="30" type="text" value="" disabled="disabled" />
<div class="clear"></div>
</div>
<div class="form_row">
<label for="pitch_link">Link to 60 Second Pitch Demo<span class="required">*</span></label>
- <input id="pitch_link" name="" size="30" type="text" value="" />
+ <input id="pitch_link" name="" size="30" type="text" value="" disabled="disabled" />
<p>Please record a 30 second clip of your best pitch, and upload to your preferred video hosting site.</p>
<div class="clear"></div>
</div>
</div>
<button type="button">Registration Will Open Next Week</button>
<!-- TERMS AND CONDITIONS - UNCOMMENT BELOW OR DELETE IF DESIRED
<div id="terms">
<p>This is a bit of text for disclaimers, implied warranties or lack thereof, etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac eros elit. Vivamus diam elit, suscipit at rhoncus quis, euismod eu dolor. Pellentesque nec ipsum eget nulla gravida accumsan eu at augue. Vestibulum porttitor justo et massa rhoncus vitae tempor dolor tincidunt. Nunc non nunc in diam viverra hendrerit. Nam ac nisl tortor. Praesent quam diam, lacinia et pretium a, adipiscing nec libero.</p>
</div>-->
</form>
<div class="clear"></div>
</div>
</div>
</div>
<div id="foot">
<div class="container_fixed">
<p>All Content © 2010 Tech Crawl East, All Rights Reserved | Site by <a class="sig" href="http://www.craftwork.net" target="_blank">Craftwork</a> | <a href="mailto:[email protected]">Contact us</a></p>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11671914-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>
</body>
</html>
|
jtrupiano/techcrawleast | 12e25733b4362e28430deea84aeaef336639d2be | First build | diff --git a/css/960.css b/css/960.css
new file mode 100755
index 0000000..e210899
--- /dev/null
+++ b/css/960.css
@@ -0,0 +1,387 @@
+.container_12, .container_16 {
+ margin-left:auto;
+ margin-right:auto;
+ width:960px
+}
+.grid_1, .grid_2, .grid_3, .grid_4, .grid_5, .grid_6, .grid_7, .grid_8, .grid_9, .grid_10, .grid_11, .grid_12, .grid_13, .grid_14, .grid_15, .grid_16 {
+ display:inline;
+ float:left;
+ position:relative;
+ margin-left:10px;
+ margin-right:10px
+}
+.container_12 .grid_3, .container_16 .grid_4 {
+ width:220px
+}
+.container_12 .grid_6, .container_16 .grid_8 {
+ width:460px
+}
+.container_12 .grid_9, .container_16 .grid_12 {
+ width:700px
+}
+.container_12 .grid_12, .container_16 .grid_16 {
+ width:940px
+}
+.alpha {
+ margin-left:0
+}
+.omega {
+ margin-right:0
+}
+.container_12 .grid_1 {
+ width:60px
+}
+.container_12 .grid_2 {
+ width:140px
+}
+.container_12 .grid_4 {
+ width:300px
+}
+.container_12 .grid_5 {
+ width:380px
+}
+.container_12 .grid_7 {
+ width:540px
+}
+.container_12 .grid_8 {
+ width:620px
+}
+.container_12 .grid_10 {
+ width:780px
+}
+.container_12 .grid_11 {
+ width:860px
+}
+.container_16 .grid_1 {
+ width:40px
+}
+.container_16 .grid_2 {
+ width:100px
+}
+.container_16 .grid_3 {
+ width:160px
+}
+.container_16 .grid_5 {
+ width:280px
+}
+.container_16 .grid_6 {
+ width:340px
+}
+.container_16 .grid_7 {
+ width:400px
+}
+.container_16 .grid_9 {
+ width:520px
+}
+.container_16 .grid_10 {
+ width:580px
+}
+.container_16 .grid_11 {
+ width:640px
+}
+.container_16 .grid_13 {
+ width:760px
+}
+.container_16 .grid_14 {
+ width:820px
+}
+.container_16 .grid_15 {
+ width:880px
+}
+.container_12 .prefix_3, .container_16 .prefix_4 {
+ padding-left:240px
+}
+.container_12 .prefix_6, .container_16 .prefix_8 {
+ padding-left:480px
+}
+.container_12 .prefix_9, .container_16 .prefix_12 {
+ padding-left:720px
+}
+.container_12 .prefix_1 {
+ padding-left:80px
+}
+.container_12 .prefix_2 {
+ padding-left:160px
+}
+.container_12 .prefix_4 {
+ padding-left:320px
+}
+.container_12 .prefix_5 {
+ padding-left:400px
+}
+.container_12 .prefix_7 {
+ padding-left:560px
+}
+.container_12 .prefix_8 {
+ padding-left:640px
+}
+.container_12 .prefix_10 {
+ padding-left:800px
+}
+.container_12 .prefix_11 {
+ padding-left:880px
+}
+.container_16 .prefix_1 {
+ padding-left:60px
+}
+.container_16 .prefix_2 {
+ padding-left:120px
+}
+.container_16 .prefix_3 {
+ padding-left:180px
+}
+.container_16 .prefix_5 {
+ padding-left:300px
+}
+.container_16 .prefix_6 {
+ padding-left:360px
+}
+.container_16 .prefix_7 {
+ padding-left:420px
+}
+.container_16 .prefix_9 {
+ padding-left:540px
+}
+.container_16 .prefix_10 {
+ padding-left:600px
+}
+.container_16 .prefix_11 {
+ padding-left:660px
+}
+.container_16 .prefix_13 {
+ padding-left:780px
+}
+.container_16 .prefix_14 {
+ padding-left:840px
+}
+.container_16 .prefix_15 {
+ padding-left:900px
+}
+.container_12 .suffix_3, .container_16 .suffix_4 {
+ padding-right:240px
+}
+.container_12 .suffix_6, .container_16 .suffix_8 {
+ padding-right:480px
+}
+.container_12 .suffix_9, .container_16 .suffix_12 {
+ padding-right:720px
+}
+.container_12 .suffix_1 {
+ padding-right:80px
+}
+.container_12 .suffix_2 {
+ padding-right:160px
+}
+.container_12 .suffix_4 {
+ padding-right:320px
+}
+.container_12 .suffix_5 {
+ padding-right:400px
+}
+.container_12 .suffix_7 {
+ padding-right:560px
+}
+.container_12 .suffix_8 {
+ padding-right:640px
+}
+.container_12 .suffix_10 {
+ padding-right:800px
+}
+.container_12 .suffix_11 {
+ padding-right:880px
+}
+.container_16 .suffix_1 {
+ padding-right:60px
+}
+.container_16 .suffix_2 {
+ padding-right:120px
+}
+.container_16 .suffix_3 {
+ padding-right:180px
+}
+.container_16 .suffix_5 {
+ padding-right:300px
+}
+.container_16 .suffix_6 {
+ padding-right:360px
+}
+.container_16 .suffix_7 {
+ padding-right:420px
+}
+.container_16 .suffix_9 {
+ padding-right:540px
+}
+.container_16 .suffix_10 {
+ padding-right:600px
+}
+.container_16 .suffix_11 {
+ padding-right:660px
+}
+.container_16 .suffix_13 {
+ padding-right:780px
+}
+.container_16 .suffix_14 {
+ padding-right:840px
+}
+.container_16 .suffix_15 {
+ padding-right:900px
+}
+.container_12 .push_3, .container_16 .push_4 {
+ left:240px
+}
+.container_12 .push_6, .container_16 .push_8 {
+ left:480px
+}
+.container_12 .push_9, .container_16 .push_12 {
+ left:720px
+}
+.container_12 .push_1 {
+ left:80px
+}
+.container_12 .push_2 {
+ left:160px
+}
+.container_12 .push_4 {
+ left:320px
+}
+.container_12 .push_5 {
+ left:400px
+}
+.container_12 .push_7 {
+ left:560px
+}
+.container_12 .push_8 {
+ left:640px
+}
+.container_12 .push_10 {
+ left:800px
+}
+.container_12 .push_11 {
+ left:880px
+}
+.container_16 .push_1 {
+ left:60px
+}
+.container_16 .push_2 {
+ left:120px
+}
+.container_16 .push_3 {
+ left:180px
+}
+.container_16 .push_5 {
+ left:300px
+}
+.container_16 .push_6 {
+ left:360px
+}
+.container_16 .push_7 {
+ left:420px
+}
+.container_16 .push_9 {
+ left:540px
+}
+.container_16 .push_10 {
+ left:600px
+}
+.container_16 .push_11 {
+ left:660px
+}
+.container_16 .push_13 {
+ left:780px
+}
+.container_16 .push_14 {
+ left:840px
+}
+.container_16 .push_15 {
+ left:900px
+}
+.container_12 .pull_3, .container_16 .pull_4 {
+ left:-240px
+}
+.container_12 .pull_6, .container_16 .pull_8 {
+ left:-480px
+}
+.container_12 .pull_9, .container_16 .pull_12 {
+ left:-720px
+}
+.container_12 .pull_1 {
+ left:-80px
+}
+.container_12 .pull_2 {
+ left:-160px
+}
+.container_12 .pull_4 {
+ left:-320px
+}
+.container_12 .pull_5 {
+ left:-400px
+}
+.container_12 .pull_7 {
+ left:-560px
+}
+.container_12 .pull_8 {
+ left:-640px
+}
+.container_12 .pull_10 {
+ left:-800px
+}
+.container_12 .pull_11 {
+ left:-880px
+}
+.container_16 .pull_1 {
+ left:-60px
+}
+.container_16 .pull_2 {
+ left:-120px
+}
+.container_16 .pull_3 {
+ left:-180px
+}
+.container_16 .pull_5 {
+ left:-300px
+}
+.container_16 .pull_6 {
+ left:-360px
+}
+.container_16 .pull_7 {
+ left:-420px
+}
+.container_16 .pull_9 {
+ left:-540px
+}
+.container_16 .pull_10 {
+ left:-600px
+}
+.container_16 .pull_11 {
+ left:-660px
+}
+.container_16 .pull_13 {
+ left:-780px
+}
+.container_16 .pull_14 {
+ left:-840px
+}
+.container_16 .pull_15 {
+ left:-900px
+}
+.clear {
+ clear:both;
+ display:block;
+ overflow:hidden;
+ visibility:hidden;
+ width:0;
+ height:0
+}
+.clearfix:after {
+ clear:both;
+ content:' ';
+ display:block;
+ font-size:0;
+ line-height:0;
+ visibility:hidden;
+ width:0;
+ height:0
+}
+* html .clearfix, *:first-child+html .clearfix {
+ zoom:1
+}
diff --git a/css/reset.css b/css/reset.css
new file mode 100755
index 0000000..99a0211
--- /dev/null
+++ b/css/reset.css
@@ -0,0 +1 @@
+html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:'';content:none}:focus{outline:0}ins{text-decoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0}
\ No newline at end of file
diff --git a/css/styles.css b/css/styles.css
new file mode 100644
index 0000000..ad7788a
--- /dev/null
+++ b/css/styles.css
@@ -0,0 +1,443 @@
+@charset "UTF-8";
+body {
+}
+/* RESET */
+
+/* v1.0 | 20080212 */
+
+html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ font-size: 100%;
+ vertical-align: baseline;
+ background: transparent;
+}
+body {
+ line-height: 1;
+}
+ol, ul {
+ list-style: none;
+}
+blockquote, q {
+ quotes: none;
+}
+blockquote:before, blockquote:after, q:before, q:after {
+ content: '';
+ content: none;
+}
+/* remember to define focus styles! */
+:focus {
+ outline: 0;
+}
+/* remember to highlight inserts somehow! */
+ins {
+ text-decoration: none;
+}
+del {
+ text-decoration: line-through;
+}
+/* tables still need 'cellspacing="0"' in the markup */
+table {
+ border-collapse: collapse;
+ border-spacing: 0;
+}
+/* tags
+----------------------------------------------- */
+
+body {
+ background-color: #fff;
+ font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
+ font-size: 18px;
+ line-height: 24px;
+}
+h1, h2, h3, h4, h5, h6 {
+ font-family: "ff-dagny-web-pro-1", "ff-dagny-web-pro-2", sans-serif;
+
+ text-shadow: 1px 1px 0px #fff;
+}
+h1 {
+}
+h2 {
+ font-size:21px;
+ font-weight:bold;
+}
+h3 {
+ padding-bottom:8px;
+ font-size:24px;
+ line-height:24px;
+ /*font-style:italic;*/
+ color:#00222e;
+ text-shadow: 1px 1px 0px #fff;
+}
+h4 {
+ padding-bottom:5px;
+ font-size:21px;
+ line-height:21px;
+}
+/*a:link, a:visited, a:focus {
+ text-decoration: none;
+ border-bottom: 1px solid #000;
+ color:#000;
+}*/
+
+a:link, a:visited, a:focus {
+ color:#0066cc;
+ text-decoration:none;
+ font-weight:normal;
+ border:none;
+}
+a:hover {
+ color:#0066cc;
+ color:#00ccff;
+ border-bottom:1px solid #0066cc;
+ border:none;
+}
+/* layout
+----------------------------------------------- */
+#content {
+}
+.container_wide {
+ padding:30px 0 30px 0;
+ width:100%;
+ background-color:#efefef;
+ border-bottom: 1px solid #ccc;
+ border-top: 1px solid #fff;
+}
+.container_fixed {
+ width:960px;
+ margin: 0 auto 0 auto;
+}
+/* head
+----------------------------------------------- */
+
+#head {
+ margin:0;
+ padding: 10px 0 10px 0;
+ position:fixed;
+ top:0px;
+ left:0px;
+ height: auto;
+ width: 100%;
+ background-color:#00222e;
+ border-bottom: 1px solid #444;
+ z-index: 1000;
+}
+#logo {
+ padding: 0 0 0 15px;
+ position:relative;
+ float:left;
+}
+#logo h2 {
+ font-size:18px;
+ font-weight:bold;
+ text-shadow:none;
+}
+#logo h2 a:link, #logo h2 a:visited, #logo h2 a:focus {
+ text-decoration:none;
+ color:#fff;
+ border:none;
+}
+#logo h2 a:hover {
+ text-decoration:none;
+ border-bottom: 1px solid #fff;
+}
+#nav {
+ position:relative;
+ float:left;
+}
+#nav a:link, #nav a:visited, #nav a:focus {
+ text-decoration:none;
+ color:#fff;
+ border:none;
+}
+#nav a:hover {
+ text-decoration:none;
+ border-bottom: 1px solid #fff;
+}
+#nav ul {
+ font-size:16px;
+}
+#nav ul li {
+ margin:0 0 0 20px;
+ position:relative;
+ float:left;
+}
+#nav .register {
+ position:relative;
+ float:right;
+}
+/* intro
+----------------------------------------------- */
+
+#intro {
+ padding-top:45px;
+ padding-bottom:45px;
+ /*height:400px;*/
+ text-align: center;
+ border:none;
+ background-color:#00222e;
+ background-color:#3399ff;
+ background-color:#0461c0;
+ /*background-image: url(../img/background_techcrawleast_illustration_2.png);
+ background-repeat: no-repeat;
+ background-position: center center;*/
+}
+
+#intro h1 {
+ padding:30px 0 0 0;
+ margin:15px 10px 0 10px;
+ font-size: 120px !important;
+ line-height: 90px;
+ font-weight:normal;
+ text-transform:uppercase;
+ color:#fff;
+}
+
+/* call-to-action
+----------------------------------------------- */
+
+#intro_register {
+ background-color:#fff;
+}
+
+.call_to_action {
+ margin: 0 10px 0 10px;
+ font-size:28px;
+ line-height:28px;
+ /*padding:15px 0 15px 0;*/
+ /*border:1px solid #ccc;
+ background-color:#fff;*/
+ text-align:center;
+
+ /*-moz-border-radius-topleft: 15px;
+ -moz-border-radius-topright: 15px;
+ -moz-border-radius-bottomleft: 15px;
+ -moz-border-radius-bottomright: 15px;
+ border-top-left-radius: 15px;
+ border-top-right-radius: 15px;
+ border-bottom-left-radius: 15px;
+ border-bottom-right-radius: 15px;
+ -webkit-border-top-left-radius: 15px;
+ -webkit-border-top-right-radius: 15px;
+ -webkit-border-bottom-left-radius: 15px;
+ -webkit-border-bottom-right-radius: 15px;*/
+}
+.call_to_action h2 {
+ padding-top:10px;
+ padding-bottom:10px;
+ font-size:34px !important;
+ /*font-family: "facitweb-1","facitweb-2",sans-serif;*/
+ line-height:34px;
+ /*color:#0461c0;
+ border-bottom:2px solid #fff;*/
+}
+
+.call_to_action a {
+ color:#ff4439;
+ border:none;
+}
+
+.call_to_action h3 {
+ font-size:26px !important;
+ line-height:26px;
+ font-weight:normal;
+ text-transform:none;
+}
+
+/* summary
+----------------------------------------------- */
+
+#summary {
+ /*background-color:#fff;*/
+ font-size:18px;
+ line-height:24px;
+}
+
+#summary h3 {
+ font-size:28px;
+ line-height:28px;
+ /*text-transform:uppercase;*/
+}
+
+#companies, #attendees {
+ margin:0 10px 0 10px;
+ position:relative;
+ float:left;
+ width:460px;
+ text-align:center;
+}
+
+
+/* details
+----------------------------------------------- */
+
+#details {
+ border-bottom:none;
+ padding-bottom:0;
+}
+
+#details_text {
+ border-top:none;
+}
+
+#map, #venue, #event_links {
+ margin:0 10px 0 10px;
+ width:298px;
+ position:relative;
+ float:left;
+ border:1px solid #ccc;
+ background-color:#fff;
+}
+
+#event_links {
+ width:300px;
+ border:none;
+ background:none;
+}
+#map {
+ width:596px;
+}
+
+#map iframe, #venue img {
+ padding:10px;
+}
+
+#event_links ul {
+ /*margin-top:20px;*/
+ margin-top:5px;
+ border-top:1px solid #ccc;
+ border-bottom:1px solid #fff;
+}
+#event_links li {
+ /*padding:8px 0 8px 25px;*/
+ padding:8px 0 8px 0;
+ font-size: 18px;
+ border-bottom: 1px solid #ccc;
+ border-top:1px solid #fff;
+ background-repeat: no-repeat;
+ background-position: left center;
+}
+/*
+li#map_link_car {
+ background-image: url(../img/icon_car.png);
+}
+
+li#map_link_train {
+ background-image: url(../img/icon_train.png);
+}
+
+li#map_link_plane {
+ background-image: url(../img/icon_plane.png);
+}
+
+li#map_link_hotel {
+ background-image: url(../img/icon_hotel.png);
+}
+
+*/
+/* faqs
+----------------------------------------------- */
+
+.column_headline, .column_text {
+ position:relative;
+ float:left;
+}
+.column_headline {
+ padding:0 10px 0 10px;
+ width:300px;
+}
+.column_text {
+ padding:0 10px 0 10px;
+ width:620px;
+}
+.column_headline h3, .column_text h3 {
+ font-size:24px;
+ line-height:24px;
+}
+
+/* register
+----------------------------------------------- */
+
+#register {
+ text-align:center;
+
+}
+
+#register h3 {
+ font-size:28px;
+ line-height:28px;
+ padding:30px 0 30px 0;
+ border:1px solid #666;
+ background-color:#fff;
+}
+
+#register h3 a {
+ color:#ff4439;
+ border:none;
+}
+
+/* sponsors
+----------------------------------------------- */
+
+#sponsors {
+ text-align:center;
+ background-color:#fff;
+}
+
+#sponsors h3 {
+ font-size:18px;
+}
+
+#sponsors p {
+ font-size:12px;
+}
+.sponsor_box {
+ margin:15px 10px 15px 10px;
+ position:relative;
+ float:left;
+ height:125px;
+ width:300px;
+ text-align:center;
+ /*border:1px dashed #000;*/
+}
+
+/* foot
+----------------------------------------------- */
+#foot {
+ background-color:#333;
+ padding:30px 0 30px 0;
+ color:#ccc;
+ font-size:14px;
+ text-align:center;
+}
+/* classes
+----------------------------------------------- */
+
+
+/* float clearing for IE6 */
+* html .clear {
+ height: 1%;
+ overflow: visible;
+}
+/* float clearing for IE7 */
+*+html .clear {
+ min-height: 1%;
+}
+/* float clearing for everyone else */
+.clear:after {
+ clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ visibility: hidden;
+}
+
+.clear {
+ clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ visibility: hidden;
+}
diff --git a/img/background_blue_gradient.jpg b/img/background_blue_gradient.jpg
new file mode 100644
index 0000000..991d258
Binary files /dev/null and b/img/background_blue_gradient.jpg differ
diff --git a/img/background_round_wave.png b/img/background_round_wave.png
new file mode 100644
index 0000000..056fa6d
Binary files /dev/null and b/img/background_round_wave.png differ
diff --git a/img/background_square_wave.png b/img/background_square_wave.png
new file mode 100644
index 0000000..b129f56
Binary files /dev/null and b/img/background_square_wave.png differ
diff --git a/img/background_techcrawleast_illustration.png b/img/background_techcrawleast_illustration.png
new file mode 100644
index 0000000..db4d801
Binary files /dev/null and b/img/background_techcrawleast_illustration.png differ
diff --git a/img/background_techcrawleast_illustration_2.png b/img/background_techcrawleast_illustration_2.png
new file mode 100644
index 0000000..c8d5dbd
Binary files /dev/null and b/img/background_techcrawleast_illustration_2.png differ
diff --git a/img/border_digital_boxes.png b/img/border_digital_boxes.png
new file mode 100644
index 0000000..946bf9c
Binary files /dev/null and b/img/border_digital_boxes.png differ
diff --git a/img/border_intro.png b/img/border_intro.png
new file mode 100644
index 0000000..b61f927
Binary files /dev/null and b/img/border_intro.png differ
diff --git a/img/border_triangle.png b/img/border_triangle.png
new file mode 100644
index 0000000..2bac6b8
Binary files /dev/null and b/img/border_triangle.png differ
diff --git a/img/icon_car.png b/img/icon_car.png
new file mode 100644
index 0000000..2f00295
Binary files /dev/null and b/img/icon_car.png differ
diff --git a/img/icon_hotel.png b/img/icon_hotel.png
new file mode 100644
index 0000000..478f66f
Binary files /dev/null and b/img/icon_hotel.png differ
diff --git a/img/icon_plane.png b/img/icon_plane.png
new file mode 100644
index 0000000..b4b9eb4
Binary files /dev/null and b/img/icon_plane.png differ
diff --git a/img/icon_train.png b/img/icon_train.png
new file mode 100644
index 0000000..a3376d2
Binary files /dev/null and b/img/icon_train.png differ
diff --git a/img/img_morgan_stanley_building.jpg b/img/img_morgan_stanley_building.jpg
new file mode 100644
index 0000000..5336df7
Binary files /dev/null and b/img/img_morgan_stanley_building.jpg differ
diff --git a/img/img_sponsor_etc-logo.jpg b/img/img_sponsor_etc-logo.jpg
new file mode 100644
index 0000000..e88e1b7
Binary files /dev/null and b/img/img_sponsor_etc-logo.jpg differ
diff --git a/img/img_sponsors_stand_in.png b/img/img_sponsors_stand_in.png
new file mode 100644
index 0000000..bb7a7a6
Binary files /dev/null and b/img/img_sponsors_stand_in.png differ
diff --git a/img/text_event_details.png b/img/text_event_details.png
new file mode 100644
index 0000000..fd17631
Binary files /dev/null and b/img/text_event_details.png differ
diff --git a/img/text_tech_crawl_east.png b/img/text_tech_crawl_east.png
new file mode 100644
index 0000000..e089a83
Binary files /dev/null and b/img/text_tech_crawl_east.png differ
diff --git a/img/text_tech_crawl_east_wave.png b/img/text_tech_crawl_east_wave.png
new file mode 100644
index 0000000..90465d9
Binary files /dev/null and b/img/text_tech_crawl_east_wave.png differ
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..9b3241d
--- /dev/null
+++ b/index.html
@@ -0,0 +1,146 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Tech Crawl East</title>
+<script type="text/javascript" src="http://use.typekit.com/loz4jeq.js"></script>
+<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
+<script type="text/javascript" src="js/jquery.js"></script>
+<script type="text/javascript">function goToByScroll(id){$('html,body').animate({scrollTop: $("#"+id).offset().top-45},'slow');}</script>
+<link href="css/styles.css" rel="stylesheet" type="text/css" />
+</head>
+<body id="body">
+<div id="head">
+ <div id="logo">
+ <h2><a href="javascript:void(0)" onclick="goToByScroll('body')">Tech Crawl East</a></h2>
+ </div>
+ <div id="nav">
+ <ul>
+ <li><a href="javascript:void(0)" onclick="goToByScroll('summary')">Introduction</a></li>
+ <li><a href="javascript:void(0)" onclick="goToByScroll('details')">Details</a></li>
+ <li><a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register</a></li>
+ </ul>
+ </div>
+ <div class="clear"></div>
+</div>
+<div id="content">
+ <div class="container_wide" id="intro">
+ <div class="container_fixed">
+ <div>
+ <h1><img src="./img/text_tech_crawl_east.png" alt="Tech Crawl East" /></h1>
+ <!--<h1>Tech Crawl East</h1>-->
+ </div>
+ </div>
+ </div>
+ <div class="container_wide" id="intro_register">
+ <div class="container_fixed">
+ <div>
+ <div class="call_to_action">
+ <h2>One Night, One Place, Top East-Coast Tech Companies</h2>
+ <h3>Thursday, September 16th, Baltimore, Maryland | <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register Now »</a></h3>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="container_wide" id="summary">
+ <div class="container_fixed">
+ <div id="companies">
+ <h3>Companies</h3>
+ <h4>Pitch in 60 Seconds to Investors and Peers</h4>
+ <p>Jump-start your fall networking activities by pitching to a few hundred people in one place in one night. Leave with the investor, partner and media contacts that your company needs. <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register for only $100 »</a></p>
+ </div>
+ <div id="attendees">
+ <h3>Attendees</h3>
+ <h4>See Who's Hot on the East Coast</h4>
+ <p>In one night, hear over 40 pitches from East Coast Tech companies. Itâs the easiest way to stay tuned into which tech companies are developing new and exciting products. <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register for free »</a></p>
+ </div>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide" id="details">
+ <div class="container_fixed">
+ <div id="venue"><img src="./img/img_morgan_stanley_building.jpg" alt="morgan stanley building" /> </div>
+ <div id="map">
+ <iframe width="575" height="185" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=901+South+Bond+Street+21231&sll=39.340823,-76.664099&sspn=0.236048,0.497475&ie=UTF8&hq=&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&ll=39.280691,-76.594355&spn=0.007383,0.015546&z=14&iwloc=near&output=embed"></iframe>
+ </div>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide" id="details_text">
+ <div class="container_fixed">
+ <div id="event_links">
+ <h3>Event Details</h3>
+ <!--<img src="./img/text_event_details.png" alt="Event Details" />-->
+ <ul>
+ <li id="map_link_car"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=Morgan+Stanley+Smith+Barney,+901+S+Bond+St+&ie=UTF8&hq=Morgan+Stanley+Smith+Barney,&hnear=901+S+Bond+St,+Baltimore,+Maryland+21231&z=16&iwloc=A" target="_blank">Get Driving Directions</a></li>
+ <!--<li><a href="#">Find Nearest Bus Routes</a></li>-->
+ <li id="map_link_train"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=penn+station+baltimore&sll=39.262031,-76.57093&sspn=0.097025,0.164967&dirflg=r&ttype=dep&date=07%2F23%2F10&time=12:16pm&noexp=0&noal=0&sort=time&ie=UTF8&hq=penn+station&hnear=Baltimore,+Maryland&ll=39.317035,-76.626892&spn=0.093628,0.164967&z=13&iwloc=A&start=0" target="_blank">Find Nearest Train Stations</a></li>
+ <li id="map_link_plane"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=bwi+airport&sll=39.218157,-76.625862&sspn=0.187521,0.329933&ie=UTF8&hq=&hnear=BWI+airport,+Baltimore,+Anne+Arundel,+Maryland+21240&ll=39.244485,-76.604576&spn=0.194098,0.329933&z=12&iwloc=A" target="_blank">Find Nearest Airport</a></li>
+ <li id="map_link_hotel"><a href="http://www.google.com/maps?f=q&source=s_q&hl=en&q=hotel&sll=39.282231,-76.592131&sspn=0.024249,0.041242&ie=UTF8&radius=1.32&split=1&rq=1&ev=zo&hq=hotel&hnear=&ll=39.286616,-76.599126&spn=0.023417,0.041242&z=15" target="_blank">Find a Hotel Near Fell's Point</a></li>
+ </ul>
+ </div>
+ <div class="column_text">
+ <p>Tech Crawl East will be held on the evening of September 16th, from 5-9PM, on the first floor of the new Morgan Stanley building in Fells Point, overlooking Baltimore Harbor. This event is the result of 2009's highly successful MD Tech Crawl (<a href="http://www.mdtechcrawl.com" target="_blank">mdtechcrawl.com</a>), where over 20 local early stage tech companies presented 60 second pitches to close to 200 attendees. Investors, media and members of the technology community offered rave reviews of the innovative 60 second pitch model, that allowed attendees to learn about all of the companies present in just a few hours. This year we aim to more than double the number of businesses present as well as attendees.</p>
+ </div>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <div class="column_headline">
+ <h3>What is a Tech Crawl?</h3>
+ </div>
+ <div class="column_text">
+ <p>A Tech Crawl is a one-evening event that brings together innovative early stage technology companies from across the East Coast. The primary goal of a Tech Crawl is to support the growth of technology companies by providing an opportunity for them to give 60 second pitches to investors, media and other technology businesses. This is intended as an annual event where, year after year, companies will return with new and exiting products and services to demo. </p>
+ </div>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide">
+ <div class="container_fixed">
+ <div class="column_headline">
+ <h3>Why the 60 Second Pitch?</h3>
+ </div>
+ <div class="column_text">
+ <p>The 60 second pitch is required of all companies attending Tech Crawl East. It is an effective way for entrepreneurs to quickly communicate their business model to hundreds of investors, media and other technologists in one evening. Investors benefit from the opportunity to hear a 60 second pitch as it allows them the opportunity to meet with all of the presenting tech companies at the event.</p>
+ </div>
+ <div class="clear"></div>
+ </div>
+ </div>
+ <div class="container_wide" id="register">
+ <div class="container_fixed">
+ <div>
+ <h3>Only $100 for Companies, and FREE for Attendees | <a href="http://techcrawleast10.eventbrite.com/" target="_blank">Register »</a></h3>
+ </div>
+ </div>
+ </div>
+ <div class="container_wide" id="sponsors">
+ <div class="container_fixed">
+ <div>
+ <h3>Please Support Our Sponsors</h3>
+ <div class="sponsor_box"><img src="./img/img_sponsor_etc-logo.jpg" alt="ETC" /></div>
+ <div class="sponsor_box"> </div>
+ <div class="sponsor_box"> </div>
+ <div class="clear"></div>
+ <p><a href="mailto:[email protected]">Become a sponsor »</a></p>
+ </div>
+ </div>
+ </div>
+</div>
+<div id="foot">
+ <div class="container_fixed">
+ <p>All Content © 2010 Tech Crawl East, All Rights Reserved | <a href="mailto:[email protected]">Contact us</a></p>
+ </div>
+</div>
+<script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-11671914-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>
+</body>
+</html>
diff --git a/js/jquery.js b/js/jquery.js
new file mode 100644
index 0000000..48a88b8
--- /dev/null
+++ b/js/jquery.js
@@ -0,0 +1,154 @@
+/*!
+ * jQuery JavaScript Library v1.4.2
+ * http://jquery.com/
+ *
+ * Copyright 2010, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2010, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Sat Feb 13 22:33:48 2010 -0500
+ */
+(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
+e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
+j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
+"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
+true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
+Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
+(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
+a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
+"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
+function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
+c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
+L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
+"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
+d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
+a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
+!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
+true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
+var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
+parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
+false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
+s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
+applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
+else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
+a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
+w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
+cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
+i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
+" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
+this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
+e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
+c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
+a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
+function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
+k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
+C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
+null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
+e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
+f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
+if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
+d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
+"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
+a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
+isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
+{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
+if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
+e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
+"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
+d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
+!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
+toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
+u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
+function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
+if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
+t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
+g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
+for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
+1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
+CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
+relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
+l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
+h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
+CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
+g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
+text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
+setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
+h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
+m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
+"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
+h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
+!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
+h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
+q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
+if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
+(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
+function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
+gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
+c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
+{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
+"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
+d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
+a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
+1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
+a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
+c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
+wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
+prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
+this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
+return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
+""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
+this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
+u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
+1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
+return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
+""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
+c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
+c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
+function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
+Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
+"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
+a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
+a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
+"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
+serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
+function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
+global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
+e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
+"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
+false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
+false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
+c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
+d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
+g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
+1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
+"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
+if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
+this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
+"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
+animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
+j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
+this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
+"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
+c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
+this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
+this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
+e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
+c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
+function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
+this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
+k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
+f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
+a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
+c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
+d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
+f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
+"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
+e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
\ No newline at end of file
|
synewaves/starlight | c7573bb1041b6e1a7b8a4fd2c5ba6b9a77afd22e | Adding namespaces for controllers in router, better handling of endpoint parameters | diff --git a/src/Starlight/Component/Dispatcher/HttpDispatcher.php b/src/Starlight/Component/Dispatcher/HttpDispatcher.php
index 6f8013c..411da10 100755
--- a/src/Starlight/Component/Dispatcher/HttpDispatcher.php
+++ b/src/Starlight/Component/Dispatcher/HttpDispatcher.php
@@ -1,71 +1,102 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Starlight\Component\Dispatcher;
use Starlight\Component\Dispatcher\Context\HttpContext;
use Starlight\Component\Routing\Router;
/**
* HTTP Dispatcher
*/
class HttpDispatcher extends Dispatcher
{
protected $router;
public function __construct(HttpContext $context, Router $router)
{
$this->context = $context;
$this->router = $router;
}
public function getContext()
{
return $this->context;
}
public function setContext(HttpContext $context)
{
$this->context = $context;
return $this;
}
public function getRouter()
{
return $this->router;
}
public function setRouter(Router $router)
{
$this->router = $router;
return $this;
}
public function dispatch()
{
$route = $this->router->match($this->context->getRequest());
if ($route) {
$params = array_filter($route->parameters, function($var){ return trim($var) != ''; });
unset($params['controller'], $params['action']);
if (is_callable($route->endpoint)) {
+ // lambda/closure
+ $params = array_merge($this->determineParameters($route->endpoint), $params);
call_user_func_array($route->endpoint, array_merge(array($this->context->getRequest()), array_values($params)));
return true;
} else {
// controller pattern
+ $controller = $route->parameters['controller'];
+ $action = $route->parameters['action'];
+ $params = array_merge($this->determineParameters(array($controller, $action)), $params);
+
+ $klass = new $controller();
+ call_user_func_array(array($klass, $action), array_values($params));
+ return true;
}
}
return false;
}
+
+ protected function determineParameters($method)
+ {
+ $klass = null;
+ if (is_array($method)) {
+ $klass = $method[0];
+ $method = $method[1];
+ }
+
+ $ref = !$klass ? new \ReflectionFunction($method) : new \ReflectionMethod($klass, $method);
+ $params = array();
+ foreach ($ref->getParameters() as $i => $param) {
+ if (!$klass && $i==0) { continue; }
+ if ($param->isOptional()) {
+ $params[$param->getName()] = $param->getDefaultValue();
+ } else {
+ $params[$param->getName()] = null;
+ }
+ }
+
+ return $params;
+ }
}
\ No newline at end of file
diff --git a/src/Starlight/Component/Routing/ResourceRoute.php b/src/Starlight/Component/Routing/ResourceRoute.php
index 92c0bd6..35e63c9 100755
--- a/src/Starlight/Component/Routing/ResourceRoute.php
+++ b/src/Starlight/Component/Routing/ResourceRoute.php
@@ -1,327 +1,327 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Inflector\Inflector;
/**
* ResourceRoute
*/
class ResourceRoute implements CompilableInterface
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%p', 'verb' => 'get', 'url' => '(.:format)'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'create' => array('name' => '%p', 'verb' => 'post', 'url' => '(.:format)'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id(.:format)'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action(.:format)'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id(.:format)'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id(.:format)'),
);
/**
* Default path names
* @var array
*/
protected static $resource_names = array(
'add' => 'add',
'edit' => 'edit',
'delete' => 'delete',
);
public $resource;
public $controller;
public $except;
public $only;
public $constraints;
public $singular;
public $plural;
public $path_names;
public $module;
public $path_prefix;
public $name_prefix;
public $member = array();
public $collection = array();
public $map_member_collection_scope = null;
/**
* Constructor
* @param string $resource resource name
* @param array $options options hash
*/
public function __construct($resource = null, array $options = array())
{
if ($resource !== null) {
$this->resource = $resource;
- $this->controller = $this->plural = Inflector::pluralize($this->resource);
- $this->singular = Inflector::singularize($this->controller);
+ $this->plural = Inflector::pluralize($this->resource);
+ $this->singular = Inflector::singularize($this->resource);
+ $this->controller = Inflector::camelize($this->plural . '_controller');
if (count($options) > 0) {
foreach ($options as $key => $value) {
$this->$key($value);
}
}
}
}
/**
* Set except routes from $resources_map
* @param array $except except resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function except(array $except)
{
$this->only = null;
$this->except = $except;
return $this;
}
/**
* Set only routes from $resources_map
* @param array $only only resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function only(array $only)
{
$this->except = null;
$this->only = $only;
return $this;
}
/**
* Set controller
* @param string $controller controller name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function controller($controller)
{
$this->controller = $controller;
return $this;
}
/**
* Set contraints
* @param mixed $constraints constraints
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set name for route paths
* @param string $name path name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function name($name)
{
$single = explode(' ', strtolower(Inflector::humanize($name)));
$plural = $single;
$count = count($single);
$single[$count - 1] = Inflector::singularize($single[$count - 1]);
$plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
$this->singular = implode('_', $single);
$this->plural = implode('_', $plural);
return $this;
}
/**
* Set path names for special routes
* @param array $names path name overrides
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function pathNames(array $names)
{
$this->path_names = $names;
return $this;
}
/**
* Set module/namespace for resource
* @param string $module module/namespace name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Set member routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function member(\Closure $callback)
{
$this->map_member_collection_scope = 'member';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set collection routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function collection(\Closure $callback)
{
$this->map_member_collection_scope = 'collection';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set an extra route which responds to GET requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function get($path, $options = array())
{
return $this->mapMethod('get', $path, $options);
}
/**
* Set an extra route which responds to PUT requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function put($path, $options = array())
{
return $this->mapMethod('put', $path, $options);
}
/**
* Set an extra route which responds to POST requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function post($path, $options = array())
{
return $this->mapMethod('post', $path, $options);
}
/**
* Set an extra route which responds to DELETE requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function delete($path, $options = array())
{
return $this->mapMethod('delete', $path, $options);
}
/**
* Map extra routes through a common interface
* @param string $method HTTP method
* @param string $path path
* @param array $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
protected function mapMethod($method, $path, $options = array())
{
$on = isset($options['on']) ? $options['on'] : $this->map_member_collection_scope;
if (!$on || ($on != 'member' && $on != 'collection')) {
throw new \InvalidArgumentException('You must pass a valid "on" option (collection/method) to ' . $method);
}
array_push($this->$on, array($path, strtoupper($method)));
return $this;
}
/**
* Compiles this resource route into individual \Starlight\Component\Routing\Route
* @return array array of \Starlight\Component\Routing\Route routes
*/
public function compile()
{
$generators = static::$resources_map;
if ($this->except) {
$generators = array_diff_key($generators, array_fill_keys($this->except, true));
} elseif ($this->only) {
$generators = array_intersect_key($generators, array_fill_keys($this->only, true));
}
if (is_array($this->path_names)) {
$this->path_names += static::$resource_names;
} else {
$this->path_names = static::$resource_names;
}
- if ($this->module) {
- $this->controller = $this->module . '\\' . $this->controller;
- }
-
if (count($this->member) > 0) {
foreach ($this->member as $member) {
list($name, $verb) = $member;
$generators[$name] = array('name' => $name . '_%s', 'verb' => $verb, 'url' => '/:id/' . $name . '(.:format)');
}
}
if (count($this->collection) > 0) {
foreach ($this->collection as $collection) {
list($name, $verb) = $collection;
$generators[$name] = array('name' => $name . '_%p', 'verb' => $verb, 'url' => '/' . $name . '(.:format)');
}
}
$routes = array();
foreach ($generators as $action => $parts) {
$path = $parts['url'];
if (strpos($path, ':action') !== false) {
$path = str_replace(':action', $this->path_names[$action], $path);
}
- $r = new Route($this->path_prefix . '/' . $this->resource . $path, $this->controller . '::' . $action);
+ $r = new Route($this->path_prefix . '/' . $this->resource . $path, $this->controller . '#' . $action);
$r->methods(array($parts['verb']));
+ if ($this->module) {
+ $r->module($this->module);
+ }
$name = str_replace('%s', $this->name_prefix . $this->singular, $parts['name']);
$name = str_replace('%p', $this->name_prefix . $this->plural, $name);
$r->name($name);
if ($this->constraints) {
$r->constraints($this->constraints);
}
$routes[] = $r->compile();
}
return $routes;
}
}
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index 7c31529..f634a29 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,213 +1,203 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
+use Starlight\Component\Inflector\Inflector;
/**
* Route
*/
class Route implements RoutableInterface, CompilableInterface
{
- /**
- * Base default values for route parameters
- * @var array
- */
- protected static $base_parameter_defaults = array(
- 'controller' => null,
- 'action' => null,
- 'id' => null,
- );
-
-
public $path;
public $endpoint;
public $regex;
public $parameters = array();
public $constraints;
public $methods = array();
public $name;
public $module;
public $path_prefix;
public $name_prefix;
/**
* Constructor
* @param string $path url path
- * @param mixed $endpoint route endpoint - "controller::action" or a valid callback
+ * @param mixed $endpoint route endpoint - "controller#action" or a valid callback
*/
public function __construct($path, $endpoint)
{
$this->path = static::normalize($path);
$this->endpoint = $endpoint;
}
/**
* Set route parameter defaults
* @param array $defaults default values hash
* @return \Starlight\Component\Routing\Route this instance
*/
public function defaults(array $defaults)
{
foreach ($defaults as $key => $value) {
if (!isset($this->parameters[$key]) || trim($this->parameters[$key]) == '') {
$this->parameters[$key] = $value;
}
}
return $this;
}
/**
* Set route constraints
* @param mixed $constraints constraints (hash or \Closure)
* @return \Starlight\Component\Routing\Route this instance
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set HTTP methods/verbs route should respond to
* @param array $methods HTTP methods
* @return \Starlight\Component\Routing\Route this instance
*/
public function methods($methods)
{
if (!is_array($methods)) {
$methods = array($methods);
}
$this->methods = $methods;
return $this;
}
/**
* Set route name for generated helpers
* @param string $name route name
* @return \Starlight\Component\Routing\Route this instance
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
* Set module/namespace for the controller
* @param string $module module/namespace
* @return \Starlight\Component\Routing\Route this instance
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Compiles the route
* @return \Starlight\Component\Routing\Route this compiled instance
*/
public function compile()
{
$parser = new RouteParser();
$regex_constraints = $other_constraints = array();
if (is_array($this->constraints)) {
foreach ($this->constraints as $k => $c) {
if (!is_callable($c)) {
$regex_constraints[$k] = $c;
} else {
$other_constraints[] = $c;
}
}
}
if ($this->path_prefix) {
$this->path = $this->path_prefix . $this->path;
}
$this->regex = $parser->parse($this->path, $regex_constraints);
- $this->parameters = array_merge(static::$base_parameter_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
+ $this->parameters = array_merge(array_fill_keys($parser->names, ''), (array) $this->parameters);
$this->constraints = $other_constraints;
// get endpoint if string:
if (is_string($this->endpoint)) {
- if (strpos($this->endpoint, '::') !== false) {
+ if (strpos($this->endpoint, '#') !== false) {
// apply module:
if ($this->module) {
$this->endpoint = $this->module . '\\' . $this->endpoint;
}
- list($this->parameters['controller'], $this->parameters['action']) = explode('::', $this->endpoint);
+ list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
}
} elseif (!is_callable($this->endpoint)) {
// should be a callback
throw new \InvalidArgumentException('Route endpoint is invalid');
}
// set name/prefix if available:
if ($this->name && $this->name_prefix) {
$this->name = $this->name_prefix . $this->name;
}
return $this;
}
/**
* Match a request
* @param \Starlight\Component\Http\Request $request current request
* @return boolean route matches request
*/
public function match(Request $request)
{
$is_match = preg_match($this->regex, $request->getBaseUri(), $matches);
if ($is_match) {
if (count($this->methods) > 0 && !in_array($request->getMethod(), $this->methods)) {
return false;
}
foreach ($this->constraints as $c) {
if (!call_user_func($c, $request)) {
return false;
}
}
foreach ($matches as $k => $v) {
if (array_key_exists($k, $this->parameters)) {
$this->parameters[$k] = $v;
}
}
}
return $is_match;
}
/**
* Normalizes path - removes trailing slashes and prepends single slash
* @param string $path original path
* @return string normalized path
*/
protected function normalize($path)
{
$path = trim($path, '/');
$path = '/' . $path;
return $path;
}
}
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index 18af40b..4164a01 100755
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,385 +1,397 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
use Starlight\Component\Inflector\Inflector;
/**
* Router
*/
class Router implements CompilableInterface
{
protected $routes = array();
protected $current = array();
protected $current_type = null;
protected $compiled = array();
protected $has_compiled = false;
protected $scopes = array();
/**
* Draw routes - router gateway
* @param \Closure $callback callback
* @return \Starlight\Component\Routing\Router this instance
*/
- public function draw(\Closure $callback)
+ public function draw($ns, \Closure $callback)
{
+ $this->ns = $ns;
+
// TODO: check for cached version before redrawing these
$callback($this);
return $this;
}
/**
* Maps a single route
* @param string $path url path
- * @param mixed $endpoint controller::action pair or callback
+ * @param mixed $endpoint controller#action pair or callback
* @return \Starlight\Component\Routing\Route route
*/
public function map($path, $endpoint)
{
if ($this->current_type == 'resource') {
- throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context.');
+ throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context. Use member() or collection() instead.');
}
if (!preg_match('/\(\.:format\)$/', $path)) {
// auto append format option to path:
$path .= '(.:format)';
}
$this->routes[] = new Route($path, $endpoint);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'route';
$this->applyScopes();
array_pop($this->current);
$this->current_type = '';
return $this->routes[count($this->routes) - 1];
}
/**
* Maps RESTful resources routes
*/
public function resources()
{
$args = func_get_args();
$count = count($args);
$callback = null;
$options = array();
if (is_callable($args[$count - 1])) {
$callback = array_pop($args);
$count--;
}
if (is_array($args[$count - 1])) {
$options = array_pop($args);
$count--;
}
// map each resource separately (if multiple)
foreach ($args as $resource) {
if ($resource == Inflector::pluralize($resource)) {
$klass = 'Starlight\Component\Routing\ResourceRoute';
} else {
$klass = 'Starlight\Component\Routing\SingularResourceRoute';
}
$this->routes[] = new $klass($resource, $options);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'resource';
$route = $this->routes[count($this->routes) - 1];
$this->applyScopes();
if ($callback) {
$callback($this, $route);
}
array_pop($this->current);
$this->current_type = 'route';
}
return $route;
}
/**
* Maps singular RESTful resource
*/
public function resource()
{
return call_user_func_array(array($this, 'resources'), func_get_args());
}
/**
*
*/
public function redirect($path)
{
// TOOD: handle inline redirection
if (is_string($path)) {
return function() use ($path) {
return $path;
};
} else {
// already a callback, need to lazy evaluate later:
return $path;
}
}
/**
* Scope routes
* @param array $scopes scopes to apply
* @param \Closure $callback callback
*/
public function scope(array $scopes, \Closure $callback)
{
$this->addScopes($scopes);
$callback($this);
$this->removeScopes($scopes);
}
/**
* Compile all routes
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
/**
*
*/
public function match(Request $request)
{
foreach ($this->compiled as $r) {
if ($r->match($request)) {
return $r;
}
}
}
/**
* Pretty version of routes
* @return string nice string
*/
public function __toString()
{
$parts = array();
$mn = $mv = $mp = 0;
foreach ($this->compiled as $r) {
$p = array(
'name' => $r->name,
'verb' => strtoupper(implode(',', $r->methods)),
'path' => $r->path,
'endp' => is_callable($r->endpoint) ? '{callback}' : $r->endpoint,
);
if (strlen($p['name']) > $mn) {
$mn = strlen($p['name']);
}
if (strlen($p['verb']) > $mv) {
$mv = strlen($p['verb']);
}
if (strlen($p['path']) > $mp) {
$mp = strlen($p['path']);
}
$parts[] = $p;
}
$rc = '<pre>';
foreach ($parts as $p) {
$rc .= sprintf("%" . $mn . "s %-" . $mv . "s %-" . $mp . "s %s\n", $p['name'], $p['verb'], $p['path'], $p['endp']);
}
$rc .= '</pre>';
return $rc;
}
/**
* Apply current scopes to currently scoped routes
*/
protected function applyScopes()
{
$count = count($this->current);
$current = $this->current[$count - 1];
$previous = isset($this->current[$count - 2]) ? $this->routes[$this->current[$count - 2]] : null;
$this->routes[$current] = $this->applyScope($this->routes[$current], $previous);
}
/**
* Apply scopes to single route
* @param mixed $route resource or route to scope
* @param \Starlight\Component\Routing\ResourceRoute $nested current parent route (if present)
* @return mixed resource or route which was scoped
*/
protected function applyScope($route, $nested = null)
{
// nested resource
if ($nested) {
$route->path_prefix .= $nested->path_prefix . '/' . $nested->plural . '/:' . $nested->singular . '_id';
$route->name_prefix .= $nested->name_prefix . $nested->singular . '_';
}
// constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
$constraints = array_merge($constraints, is_array($c) ? $c : (array) $c);
}
$route->constraints($constraints);
}
// name
if (isset($this->scopes['name'])) {
$count = count($this->scopes['name']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
} else {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
}
- // module
+ // module/class namespace
+ $module = '';
if (isset($this->scopes['module'])) {
- $route->module(implode('\\', $this->scopes['module']));
+ if (trim($this->ns) != '') {
+ $module .= $this->ns . '\\';
+ }
+ $module .= implode('\\', $this->scopes['module']);
+ } elseif (trim($this->ns) != '') {
+ $module .= $this->ns;
+ }
+
+ if ($module != '') {
+ $route->module($module);
}
// path
if (isset($this->scopes['path'])) {
$count = count($this->scopes['path']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
} else {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
}
if ($this->current_type == 'route') {
// route only cases
// HTTP methods/verbs
if (isset($this->scopes['methods'])) {
// only consider the last on the stack:
$route->methods($this->scopes['methods'][count($this->scopes['methods']) - 1]);
}
// parameter defaults
if (isset($this->scopes['defaults'])) {
$defaults = array();
foreach ($this->scopes['defaults'] as $d) {
$defaults = array_merge($defaults, $d);
}
$route->defaults($d);
}
} elseif ($this->current_type == 'resource') {
// resource only cases
// except
if (isset($this->scopes['except'])) {
// only consider the last on the stack:
$route->except($this->scopes['except'][count($this->scopes['except']) - 1]);
}
// only
if (isset($this->scopes['only'])) {
// only consider the last on the stack:
$route->only($this->scopes['only'][count($this->scopes['only']) - 1]);
}
// path_names
if (isset($this->scopes['path_names'])) {
// only consider the last on the stack:
$route->pathNames($this->scopes['path_names'][count($this->scopes['path_names']) - 1]);
}
}
return $route;
}
/**
* Add scopes to parse tree
* @param array $scopes scopes to add
*/
protected function addScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->addScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
$this->scopes[$scope][] = $options;
} else {
$this->scopes[$scope] = array($options);
}
}
}
/**
* Remove scopes from parse tree
* @param array $scopes scopes to remove
*/
protected function removeScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->removeScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
if (($position = array_search($options, $this->scopes[$scope])) !== false) {
unset($this->scopes[$scope][$position]);
if (count($this->scopes[$scope]) == 0) {
unset($this->scopes[$scope]);
}
}
}
}
}
}
diff --git a/src/Starlight/Component/Routing/SingularResourceRoute.php b/src/Starlight/Component/Routing/SingularResourceRoute.php
old mode 100644
new mode 100755
index e6033d3..f2a27c9
--- a/src/Starlight/Component/Routing/SingularResourceRoute.php
+++ b/src/Starlight/Component/Routing/SingularResourceRoute.php
@@ -1,32 +1,31 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
/**
* Singular resource
*/
class SingularResourceRoute extends ResourceRoute
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
- 'index' => array('name' => '%s', 'verb' => 'get', 'url' => '(.:format)'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'create' => array('name' => '%s', 'verb' => 'post', 'url' => '(.:format)'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '(.:format)'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '(.:format)'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '(.:format)'),
);
}
diff --git a/tests/Starlight/Component/Routing/RouteTest.php b/tests/Starlight/Component/Routing/RouteTest.php
index d779bc8..ad1b6fb 100755
--- a/tests/Starlight/Component/Routing/RouteTest.php
+++ b/tests/Starlight/Component/Routing/RouteTest.php
@@ -1,100 +1,100 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\Route;
/**
*/
class RouteTest extends \PHPUnit_Framework_TestCase
{
public function testRouteIsNormalized()
{
$route = new Route('some/path', 'controller::action');
$this->assertEquals('/some/path', $route->path);
}
public function testSetDefaults()
{
$route = $this->getRoute();
$defaults = array('id' => 24);
$return = $route->defaults($defaults);
$this->assertEquals($defaults, $route->parameters);
$this->assertEquals($return, $route);
}
public function testDefaultsDontOverrideSetParameters()
{
$route = $this->getRoute();
$defaults = array('id' => 24);
$route->parameters = array('id' => 25);
$return = $route->defaults($defaults);
$this->assertEquals(25, $route->parameters['id']);
$this->assertEquals($return, $route);
}
public function testSetConstraints()
{
$route = $this->getRoute();
$constraints = array('id' => '[0-9]+');
$return = $route->constraints($constraints);
$this->assertEquals($constraints, $route->constraints);
$this->assertEquals($return, $route);
}
public function testSetMethods()
{
$route = $this->getRoute();
$methods = array('get', 'post');
$return = $route->methods($methods);
$this->assertEquals($methods, $route->methods);
$this->assertEquals($return, $route);
}
public function testSetName()
{
$route = $this->getRoute();
$name = 'login';
$return = $route->name($name);
$this->assertEquals($name, $route->name);
$this->assertEquals($return, $route);
}
public function testDetermineControllerActionFromEndpoint()
{
- $route = $this->getRoute(array('endpoint' => 'users::view'));
+ $route = $this->getRoute(array('endpoint' => 'UsersController#view'));
$route->compile();
- $this->assertEquals('users', $route->parameters['controller']);
+ $this->assertEquals('UsersController', $route->parameters['controller']);
$this->assertEquals('view', $route->parameters['action']);
}
protected function getRoute(array $options = array())
{
$defaults = array(
'path' => '/:controller/:action/:id',
'endpoint' => 'controller::action',
);
$options = array_merge($defaults, $options);
return new Route($options['path'], $options['endpoint']);
}
}
|
synewaves/starlight | e981358991219efd8661cc67a12b070eff88eb2e | Updating license | diff --git a/LICENSE b/LICENSE
index 42f5cf6..7a66df9 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,19 +1,19 @@
-Copyright (c) 2010 Matthew Vince
+Copyright (c) 2010-2011 Matthew Vince
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
diff --git a/autoload.php.dist b/autoload.php.dist
index 98f6134..c19c97d 100644
--- a/autoload.php.dist
+++ b/autoload.php.dist
@@ -1,17 +1,17 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
require_once __DIR__ . '/src/Starlight/Framework/Support/UniversalClassLoader.php';
$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
$autoloader->registerNamespaces(array(
'Starlight' => __DIR__ . '/src',
));
$autoloader->register();
diff --git a/src/Starlight/Component/Dispatcher/Context/Context.php b/src/Starlight/Component/Dispatcher/Context/Context.php
index 6aed097..3d104d7 100644
--- a/src/Starlight/Component/Dispatcher/Context/Context.php
+++ b/src/Starlight/Component/Dispatcher/Context/Context.php
@@ -1,16 +1,19 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Dispatcher\Context;
+/**
+ * Context
+ */
class Context
{
}
diff --git a/src/Starlight/Component/Dispatcher/Context/HttpContext.php b/src/Starlight/Component/Dispatcher/Context/HttpContext.php
new file mode 100755
index 0000000..60b1aa8
--- /dev/null
+++ b/src/Starlight/Component/Dispatcher/Context/HttpContext.php
@@ -0,0 +1,54 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Starlight\Component\Dispatcher\Context;
+use Starlight\Component\Http\Request;
+use Starlight\Component\Http\Response;
+
+
+/**
+ * HTTP Context
+ */
+class HttpContext extends Context
+{
+ protected $request;
+ protected $response;
+
+
+ public function __construct(Request $request = null)
+ {
+ $this->request = !is_null($request) ? $request : new Request();
+ $this->response = new Response();
+ }
+
+ public function getRequest()
+ {
+ return $this->request;
+ }
+
+ public function setRequest(Request $request)
+ {
+ $this->request = $request;
+
+ return $this;
+ }
+
+ public function getResponse()
+ {
+ return $this->response;
+ }
+
+ public function setResponse(Response $response)
+ {
+ $this->response = $response;
+
+ return $this;
+ }
+}
diff --git a/src/Starlight/Component/Dispatcher/Dispatcher.php b/src/Starlight/Component/Dispatcher/Dispatcher.php
index 2172f67..b5006e8 100644
--- a/src/Starlight/Component/Dispatcher/Dispatcher.php
+++ b/src/Starlight/Component/Dispatcher/Dispatcher.php
@@ -1,25 +1,25 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Dispatcher;
use Starlight\Component\Dispatcher\Context\Context;
abstract class Dispatcher
{
- public $context;
+ protected $context;
public function __construct(Context $context)
{
$this->context = $context;
}
abstract public function dispatch();
}
diff --git a/src/Starlight/Component/Dispatcher/HttpDispatcher.php b/src/Starlight/Component/Dispatcher/HttpDispatcher.php
new file mode 100755
index 0000000..6f8013c
--- /dev/null
+++ b/src/Starlight/Component/Dispatcher/HttpDispatcher.php
@@ -0,0 +1,71 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Starlight\Component\Dispatcher;
+use Starlight\Component\Dispatcher\Context\HttpContext;
+use Starlight\Component\Routing\Router;
+
+
+/**
+ * HTTP Dispatcher
+ */
+class HttpDispatcher extends Dispatcher
+{
+ protected $router;
+
+ public function __construct(HttpContext $context, Router $router)
+ {
+ $this->context = $context;
+ $this->router = $router;
+ }
+
+ public function getContext()
+ {
+ return $this->context;
+ }
+
+ public function setContext(HttpContext $context)
+ {
+ $this->context = $context;
+
+ return $this;
+ }
+
+ public function getRouter()
+ {
+ return $this->router;
+ }
+
+ public function setRouter(Router $router)
+ {
+ $this->router = $router;
+
+ return $this;
+ }
+
+ public function dispatch()
+ {
+ $route = $this->router->match($this->context->getRequest());
+ if ($route) {
+ $params = array_filter($route->parameters, function($var){ return trim($var) != ''; });
+ unset($params['controller'], $params['action']);
+
+ if (is_callable($route->endpoint)) {
+ call_user_func_array($route->endpoint, array_merge(array($this->context->getRequest()), array_values($params)));
+ return true;
+ } else {
+ // controller pattern
+
+ }
+ }
+
+ return false;
+ }
+}
\ No newline at end of file
diff --git a/src/Starlight/Component/EventDispatcher/Event.php b/src/Starlight/Component/EventDispatcher/Event.php
index 7826478..1b967e9 100755
--- a/src/Starlight/Component/EventDispatcher/Event.php
+++ b/src/Starlight/Component/EventDispatcher/Event.php
@@ -1,138 +1,138 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\EventDispatcher;
/**
* Event
*/
class Event implements EventInterface
{
/**
* Is processed flag
* @var boolean
*/
protected $processed = false;
/**
* Subeject
* @var mixed
*/
protected $subject;
/**
* Unique idenfitier
* @var string
*/
protected $name;
/**
* Parameters
* @var array
*/
protected $parameters;
/**
* Constructor
* @param mixed $subject The subject
* @param string $name The event name
* @param array $parameters An array of parameters
*/
public function __construct($subject, $name, $parameters = array())
{
$this->subject = $subject;
$this->name = $name;
$this->parameters = $parameters;
}
/**
* Returns the event's subject
* @return mixed subject
*/
public function getSubject()
{
return $this->subject;
}
/**
* Returns the event's name
* @return string name
*/
public function getName()
{
return $this->name;
}
/**
* Sets the event's processed flag to true
*
* This method must be called by listeners after the listener has processed the event.
* (This is only used when calling notifyUntil() in the event manager)
*/
public function setProcessed()
{
$this->processed = true;
}
/**
* Returns whether the event has been processed by a listener or not
* @see setProcessed()
* @return boolean true if the event has been processed
*/
public function isProcessed()
{
return $this->processed;
}
/**
* Returns the event's parameters
* @return array parameters
*/
public function all()
{
return $this->parameters;
}
/**
* Returns true if the parameter exists
* @param string $name The parameter name
* @return boolean true if the parameter exists
*/
public function has($name)
{
return array_key_exists($name, $this->parameters);
}
/**
* Returns a parameter value
* @param string $name The parameter name
* @return mixed The parameter value
* @throws \InvalidArgumentException When parameter doesn't exist
*/
public function get($name)
{
if (!array_key_exists($name, $this->parameters)) {
throw new \InvalidArgumentException(sprintf('The event "%s" doesn\'t have a "%s" parameter', $this->name, $name));
}
return $this->parameters[$name];
}
/**
* Sets a parameter
* @param string $name The parameter name
* @param mixed $value The parameter value
*/
public function set($name, $value)
{
$this->parameters[$name] = $value;
}
}
diff --git a/src/Starlight/Component/EventDispatcher/EventDispatcher.php b/src/Starlight/Component/EventDispatcher/EventDispatcher.php
index 42196e0..24a077d 100755
--- a/src/Starlight/Component/EventDispatcher/EventDispatcher.php
+++ b/src/Starlight/Component/EventDispatcher/EventDispatcher.php
@@ -1,142 +1,142 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\EventDispatcher;
/**
* EventDispatcher
*/
class EventDispatcher implements EventDispatcherInterface
{
/**
* Registered event listeners
* @var array
*/
protected $listeners = array();
/**
* Connects a listener to a given event name
* Listeners with a higher priority are executed first
* @param string $name An event name
* @param mixed $listener A PHP callable
* @param integer $priority The priority (between -10 and 10 -- defaults to 0)
*/
public function connect($name, $listener, $priority = 0)
{
if (!isset($this->listeners[$name][$priority])) {
if (!isset($this->listeners[$name])) {
$this->listeners[$name] = array();
}
$this->listeners[$name][$priority] = array();
}
$this->listeners[$name][$priority][] = $listener;
}
/**
* Disconnects one, or all listeners for the given event name
* @param string $name An event name
* @param mixed|null $listener The listener to remove, or null to remove all
*/
public function disconnect($name, $listener = null)
{
if (!isset($this->listeners[$name])) {
return;
}
if ($listener === null) {
unset($this->listeners[$name]);
return;
}
foreach ($this->listeners[$name] as $priority => $callables) {
foreach ($callables as $i => $callable) {
if ($listener === $callable) {
unset($this->listeners[$name][$priority][$i]);
}
}
}
}
/**
* Notifies all listeners of a given event
* @param EventInterface $event An EventInterface instance
*/
public function notify(EventInterface $event)
{
foreach ($this->getListeners($event->getName()) as $listener) {
call_user_func($listener, $event);
}
}
/**
* Notifies all listeners of a given event until one processes the event
* A listener tells the dispatcher that it has processed the event by calling the setProcessed() method on it.
* It can then return a value that will be fowarded to the caller.
* @param EventInterface $event An EventInterface instance
* @return mixed The returned value of the listener that processed the event
*/
public function notifyUntil(EventInterface $event)
{
foreach ($this->getListeners($event->getName()) as $listener) {
$ret = call_user_func($listener, $event);
if ($event->isProcessed()) {
return $ret;
}
}
}
/**
* Filters a value by calling all listeners of a given event
* @param EventInterface $event An EventInterface instance
* @param mixed $value The value to be filtered
* @return mixed The filtered value
*/
public function filter(EventInterface $event, $value)
{
foreach ($this->getListeners($event->getName()) as $listener) {
$value = call_user_func($listener, $event, $value);
}
return $value;
}
/**
* Returns true if the given event name has some listeners
* @param string $name The event name
* @return Boolean true if some listeners are connected, false otherwise
*/
public function hasListeners($name)
{
return (Boolean) count($this->getListeners($name));
}
/**
* Returns all listeners associated with a given event name
* @param string $name The event name
* @return array An array of listeners
*/
public function getListeners($name)
{
if (!isset($this->listeners[$name])) {
return array();
}
$listeners = array();
$all = $this->listeners[$name];
krsort($all);
foreach ($all as $l) {
$listeners = array_merge($listeners, $l);
}
return $listeners;
}
}
diff --git a/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php b/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php
index 57f8964..f099a19 100755
--- a/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php
+++ b/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php
@@ -1,71 +1,71 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\EventDispatcher;
/**
* EventDispatcherInterface describes an event dispatcher class
* @see http://developer.apple.com/documentation/Cocoa/Conceptual/Notifications/index.html Apple's Cocoa framework
*/
interface EventDispatcherInterface
{
/**
* Connects a listener to a given event name
* Listeners with a higher priority are executed first
* @param string $name An event name
* @param mixed $listener A PHP callable
* @param integer $priority The priority (between -10 and 10 -- defaults to 0)
*/
function connect($name, $listener, $priority = 0);
/**
* Disconnects one, or all listeners for the given event name
* @param string $name An event name
* @param mixed|null $listener The listener to remove, or null to remove all
*/
function disconnect($name, $listener = null);
/**
* Notifies all listeners of a given event
* @param EventInterface $event An EventInterface instance
*/
function notify(EventInterface $event);
/**
* Notifies all listeners of a given event until one processes the event
* A listener tells the dispatcher that it has processed the event by calling the setProcessed() method on it.
* It can then return a value that will be fowarded to the caller.
* @param EventInterface $event An EventInterface instance
* @return mixed The returned value of the listener that processed the event
*/
function notifyUntil(EventInterface $event);
/**
* Filters a value by calling all listeners of a given event
* @param EventInterface $event An EventInterface instance
* @param mixed $value The value to be filtered
* @return mixed The filtered value
*/
function filter(EventInterface $event, $value);
/**
* Returns true if the given event name has some listeners
* @param string $name The event name
* @return Boolean true if some listeners are connected, false otherwise
*/
function hasListeners($name);
/**
* Returns all listeners associated with a given event name
* @param string $name The event name
* @return array An array of listeners
*/
function getListeners($name);
}
diff --git a/src/Starlight/Component/EventDispatcher/EventInterface.php b/src/Starlight/Component/EventDispatcher/EventInterface.php
index b38947c..7ba2ad8 100755
--- a/src/Starlight/Component/EventDispatcher/EventInterface.php
+++ b/src/Starlight/Component/EventDispatcher/EventInterface.php
@@ -1,72 +1,72 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\EventDispatcher;
/**
* EventInterface
*/
interface EventInterface
{
/**
* Returns the event's subject
* @return mixed subject
*/
function getSubject();
/**
* Returns the event's name
* @return string name
*/
function getName();
/**
* Sets the event's processed flag to true
*
* This method must be called by listeners after the listener has processed the event.
* (This is only used when calling notifyUntil() in the event manager)
*/
function setProcessed();
/**
* Returns whether the event has been processed by a listener or not
* @see setProcessed()
* @return boolean true if the event has been processed
*/
function isProcessed();
/**
* Returns the event's parameters
* @return array parameters
*/
function all();
/**
* Returns true if the parameter exists
* @param string $name The parameter name
* @return boolean true if the parameter exists
*/
function has($name);
/**
* Returns a parameter value
* @param string $name The parameter name
* @return mixed The parameter value
* @throws \InvalidArgumentException When parameter doesn't exist
*/
function get($name);
/**
* Sets a parameter
* @param string $name The parameter name
* @param mixed $value The parameter value
*/
function set($name, $value);
}
diff --git a/src/Starlight/Component/Http/Cookie.php b/src/Starlight/Component/Http/Cookie.php
index bf14416..dacbcb9 100755
--- a/src/Starlight/Component/Http/Cookie.php
+++ b/src/Starlight/Component/Http/Cookie.php
@@ -1,270 +1,270 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http;
/**
* HTTP Cookie
*/
class Cookie
{
protected $name;
protected $value;
protected $options;
/**
* Constructor
*
* Available options:
*
* * expires: Expiration date (string, int or \DateTime) (default: 0)
* * path: Path (default: null)
* * domain: Domain (default: null)
* * secure: Secure cookie (default: false)
* * http_only: HTTP only (default: true)
*
* @param string $name name
* @param mixed $value value
* @param array $options options hash
*/
public function __construct($name, $value, array $options = array())
{
$options = array_merge(array(
'expires' => 0,
'path' => null,
'domain' => null,
'secure' => false,
'http_only' => true,
), $options);
$this->setName($name)
->setValue($value)
->setExpires($options['expires'])
->setPath($options['path'])
->setDomain($options['domain'])
->setSecure($options['secure'])
->setHttpOnly($options['http_only']);
}
/**
* Gets the name
* @return string name
*/
public function getName()
{
return $this->name;
}
/**
* Sets the name
* @param string $name name
* @throws \InvalidArgumentException if invalid name
* @return Cookie this instance
*/
public function setName($name)
{
if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
}
if (empty($name)) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
$this->name = $name;
return $this;
}
/**
* Gets the value
* @return string value
*/
public function getValue()
{
return $this->value;
}
/**
* Sets the value
* @param string $value value
* @throws \InvalidArgumentException if invalid value
* @return Cookie this instance
*/
public function setValue($value)
{
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
$this->value = $value;
return $this;
}
/**
* Gets the expiration date
* @return int expiration date
*/
public function getExpires()
{
return $this->options['expires'];
}
/**
* Sets the expiration date
* @param string|int|\DateTime $expires expiration date
* @return Cookie this instance
*/
public function setExpires($expires)
{
if (is_numeric($expires)) {
$expires = \DateTime::createFromFormat('U', $expires);
} elseif (!($expires instanceof \DateTime)) {
$o_expires = $expires;
try {
$expires = new \DateTime($expires);
} catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid: "%s".', $o_expires));
}
}
$this->options['expires'] = $expires;
return $this;
}
/**
* Gets the path
* @return string path
*/
public function getPath()
{
return $this->options['path'];
}
/**
* Sets the path
* @param string $path path
* @return Cookie this instance
*/
public function setPath($path)
{
$this->options['path'] = $path;
return $this;
}
/**
* Gets the domain
* @return string domain
*/
public function getDomain()
{
return $this->options['domain'];
}
/**
* Sets the domain
* @param string $domain domain
* @return Cookie this instance
*/
public function setDomain($domain)
{
$this->options['domain'] = $domain;
return $this;
}
/**
* Gets the secure flag
* @return boolean secure flag
*/
public function getSecure()
{
return (bool) $this->options['secure'];
}
/**
* Sets the secure flag
* @param boolean $secure secure flag
* @return Cookie this instance
*/
public function setSecure($secure)
{
$this->options['secure'] = (bool) $secure;
return $this;
}
/**
* Gets the http only flag
* @return boolean http only
*/
public function getHttpOnly()
{
return (bool) $this->options['http_only'];
}
/**
* Sets the http only flag
* @param boolean $http_only http only flag
* @return Cookie this instance
*/
public function setHttpOnly($http_only)
{
$this->options['http_only'] = (bool) $http_only;
return $this;
}
/**
* Is this cookie going to be cleared
* @return boolean is cleared
*/
public function isCleared()
{
return $this->options['expires'] < new \DateTime();
}
/**
* Get formatted cookie header value
* @return string formatted value
*/
public function toHeaderValue()
{
$cookie = sprintf('%s=%s', $this->name, urlencode($this->value));
if ($this->options['expires'] !== null) {
$cookie .= '; expires=' . $this->options['expires']->format(DATE_COOKIE);
}
if ($this->options['domain']) {
$cookie .= '; domain=' . $this->options['domain'];
}
if ($this->options['path'] && $this->options['path'] !== '/') {
$cookie .= '; path=' . $this->options['path'];
}
if ($this->options['secure']) {
$cookie .= '; secure';
}
if ($this->options['http_only']) {
$cookie .= '; httponly';
}
return $cookie;
}
/**
* Get formatted cookie header value
* @return string formatted value
*/
public function __toString()
{
return $this->toHeaderValue();
}
}
diff --git a/src/Starlight/Component/Http/Exception/IpSpoofingException.php b/src/Starlight/Component/Http/Exception/IpSpoofingException.php
index fbfde02..c8e56f3 100755
--- a/src/Starlight/Component/Http/Exception/IpSpoofingException.php
+++ b/src/Starlight/Component/Http/Exception/IpSpoofingException.php
@@ -1,20 +1,20 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http\Exception;
/**
* IP Spoofing exception
* @see \Starlight\Component\Http\Request::getRemoteIp()
*/
class IpSpoofingException extends \Exception
{
}
\ No newline at end of file
diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index 53a6859..b61170d 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,305 +1,305 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http;
use Starlight\Component\StdLib\StorageBucket;
/**
* Wrapper class for request/response headers
*/
class HeaderBucket extends StorageBucket
{
protected $cookies = array();
protected $cache_control = array();
/**
* Returns a header value by name
* @param string $key The header name
* @param mixed $default default value if none found
* @param boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function get($key, $default = null, $first = true)
{
$key = strtr(strtolower($key), '_', '-');
if (!array_key_exists($key, $this->contents)) {
if ($default === null) {
return $first ? null : array();
} else {
return $first ? $default : array($default);
}
}
if ($first) {
return count($this->contents[$key]) ? $this->contents[$key][0] : $default;
} else {
return $this->contents[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
$key = strtr(strtolower($key), '_', '-');
if (!is_array($values)) {
$values = array($values);
}
if ($replace === true || !isset($this->contents[$key])) {
$this->contents[$key] = $values;
} else {
$this->contents[$key] = array_merge($this->contents[$key], $values);
}
if ($key === 'cache-control') {
$this->cache_control = $this->parseCacheControl($values[0]);
}
return $this;
}
/**
* Replaces the current contents with a new set
* @param array $contents contents
* @return HeaderBucket this instance
*/
public function replace(array $contents = array())
{
$this->contents = array();
$this->add($contents);
return $this;
}
/**
* Adds contents
* @param array $contents contents
* @return HeaderBucket this instance
*/
public function add(array $contents = array())
{
foreach ($contents as $key => $value) {
$this->set($key, $value);
}
return $this;
}
/**
* Returns true if the content is defined
* @param string $key The key
* @return boolean true if the contents exists, false otherwise
*/
public function has($key)
{
return parent::has(strtr(strtolower($key), '_', '-'));
}
/**
* Returns true if the given HTTP header contains the given value
* @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, null, false));
}
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
$key = strtr(strtolower($key), '_', '-');
parent::delete($key);
if ($key == 'cache-control') {
$this->cache_control = array();
}
return $this;
}
/**
* Sets a cookie
* @param Cookie $cookie
* @throws \InvalidArgumentException When the cookie expire parameter is not valid
* @return HeaderBucket this instance
*/
public function setCookie(Cookie $cookie)
{
$this->cookies[$cookie->getName()] = $cookie;
return $this;
}
/**
* Removes a cookie from the array, but does not unset it in the browser
* @param string $name
* @return HeaderBucket this instance
*/
public function removeCookie($name)
{
unset($this->cookies[$name]);
return $this;
}
/**
* Whether the array contains any cookie with this name
* @param string $name
* @return boolean cookie exists
*/
public function hasCookie($name)
{
return isset($this->cookies[$name]);
}
/**
* Returns a cookie
* @param string $name
* @throws \InvalidArgumentException if cookie not found
* @return Cookie cookie
*/
public function getCookie($name)
{
if (!$this->hasCookie($name)) {
throw new \InvalidArgumentException(sprintf('There is no cookie with name "%s".', $name));
}
return $this->cookies[$name];
}
/**
* Returns an array with all cookies
* @return array all cookies
*/
public function getCookies()
{
return $this->cookies;
}
/**
* Returns the HTTP header value converted to a date
* @param string $key The parameter key
* @param \DateTime $default The default value
* @throws \RuntimeException if cannot parse header
* @return \DateTime The filtered value
*/
public function getDate($key, \DateTime $default = null)
{
if (($value = $this->get($key)) === null) {
return $default;
}
if (($date = \DateTime::createFromFormat(DATE_RFC2822, $value)) === false) {
throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
}
return $date;
}
/**
* Adds the cache control headers
* @param string $key key
* @param mixed $value value
* @return HeaderBag this instance
*/
public function addCacheControlDirective($key, $value = true)
{
$this->cache_control[$key] = $value;
$this->set('Cache-Control', $this->getCacheControlHeader());
return $this;
}
/**
* Is there a cache control directive present
* @param string $key key
* @return boolean is present
*/
public function hasCacheControlDirective($key)
{
return array_key_exists($key, $this->cache_control);
}
/**
* Gets the cache control directive header
* @param string $key key
* @return string cache control header
*/
public function getCacheControlDirective($key)
{
return array_key_exists($key, $this->cache_control) ? $this->cache_control[$key] : null;
}
/**
* Removes the cache control directive header
* @param string $key key
* @return HeaderBag this instance
*/
public function removeCacheControlDirective($key)
{
unset($this->cache_control[$key]);
$this->set('Cache-Control', $this->getCacheControlHeader());
return $this;
}
/**
* Generates the cache control header value
* @return string header value
*/
protected function getCacheControlHeader()
{
$parts = array();
ksort($this->cache_control);
foreach ($this->cache_control as $key => $value) {
if ($value === true) {
$parts[] = $key;
} else {
if (preg_match('/[^a-zA-Z0-9._-]/', $value)) {
$value = '"' . $value . '"';
}
$parts[] = "$key=$value";
}
}
return implode(', ', $parts);
}
/**
* Parses a Cache-Control HTTP header
* @param string $header The value of the Cache-Control HTTP header
* @return array An array representing the attribute values
*/
protected function parseCacheControl($header)
{
$cache_control = array();
preg_match_all('/([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?/', $header, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$cache_control[strtolower($match[1])] = isset($match[2]) && $match[2] ? $match[2] : (isset($match[3]) ? $match[3] : true);
}
return $cache_control;
}
}
diff --git a/src/Starlight/Component/Http/ParameterBucket.php b/src/Starlight/Component/Http/ParameterBucket.php
index 9164680..15880d6 100755
--- a/src/Starlight/Component/Http/ParameterBucket.php
+++ b/src/Starlight/Component/Http/ParameterBucket.php
@@ -1,64 +1,64 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http;
use Starlight\Component\StdLib\StorageBucket;
/**
* Wrapper class request parameters
* @see Request
*/
class ParameterBucket extends StorageBucket
{
/**
* Returns the alphabetic characters of the parameter value
* @param string $key The parameter key
* @param mixed $default The default value
* @return string The filtered value
*/
public function getAlpha($key, $default = '')
{
return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default));
}
/**
* Returns the alphabetic characters and digits of the parameter value
* @param string $key The parameter key
* @param mixed $default The default value
* @return string The filtered value
*/
public function getAlnum($key, $default = '')
{
return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default));
}
/**
* Returns the digits of the parameter value
* @param string $key The parameter key
* @param mixed $default The default value
* @return string The filtered value
*/
public function getDigits($key, $default = '')
{
return preg_replace('/[^[:digit:]]/', '', $this->get($key, $default));
}
/**
* Returns the parameter value converted to integer
* @param string $key The parameter key
* @param mixed $default The default value
* @return string The filtered value
*/
public function getInt($key, $default = 0)
{
return (int) $this->get($key, $default);
}
}
diff --git a/src/Starlight/Component/Http/Request.php b/src/Starlight/Component/Http/Request.php
index 4e72b6c..0778c97 100755
--- a/src/Starlight/Component/Http/Request.php
+++ b/src/Starlight/Component/Http/Request.php
@@ -1,332 +1,332 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http;
/**
* HTTP Request
*/
class Request
{
public static $local_ips = array('127.0.0.1', '::1');
public $post;
public $get;
public $cookies;
public $files;
public $server;
public $headers;
protected $host;
protected $port;
protected $remote_ip;
protected $url;
/**
* Constructor
* @param array $post POST values
* @param array $get GET values
* @param array $cookies COOKIE values
* @param array $files FILES values
* @param array $server SERVER values
*/
public function __construct(array $post = null, array $get = null, array $cookies = null, array $files = null, array $server = null)
{
$this->post = new ParameterBucket($post ?: $_POST);
$this->get = new ParameterBucket($get ?: $_GET);
$this->cookies = new ParameterBucket($cookies ?: $_COOKIE);
$this->files = new ParameterBucket($files ?: $_FILES);
$this->server = new ParameterBucket($server ?: $_SERVER);
$this->headers = new HeaderBucket($this->initializeHeaders(), 'request');
}
/**
* Clone
*/
public function __clone()
{
$this->post = clone $this->post;
$this->get = clone $this->get;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Get a value from the request
*
* Order or precedence: GET, POST, COOKIE
*/
public function get($key, $default = null)
{
return $this->get->get($key, $this->post->get($key, $this->cookies->get($key, $default)));
}
/**
* Gets request method, lowercased
*
* Method can come from three places in this order:
* <ol>
* <li>$_POST[_method]</li>
* <li>$_SERVER[X_HTTP_METHOD_OVERRIDE]</li>
* <li>$_SERVER[REQUEST_METHOD]</li>
* </ol>
* @return string request method
*/
public function getMethod()
{
$method = $this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD')));
return $method !== null ? strtolower($method) : null;
}
/**
* Is this a DELETE request
* @return boolean is DELETE request
*/
public function isDelete()
{
return $this->getMethod() == 'delete';
}
/**
* Is this a GET request
* @see head()
* @return boolean is GET request
*/
public function isGet()
{
return $this->isHead();
}
/**
* Is this a POST request
* @return boolean is POST request
*/
public function isPost()
{
return $this->getMethod() == 'post';
}
/**
* Is this a HEAD request
*
* Functionally equivalent to get()
* @return boolean is HEAD request
*/
public function isHead()
{
return $this->getMethod() == 'head' || $this->getMethod() == 'get';
}
/**
* Is this a PUT request
* @return boolean is PUT request
*/
public function isPut()
{
return $this->getMethod() == 'put';
}
/**
* Is this an SSL request
* @return boolean is SSL request
*/
public function isSsl()
{
return strtolower($this->server->get('HTTPS')) == 'on';
}
/**
* Gets server protocol
* @return string protocol
*/
public function getProtocol()
{
return $this->isSsl() ? 'https://' : 'http://';
}
/**
* Gets the server host
* @return string host
*/
public function getHost()
{
if ($this->host === null) {
$host = $this->server->get('HTTP_X_FORWARDED_HOST', $this->server->get('HTTP_HOST'));
$pos = strpos($host, ':');
if ($pos !== false) {
$this->host = substr($host, 0, $pos);
if ($this->port === null) {
$this->port = (int) substr($host, $pos + 1);
}
} else {
$this->host = $host;
}
}
return $this->host;
}
/**
* Gets the server port
* @return integer port
*/
public function getPort()
{
if ($this->port === null) {
$this->port = (int) $this->server->get('SERVER_PORT', $this->getStandardPort());
}
return $this->port;
}
/**
* Gets the standard port number for the current protocol
* @return integer port (443, 80)
*/
public function getStandardPort()
{
return $this->isSsl() ? 443 : 80;
}
/**
* Gets the port string with colon delimiter if not standard port
* @return string port
*/
public function getPortString()
{
return (in_array($this->getPort(), array(443, 80))) ? '' : ':' . $this->getPort();
}
/**
* Gets the host with the port
* @return string host with port
*/
public function getHostWithPort()
{
return $this->getHost() . $this->getPortString();
}
/**
* Gets the client's remote ip
* @return string IP
*/
public function getRemoteIp()
{
if ($this->remote_ip === null) {
$remote_ips = null;
if ($x_forward = $this->server->get('HTTP_X_FORWARDED_FOR')) {
$remote_ips = array_map('trim', explode(',', $x_forward));
}
$client_ip = $this->server->get('HTTP_CLIENT_IP');
if ($client_ip) {
if (is_array($remote_ips) && !in_array($client_ip, $remote_ips)) {
// don't know which came from the proxy, and which from the user
throw new Exception\IpSpoofingException(sprintf("IP spoofing attack?!\nHTTP_CLIENT_IP=%s\nHTTP_X_FORWARDED_FOR=%s", $this->server->get('HTTP_CLIENT_IP'), $this->server->get('HTTP_X_FORWARDED_FOR')));
}
$this->remote_ip = $client_ip;
} elseif (is_array($remote_ips)) {
$this->remote_ip = $remote_ips[0];
} else {
$this->remote_ip = $this->server->get('REMOTE_ADDR');
}
}
return $this->remote_ip;
}
/**
* Is this request local?
* @return boolean local
*/
public function isLocal()
{
return in_array($this->getRemoteIp(), static::$local_ips);
}
/**
* Check if the request is an XMLHttpRequest (AJAX)
* @return boolean is XHR (AJAX) request
*/
public function isXmlHttpRequest()
{
return (bool) preg_match('/XMLHttpRequest/i', $this->server->get('HTTP_X_REQUESTED_WITH'));
}
/**
* Gets the full server url with protocol and port
* @return string server path
*/
public function getServer()
{
return $this->getProtocol() . $this->getHostWithPort();
}
/**
* Gets the requested URI path without domain or script name
* @return string uri
*/
public function getUri()
{
$url = $this->server->get('REQUEST_URI');
return trim($url) != '' ? $url : '/';
}
/**
* Gets the requested URI path without query string information
* @return string uri
*/
public function getBaseUri()
{
$url = $this->getUri();
if (trim($this->server->get('QUERY_STRING')) != '') {
$url = substr($url, 0, strpos($url, '?'));
}
return $url;
}
/**
* Gets the requested route from the URI
* @return string route
*/
public function getRoute()
{
$route = $this->getUri();
// remove query string
if (($qs = strpos($route, '?')) !== false) {
$route = substr($route, 0, $qs);
}
return $route;
}
/**
* Initialize request headers for HeaderBucket
* @return array headers
*/
protected function initializeHeaders()
{
$headers = array();
foreach ($this->server->all() as $key => $value) {
if (strtolower(substr($key, 0, 5)) === 'http_') {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
}
diff --git a/src/Starlight/Component/Http/Response.php b/src/Starlight/Component/Http/Response.php
index d272df6..13de40a 100644
--- a/src/Starlight/Component/Http/Response.php
+++ b/src/Starlight/Component/Http/Response.php
@@ -1,98 +1,98 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http;
/**
* HTTP Response
*/
class Response
{
/**
* Standard HTTP status codes and default messages
* @link http://www.iana.org/assignments/http-status-codes
* @var array
*/
protected static $status_codes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
507 => 'Insufficient Storage',
510 => 'Not Extended'
);
protected $content;
protected $status;
public function __construct($content = '', $status = 200)
{
$this->content($content)->status($status);
}
public function content($content)
{
$this->content = $content;
return $this;
}
public function status($status)
{
$this->status = $status;
return $this;
}
}
diff --git a/src/Starlight/Component/Http/Session.php b/src/Starlight/Component/Http/Session.php
index ef5e82e..994da07 100755
--- a/src/Starlight/Component/Http/Session.php
+++ b/src/Starlight/Component/Http/Session.php
@@ -1,274 +1,274 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http;
use Starlight\Component\Http\SessionStorage;
/**
* Session
*/
class Session implements \Serializable
{
const FLASH_KEY = '_flash';
const SAVE_KEY = '_starlight';
protected $storage;
protected $options = array();
protected $attributes = array();
protected $old_flash_data = array();
protected $is_started = false;
/**
* Constructor
*/
public function __construct(SessionStorageInterface $storage, array $options = array())
{
$this->storage = $storage;
$this->options = $options;
$this->attributes = array(self::FLASH_KEY => array());
$this->is_started = false;
}
/**
* Destructor
*/
public function __destruct()
{
$this->save();
}
/**
* Serialize
* @return string serialized data
*/
public function serialize()
{
return serialize(array($this->storage, $this->options));
}
/**
* Unserialize
* @param string $serialized serialized data
*/
public function unserialize($serialized)
{
list($this->storage, $this->options) = unserialize($serialized);
$this->attributes = array();
$this->is_started = false;
}
/**
* Save session
*/
public function save()
{
if ($this->isStarted()) {
if (isset($this->attributes[self::FLASH_KEY])) {
$this->attributes[self::FLASH_KEY] = array_diff_key($this->attributes[self::FLASH_KEY], $this->old_flash_data);
}
$this->storage->write(self::SAVE_KEY, $this->attributes);
}
}
/**
* Start session and storage engine
*/
public function start()
{
if ($this->isStarted()) {
return;
}
$this->storage->start();
$this->attributes = $this->storage->read(self::SAVE_KEY);
if (!isset($this->attributes[self::FLASH_KEY])) {
$this->attributes[self::FLASH_KEY] = array();
}
$this->old_flash_data = array_flip(array_keys($this->attributes[self::FLASH_KEY]));
$this->is_started = true;
}
/**
* Check if an attribute exists
* @param string $name attribute name
* @return boolean attribute exists
*/
public function has($name)
{
return array_key_exists($name, $this->attributes);
}
/**
* Gets an attribute's value
* @param string $name attribute's name
* @param mixed $default default value if not found
* @return mixed
*/
public function get($name, $default = null)
{
return $this->has($name) ? $this->attributes[$name] : $default;
}
/**
* Set an attribute's value
* @param string $name attribute name
* @param mixed $value attribute value
*/
public function set($name, $value)
{
if (!$this->isStarted()) {
$this->start();
}
$this->attributes[$name] = $value;
}
/**
* Delete an attribute
* @param string $name attribute name
*/
public function delete($name)
{
if (!$this->isStarted()) {
$this->start();
}
if ($this->has($name)) {
unset($this->attributes[$name]);
}
}
/**
* Clear all attributes
*/
public function clear()
{
if (!$this->isStarted()) {
$this->start();
}
$this->attributes = array();
$this->clearFlashes();
}
/**
* Invalidates the session
*/
public function invalidate()
{
$this->clear();
$this->storage->regenerate();
}
/**
* Migrates the session to a new session id, keeping existing attributes
*/
public function migrate()
{
$this->storage->regenerate();
}
/**
* Gets the session id
* @return string id
*/
public function id()
{
return $this->storage->id();
}
/**
* Gets all flash values
* @return array flash values
*/
public function getFlashes()
{
return $this->attributes[self::FLASH_KEY];
}
/**
* Sets all flash values at once
* @param array $values flash values
*/
public function setFlashes($values)
{
if (!$this->isStarted()) {
$this->start();
}
$this->attributes[self::FLASH_KEY] = $values;
}
/**
* Clears all flash data
*/
public function clearFlashes()
{
$this->attributes[self::FLASH_KEY] = array();
}
/**
* Gets a flash value
* @param string $name flash name
* @param mixed $default default value if missing
* @return mixed value
*/
public function getFlash($name, $default = null)
{
return $this->hasFlash($name) ? $this->attributes[self::FLASH_KEY][$name] : $default;
}
/**
* Sets a flash value
* @param string $name flash name
* @param mixed $value value
*/
public function setFlash($name, $value)
{
if (!$this->isStarted()) {
$this->start();
}
$this->attributes[self::FLASH_KEY][$name] = $value;
}
/**
* Checks if a flash value exists
* @param string $name flash name
* @return boolean exists
*/
public function hasFlash($name)
{
return array_key_exists($name, $this->attributes[self::FLASH_KEY]);
}
/**
* Deletes a flash value
* @param string $name flash name
*/
public function deleteFlash($name)
{
if ($this->hasFlash($name)) {
unset($this->attributes[self::FLASH_KEY][$name]);
}
}
/**
* Is the current session started
* @return boolean session started
*/
protected function isStarted()
{
return $this->is_started;
}
}
diff --git a/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php b/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php
index 8a01a7d..0117aed 100755
--- a/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php
+++ b/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php
@@ -1,156 +1,156 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http\SessionStorage;
/**
* Native Session Storage
*/
class NativeSessionStorage implements SessionStorageInterface
{
static protected $regenerated = false;
static protected $started = false;
protected $options;
/**
* Constructor
*
* Available options:
*
* * name: The cookie name (_SESS by default)
* * id: The session id (null by default)
* * lifetime: Cookie lifetime
* * path: Cookie path
* * domain: Cookie domain
* * secure: Cookie secure
* * httponly: Cookie http only
*
* The default values for most options are those returned by the session_get_cookie_params() function
* @param array $options An associative array of options
*/
public function __construct(array $options = array())
{
$defaults = session_get_cookie_params();
$this->options = array_merge(array(
'name' => '_SESS',
'lifetime' => $defaults['lifetime'],
'path' => $defaults['path'],
'domain' => $defaults['domain'],
'secure' => $defaults['secure'],
'httponly' => isset($defaults['httponly']) ? $defaults['httponly'] : false,
), $options);
session_name($this->options['name']);
}
/**
* Starts the session.
*/
public function start()
{
if (self::$started) {
return;
}
session_set_cookie_params(
$this->options['lifetime'],
$this->options['path'],
$this->options['domain'],
$this->options['secure'],
$this->options['httponly']
);
// disable native cache limiter as this is managed by HeaderBag directly
// session_cache_limiter(false);
if (!ini_get('session.use_cookies') && $this->options['id'] && $this->options['id'] != session_id()) {
session_id($this->options['id']);
}
session_start();
self::$started = true;
}
/**
* Returns the session ID
* @return mixed The session ID
* @throws \RuntimeException If the session was not started yet
*/
public function id()
{
if (!self::$started) {
throw new \RuntimeException('The session must be started before reading its ID');
}
return session_id();
}
/**
* Reads data from this storage
* The preferred format for a key is directory style so naming conflicts can be avoided.
* @param string $key A unique key identifying your data
* @return mixed Data associated with the key
* @throws \RuntimeException If an error occurs while reading data from this storage
*/
public function read($key, $default = null)
{
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
/**
* Removes data from this storage
* The preferred format for a key is directory style so naming conflicts can be avoided.
* @param string $key A unique key identifying your data
* @return mixed Data associated with the key
* @throws \RuntimeException If an error occurs while removing data from this storage
*/
public function remove($key)
{
$rc = null;
if (isset($_SESSION[$key])) {
$rc = $_SESSION[$key];
unset($_SESSION[$key]);
}
return $rc;
}
/**
* Writes data to this storage
* The preferred format for a key is directory style so naming conflicts can be avoided.
* @param string $key A unique key identifying your data
* @param mixed $data Data associated with your key
* @throws \RuntimeException If an error occurs while writing to this storage
*/
public function write($key, $data)
{
$_SESSION[$key] = $data;
}
/**
* Regenerates id that represents this storage
* @param Boolean $destroy Destroy session when regenerating?
* @return Boolean True if session regenerated, false if error
* @throws \RuntimeException If an error occurs while regenerating this storage
*/
public function regenerate($destroy = false)
{
if (self::$regenerated) {
return;
}
session_regenerate_id($destroy);
self::$regenerated = true;
}
}
diff --git a/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php b/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php
index 564a193..888c303 100755
--- a/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php
+++ b/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php
@@ -1,64 +1,64 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Http\SessionStorage;
/**
* Session Storage Interface
*/
interface SessionStorageInterface
{
/**
* Starts the session.
*/
function start();
/**
* Returns the session ID
* @return mixed The session ID
* @throws \RuntimeException If the session was not started yet
*/
function id();
/**
* Reads data from this storage
* The preferred format for a key is directory style so naming conflicts can be avoided.
* @param string $key A unique key identifying your data
* @return mixed Data associated with the key
* @throws \RuntimeException If an error occurs while reading data from this storage
*/
function read($key);
/**
* Removes data from this storage
* The preferred format for a key is directory style so naming conflicts can be avoided.
* @param string $key A unique key identifying your data
* @return mixed Data associated with the key
* @throws \RuntimeException If an error occurs while removing data from this storage
*/
function remove($key);
/**
* Writes data to this storage
* The preferred format for a key is directory style so naming conflicts can be avoided.
* @param string $key A unique key identifying your data
* @param mixed $data Data associated with your key
* @throws \RuntimeException If an error occurs while writing to this storage
*/
function write($key, $data);
/**
* Regenerates id that represents this storage
* @param Boolean $destroy Destroy session when regenerating?
* @return Boolean True if session regenerated, false if error
* @throws \RuntimeException If an error occurs while regenerating this storage
*/
function regenerate($destroy = false);
}
diff --git a/src/Starlight/Component/Inflector/Inflector.php b/src/Starlight/Component/Inflector/Inflector.php
index cf3da6a..ff45565 100644
--- a/src/Starlight/Component/Inflector/Inflector.php
+++ b/src/Starlight/Component/Inflector/Inflector.php
@@ -1,312 +1,312 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Inflector;
/**
* Inflector
*/
class Inflector
{
/**
* Plural inflections
* @var array
*/
protected static $plurals = array();
/**
* Singular inflections
* @var array
*/
protected static $singulars = array();
/**
* Uncountable item reflections
* @var array
*/
protected static $uncountables = array();
/**
* Adds a plural inflection
* @param string $rule regex rule
* @param string $replacement regex replacement
*/
public static function plural($rule, $replacement)
{
if (!preg_match('/^\//', $rule)) {
// looks like a string
// TODO: make string vs regex detection better
static::$uncountables = array_diff(static::$uncountables, array($rule));
$rule = '/' . $rule . '/i';
}
static::$uncountables = array_diff(static::$uncountables, array($replacement));
array_unshift(static::$plurals, array($rule, $replacement));
}
/**
* Adds a singular inflection
* @param string $rule regex rule
* @param string $replacement regex replacement
*/
public static function singular($rule, $replacement)
{
if (!preg_match('/^\//', $rule)) {
// looks like a string
// TODO: make string vs regex detection better
static::$uncountables = array_diff(static::$uncountables, array($rule));
$rule = '/' . $rule . '/i';
}
static::$uncountables = array_diff(static::$uncountables, array($replacement));
array_unshift(static::$singulars, array($rule, $replacement));
}
/**
* Adds an irregular inflection
* @param string $singular singular rule
* @param string $plural plural rule
*/
public static function irregular($singular, $plural)
{
static::plural('/(' . $singular[0] . ')' . substr($singular, 1) . '$/i', '\1' . substr($plural, 1));
static::singular('/(' . $plural[0] . ')' . substr($plural, 1) . '$/i', '\1' . substr($singular, 1));
}
/**
* Adds an uncountable word(s)
* @param string|array single word or array of words
*/
public static function uncountable($words)
{
static::$uncountables += !is_array($words) ? array($words) : $words;
}
/**
* Pluralizes a word
* @param string $str word
* @return string pluralized word
*/
public static function pluralize($str)
{
$str = strval($str);
if (!in_array(strtolower($str), static::$uncountables) && $str != '') {
foreach (static::$plurals as $pair) {
if (preg_match($pair[0], $str)) {
return preg_replace($pair[0], $pair[1], $str);
}
}
}
return $str;
}
/**
* Singularizes a word
* @param string $str word
* @return string singularized word
*/
public static function singularize($str)
{
$str = strval($str);
if (!in_array(strtolower($str), static::$uncountables) && $str != '') {
foreach (static::$singulars as $pair) {
if (preg_match($pair[0], $str)) {
return preg_replace($pair[0], $pair[1], $str);
}
}
}
return $str;
}
/**
* Normalizes a string for a url
*
* This removes any non alphanumeric character, dash, space or underscore
* with supplied separator
*
* <code>
* echo Inflector::normalize('This is an example');
* > this-is-an-example
* </code>
* @param string $str string to normalize
* @param string $sep string separator
* @return normalized string
*/
public static function normalize($str, $sep = '-')
{
return strtolower(preg_replace(array('/[^a-zA-Z0-9\_ \-]/', '/\s+/',), array('', $sep), strval($str)));
}
/**
* Humanizes an underscored string
*
* <code>
* echo Inflector::humanize('this_is_an_example');
* > This is an example
* </code>
* @param string $str string to humanize (underscored)
* @return string humanized string
*/
public static function humanize($str)
{
return ucfirst(strtolower(preg_replace('/_/', ' ', preg_replace('/_id$/', '', strval($str)))));
}
/**
* Titleizes an underscored string
*
* <code>
* echo Inflector::titleize('this_is_an_example');
* > This Is An Example
* </code>
* @param string $str string to titleize (underscored)
* @return string titleized string
*/
public static function titleize($str)
{
return ucwords(static::humanize(static::underscore($str)));
}
/**
* Creates a table name from a class name
*
* <code>
* echo Inflector::tableize('ExampleWord');
* > example_words
* </code>
* @param string $str string to tableize (underscored)
* @return string humanized string
*/
public static function tableize($str)
{
return static::pluralize(static::underscore($str));
}
/**
* Creates a class name from a table name
*
* <code>
* echo Inflector::classify('example_words');
* > ExampleWord
* </code>
* @param string $str string to classify (camel-cased, pluralized)
* @return string classified string
*/
public static function classify($str)
{
return static::camelize(static::singularize(preg_replace('/.*\./', '', $str)));
}
/**
* Camelizes a string
*
* <code>
* echo Inflector::camelize('This is an example');
* > ThisIsAnExample
* </code>
* @param string $str string to camelize
* @param boolean $uc_first uppercase first letter
* @return camelized string
*/
public static function camelize($str, $uc_first = true)
{
$base = str_replace(' ', '', ucwords(str_replace('_', ' ', strval($str))));
return !$uc_first ? strtolower(substr($base, 0, 1)) . substr($base, 1) : $base;
}
/**
* Underscores a camelized string
*
* <code>
* echo Inflector::underscore('thisIsAnExample');
* > this_is_an_example
* </code>
* @param string $str string to underscore (camelized)
* @return string underscored string
*/
public static function underscore($str)
{
$str = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\\1_\\2', strval($str));
$str = preg_replace('/([a-z\d])([A-Z])/', '\\1_\\2', $str);
$str = str_replace('-', '_', $str);
return strtolower($str);
}
/**
* Dasherizes a string
*
* <code>
* echo Inflector::dasherize('this_is_an_example');
* > this-is-an-example
* </code>
* @param string $str string to dasherize
* @return dasherized string
*/
public static function dasherize($str)
{
return str_replace('_', '-', strval($str));
}
/**
* Ordinalizes a number
*
* <code>
* echo Inflector::ordinalize(10);
* > 10th
* </code>
* @param integer $number number
* @return string ordinalized number
*/
public static function ordinalize($number)
{
if (in_array(($number % 100), array(11, 12, 13))) {
return $number . 'th';
} else {
$mod = $number % 10;
if ($mod == 1) {
return $number . 'st';
} elseif ($mod == 2) {
return $number . 'nd';
} elseif ($mod == 3) {
return $number . 'rd';
} else {
return $number . 'th';
}
}
}
/**
* Creates a foreign key name from a class name
*
* <code>
* echo Inflector::foreignKey('Example');
* > example_id
* </code>
* @param string $str string to make foreign key for
* @param boolean $underscore use underscore delimiter
* @return string foreign key string
*/
public static function foreignKey($str, $underscore = true)
{
return static::underscore($str) . ($underscore ? '_id' : 'id');
}
}
// include default inflections
require_once __DIR__ . '/inflections.php';
diff --git a/src/Starlight/Component/Inflector/inflections.php b/src/Starlight/Component/Inflector/inflections.php
index d38898c..75a73ca 100644
--- a/src/Starlight/Component/Inflector/inflections.php
+++ b/src/Starlight/Component/Inflector/inflections.php
@@ -1,65 +1,65 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Inflector;
Inflector::plural('/$/', 's');
Inflector::plural('/s$/i', 's');
Inflector::plural('/(ax|test)is$/i', '\1es');
Inflector::plural('/(octop|vir)us$/i', '\1i');
Inflector::plural('/(alias|status)$/i', '\1es');
Inflector::plural('/(bu)s$/i', '\1ses');
Inflector::plural('/(buffal|tomat)o$/i', '\1oes');
Inflector::plural('/([ti])um$/i', '\1a');
Inflector::plural('/sis$/i', 'ses');
Inflector::plural('/(?:([^f])fe|([lr])f)$/i', '\1\2ves');
Inflector::plural('/(hive)$/i', '\1s');
Inflector::plural('/([^aeiouy]|qu)y$/i', '\1ies');
Inflector::plural('/(x|ch|ss|sh)$/i', '\1es');
Inflector::plural('/(matr|vert|ind)(?:ix|ex)$/i', '\1ices');
Inflector::plural('/([m|l])ouse$/i', '\1ice');
Inflector::plural('/^(ox)$/i', '\1en');
Inflector::plural('/(quiz)$/i', '\1zes');
Inflector::singular('/s$/i', '');
Inflector::singular('/(n)ews$/i', '\1ews');
Inflector::singular('/([ti])a$/i', '\1um');
Inflector::singular('/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i', '\1\2sis');
Inflector::singular('/(^analy)ses$/i', '\1sis');
Inflector::singular('/([^f])ves$/i', '\1fe');
Inflector::singular('/(hive)s$/i', '\1');
Inflector::singular('/(tive)s$/i', '\1');
Inflector::singular('/([lr])ves$/i', '\1f');
Inflector::singular('/([^aeiouy]|qu)ies$/i', '\1y');
Inflector::singular('/(s)eries$/i', '\1eries');
Inflector::singular('/(m)ovies$/i', '\1ovie');
Inflector::singular('/(x|ch|ss|sh)es$/i', '\1');
Inflector::singular('/([m|l])ice$/i', '\1ouse');
Inflector::singular('/(bus)es$/i', '\1');
Inflector::singular('/(o)es$/i', '\1');
Inflector::singular('/(shoe)s$/i', '\1');
Inflector::singular('/(cris|ax|test)es$/i', '\1is');
Inflector::singular('/(octop|vir)i$/i', '\1us');
Inflector::singular('/(alias|status)es$/i', '\1');
Inflector::singular('/^(ox)en/i', '\1');
Inflector::singular('/(vert|ind)ices$/i', '\1ex');
Inflector::singular('/(matr)ices$/i', '\1ix');
Inflector::singular('/(quiz)zes$/i', '\1');
Inflector::singular('/(database)s$/i', '\1');
Inflector::irregular('person', 'people');
Inflector::irregular('man', 'men');
Inflector::irregular('child', 'children');
Inflector::irregular('sex', 'sexes');
Inflector::irregular('move', 'moves');
Inflector::irregular('cow', 'cattle');
Inflector::uncountable(array('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans'));
diff --git a/src/Starlight/Component/Routing/CompilableInterface.php b/src/Starlight/Component/Routing/CompilableInterface.php
index 1e91719..841f68d 100755
--- a/src/Starlight/Component/Routing/CompilableInterface.php
+++ b/src/Starlight/Component/Routing/CompilableInterface.php
@@ -1,23 +1,23 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
/**
* Compilable interface
*/
interface CompilableInterface
{
/**
* Compile
*/
public function compile();
}
diff --git a/src/Starlight/Component/Routing/ResourceRoute.php b/src/Starlight/Component/Routing/ResourceRoute.php
index 161f1fe..92c0bd6 100755
--- a/src/Starlight/Component/Routing/ResourceRoute.php
+++ b/src/Starlight/Component/Routing/ResourceRoute.php
@@ -1,327 +1,327 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Inflector\Inflector;
/**
* ResourceRoute
*/
class ResourceRoute implements CompilableInterface
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%p', 'verb' => 'get', 'url' => '(.:format)'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'create' => array('name' => '%p', 'verb' => 'post', 'url' => '(.:format)'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id(.:format)'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action(.:format)'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id(.:format)'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id(.:format)'),
);
/**
* Default path names
* @var array
*/
protected static $resource_names = array(
'add' => 'add',
'edit' => 'edit',
'delete' => 'delete',
);
public $resource;
public $controller;
public $except;
public $only;
public $constraints;
public $singular;
public $plural;
public $path_names;
public $module;
public $path_prefix;
public $name_prefix;
public $member = array();
public $collection = array();
public $map_member_collection_scope = null;
/**
* Constructor
* @param string $resource resource name
* @param array $options options hash
*/
public function __construct($resource = null, array $options = array())
{
if ($resource !== null) {
$this->resource = $resource;
$this->controller = $this->plural = Inflector::pluralize($this->resource);
$this->singular = Inflector::singularize($this->controller);
if (count($options) > 0) {
foreach ($options as $key => $value) {
$this->$key($value);
}
}
}
}
/**
* Set except routes from $resources_map
* @param array $except except resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function except(array $except)
{
$this->only = null;
$this->except = $except;
return $this;
}
/**
* Set only routes from $resources_map
* @param array $only only resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function only(array $only)
{
$this->except = null;
$this->only = $only;
return $this;
}
/**
* Set controller
* @param string $controller controller name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function controller($controller)
{
$this->controller = $controller;
return $this;
}
/**
* Set contraints
* @param mixed $constraints constraints
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set name for route paths
* @param string $name path name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function name($name)
{
$single = explode(' ', strtolower(Inflector::humanize($name)));
$plural = $single;
$count = count($single);
$single[$count - 1] = Inflector::singularize($single[$count - 1]);
$plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
$this->singular = implode('_', $single);
$this->plural = implode('_', $plural);
return $this;
}
/**
* Set path names for special routes
* @param array $names path name overrides
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function pathNames(array $names)
{
$this->path_names = $names;
return $this;
}
/**
* Set module/namespace for resource
* @param string $module module/namespace name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Set member routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function member(\Closure $callback)
{
$this->map_member_collection_scope = 'member';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set collection routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function collection(\Closure $callback)
{
$this->map_member_collection_scope = 'collection';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set an extra route which responds to GET requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function get($path, $options = array())
{
return $this->mapMethod('get', $path, $options);
}
/**
* Set an extra route which responds to PUT requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function put($path, $options = array())
{
return $this->mapMethod('put', $path, $options);
}
/**
* Set an extra route which responds to POST requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function post($path, $options = array())
{
return $this->mapMethod('post', $path, $options);
}
/**
* Set an extra route which responds to DELETE requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function delete($path, $options = array())
{
return $this->mapMethod('delete', $path, $options);
}
/**
* Map extra routes through a common interface
* @param string $method HTTP method
* @param string $path path
* @param array $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
protected function mapMethod($method, $path, $options = array())
{
$on = isset($options['on']) ? $options['on'] : $this->map_member_collection_scope;
if (!$on || ($on != 'member' && $on != 'collection')) {
throw new \InvalidArgumentException('You must pass a valid "on" option (collection/method) to ' . $method);
}
array_push($this->$on, array($path, strtoupper($method)));
return $this;
}
/**
* Compiles this resource route into individual \Starlight\Component\Routing\Route
* @return array array of \Starlight\Component\Routing\Route routes
*/
public function compile()
{
$generators = static::$resources_map;
if ($this->except) {
$generators = array_diff_key($generators, array_fill_keys($this->except, true));
} elseif ($this->only) {
$generators = array_intersect_key($generators, array_fill_keys($this->only, true));
}
if (is_array($this->path_names)) {
$this->path_names += static::$resource_names;
} else {
$this->path_names = static::$resource_names;
}
if ($this->module) {
$this->controller = $this->module . '\\' . $this->controller;
}
if (count($this->member) > 0) {
foreach ($this->member as $member) {
list($name, $verb) = $member;
$generators[$name] = array('name' => $name . '_%s', 'verb' => $verb, 'url' => '/:id/' . $name . '(.:format)');
}
}
if (count($this->collection) > 0) {
foreach ($this->collection as $collection) {
list($name, $verb) = $collection;
$generators[$name] = array('name' => $name . '_%p', 'verb' => $verb, 'url' => '/' . $name . '(.:format)');
}
}
$routes = array();
foreach ($generators as $action => $parts) {
$path = $parts['url'];
if (strpos($path, ':action') !== false) {
$path = str_replace(':action', $this->path_names[$action], $path);
}
$r = new Route($this->path_prefix . '/' . $this->resource . $path, $this->controller . '::' . $action);
$r->methods(array($parts['verb']));
$name = str_replace('%s', $this->name_prefix . $this->singular, $parts['name']);
$name = str_replace('%p', $this->name_prefix . $this->plural, $name);
$r->name($name);
if ($this->constraints) {
$r->constraints($this->constraints);
}
$routes[] = $r->compile();
}
return $routes;
}
}
diff --git a/src/Starlight/Component/Routing/RoutableInterface.php b/src/Starlight/Component/Routing/RoutableInterface.php
index b879653..794f27b 100755
--- a/src/Starlight/Component/Routing/RoutableInterface.php
+++ b/src/Starlight/Component/Routing/RoutableInterface.php
@@ -1,25 +1,25 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Routable interface
*/
interface RoutableInterface
{
/**
* Match a request
* @param \Starlight\Component\Http\Request $request current request
*/
public function match(Request $request);
}
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index 8036474..7c31529 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,230 +1,213 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements RoutableInterface, CompilableInterface
{
/**
* Base default values for route parameters
* @var array
*/
protected static $base_parameter_defaults = array(
'controller' => null,
'action' => null,
'id' => null,
);
public $path;
public $endpoint;
public $regex;
public $parameters = array();
public $constraints;
public $methods = array();
public $name;
public $module;
public $path_prefix;
public $name_prefix;
/**
* Constructor
* @param string $path url path
* @param mixed $endpoint route endpoint - "controller::action" or a valid callback
*/
public function __construct($path, $endpoint)
{
$this->path = static::normalize($path);
$this->endpoint = $endpoint;
}
/**
* Set route parameter defaults
* @param array $defaults default values hash
* @return \Starlight\Component\Routing\Route this instance
*/
public function defaults(array $defaults)
{
foreach ($defaults as $key => $value) {
if (!isset($this->parameters[$key]) || trim($this->parameters[$key]) == '') {
$this->parameters[$key] = $value;
}
}
return $this;
}
/**
* Set route constraints
* @param mixed $constraints constraints (hash or \Closure)
* @return \Starlight\Component\Routing\Route this instance
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set HTTP methods/verbs route should respond to
* @param array $methods HTTP methods
* @return \Starlight\Component\Routing\Route this instance
*/
public function methods($methods)
{
if (!is_array($methods)) {
$methods = array($methods);
}
$this->methods = $methods;
return $this;
}
/**
* Set route name for generated helpers
* @param string $name route name
* @return \Starlight\Component\Routing\Route this instance
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
* Set module/namespace for the controller
* @param string $module module/namespace
* @return \Starlight\Component\Routing\Route this instance
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Compiles the route
* @return \Starlight\Component\Routing\Route this compiled instance
*/
public function compile()
{
$parser = new RouteParser();
$regex_constraints = $other_constraints = array();
if (is_array($this->constraints)) {
foreach ($this->constraints as $k => $c) {
if (!is_callable($c)) {
$regex_constraints[$k] = $c;
} else {
$other_constraints[] = $c;
}
}
}
if ($this->path_prefix) {
$this->path = $this->path_prefix . $this->path;
}
$this->regex = $parser->parse($this->path, $regex_constraints);
$this->parameters = array_merge(static::$base_parameter_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
$this->constraints = $other_constraints;
// get endpoint if string:
if (is_string($this->endpoint)) {
if (strpos($this->endpoint, '::') !== false) {
// apply module:
if ($this->module) {
$this->endpoint = $this->module . '\\' . $this->endpoint;
}
list($this->parameters['controller'], $this->parameters['action']) = explode('::', $this->endpoint);
}
} elseif (!is_callable($this->endpoint)) {
// should be a callback
throw new \InvalidArgumentException('Route endpoint is invalid');
}
// set name/prefix if available:
if ($this->name && $this->name_prefix) {
$this->name = $this->name_prefix . $this->name;
}
return $this;
}
/**
* Match a request
* @param \Starlight\Component\Http\Request $request current request
* @return boolean route matches request
*/
public function match(Request $request)
{
$is_match = preg_match($this->regex, $request->getBaseUri(), $matches);
if ($is_match) {
- if (!in_array($request->getMethod(), $this->methods)) {
+ if (count($this->methods) > 0 && !in_array($request->getMethod(), $this->methods)) {
return false;
}
foreach ($this->constraints as $c) {
if (!call_user_func($c, $request)) {
return false;
}
}
foreach ($matches as $k => $v) {
if (array_key_exists($k, $this->parameters)) {
$this->parameters[$k] = $v;
}
}
}
return $is_match;
}
- /**
- *
- */
- public function dispatch(Request $request)
- {
- $p = array_filter($this->parameters, function($var){ return trim($var) != ''; });
- unset($p['controller'], $p['action']);
-
- if (is_callable($this->endpoint)) {
- call_user_func_array($this->endpoint, array_merge(array($request), array_values($p)));
- return true;
- } else {
- // controller pattern
-
- }
- }
-
/**
* Normalizes path - removes trailing slashes and prepends single slash
* @param string $path original path
* @return string normalized path
*/
protected function normalize($path)
{
$path = trim($path, '/');
$path = '/' . $path;
return $path;
}
}
diff --git a/src/Starlight/Component/Routing/RouteParser.php b/src/Starlight/Component/Routing/RouteParser.php
index 2fe8107..5d2e9a8 100755
--- a/src/Starlight/Component/Routing/RouteParser.php
+++ b/src/Starlight/Component/Routing/RouteParser.php
@@ -1,151 +1,151 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
/**
* RouteParser
*/
class RouteParser
{
/**
* URL path separators
* '\' and '.'
* @var string
*/
protected static $default_separators = array('/', '.');
public $path;
public $regex;
public $requirements;
public $separators;
public $names = array();
protected $quoted_separators;
/**
* Parse a route path into a regular expression
* @param string $path original url path
* @param array $requirements requirements hash
* @param array $separators path separators
* @return string regular expression
*/
public function parse($path, array $requirements = array(), array $separators = array())
{
$this->regex = '';
$this->path = trim($path);
$this->requirements = $requirements;
$this->separators = count($separators) > 0 ? $separators : static::$default_separators;
$this->quoted_separators = $this->quote(implode('', $this->separators));
$this->regex = $this->reduce();
return $this->regex;
}
/**
* Reduce the path into the regular expression
* @return string reduced path
*/
protected function reduce()
{
$balance = 0;
$prev = $next = $literal = '';
$length = strlen($this->path);
$segments = array();
for ($i=0; $i<$length; $i++)
{
$curr = $this->path[$i];
$next = isset($this->path[$i + 1]) ? $this->path[$i + 1] : '';
$prev = ($i > 0) ? $this->path[$i - 1] : '';
if ($curr == '\\') {
if (preg_match('/[\(|\)|\:|\*]/', $next)) {
// escaped special character
$i++;
$literal .= $next;
} else {
// literal
$literal .= $curr;
}
} else {
if (preg_match('/[\(|\)]/', $curr)) {
// parenthesis
if ($literal != '') {
$segments[] = $this->quote($literal);
$literal = '';
}
if ($curr == '(') {
$balance += 1;
$segments[] = '(?:';
} else {
$balance -= 1;
$segments[] = ')?';
}
} elseif (preg_match('/[\:|\*]/', $curr)) {
// identifier
preg_match('/(\:|\*){1}[a-z\_]+/i', $this->path, $matches, PREG_OFFSET_CAPTURE, $i);
if (isset($matches[0]) && count($matches[0]) > 0) {
if ($literal != '') {
$segments[] = $this->quote($literal);
$literal = '';
}
$id = substr($matches[0][0], 0, 1);
$key = substr($matches[0][0], 1);
if (isset($this->requirements[$key])) {
// custom requirements
$regex = $this->requirements[$key];
} elseif ($id == '*') {
// glob
$regex = '.+';
} else {
// standard segments
$regex = '[^' . $this->quoted_separators . ']+';
}
$segments[] = '(?<' . $key . '>' . $regex . ')';
$this->names[] = $key;
$i += strlen($key);
} else {
// invalid identifier:
$literal .= $curr;
}
} else {
// just normal text
$literal .= $curr;
}
}
}
if ($literal != '') {
$segments[] = $this->quote($literal);
}
if ($balance != 0) {
throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
}
return '/\A' . implode('', $segments) . '\Z/';
}
/**
* Quote string for preg parsing
* @param string $string string to quote
* @return string quoted string
*/
protected function quote($string)
{
return preg_quote($string, '/');
}
}
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index 8dbacf0..18af40b 100755
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,395 +1,385 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
use Starlight\Component\Inflector\Inflector;
/**
* Router
*/
class Router implements CompilableInterface
{
protected $routes = array();
protected $current = array();
protected $current_type = null;
protected $compiled = array();
protected $has_compiled = false;
protected $scopes = array();
/**
* Draw routes - router gateway
* @param \Closure $callback callback
* @return \Starlight\Component\Routing\Router this instance
*/
public function draw(\Closure $callback)
{
// TODO: check for cached version before redrawing these
$callback($this);
return $this;
}
/**
* Maps a single route
* @param string $path url path
* @param mixed $endpoint controller::action pair or callback
* @return \Starlight\Component\Routing\Route route
*/
public function map($path, $endpoint)
{
if ($this->current_type == 'resource') {
throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context.');
}
if (!preg_match('/\(\.:format\)$/', $path)) {
// auto append format option to path:
$path .= '(.:format)';
}
$this->routes[] = new Route($path, $endpoint);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'route';
$this->applyScopes();
array_pop($this->current);
$this->current_type = '';
return $this->routes[count($this->routes) - 1];
}
/**
* Maps RESTful resources routes
*/
public function resources()
{
$args = func_get_args();
$count = count($args);
$callback = null;
$options = array();
if (is_callable($args[$count - 1])) {
$callback = array_pop($args);
$count--;
}
if (is_array($args[$count - 1])) {
$options = array_pop($args);
$count--;
}
// map each resource separately (if multiple)
foreach ($args as $resource) {
if ($resource == Inflector::pluralize($resource)) {
$klass = 'Starlight\Component\Routing\ResourceRoute';
} else {
$klass = 'Starlight\Component\Routing\SingularResourceRoute';
}
$this->routes[] = new $klass($resource, $options);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'resource';
$route = $this->routes[count($this->routes) - 1];
$this->applyScopes();
if ($callback) {
$callback($this, $route);
}
array_pop($this->current);
$this->current_type = 'route';
}
return $route;
}
/**
* Maps singular RESTful resource
*/
public function resource()
{
return call_user_func_array(array($this, 'resources'), func_get_args());
}
/**
*
*/
public function redirect($path)
{
// TOOD: handle inline redirection
if (is_string($path)) {
return function() use ($path) {
return $path;
};
} else {
// already a callback, need to lazy evaluate later:
return $path;
}
}
/**
* Scope routes
* @param array $scopes scopes to apply
* @param \Closure $callback callback
*/
public function scope(array $scopes, \Closure $callback)
{
$this->addScopes($scopes);
$callback($this);
$this->removeScopes($scopes);
}
/**
* Compile all routes
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
/**
*
*/
public function match(Request $request)
{
foreach ($this->compiled as $r) {
if ($r->match($request)) {
return $r;
}
}
-
- // nothing matched:
- }
-
- /**
- *
- */
- public function dispatch(Route $endpoint, Request $request)
- {
- return $endpoint->dispatch($request);
}
/**
* Pretty version of routes
* @return string nice string
*/
public function __toString()
{
$parts = array();
$mn = $mv = $mp = 0;
foreach ($this->compiled as $r) {
$p = array(
'name' => $r->name,
'verb' => strtoupper(implode(',', $r->methods)),
'path' => $r->path,
'endp' => is_callable($r->endpoint) ? '{callback}' : $r->endpoint,
);
if (strlen($p['name']) > $mn) {
$mn = strlen($p['name']);
}
if (strlen($p['verb']) > $mv) {
$mv = strlen($p['verb']);
}
if (strlen($p['path']) > $mp) {
$mp = strlen($p['path']);
}
$parts[] = $p;
}
$rc = '<pre>';
foreach ($parts as $p) {
$rc .= sprintf("%" . $mn . "s %-" . $mv . "s %-" . $mp . "s %s\n", $p['name'], $p['verb'], $p['path'], $p['endp']);
}
$rc .= '</pre>';
return $rc;
}
/**
* Apply current scopes to currently scoped routes
*/
protected function applyScopes()
{
$count = count($this->current);
$current = $this->current[$count - 1];
$previous = isset($this->current[$count - 2]) ? $this->routes[$this->current[$count - 2]] : null;
$this->routes[$current] = $this->applyScope($this->routes[$current], $previous);
}
/**
* Apply scopes to single route
* @param mixed $route resource or route to scope
* @param \Starlight\Component\Routing\ResourceRoute $nested current parent route (if present)
* @return mixed resource or route which was scoped
*/
protected function applyScope($route, $nested = null)
{
// nested resource
if ($nested) {
$route->path_prefix .= $nested->path_prefix . '/' . $nested->plural . '/:' . $nested->singular . '_id';
$route->name_prefix .= $nested->name_prefix . $nested->singular . '_';
}
// constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
$constraints = array_merge($constraints, is_array($c) ? $c : (array) $c);
}
$route->constraints($constraints);
}
// name
if (isset($this->scopes['name'])) {
$count = count($this->scopes['name']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
} else {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
}
// module
if (isset($this->scopes['module'])) {
$route->module(implode('\\', $this->scopes['module']));
}
// path
if (isset($this->scopes['path'])) {
$count = count($this->scopes['path']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
} else {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
}
if ($this->current_type == 'route') {
// route only cases
// HTTP methods/verbs
if (isset($this->scopes['methods'])) {
// only consider the last on the stack:
$route->methods($this->scopes['methods'][count($this->scopes['methods']) - 1]);
}
// parameter defaults
if (isset($this->scopes['defaults'])) {
$defaults = array();
foreach ($this->scopes['defaults'] as $d) {
$defaults = array_merge($defaults, $d);
}
$route->defaults($d);
}
} elseif ($this->current_type == 'resource') {
// resource only cases
// except
if (isset($this->scopes['except'])) {
// only consider the last on the stack:
$route->except($this->scopes['except'][count($this->scopes['except']) - 1]);
}
// only
if (isset($this->scopes['only'])) {
// only consider the last on the stack:
$route->only($this->scopes['only'][count($this->scopes['only']) - 1]);
}
// path_names
if (isset($this->scopes['path_names'])) {
// only consider the last on the stack:
$route->pathNames($this->scopes['path_names'][count($this->scopes['path_names']) - 1]);
}
}
return $route;
}
/**
* Add scopes to parse tree
* @param array $scopes scopes to add
*/
protected function addScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->addScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
$this->scopes[$scope][] = $options;
} else {
$this->scopes[$scope] = array($options);
}
}
}
/**
* Remove scopes from parse tree
* @param array $scopes scopes to remove
*/
protected function removeScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->removeScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
if (($position = array_search($options, $this->scopes[$scope])) !== false) {
unset($this->scopes[$scope][$position]);
if (count($this->scopes[$scope]) == 0) {
unset($this->scopes[$scope]);
}
}
}
}
}
}
diff --git a/src/Starlight/Component/Routing/SingularResourceRoute.php b/src/Starlight/Component/Routing/SingularResourceRoute.php
index c33e679..e6033d3 100644
--- a/src/Starlight/Component/Routing/SingularResourceRoute.php
+++ b/src/Starlight/Component/Routing/SingularResourceRoute.php
@@ -1,32 +1,32 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\Routing;
/**
* Singular resource
*/
class SingularResourceRoute extends ResourceRoute
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%s', 'verb' => 'get', 'url' => '(.:format)'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'create' => array('name' => '%s', 'verb' => 'post', 'url' => '(.:format)'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '(.:format)'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '(.:format)'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '(.:format)'),
);
}
diff --git a/src/Starlight/Component/StdLib/StorageBucket.php b/src/Starlight/Component/StdLib/StorageBucket.php
index cfb29e8..4a4a2cc 100755
--- a/src/Starlight/Component/StdLib/StorageBucket.php
+++ b/src/Starlight/Component/StdLib/StorageBucket.php
@@ -1,157 +1,157 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\StdLib;
/**
* Generic storage bucket
*/
class StorageBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Bucket contents
* @var array
*/
protected $contents;
/**
* Constructor
* @param array $contents contents
*/
public function __construct(array $contents = array())
{
$this->replace($contents);
}
/**
* Returns the contents
* @return array contents
*/
public function all()
{
return $this->contents;
}
/**
* Returns the contents keys
* @return array contents keys
*/
public function keys()
{
return array_keys($this->contents);
}
/**
* Replaces the current contents with a new set
* @param array $contents contents
* @return StorageBucket this instance
*/
public function replace(array $contents = array())
{
$this->contents = $contents;
return $this;
}
/**
* Adds contents
* @param array $contents contents
* @return StorageBucket this instance
*/
public function add(array $contents = array())
{
$this->contents = array_replace($this->contents, $contents);
return $this;
}
/**
* Returns content by name
* @param string $key The key
* @param mixed $default default value
* @return mixed value
*/
public function get($key, $default = null)
{
return array_key_exists($key, $this->contents) ? $this->contents[$key] : $default;
}
/**
* Sets content by name
* @param string $key The key
* @param mixed $value value
* @return StorageBucket this instance
*/
public function set($key, $value)
{
$this->contents[$key] = $value;
return $this;
}
/**
* Returns true if the content is defined
* @param string $key The key
* @return boolean true if the contents exists, false otherwise
*/
public function has($key)
{
return array_key_exists($key, $this->contents);
}
/**
* Deletes a content
* @param string $key key
* @return StorageBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->contents[$key]);
}
return $this;
}
// --------------------------
// ArrayAccess implementation
// --------------------------
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
public function offsetUnset($offset)
{
return $this->delete($offset);
}
// --------------------------------
// IteratorAggregate implementation
// --------------------------------
public function getIterator()
{
return new \ArrayIterator($this->all());
}
}
diff --git a/src/Starlight/Framework/Support/UniversalClassLoader.php b/src/Starlight/Framework/Support/UniversalClassLoader.php
index 51b7aa2..9037121 100755
--- a/src/Starlight/Framework/Support/UniversalClassLoader.php
+++ b/src/Starlight/Framework/Support/UniversalClassLoader.php
@@ -1,150 +1,150 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Framework\Support;
/**
* UniversalClassLoader implements a "universal" autoloader for PHP 5.3.
*
* It is able to load classes that use either:
*
* * The technical interoperability standards for PHP 5.3 namespaces and
* class names (http://groups.google.com/group/php-standards/web/psr-0-final-proposal);
*
* * The PEAR naming convention for classes (http://pear.php.net/).
*
* Classes from a sub-namespace or a sub-hierarchy of PEAR classes can be
* looked for in a list of locations to ease the vendoring of a sub-set of
* classes for large projects.
*
* Example usage:
*
* $loader = new UniversalClassLoader();
*
* // register classes with namespaces
* $loader->registerNamespaces(array(
* 'Starlight\Support' => __DIR__.'/component',
* 'Starlight' => __DIR__.'/framework',
* ));
*
* // register a library using the PEAR naming convention
* $loader->registerPrefixes(array(
* 'Swift_' => __DIR__.'/Swift',
* ));
*
* // activate the autoloader
* $loader->register();
*
* In this example, if you try to use a class in the Starlight\Support
* namespace or one of its children (Starlight\Support\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*/
class UniversalClassLoader
{
/**
* Current namespaces
* @var array
*/
protected $namespaces = array();
/**
* Current prefixes
* @var array
*/
protected $prefixes = array();
/**
* Get current namespaces
*
* @return array current namespaces
*/
public function getNamespaces()
{
return $this->namespaces;
}
/**
* Get current prefixes
*
* @return array current prefixes
*/
public function getPrefixes()
{
return $this->prefixes;
}
/**
* Registers an array of namespaces
*
* @param array $namespaces An array of namespaces (namespaces as keys and locations as values)
*/
public function registerNamespaces(array $namespaces)
{
$this->namespaces = array_merge($this->namespaces, $namespaces);
}
/**
* Registers a namespace.
*
* @param string $namespace The namespace
* @param string $path The location of the namespace
*/
public function registerNamespace($namespace, $path)
{
$this->namespaces[$namespace] = $path;
}
/**
* Register with the php autoload subsystem
*/
public function register()
{
spl_autoload_register(array($this, 'load'));
}
/**
* Loads the given class/interface
*
* @param string $class fully-qualified class name to load
*/
public function load($class)
{
if (($pos = stripos($class, '\\')) !== false) {
// namespace
$namespace = substr($class, 0, $pos);
foreach ($this->namespaces as $ns => $dir) {
if (strpos($namespace, $ns) === 0) {
$class = substr($class, $pos + 1);
$file = $dir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
if (file_exists($file)) {
require_once $file;
}
return;
}
}
} else {
// PEAR style
foreach ($this->prefixes as $prefix => $dir) {
if (strpos($class, $prefix) === 0) {
$file = $dir . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
if (file_exists($file)) {
require_once $file;
}
return;
}
}
}
}
};
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index d26ee6e..fc07e5f 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,9 +1,9 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
\ No newline at end of file
diff --git a/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php b/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php
index 06b53af..f3d2c94 100755
--- a/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php
+++ b/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php
@@ -1,136 +1,136 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\EventDispatcher;
use Starlight\Component\EventDispatcher\EventDispatcher;
/**
*/
class EventDispatcherTest extends \PHPUnit_Framework_TestCase
{
public function testConnectAndDisconnect()
{
$dispatcher = new EventDispatcher();
$dispatcher->connect('bar', 'listenToBar');
$this->assertEquals(array('listenToBar'), $dispatcher->getListeners('bar'), '->connect() connects a listener to an event name');
$dispatcher->connect('bar', 'listenToBarBar');
$this->assertEquals(array('listenToBar', 'listenToBarBar'), $dispatcher->getListeners('bar'), '->connect() can connect several listeners for the same event name');
$dispatcher->connect('barbar', 'listenToBarBar');
$dispatcher->disconnect('bar');
$this->assertEquals(array(), $dispatcher->getListeners('bar'), '->disconnect() without a listener disconnects all listeners of for an event name');
$this->assertEquals(array('listenToBarBar'), $dispatcher->getListeners('barbar'), '->disconnect() without a listener disconnects all listeners of for an event name');
}
public function testGetHasListeners()
{
$dispatcher = new EventDispatcher();
$this->assertFalse($dispatcher->hasListeners('foo'), '->hasListeners() returns false if the event has no listener');
$dispatcher->connect('foo', 'listenToFoo');
$this->assertEquals(true, $dispatcher->hasListeners('foo'), '->hasListeners() returns true if the event has some listeners');
$dispatcher->disconnect('foo', 'listenToFoo');
$this->assertFalse($dispatcher->hasListeners('foo'), '->hasListeners() returns false if the event has no listener');
$dispatcher->connect('bar', 'listenToBar');
$this->assertEquals(array('listenToBar'), $dispatcher->getListeners('bar'), '->getListeners() returns an array of listeners connected to the given event name');
$this->assertEquals(array(), $dispatcher->getListeners('foobar'), '->getListeners() returns an empty array if no listener are connected to the given event name');
}
public function testNotify()
{
$listener = new TestListener();
$dispatcher = new EventDispatcher();
$dispatcher->connect('foo', array($listener, 'listenToFoo'));
$dispatcher->connect('foo', array($listener, 'listenToFooBis'));
$e = $dispatcher->notify($event = new Event(new \stdClass(), 'foo'));
$this->assertEquals('listenToFoolistenToFooBis', $listener->getValue(), '->notify() notifies all registered listeners in order');
$listener->reset();
$dispatcher = new EventDispatcher();
$dispatcher->connect('foo', array($listener, 'listenToFooBis'));
$dispatcher->connect('foo', array($listener, 'listenToFoo'));
$dispatcher->notify(new Event(new \stdClass(), 'foo'));
$this->assertEquals('listenToFooBislistenToFoo', $listener->getValue(), '->notify() notifies all registered listeners in order');
}
public function testNotifyUntil()
{
$listener = new TestListener();
$dispatcher = new EventDispatcher();
$dispatcher->connect('foo', array($listener, 'listenToFoo'));
$dispatcher->connect('foo', array($listener, 'listenToFooBis'));
$dispatcher->notifyUntil($event = new Event(new \stdClass(), 'foo'));
$this->assertEquals('listenToFoolistenToFooBis', $listener->getValue(), '->notifyUntil() notifies all registered listeners in order and stops when the event is processed');
$listener->reset();
$dispatcher = new EventDispatcher();
$dispatcher->connect('foo', array($listener, 'listenToFooBis'));
$dispatcher->connect('foo', array($listener, 'listenToFoo'));
$dispatcher->notifyUntil($event = new Event(new \stdClass(), 'foo'));
$this->assertEquals('listenToFooBis', $listener->getValue(), '->notifyUntil() notifies all registered listeners in order and stops when the event is processed');
}
public function testFilter()
{
$listener = new TestListener();
$dispatcher = new EventDispatcher();
$dispatcher->connect('foo', array($listener, 'filterFoo'));
$dispatcher->connect('foo', array($listener, 'filterFooBis'));
$ret = $dispatcher->filter($event = new Event(new \stdClass(), 'foo'), 'foo');
$this->assertEquals('-*foo*-', $ret, '->filter() returns the filtered value');
$listener->reset();
$dispatcher = new EventDispatcher();
$dispatcher->connect('foo', array($listener, 'filterFooBis'));
$dispatcher->connect('foo', array($listener, 'filterFoo'));
$ret = $dispatcher->filter($event = new Event(new \stdClass(), 'foo'), 'foo');
$this->assertEquals('*-foo-*', $ret, '->filter() returns the filtered value');
}
}
class TestListener
{
protected $value = '';
function filterFoo(Event $event, $foo)
{
return "*$foo*";
}
function filterFooBis(Event $event, $foo)
{
return "-$foo-";
}
function listenToFoo(Event $event)
{
$this->value .= 'listenToFoo';
}
function listenToFooBis(Event $event)
{
$this->value .= 'listenToFooBis';
$event->setProcessed();
}
function getValue()
{
return $this->value;
}
function reset()
{
$this->value = '';
}
}
diff --git a/tests/Starlight/Component/EventDispatcher/EventTest.php b/tests/Starlight/Component/EventDispatcher/EventTest.php
index dad1f2a..51ab23c 100755
--- a/tests/Starlight/Component/EventDispatcher/EventTest.php
+++ b/tests/Starlight/Component/EventDispatcher/EventTest.php
@@ -1,68 +1,68 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Component\EventDispatcher;
use Starlight\Component\EventDispatcher\Event;
/**
*/
class EventTest extends \PHPUnit_Framework_TestCase
{
protected $subject;
protected $parameters;
public function testGetSubject()
{
$event = $this->createEvent();
$this->assertEquals($this->subject, $event->getSubject(), '->getSubject() returns the event subject');
}
public function testGetName()
{
$this->assertEquals('name', $this->createEvent()->getName(), '->getName() returns the event name');
}
public function testParameters()
{
$event = $this->createEvent();
$this->assertEquals($this->parameters, $event->all(), '->all() returns the event parameters');
$this->assertEquals('bar', $event->get('foo'), '->get() returns the value of a parameter');
$event->set('foo', 'foo');
$this->assertEquals('foo', $event->get('foo'), '->set() changes the value of a parameter');
$this->assertTrue($event->has('foo'), '->has() returns true if the parameter is defined');
$this->assertFalse($event->has('oof'), '->has() returns false if the parameter is not defined');
try {
$event->get('foobar');
$this->fail('->get() throws an \InvalidArgumentException exception when the parameter does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws an \InvalidArgumentException exception when the parameter does not exist');
$this->assertEquals('The event "name" doesn\'t have a "foobar" parameter', $e->getMessage(), '->get() throws an \InvalidArgumentException exception when the parameter does not exist');
}
$event = new Event($this->subject, 'name', $this->parameters);
}
public function testSetIsProcessed()
{
$event = $this->createEvent();
$this->assertFalse($event->isProcessed(), '->isProcessed() returns false by default');
$event->setProcessed();
$this->assertTrue($event->isProcessed(), '->isProcessed() returns true if the event has been processed');
}
protected function createEvent()
{
$this->subject = new \stdClass();
$this->parameters = array('foo' => 'bar');
return new Event($this->subject, 'name', $this->parameters);
}
}
diff --git a/tests/Starlight/Component/Http/CookieTest.php b/tests/Starlight/Component/Http/CookieTest.php
index 577fa1e..d894833 100644
--- a/tests/Starlight/Component/Http/CookieTest.php
+++ b/tests/Starlight/Component/Http/CookieTest.php
@@ -1,154 +1,154 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Http\Cookie;
use Starlight\Component\Http\Cookie;
/**
*/
class CookieTest extends \PHPUnit_Framework_TestCase
{
public function testConstructor()
{
$cookie = new Cookie('name', 'value', array(
'expires' => time(),
'http_only' => true,
));
$this->assertEquals($cookie->getName(), 'name');
$this->assertEquals($cookie->getValue(), 'value');
$this->assertTrue($cookie->getHttpOnly());
$this->assertFalse($cookie->getSecure());
}
public function testGetSetName()
{
$cookie = new Cookie('name', 'value');
$this->assertEquals($cookie->getName(), 'name');
try {
$cookie->setName("name\n");
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e);
}
try {
$cookie->setName("");
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e);
}
}
public function testGetSetValue()
{
$cookie = new Cookie('name', 'value');
$this->assertEquals($cookie->getValue(), 'value');
try {
$cookie->setValue("value\n");
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e);
}
}
public function testGetSetExpires()
{
$date = new \DateTime();
$cookie = new Cookie('name', 'value');
$cookie->setExpires($date);
$this->assertEquals($date->format('U'), $cookie->getExpires()->format('U'));
$cookie->setExpires($date->format('U'));
$this->assertEquals($date->format('U'), $cookie->getExpires()->format('U'));
$cookie->setExpires($date->format(DATE_RFC822));
$this->assertEquals($date->format('U'), $cookie->getExpires()->format('U'));
try {
$cookie->setExpires('this obviously is not a date');
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e);
}
}
public function testGetSetPath()
{
$cookie = new Cookie('name', 'value');
$cookie->setPath('/');
$this->assertEquals('/', $cookie->getPath());
}
public function testGetSetDomain()
{
$cookie = new Cookie('name', 'value');
$cookie->setDomain('example.com');
$this->assertEquals('example.com', $cookie->getDomain());
}
public function testGetSetSecure()
{
$cookie = new Cookie('name', 'value');
$cookie->setSecure(true);
$this->assertTrue($cookie->getSecure());
$cookie->setSecure(0);
$this->assertFalse($cookie->getSecure());
$cookie->setSecure('true');
$this->assertTrue($cookie->getSecure());
}
public function testGetSetHttpOnly()
{
$cookie = new Cookie('name', 'value');
$cookie->setHttpOnly(true);
$this->assertTrue($cookie->getHttpOnly());
$cookie->setHttpOnly(0);
$this->assertFalse($cookie->getHttpOnly());
$cookie->setHttpOnly('true');
$this->assertTrue($cookie->getHttpOnly());
}
public function testIsCleared()
{
$cookie = new Cookie('name', 'value');
$cookie->setExpires(new \DateTime('+2 days'));
$this->assertFalse($cookie->isCleared());
$cookie->setExpires(time() - 20);
$this->assertTrue($cookie->isCleared());
}
public function testToString()
{
$date = new \DateTime();
$cookie = new Cookie('name', 'value', array(
'expires' => $date,
'path' => '/path',
'domain' => 'example.com',
'secure' => true,
'http_only' => true,
));
$expected_value = 'name=value; expires=' . $date->format(DATE_COOKIE) . '; domain=example.com; path=/path; secure; httponly';
$this->assertEquals($expected_value, $cookie->toHeaderValue());
$this->assertEquals($expected_value, (string) $cookie);
}
}
diff --git a/tests/Starlight/Component/Http/HeaderBucketTest.php b/tests/Starlight/Component/Http/HeaderBucketTest.php
index 51583c1..2736abf 100755
--- a/tests/Starlight/Component/Http/HeaderBucketTest.php
+++ b/tests/Starlight/Component/Http/HeaderBucketTest.php
@@ -1,110 +1,110 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Http\HeaderBucket;
use Starlight\Component\Http\HeaderBucket;
/**
*/
class HeaderBucketTest extends \PHPUnit_Framework_TestCase
{
public function testHas()
{
$bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
$this->assertEquals(true, $bucket->has('foo'));
$this->assertEquals(true, $bucket->has('FoO'));
$this->assertEquals(false, $bucket->has('bizz'));
}
public function testGet()
{
$bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
$this->assertEquals('bar', $bucket->get('foo'), '->get return current value');
$this->assertEquals('bar', $bucket->get('FoO'), '->get key in case insensitive');
$this->assertEquals(array('bar'), $bucket->get('foo', 'nope', false), '->get return the value as array');
// defaults
$this->assertNull($bucket->get('none'), '->get unknown values returns null');
$this->assertEquals('default', $bucket->get('none', 'default'), '->get unknown values returns default');
$this->assertEquals(array('default'), $bucket->get('none', 'default', false), '->get unknown values returns default as array');
$bucket->set('foo', 'bor', false);
$this->assertEquals('bar', $bucket->get('foo'), '->get return first value');
$this->assertEquals(array('bar', 'bor'), $bucket->get('foo', 'nope', false), '->get return all values as array');
}
public function testContains()
{
$bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
$this->assertTrue($bucket->contains('foo', 'bar'), '->contains first value');
$this->assertTrue($bucket->contains('fuzz', 'bizz'), '->contains second value');
$this->assertFalse($bucket->contains('nope', 'nope'), '->contains unknown value');
$this->assertFalse($bucket->contains('foo', 'nope'), '->contains unknown value');
// Multiple values
$bucket->set('foo', 'bor', false);
$this->assertTrue($bucket->contains('foo', 'bar'), '->contains first value');
$this->assertTrue($bucket->contains('foo', 'bor'), '->contains second value');
$this->assertFalse($bucket->contains('foo', 'nope'), '->contains unknown value');
}
public function testDelete()
{
$bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
$bucket->delete('foo');
$bucket->delete('FuZZ');
$this->assertFalse($bucket->has('foo'));
$this->assertFalse($bucket->has('Fuzz'));
}
public function testCacheControlDirectiveAccessors()
{
$bucket = new HeaderBucket();
$bucket->addCacheControlDirective('public');
$this->assertTrue($bucket->hasCacheControlDirective('public'));
$this->assertEquals(true, $bucket->getCacheControlDirective('public'));
$this->assertEquals('public', $bucket->get('cache-control'));
$bucket->addCacheControlDirective('max-age', 10);
$this->assertTrue($bucket->hasCacheControlDirective('max-age'));
$this->assertEquals(10, $bucket->getCacheControlDirective('max-age'));
$this->assertEquals('max-age=10, public', $bucket->get('cache-control'));
$bucket->removeCacheControlDirective('max-age');
$this->assertFalse($bucket->hasCacheControlDirective('max-age'));
}
public function testCacheControlDirectiveParsing()
{
$bucket = new HeaderBucket(array('cache-control' => 'public, max-age=10'));
$this->assertTrue($bucket->hasCacheControlDirective('public'));
$this->assertEquals(true, $bucket->getCacheControlDirective('public'));
$this->assertTrue($bucket->hasCacheControlDirective('max-age'));
$this->assertEquals(10, $bucket->getCacheControlDirective('max-age'));
$bucket->addCacheControlDirective('s-maxage', 100);
$this->assertEquals('max-age=10, public, s-maxage=100', $bucket->get('cache-control'));
}
public function testCacheControlDirectiveOverrideWithReplace()
{
$bucket = new HeaderBucket(array('cache-control' => 'private, max-age=100'));
$bucket->replace(array('cache-control' => 'public, max-age=10'));
$this->assertTrue($bucket->hasCacheControlDirective('public'));
$this->assertEquals(true, $bucket->getCacheControlDirective('public'));
$this->assertTrue($bucket->hasCacheControlDirective('max-age'));
$this->assertEquals(10, $bucket->getCacheControlDirective('max-age'));
}
}
diff --git a/tests/Starlight/Component/Http/ParameterBucketTest.php b/tests/Starlight/Component/Http/ParameterBucketTest.php
index 9a4c3e9..5f3bb7c 100755
--- a/tests/Starlight/Component/Http/ParameterBucketTest.php
+++ b/tests/Starlight/Component/Http/ParameterBucketTest.php
@@ -1,67 +1,67 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Http\ParameterBucket;
use Starlight\Component\Http\ParameterBucket;
/**
*/
class ParameterBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->params = array(
'test_1' => 'value_1',
'test_2' => 'value_2',
'test_3' => 'value_3',
'test_4' => 12321,
'test_5' => '12341',
'test_6' => 'value_1matt23_again',
);
}
public function testGetAlpha()
{
$this->assertEquals($this->getBucket()->getAlpha('test_1'), 'value');
$this->assertEquals($this->getBucket()->getAlpha('test_4'), '');
$this->assertEquals($this->getBucket()->getAlpha('test_5'), '');
$this->assertEquals($this->getBucket()->getAlpha('test_6'), 'valuemattagain');
}
public function testGetAlnum()
{
$this->assertEquals($this->getBucket()->getAlnum('test_1'), 'value1');
$this->assertEquals($this->getBucket()->getAlnum('test_4'), '12321');
$this->assertEquals($this->getBucket()->getAlnum('test_5'), '12341');
$this->assertEquals($this->getBucket()->getAlnum('test_6'), 'value1matt23again');
}
public function testGetDigits()
{
$this->assertEquals($this->getBucket()->getDigits('test_1'), '1');
$this->assertEquals($this->getBucket()->getDigits('test_4'), '12321');
$this->assertEquals($this->getBucket()->getDigits('test_5'), '12341');
$this->assertEquals($this->getBucket()->getDigits('test_6'), '123');
}
public function testGetInt()
{
$this->assertEquals($this->getBucket()->getInt('test_1'), 0);
$this->assertEquals($this->getBucket()->getInt('test_4'), 12321);
$this->assertEquals($this->getBucket()->getInt('test_5'), 12341);
$this->assertEquals($this->getBucket()->getInt('test_6'), 0);
}
protected function getBucket()
{
return new ParameterBucket($this->params);
}
}
diff --git a/tests/Starlight/Component/Http/RequestTest.php b/tests/Starlight/Component/Http/RequestTest.php
index 36ce510..c6ce562 100755
--- a/tests/Starlight/Component/Http/RequestTest.php
+++ b/tests/Starlight/Component/Http/RequestTest.php
@@ -1,301 +1,301 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Http\Request;
use Starlight\Component\Http\Request;
/**
*/
class RequestTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->post = array();
$this->get = array();
$this->cookies = array();
$this->files = array();
$this->server = array();
}
public function testClone()
{
$this->post['test'] = 'example';
$this->cookies['my_cookie'] = 'the value';
$request1 = $this->getRequest();
$request2 = clone $request1;
$this->assertEquals($request1->post->get('test'), $request2->post->get('test'));
$this->assertEquals($request1->cookies->get('my_cookie'), $request2->cookies->get('my_cookie'));
$request1->post->set('test', 'something new');
$this->assertNotEquals($request1->post->get('test'), $request2->post->get('test'));
}
public function testGet()
{
$this->cookies['check'] = 'cookies';
$this->post['check'] = 'post';
$this->get['check'] = 'get';
$this->assertEquals($this->getRequest()->get('check'), 'get');
unset($this->get['check']);
$this->assertEquals($this->getRequest()->get('check'), 'post');
unset($this->post['check']);
$this->assertEquals($this->getRequest()->get('check'), 'cookies');
unset($this->cookies['check']);
$this->assertNull($this->getRequest()->get('check'));
$this->assertEquals($this->getRequest()->get('check', 'default'), 'default');
}
public function testGetMethod()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->server['X_HTTP_METHOD_OVERRIDE'] = 'put';
$this->post['_method'] = 'get';
$this->assertEquals($this->getRequest()->getMethod(), 'get');
unset($this->post['_method']);
$this->assertEquals($this->getRequest()->getMethod(), 'put');
unset($this->server['X_HTTP_METHOD_OVERRIDE']);
$this->assertEquals($this->getRequest()->getMethod(), 'post');
unset($this->server['REQUEST_METHOD']);
$this->assertNull($this->getRequest()->getMethod());
}
public function testIsDelete()
{
$this->server['REQUEST_METHOD'] = 'delete';
$this->assertTrue($this->getRequest()->isDelete());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isDelete());
}
public function testIsGet()
{
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isGet());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isGet());
}
public function testIsPost()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->assertTrue($this->getRequest()->isPost());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertFalse($this->getRequest()->isPost());
}
public function testIsPut()
{
$this->server['REQUEST_METHOD'] = 'put';
$this->assertTrue($this->getRequest()->isPut());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isPut());
}
public function testIsHead()
{
$this->server['REQUEST_METHOD'] = 'head';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isHead());
}
public function testIsSsl()
{
$this->server['HTTPS'] = 'On';
$this->assertTrue($this->getRequest()->isSsl());
$this->server['HTTPS'] = '';
$this->assertFalse($this->getRequest()->isSsl());
}
public function testGetProtocol()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getProtocol(), 'https://');
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getProtocol(), 'http://');
}
public function testGetHost()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['HTTP_X_FORWARDED_HOST'] = 'forwarded.example.com';
$this->assertEquals($this->getRequest()->getHost(), 'forwarded.example.com');
unset($this->server['HTTP_X_FORWARDED_HOST']);
$this->assertEquals($this->getRequest()->getHost(), 'example.com');
}
public function testSetPortFromHost()
{
$this->server['HTTP_HOST'] = 'example.com:8080';
$request = $this->getRequest();
$request->getHost();
$this->assertEquals($request->getPort(), 8080);
}
public function testGetPort()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPort(), 8080);
}
public function testGetStandardPort()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getStandardPort(), 443);
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getStandardPort(), 80);
}
public function testGetPortString()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPortString(), ':8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getPortString(), '');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getPortString(), '');
}
public function testGetHostWithPort()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
}
public function testGetRemoteIp()
{
$this->server['REMOTE_ADDR'] = '127.0.0.3';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.3');
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.2');
unset($this->server['HTTP_CLIENT_IP']);
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.1');
}
public function testGetRemoteIpException()
{
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
try {
$this->getRequest()->getRemoteIp();
} catch (\Exception $e) {
$this->assertInstanceOf('Starlight\\Component\\Http\\Exception\\IpSpoofingException', $e);
}
}
public function testIsXmlHttpRequest()
{
$this->assertFalse($this->getRequest()->isXmlHttpRequest());
$this->server['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->assertTrue($this->getRequesT()->isXmlHttpRequest());
}
public function testGetServer()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com');
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com');
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com:8080');
}
public function testGetUri()
{
$this->server['REQUEST_URI'] = '/src/Starlight/Framework/bootloader.php';
$this->assertEquals($this->getRequest()->getUri(), '/src/Starlight/Framework/bootloader.php');
$this->server['REQUEST_URI'] = '';
$this->assertEquals($this->getRequest()->getUri(), '/');
}
public function testGetRoute()
{
$this->server['REQUEST_URI'] = '/photos/1/users';
$this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
$this->server['REQUEST_URI'] = '/photos/1/users?querystring=1';
$this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
$this->server['REQUEST_URI'] = '';
$this->assertEquals($this->getRequest()->getRoute(), '/');
}
public function testIsLocalStandard()
{
$this->server['REMOTE_ADDR'] = '127.0.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '127.0.0.2';
$this->assertFalse($this->getRequest()->isLocal());
}
public function testIsLocalCustom()
{
Request::$local_ips[] = '192.168.0.1';
$this->server['REMOTE_ADDR'] = '127.0.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '192.168.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '127.0.0.2';
$this->assertFalse($this->getRequest()->isLocal());
}
protected function getRequest()
{
return new Request($this->post, $this->get, $this->cookies, $this->files, $this->server);
}
}
diff --git a/tests/Starlight/Component/Inflector/InflectorTest.php b/tests/Starlight/Component/Inflector/InflectorTest.php
index 9f153a0..4813869 100644
--- a/tests/Starlight/Component/Inflector/InflectorTest.php
+++ b/tests/Starlight/Component/Inflector/InflectorTest.php
@@ -1,367 +1,367 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Component\Inflector;
use Starlight\Component\Inflector\Inflector;
/**
*/
class InflectorTest extends \PHPUnit_Framework_TestCase
{
protected static $singular_to_plural = array(
'search' => 'searches',
'switch' => 'switches',
'fix' => 'fixes',
'box' => 'boxes',
'process' => 'processes',
'address' => 'addresses',
'case' => 'cases',
'stack' => 'stacks',
'wish' => 'wishes',
'fish' => 'fish',
'category' => 'categories',
'query' => 'queries',
'ability' => 'abilities',
'agency' => 'agencies',
'movie' => 'movies',
'archive' => 'archives',
'index' => 'indices',
'wife' => 'wives',
'safe' => 'saves',
'half' => 'halves',
'move' => 'moves',
'salesperson' => 'salespeople',
'person' => 'people',
'spokesman' => 'spokesmen',
'man' => 'men',
'woman' => 'women',
'basis' => 'bases',
'diagnosis' => 'diagnoses',
'diagnosis_a' => 'diagnosis_as',
'datum' => 'data',
'medium' => 'media',
'analysis' => 'analyses',
'node_child' => 'node_children',
'child' => 'children',
'experience' => 'experiences',
'day' => 'days',
'comment' => 'comments',
'foobar' => 'foobars',
'newsletter' => 'newsletters',
'old_news' => 'old_news',
'news' => 'news',
'series' => 'series',
'species' => 'species',
'quiz' => 'quizzes',
'perspective' => 'perspectives',
'ox' => 'oxen',
'photo' => 'photos',
'buffalo' => 'buffaloes',
'tomato' => 'tomatoes',
'dwarf' => 'dwarves',
'elf' => 'elves',
'information' => 'information',
'equipment' => 'equipment',
'bus' => 'buses',
'status' => 'statuses',
'status_code' => 'status_codes',
'mouse' => 'mice',
'louse' => 'lice',
'house' => 'houses',
'octopus' => 'octopi',
'virus' => 'viri',
'alias' => 'aliases',
'portfolio' => 'portfolios',
'vertex' => 'vertices',
'matrix' => 'matrices',
'matrix_fu' => 'matrix_fus',
'axis' => 'axes',
'testis' => 'testes',
'crisis' => 'crises',
'rice' => 'rice',
'shoe' => 'shoes',
'horse' => 'horses',
'prize' => 'prizes',
'edge' => 'edges',
'cow' => 'cattle',
'database' => 'databases',
);
protected static $string_to_normalized = array(
'Donald E. Knuth' => 'donald-e-knuth',
'Random text with *(bad)* characters' => 'random-text-with-bad-characters',
'Allow_Under_Scores' => 'allow_under_scores',
'Trailing bad characters!@#' => 'trailing-bad-characters',
'!@#Leading bad characters' => 'leading-bad-characters',
'Squeeze separators' => 'squeeze-separators',
);
protected static $string_to_normalized_no_sep = array(
'Donald E. Knuth' => 'donaldeknuth',
'Random text with *(bad)* characters' => 'randomtextwithbadcharacters',
'Trailing bad characters!@#' => 'trailingbadcharacters',
'!@#Leading bad characters' => 'leadingbadcharacters',
'Squeeze separators' => 'squeezeseparators',
);
protected static $string_to_normalized_with_underscore = array(
'Donald E. Knuth' => 'donald_e_knuth',
'Random text with *(bad)* characters' => 'random_text_with_bad_characters',
'Trailing bad characters!@#' => 'trailing_bad_characters',
'!@#Leading bad characters' => 'leading_bad_characters',
'Squeeze separators' => 'squeeze_separators',
);
protected static $string_to_title = array(
'starlight_base' => 'Starlight Base',
'StarlightBase' => 'Starlight Base',
'starlight base code' => 'Starlight Base Code',
'Starlight base Code' => 'Starlight Base Code',
'Starlight Base Code' => 'Starlight Base Code',
'starlightbasecode' => 'Starlightbasecode',
'Starlightbasecode' => 'Starlightbasecode',
'Person\'s stuff' => 'Person\'s Stuff',
'person\'s Stuff' => 'Person\'s Stuff',
'Person\'s Stuff' => 'Person\'s Stuff',
);
protected static $camel_to_underscore = array(
'Product' => 'product',
'SpecialGuest' => 'special_guest',
'ApplicationController' => 'application_controller',
'Area51Controller' => 'area51_controller',
);
protected static $camel_to_underscore_wo_rev = array(
'HTMLTidy' => 'html_tidy',
'HTMLTidyGenerator' => 'html_tidy_generator',
'FreeBSD' => 'free_bsd',
'HTML' => 'html',
);
protected static $class_to_fk_underscore = array(
'Person' => 'person_id',
);
protected static $class_to_fk_no_underscore = array(
'Person' => 'personid',
);
protected static $class_to_table = array(
'PrimarySpokesman' => 'primary_spokesmen',
'NodeChild' => 'node_children',
);
protected static $underscore_to_human = array(
'employee_salary' => 'Employee salary',
'employee_id' => 'Employee',
'underground' => 'Underground',
);
protected static $ordinals = array(
'0' => '0th',
'1' => '1st',
'2' => '2nd',
'3' => '3rd',
'4' => '4th',
'5' => '5th',
'6' => '6th',
'7' => '7th',
'8' => '8th',
'9' => '9th',
'10' => '10th',
'11' => '11th',
'12' => '12th',
'13' => '13th',
'14' => '14th',
'20' => '20th',
'21' => '21st',
'22' => '22nd',
'23' => '23rd',
'24' => '24th',
'100' => '100th',
'101' => '101st',
'102' => '102nd',
'103' => '103rd',
'104' => '104th',
'110' => '110th',
'111' => '111th',
'112' => '112th',
'113' => '113th',
'1000' => '1000th',
'1001' => '1001st',
);
protected static $underscores_to_dashes = array(
'street' => 'street',
'street_address' => 'street-address',
'person_street_address' => 'person-street-address',
);
protected static $underscores_to_lower_camel = array(
'product' => 'product',
'special_guest' => 'specialGuest',
'application_controller' => 'applicationController',
'area51_controller' => 'area51Controller',
);
public function testPluralizePlurals()
{
$this->assertEquals('plurals', Inflector::pluralize('plurals'));
$this->assertEquals('Plurals', Inflector::pluralize('Plurals'));
}
public function testPluralizeEmptyString()
{
$this->assertEquals('', Inflector::pluralize(''));
}
public function testSingularToPlural()
{
foreach (self::$singular_to_plural as $singular => $plural) {
$this->assertEquals($plural, Inflector::pluralize($singular));
$this->assertEquals(ucfirst($plural), Inflector::pluralize(ucfirst($singular)));
$this->assertEquals($singular, Inflector::singularize($plural));
$this->assertEquals(ucfirst($singular), Inflector::singularize(ucfirst($plural)));
}
}
public function testCamelize()
{
foreach (self::$camel_to_underscore as $camel => $underscore) {
$this->assertEquals($camel, Inflector::camelize($underscore));
}
}
public function testOverwritePreviousInflectors()
{
$this->assertEquals('series', Inflector::singularize('series'));
Inflector::singular('series', 'serie');
$this->assertEquals('serie', Inflector::singularize('series'));
Inflector::uncountable('series');
$this->assertEquals('series', Inflector::pluralize('series'));
Inflector::plural('series', 'seria');
$this->assertEquals('seria', Inflector::pluralize('series'));
Inflector::uncountable('series');
$this->assertEquals('dies', Inflector::pluralize('die'));
Inflector::irregular('die', 'dice');
$this->assertEquals('dice', Inflector::pluralize('die'));
$this->assertEquals('die', Inflector::singularize('dice'));
}
public function testTitleize()
{
foreach (self::$string_to_title as $before => $title) {
$this->assertEquals($title, Inflector::titleize($before));
}
}
public function testNormalize()
{
foreach (self::$string_to_normalized as $string => $normalized) {
$this->assertEquals($normalized, Inflector::normalize($string));
}
}
public function testNormalizeWithNoSeparator()
{
foreach (self::$string_to_normalized_no_sep as $string => $normalized) {
$this->assertEquals($normalized, Inflector::normalize($string, ''));
}
}
public function testNormalizeWithUnderscore()
{
foreach (self::$string_to_normalized_with_underscore as $string => $normalized) {
$this->assertEquals($normalized, Inflector::normalize($string, '_'));
}
}
public function testCamelizeLowercasesFirstLetter()
{
$this->assertEquals('capitalPlayersLeague', Inflector::camelize('Capital_players_League', false));
}
public function testUnderscore()
{
foreach (self::$camel_to_underscore as $camel => $underscore) {
$this->assertEquals($underscore, Inflector::underscore($camel));
}
foreach (self::$camel_to_underscore_wo_rev as $camel => $underscore) {
$this->assertEquals($underscore, Inflector::underscore($camel));
}
}
public function testforeignKey()
{
foreach (self::$class_to_fk_underscore as $klass => $fk) {
$this->assertEquals($fk, Inflector::foreignKey($klass));
}
foreach (self::$class_to_fk_no_underscore as $klass => $fk) {
$this->assertEquals($fk, Inflector::foreignKey($klass, false));
}
}
public function testTableize()
{
foreach (self::$class_to_table as $klass => $table) {
$this->assertEquals($table, Inflector::tableize($klass));
}
}
public function testClassify()
{
foreach (self::$class_to_table as $klass => $table) {
$this->assertEquals($klass, Inflector::classify($table));
$this->assertEquals($klass, Inflector::classify('prefix.' . $table));
}
}
public function testHumanize()
{
foreach (self::$underscore_to_human as $underscore => $human) {
$this->assertEquals($human, Inflector::humanize($underscore));
}
}
public function testOrdinal()
{
foreach (self::$ordinals as $number => $ordinal) {
$this->assertEquals($ordinal, Inflector::ordinalize($number));
}
}
public function testDasherize()
{
foreach (self::$underscores_to_dashes as $underscored => $dashes) {
$this->assertEquals($dashes, Inflector::dasherize($underscored));
}
}
public function testUnderscoreAsReverseOfDasherize()
{
foreach (self::$underscores_to_dashes as $underscored => $dashes) {
$this->assertEquals($underscored, Inflector::underscore(Inflector::dasherize($underscored)));
}
}
public function testUnderscoreToLowerCamel()
{
foreach (self::$underscores_to_lower_camel as $underscored => $lower_camel) {
$this->assertEquals($lower_camel, Inflector::camelize($underscored, false));
}
}
}
diff --git a/tests/Starlight/Component/Routing/RouteParserTest.php b/tests/Starlight/Component/Routing/RouteParserTest.php
index d82f7f7..63a0d3c 100755
--- a/tests/Starlight/Component/Routing/RouteParserTest.php
+++ b/tests/Starlight/Component/Routing/RouteParserTest.php
@@ -1,160 +1,160 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\RouteParser;
/**
*/
class RouteParserTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->parser = new RouteParser();
}
public function testStaticSegment()
{
$this->parser->parse('sample');
$this->assertEquals('/\Asample\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testMultipleStaticSegments()
{
$this->parser->parse('sample/index.html');
$this->assertEquals('/\Asample\/index\.html\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testDynamicSegment()
{
$this->parser->parse(':subdomain.example.com');
$this->assertEquals('/\A(?<subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array('subdomain'), $this->parser->names);
}
public function testDynamicSegmentWithLedingUnderscore()
{
$this->parser->parse(':_subdomain.example.com');
$this->assertEquals('/\A(?<_subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array('_subdomain'), $this->parser->names);
}
public function testInvalidSegmentNames()
{
$this->assertEquals('/\A\:123\.example\.com\Z/', $this->parser->parse(':123.example.com'));
$this->assertEquals('/\A\:\$\.example\.com\Z/', $this->parser->parse(':$.example.com'));
}
public function testEscapedDynamicSegment()
{
$this->parser->parse('\:subdomain.example.com');
$this->assertEquals('/\A\:subdomain\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testDynamicSegmentWithSeparators()
{
$this->assertEquals('/\Afoo\/(?<bar>[^\/]+)\Z/', $this->parser->parse('foo/:bar', array(), array('/')));
}
public function testDynamicSegmentWithRequirements()
{
$this->assertEquals('/\Afoo\/(?<bar>[a-z]+)\Z/', $this->parser->parse('foo/:bar', array('bar' => '[a-z]+'), array('/')));
}
public function testDynamicSegmentInsideOptionalSegment()
{
$this->assertEquals('/\Afoo(?:\.(?<extension>[^\/\.]+))?\Z/', $this->parser->parse('foo(.:extension)'));
}
public function testGlobSegment()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files'));
}
public function testGlobIgnoresSeparators()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files', array(), array('/', '.', '?')));
}
public function testGlobSegmentAtBeginning()
{
$this->assertEquals('/\A(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('*files/foo.txt'));
}
public function testGlobSegmentInMiddle()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/foo.txt'));
}
public function testMultipleGlobSegments()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\/dir\/(?<morefiles>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/dir/*morefiles/foo.txt'));
}
public function testEscapedGlobSegment()
{
$this->parser->parse('src/\*files');
$this->assertEquals('/\Asrc\/\*files\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testOptionalSegment()
{
$this->assertEquals('/\A\/foo(?:\/bar)?\Z/', $this->parser->parse('/foo(/bar)'));
}
public function testConsecutiveOptionalSegments()
{
$this->assertEquals('/\A\/foo(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('/foo(/bar)(/baz)'));
}
public function testMultipleOptionalSegments()
{
$this->assertEquals('/\A(?:\/foo)?(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('(/foo)(/bar)(/baz)'));
}
public function testEscapesOptionalSegmentParenthesis()
{
$this->assertEquals('/\A\/foo\(\/bar\)\Z/', $this->parser->parse('/foo\(/bar\)'));
}
public function testEscapesOneOptionalSegmentParenthesis()
{
$this->assertEquals('/\A\/foo\((?:\/bar)?\Z/', $this->parser->parse('/foo\((/bar)'));
}
public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedFront()
{
try {
$this->parser->parse('/foo((/bar)');
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e);
}
}
public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedBack()
{
try {
$this->parser->parse('/foo(/bar))');
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e);
}
}
}
diff --git a/tests/Starlight/Component/Routing/RouteTest.php b/tests/Starlight/Component/Routing/RouteTest.php
index 3a542f2..d779bc8 100755
--- a/tests/Starlight/Component/Routing/RouteTest.php
+++ b/tests/Starlight/Component/Routing/RouteTest.php
@@ -1,100 +1,100 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\Route;
/**
*/
class RouteTest extends \PHPUnit_Framework_TestCase
{
public function testRouteIsNormalized()
{
$route = new Route('some/path', 'controller::action');
$this->assertEquals('/some/path', $route->path);
}
public function testSetDefaults()
{
$route = $this->getRoute();
$defaults = array('id' => 24);
$return = $route->defaults($defaults);
$this->assertEquals($defaults, $route->parameters);
$this->assertEquals($return, $route);
}
public function testDefaultsDontOverrideSetParameters()
{
$route = $this->getRoute();
$defaults = array('id' => 24);
$route->parameters = array('id' => 25);
$return = $route->defaults($defaults);
$this->assertEquals(25, $route->parameters['id']);
$this->assertEquals($return, $route);
}
public function testSetConstraints()
{
$route = $this->getRoute();
$constraints = array('id' => '[0-9]+');
$return = $route->constraints($constraints);
$this->assertEquals($constraints, $route->constraints);
$this->assertEquals($return, $route);
}
public function testSetMethods()
{
$route = $this->getRoute();
$methods = array('get', 'post');
$return = $route->methods($methods);
$this->assertEquals($methods, $route->methods);
$this->assertEquals($return, $route);
}
public function testSetName()
{
$route = $this->getRoute();
$name = 'login';
$return = $route->name($name);
$this->assertEquals($name, $route->name);
$this->assertEquals($return, $route);
}
public function testDetermineControllerActionFromEndpoint()
{
$route = $this->getRoute(array('endpoint' => 'users::view'));
$route->compile();
$this->assertEquals('users', $route->parameters['controller']);
$this->assertEquals('view', $route->parameters['action']);
}
protected function getRoute(array $options = array())
{
$defaults = array(
'path' => '/:controller/:action/:id',
'endpoint' => 'controller::action',
);
$options = array_merge($defaults, $options);
return new Route($options['path'], $options['endpoint']);
}
}
diff --git a/tests/Starlight/Component/StdLib/StorageBucketTest.php b/tests/Starlight/Component/StdLib/StorageBucketTest.php
index 6513d07..97bdf51 100755
--- a/tests/Starlight/Component/StdLib/StorageBucketTest.php
+++ b/tests/Starlight/Component/StdLib/StorageBucketTest.php
@@ -1,124 +1,124 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
namespace Starlight\Tests\StdLib\StorageBucket;
use Starlight\Component\StdLib\StorageBucket;
/**
*/
class StorageBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->params = array(
'test_1' => 'value_1',
'test_2' => 'value_2',
'test_3' => 'value_3',
);
}
public function testAll()
{
$this->assertEquals($this->getBucket()->all(), $this->params);
}
public function testKeys()
{
$this->assertEquals($this->getBucket()->keys(), array_keys($this->params));
}
public function testReplace()
{
$bucket = $this->getBucket();
$new_parameters = array('test_4' => 'value_4');
$bucket->replace($new_parameters);
$this->assertEquals($bucket->all(), $new_parameters);
$this->assertNotEquals($bucket->all(), $this->params);
}
public function testAdd()
{
$bucket = $this->getBucket();
$new_parameters = array('test_4' => 'value_4');
$bucket->add($new_parameters);
$this->assertEquals($bucket->all(), array_replace($this->params, $new_parameters));
$this->assertNotEquals($bucket->all(), $this->params);
}
public function testGet()
{
$this->assertEquals($this->getBucket()->get('test_1'), 'value_1');
$this->assertNull($this->getBucket()->get('test_4'));
$this->assertEquals($this->getBucket()->get('test_4', 'value_4'), 'value_4');
}
public function testSet()
{
$bucket = $this->getBucket();
$this->assertNull($bucket->get('test_4'));
$bucket->set('test_4', 'value_4');
$this->assertEquals($bucket->get('test_4'), 'value_4');
$this->assertEquals($bucket->get('test_2'), 'value_2');
$bucket->set('test_2', 'value_22');
$this->assertEquals($bucket->get('test_2'), 'value_22');
}
public function testHas()
{
$this->assertTrue($this->getBucket()->has('test_1'));
$this->assertFalse($this->getBucket()->has('test_4'));
}
public function testDelete()
{
$bucket = $this->getBucket();
$this->assertTrue($bucket->has('test_1'));
$bucket->delete('test_1');
$this->assertFalse($bucket->has('test_1'));
$this->assertFalse($bucket->has('test_4'));
$bucket->delete('test_4');
$this->assertFalse($bucket->has('test_4'));
}
public function testArrayAccess()
{
$bucket = $this->getBucket();
$this->assertTrue(isset($bucket['test_1']));
$this->assertEquals($bucket['test_1'], 'value_1');
$bucket['test_4'] = 'anything';
$this->assertTrue(isset($bucket['test_4']));
unset($bucket['test_4']);
$this->assertFalse(isset($bucket['test_4']));
}
public function testIteratorAggreate()
{
$bucket = $this->getBucket();
foreach ($bucket as $key => $value) {
$this->assertEquals($value, $this->params[$key]);
}
}
protected function getBucket()
{
return new StorageBucket($this->params);
}
}
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index 4a8c49c..1ea9444 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -1,15 +1,15 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
*/
if (file_exists($file = __DIR__ . '/../autoload.php')) {
require_once $file;
} elseif (file_exists($file = __DIR__ . '/../autoload.php.dist')) {
require_once $file;
}
\ No newline at end of file
|
synewaves/starlight | 0c7aae55708d43f99701fa4d7e16d974f518808f | Begin routing/dispatching | diff --git a/src/Starlight/Component/Http/Request.php b/src/Starlight/Component/Http/Request.php
index dd6dcab..4e72b6c 100755
--- a/src/Starlight/Component/Http/Request.php
+++ b/src/Starlight/Component/Http/Request.php
@@ -1,317 +1,332 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Request
*/
class Request
{
- public static $local_ips = array('127.0.0.1');
+ public static $local_ips = array('127.0.0.1', '::1');
public $post;
public $get;
public $cookies;
public $files;
public $server;
public $headers;
protected $host;
protected $port;
protected $remote_ip;
protected $url;
/**
* Constructor
* @param array $post POST values
* @param array $get GET values
* @param array $cookies COOKIE values
* @param array $files FILES values
* @param array $server SERVER values
*/
public function __construct(array $post = null, array $get = null, array $cookies = null, array $files = null, array $server = null)
{
$this->post = new ParameterBucket($post ?: $_POST);
$this->get = new ParameterBucket($get ?: $_GET);
$this->cookies = new ParameterBucket($cookies ?: $_COOKIE);
$this->files = new ParameterBucket($files ?: $_FILES);
$this->server = new ParameterBucket($server ?: $_SERVER);
$this->headers = new HeaderBucket($this->initializeHeaders(), 'request');
}
/**
* Clone
*/
public function __clone()
{
$this->post = clone $this->post;
$this->get = clone $this->get;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Get a value from the request
*
* Order or precedence: GET, POST, COOKIE
*/
public function get($key, $default = null)
{
return $this->get->get($key, $this->post->get($key, $this->cookies->get($key, $default)));
}
/**
* Gets request method, lowercased
*
* Method can come from three places in this order:
* <ol>
* <li>$_POST[_method]</li>
* <li>$_SERVER[X_HTTP_METHOD_OVERRIDE]</li>
* <li>$_SERVER[REQUEST_METHOD]</li>
* </ol>
* @return string request method
*/
public function getMethod()
{
$method = $this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD')));
return $method !== null ? strtolower($method) : null;
}
/**
* Is this a DELETE request
* @return boolean is DELETE request
*/
public function isDelete()
{
return $this->getMethod() == 'delete';
}
/**
* Is this a GET request
* @see head()
* @return boolean is GET request
*/
public function isGet()
{
return $this->isHead();
}
/**
* Is this a POST request
* @return boolean is POST request
*/
public function isPost()
{
return $this->getMethod() == 'post';
}
/**
* Is this a HEAD request
*
* Functionally equivalent to get()
* @return boolean is HEAD request
*/
public function isHead()
{
return $this->getMethod() == 'head' || $this->getMethod() == 'get';
}
/**
* Is this a PUT request
* @return boolean is PUT request
*/
public function isPut()
{
return $this->getMethod() == 'put';
}
/**
* Is this an SSL request
* @return boolean is SSL request
*/
public function isSsl()
{
return strtolower($this->server->get('HTTPS')) == 'on';
}
/**
* Gets server protocol
* @return string protocol
*/
public function getProtocol()
{
return $this->isSsl() ? 'https://' : 'http://';
}
/**
* Gets the server host
* @return string host
*/
public function getHost()
{
if ($this->host === null) {
$host = $this->server->get('HTTP_X_FORWARDED_HOST', $this->server->get('HTTP_HOST'));
$pos = strpos($host, ':');
if ($pos !== false) {
$this->host = substr($host, 0, $pos);
if ($this->port === null) {
$this->port = (int) substr($host, $pos + 1);
}
} else {
$this->host = $host;
}
}
return $this->host;
}
/**
* Gets the server port
* @return integer port
*/
public function getPort()
{
if ($this->port === null) {
$this->port = (int) $this->server->get('SERVER_PORT', $this->getStandardPort());
}
return $this->port;
}
/**
* Gets the standard port number for the current protocol
* @return integer port (443, 80)
*/
public function getStandardPort()
{
return $this->isSsl() ? 443 : 80;
}
/**
* Gets the port string with colon delimiter if not standard port
* @return string port
*/
public function getPortString()
{
return (in_array($this->getPort(), array(443, 80))) ? '' : ':' . $this->getPort();
}
/**
* Gets the host with the port
* @return string host with port
*/
public function getHostWithPort()
{
return $this->getHost() . $this->getPortString();
}
/**
* Gets the client's remote ip
* @return string IP
*/
public function getRemoteIp()
{
if ($this->remote_ip === null) {
$remote_ips = null;
if ($x_forward = $this->server->get('HTTP_X_FORWARDED_FOR')) {
$remote_ips = array_map('trim', explode(',', $x_forward));
}
$client_ip = $this->server->get('HTTP_CLIENT_IP');
if ($client_ip) {
if (is_array($remote_ips) && !in_array($client_ip, $remote_ips)) {
// don't know which came from the proxy, and which from the user
throw new Exception\IpSpoofingException(sprintf("IP spoofing attack?!\nHTTP_CLIENT_IP=%s\nHTTP_X_FORWARDED_FOR=%s", $this->server->get('HTTP_CLIENT_IP'), $this->server->get('HTTP_X_FORWARDED_FOR')));
}
$this->remote_ip = $client_ip;
} elseif (is_array($remote_ips)) {
$this->remote_ip = $remote_ips[0];
} else {
$this->remote_ip = $this->server->get('REMOTE_ADDR');
}
}
return $this->remote_ip;
}
/**
* Is this request local?
* @return boolean local
*/
public function isLocal()
{
return in_array($this->getRemoteIp(), static::$local_ips);
}
/**
* Check if the request is an XMLHttpRequest (AJAX)
* @return boolean is XHR (AJAX) request
*/
public function isXmlHttpRequest()
{
return (bool) preg_match('/XMLHttpRequest/i', $this->server->get('HTTP_X_REQUESTED_WITH'));
}
/**
* Gets the full server url with protocol and port
* @return string server path
*/
public function getServer()
{
return $this->getProtocol() . $this->getHostWithPort();
}
/**
* Gets the requested URI path without domain or script name
* @return string uri
*/
public function getUri()
{
$url = $this->server->get('REQUEST_URI');
return trim($url) != '' ? $url : '/';
}
+ /**
+ * Gets the requested URI path without query string information
+ * @return string uri
+ */
+ public function getBaseUri()
+ {
+ $url = $this->getUri();
+
+ if (trim($this->server->get('QUERY_STRING')) != '') {
+ $url = substr($url, 0, strpos($url, '?'));
+ }
+
+ return $url;
+ }
+
/**
* Gets the requested route from the URI
* @return string route
*/
public function getRoute()
{
$route = $this->getUri();
// remove query string
if (($qs = strpos($route, '?')) !== false) {
$route = substr($route, 0, $qs);
}
return $route;
}
/**
* Initialize request headers for HeaderBucket
* @return array headers
*/
protected function initializeHeaders()
{
$headers = array();
foreach ($this->server->all() as $key => $value) {
if (strtolower(substr($key, 0, 5)) === 'http_') {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
}
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index fd0284e..8036474 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,181 +1,230 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements RoutableInterface, CompilableInterface
{
/**
* Base default values for route parameters
* @var array
*/
protected static $base_parameter_defaults = array(
'controller' => null,
'action' => null,
'id' => null,
);
public $path;
public $endpoint;
public $regex;
public $parameters = array();
public $constraints;
public $methods = array();
public $name;
public $module;
public $path_prefix;
public $name_prefix;
/**
* Constructor
* @param string $path url path
* @param mixed $endpoint route endpoint - "controller::action" or a valid callback
*/
public function __construct($path, $endpoint)
{
$this->path = static::normalize($path);
$this->endpoint = $endpoint;
}
/**
* Set route parameter defaults
* @param array $defaults default values hash
* @return \Starlight\Component\Routing\Route this instance
*/
public function defaults(array $defaults)
{
foreach ($defaults as $key => $value) {
if (!isset($this->parameters[$key]) || trim($this->parameters[$key]) == '') {
$this->parameters[$key] = $value;
}
}
return $this;
}
/**
* Set route constraints
* @param mixed $constraints constraints (hash or \Closure)
* @return \Starlight\Component\Routing\Route this instance
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set HTTP methods/verbs route should respond to
* @param array $methods HTTP methods
* @return \Starlight\Component\Routing\Route this instance
*/
public function methods($methods)
{
if (!is_array($methods)) {
$methods = array($methods);
}
$this->methods = $methods;
return $this;
}
/**
* Set route name for generated helpers
* @param string $name route name
* @return \Starlight\Component\Routing\Route this instance
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
* Set module/namespace for the controller
* @param string $module module/namespace
* @return \Starlight\Component\Routing\Route this instance
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Compiles the route
* @return \Starlight\Component\Routing\Route this compiled instance
*/
public function compile()
{
$parser = new RouteParser();
- $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
+
+ $regex_constraints = $other_constraints = array();
+ if (is_array($this->constraints)) {
+ foreach ($this->constraints as $k => $c) {
+ if (!is_callable($c)) {
+ $regex_constraints[$k] = $c;
+ } else {
+ $other_constraints[] = $c;
+ }
+ }
+ }
if ($this->path_prefix) {
$this->path = $this->path_prefix . $this->path;
}
- $this->regex = $parser->parse($this->path, $constraints);
+ $this->regex = $parser->parse($this->path, $regex_constraints);
$this->parameters = array_merge(static::$base_parameter_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
+ $this->constraints = $other_constraints;
// get endpoint if string:
if (is_string($this->endpoint)) {
if (strpos($this->endpoint, '::') !== false) {
// apply module:
if ($this->module) {
$this->endpoint = $this->module . '\\' . $this->endpoint;
}
list($this->parameters['controller'], $this->parameters['action']) = explode('::', $this->endpoint);
}
- } else {
+ } elseif (!is_callable($this->endpoint)) {
// should be a callback
- // TODO: handle callbacks
+ throw new \InvalidArgumentException('Route endpoint is invalid');
}
// set name/prefix if available:
if ($this->name && $this->name_prefix) {
$this->name = $this->name_prefix . $this->name;
}
return $this;
}
/**
* Match a request
* @param \Starlight\Component\Http\Request $request current request
+ * @return boolean route matches request
*/
public function match(Request $request)
+ {
+ $is_match = preg_match($this->regex, $request->getBaseUri(), $matches);
+ if ($is_match) {
+ if (!in_array($request->getMethod(), $this->methods)) {
+ return false;
+ }
+
+ foreach ($this->constraints as $c) {
+ if (!call_user_func($c, $request)) {
+ return false;
+ }
+ }
+
+ foreach ($matches as $k => $v) {
+ if (array_key_exists($k, $this->parameters)) {
+ $this->parameters[$k] = $v;
+ }
+ }
+ }
+
+ return $is_match;
+ }
+
+ /**
+ *
+ */
+ public function dispatch(Request $request)
{
+ $p = array_filter($this->parameters, function($var){ return trim($var) != ''; });
+ unset($p['controller'], $p['action']);
+
+ if (is_callable($this->endpoint)) {
+ call_user_func_array($this->endpoint, array_merge(array($request), array_values($p)));
+ return true;
+ } else {
+ // controller pattern
+
+ }
}
/**
* Normalizes path - removes trailing slashes and prepends single slash
* @param string $path original path
* @return string normalized path
*/
protected function normalize($path)
{
$path = trim($path, '/');
$path = '/' . $path;
return $path;
}
}
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index 0a7e92a..8dbacf0 100755
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,388 +1,395 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
use Starlight\Component\Inflector\Inflector;
/**
* Router
*/
class Router implements CompilableInterface
{
protected $routes = array();
protected $current = array();
protected $current_type = null;
protected $compiled = array();
protected $has_compiled = false;
protected $scopes = array();
/**
* Draw routes - router gateway
* @param \Closure $callback callback
* @return \Starlight\Component\Routing\Router this instance
*/
public function draw(\Closure $callback)
{
// TODO: check for cached version before redrawing these
$callback($this);
return $this;
}
/**
* Maps a single route
* @param string $path url path
* @param mixed $endpoint controller::action pair or callback
* @return \Starlight\Component\Routing\Route route
*/
public function map($path, $endpoint)
{
if ($this->current_type == 'resource') {
throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context.');
}
if (!preg_match('/\(\.:format\)$/', $path)) {
// auto append format option to path:
$path .= '(.:format)';
}
$this->routes[] = new Route($path, $endpoint);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'route';
$this->applyScopes();
array_pop($this->current);
$this->current_type = '';
return $this->routes[count($this->routes) - 1];
}
/**
* Maps RESTful resources routes
*/
public function resources()
{
$args = func_get_args();
$count = count($args);
$callback = null;
$options = array();
if (is_callable($args[$count - 1])) {
$callback = array_pop($args);
$count--;
}
if (is_array($args[$count - 1])) {
$options = array_pop($args);
$count--;
}
// map each resource separately (if multiple)
foreach ($args as $resource) {
if ($resource == Inflector::pluralize($resource)) {
$klass = 'Starlight\Component\Routing\ResourceRoute';
} else {
$klass = 'Starlight\Component\Routing\SingularResourceRoute';
}
$this->routes[] = new $klass($resource, $options);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'resource';
$route = $this->routes[count($this->routes) - 1];
$this->applyScopes();
if ($callback) {
$callback($this, $route);
}
array_pop($this->current);
$this->current_type = 'route';
}
return $route;
}
/**
* Maps singular RESTful resource
*/
public function resource()
{
return call_user_func_array(array($this, 'resources'), func_get_args());
}
/**
*
*/
public function redirect($path)
{
// TOOD: handle inline redirection
if (is_string($path)) {
return function() use ($path) {
return $path;
};
} else {
// already a callback, need to lazy evaluate later:
return $path;
}
}
/**
* Scope routes
* @param array $scopes scopes to apply
* @param \Closure $callback callback
*/
public function scope(array $scopes, \Closure $callback)
{
$this->addScopes($scopes);
$callback($this);
$this->removeScopes($scopes);
}
/**
* Compile all routes
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
- // /**
- // *
- // */
- // public function match(Request $request)
- // {
- // foreach ($this->compiled as $r) {
- // if ($r->match($request)) {
- // //
- // return;
- // }
- // }
- //
- // // nothing matched:
- // }
+ /**
+ *
+ */
+ public function match(Request $request)
+ {
+ foreach ($this->compiled as $r) {
+ if ($r->match($request)) {
+ return $r;
+ }
+ }
+
+ // nothing matched:
+ }
+
+ /**
+ *
+ */
+ public function dispatch(Route $endpoint, Request $request)
+ {
+ return $endpoint->dispatch($request);
+ }
/**
* Pretty version of routes
* @return string nice string
*/
public function __toString()
{
$parts = array();
$mn = $mv = $mp = 0;
foreach ($this->compiled as $r) {
$p = array(
'name' => $r->name,
'verb' => strtoupper(implode(',', $r->methods)),
'path' => $r->path,
'endp' => is_callable($r->endpoint) ? '{callback}' : $r->endpoint,
);
if (strlen($p['name']) > $mn) {
$mn = strlen($p['name']);
}
if (strlen($p['verb']) > $mv) {
$mv = strlen($p['verb']);
}
if (strlen($p['path']) > $mp) {
$mp = strlen($p['path']);
}
$parts[] = $p;
}
$rc = '<pre>';
foreach ($parts as $p) {
$rc .= sprintf("%" . $mn . "s %-" . $mv . "s %-" . $mp . "s %s\n", $p['name'], $p['verb'], $p['path'], $p['endp']);
}
$rc .= '</pre>';
return $rc;
}
/**
* Apply current scopes to currently scoped routes
*/
protected function applyScopes()
{
$count = count($this->current);
$current = $this->current[$count - 1];
$previous = isset($this->current[$count - 2]) ? $this->routes[$this->current[$count - 2]] : null;
$this->routes[$current] = $this->applyScope($this->routes[$current], $previous);
}
/**
* Apply scopes to single route
* @param mixed $route resource or route to scope
* @param \Starlight\Component\Routing\ResourceRoute $nested current parent route (if present)
* @return mixed resource or route which was scoped
*/
protected function applyScope($route, $nested = null)
{
// nested resource
if ($nested) {
$route->path_prefix .= $nested->path_prefix . '/' . $nested->plural . '/:' . $nested->singular . '_id';
$route->name_prefix .= $nested->name_prefix . $nested->singular . '_';
}
// constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
- $constraints = array_merge($constraints, $c);
+ $constraints = array_merge($constraints, is_array($c) ? $c : (array) $c);
}
$route->constraints($constraints);
}
// name
if (isset($this->scopes['name'])) {
$count = count($this->scopes['name']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
} else {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
}
// module
if (isset($this->scopes['module'])) {
$route->module(implode('\\', $this->scopes['module']));
}
// path
if (isset($this->scopes['path'])) {
$count = count($this->scopes['path']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
} else {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
}
if ($this->current_type == 'route') {
// route only cases
// HTTP methods/verbs
if (isset($this->scopes['methods'])) {
// only consider the last on the stack:
$route->methods($this->scopes['methods'][count($this->scopes['methods']) - 1]);
}
// parameter defaults
if (isset($this->scopes['defaults'])) {
$defaults = array();
foreach ($this->scopes['defaults'] as $d) {
$defaults = array_merge($defaults, $d);
}
$route->defaults($d);
}
} elseif ($this->current_type == 'resource') {
// resource only cases
// except
if (isset($this->scopes['except'])) {
// only consider the last on the stack:
$route->except($this->scopes['except'][count($this->scopes['except']) - 1]);
}
// only
if (isset($this->scopes['only'])) {
// only consider the last on the stack:
$route->only($this->scopes['only'][count($this->scopes['only']) - 1]);
}
// path_names
if (isset($this->scopes['path_names'])) {
// only consider the last on the stack:
$route->pathNames($this->scopes['path_names'][count($this->scopes['path_names']) - 1]);
}
}
return $route;
}
/**
* Add scopes to parse tree
* @param array $scopes scopes to add
*/
protected function addScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->addScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
$this->scopes[$scope][] = $options;
} else {
$this->scopes[$scope] = array($options);
}
}
}
/**
* Remove scopes from parse tree
* @param array $scopes scopes to remove
*/
protected function removeScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->removeScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
if (($position = array_search($options, $this->scopes[$scope])) !== false) {
unset($this->scopes[$scope][$position]);
if (count($this->scopes[$scope]) == 0) {
unset($this->scopes[$scope]);
}
}
}
}
}
}
|
synewaves/starlight | 892ad4eb8b5bda30f46d4145700a74e89d00f56a | Add cookie tests | diff --git a/src/Starlight/Component/Http/Cookie.php b/src/Starlight/Component/Http/Cookie.php
index ce0a09b..bf14416 100755
--- a/src/Starlight/Component/Http/Cookie.php
+++ b/src/Starlight/Component/Http/Cookie.php
@@ -1,264 +1,270 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Cookie
*/
class Cookie
{
protected $name;
protected $value;
protected $options;
/**
* Constructor
*
* Available options:
*
* * expires: Expiration date (string, int or \DateTime) (default: 0)
* * path: Path (default: null)
* * domain: Domain (default: null)
* * secure: Secure cookie (default: false)
* * http_only: HTTP only (default: true)
*
* @param string $name name
* @param mixed $value value
* @param array $options options hash
*/
public function __construct($name, $value, array $options = array())
{
$options = array_merge(array(
'expires' => 0,
'path' => null,
'domain' => null,
'secure' => false,
'http_only' => true,
), $options);
$this->setName($name)
->setValue($value)
->setExpires($options['expires'])
->setPath($options['path'])
->setDomain($options['domain'])
->setSecure($options['secure'])
->setHttpOnly($options['http_only']);
}
/**
* Gets the name
* @return string name
*/
public function getName()
{
return $this->name;
}
/**
* Sets the name
* @param string $name name
* @throws \InvalidArgumentException if invalid name
* @return Cookie this instance
*/
public function setName($name)
{
- // from PHP source code
if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
}
if (empty($name)) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
$this->name = $name;
return $this;
}
/**
* Gets the value
* @return string value
*/
public function getValue()
{
return $this->value;
}
/**
* Sets the value
* @param string $value value
* @throws \InvalidArgumentException if invalid value
* @return Cookie this instance
*/
public function setValue($value)
{
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
- throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $name));
+ throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
$this->value = $value;
return $this;
}
/**
* Gets the expiration date
* @return int expiration date
*/
public function getExpires()
{
- return $this->options['expire'];
+ return $this->options['expires'];
}
/**
* Sets the expiration date
* @param string|int|\DateTime $expires expiration date
* @return Cookie this instance
*/
public function setExpires($expires)
{
if (is_numeric($expires)) {
- $expires = (int) $expires;
- } elseif ($expires instanceof \DateTime) {
- $expires = $expires->getTimestamp();
- } else {
+ $expires = \DateTime::createFromFormat('U', $expires);
+ } elseif (!($expires instanceof \DateTime)) {
$o_expires = $expires;
- $expires = strtotime($expires);
- if ($expires === false || $expires == -1) {
+ try {
+ $expires = new \DateTime($expires);
+ } catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid: "%s".', $o_expires));
}
}
$this->options['expires'] = $expires;
return $this;
}
/**
* Gets the path
* @return string path
*/
public function getPath()
{
return $this->options['path'];
}
/**
* Sets the path
* @param string $path path
* @return Cookie this instance
*/
public function setPath($path)
{
$this->options['path'] = $path;
return $this;
}
/**
* Gets the domain
* @return string domain
*/
public function getDomain()
{
return $this->options['domain'];
}
/**
* Sets the domain
* @param string $domain domain
* @return Cookie this instance
*/
public function setDomain($domain)
{
$this->options['domain'] = $domain;
return $this;
}
/**
* Gets the secure flag
* @return boolean secure flag
*/
public function getSecure()
{
return (bool) $this->options['secure'];
}
/**
* Sets the secure flag
* @param boolean $secure secure flag
* @return Cookie this instance
*/
public function setSecure($secure)
{
$this->options['secure'] = (bool) $secure;
return $this;
}
/**
* Gets the http only flag
* @return boolean http only
*/
public function getHttpOnly()
{
return (bool) $this->options['http_only'];
}
/**
* Sets the http only flag
* @param boolean $http_only http only flag
* @return Cookie this instance
*/
public function setHttpOnly($http_only)
{
$this->options['http_only'] = (bool) $http_only;
return $this;
}
/**
* Is this cookie going to be cleared
* @return boolean is cleared
*/
public function isCleared()
{
- return $this->options['expires'] < time();
+ return $this->options['expires'] < new \DateTime();
}
/**
* Get formatted cookie header value
* @return string formatted value
*/
- public function __toString()
+ public function toHeaderValue()
{
$cookie = sprintf('%s=%s', $this->name, urlencode($this->value));
- if ($options['expires'] !== null) {
- $date = \DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'));
- $cookie .= '; expires=' . substr($date->format('D, d-M-Y H:i:s T'), 0, -5);
+ if ($this->options['expires'] !== null) {
+ $cookie .= '; expires=' . $this->options['expires']->format(DATE_COOKIE);
}
- if ($options['domain']) {
- $cookie .= '; domain=' . $options['domain'];
+ if ($this->options['domain']) {
+ $cookie .= '; domain=' . $this->options['domain'];
}
- if ($options['path'] && $options['path'] !== '/') {
- $cookie .= '; path=' . $options['path'];
+ if ($this->options['path'] && $this->options['path'] !== '/') {
+ $cookie .= '; path=' . $this->options['path'];
}
- if ($options['secure']) {
+ if ($this->options['secure']) {
$cookie .= '; secure';
}
- if ($options['http_only']) {
+ if ($this->options['http_only']) {
$cookie .= '; httponly';
}
return $cookie;
}
+
+ /**
+ * Get formatted cookie header value
+ * @return string formatted value
+ */
+ public function __toString()
+ {
+ return $this->toHeaderValue();
+ }
}
diff --git a/tests/Starlight/Component/Http/CookieTest.php b/tests/Starlight/Component/Http/CookieTest.php
new file mode 100644
index 0000000..577fa1e
--- /dev/null
+++ b/tests/Starlight/Component/Http/CookieTest.php
@@ -0,0 +1,154 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\Http\Cookie;
+use Starlight\Component\Http\Cookie;
+
+
+/**
+ */
+class CookieTest extends \PHPUnit_Framework_TestCase
+{
+ public function testConstructor()
+ {
+ $cookie = new Cookie('name', 'value', array(
+ 'expires' => time(),
+ 'http_only' => true,
+ ));
+
+ $this->assertEquals($cookie->getName(), 'name');
+ $this->assertEquals($cookie->getValue(), 'value');
+ $this->assertTrue($cookie->getHttpOnly());
+ $this->assertFalse($cookie->getSecure());
+ }
+
+ public function testGetSetName()
+ {
+ $cookie = new Cookie('name', 'value');
+ $this->assertEquals($cookie->getName(), 'name');
+
+ try {
+ $cookie->setName("name\n");
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('InvalidArgumentException', $e);
+ }
+
+ try {
+ $cookie->setName("");
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('InvalidArgumentException', $e);
+ }
+ }
+
+ public function testGetSetValue()
+ {
+ $cookie = new Cookie('name', 'value');
+ $this->assertEquals($cookie->getValue(), 'value');
+
+ try {
+ $cookie->setValue("value\n");
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('InvalidArgumentException', $e);
+ }
+ }
+
+ public function testGetSetExpires()
+ {
+ $date = new \DateTime();
+
+ $cookie = new Cookie('name', 'value');
+ $cookie->setExpires($date);
+ $this->assertEquals($date->format('U'), $cookie->getExpires()->format('U'));
+
+ $cookie->setExpires($date->format('U'));
+ $this->assertEquals($date->format('U'), $cookie->getExpires()->format('U'));
+
+ $cookie->setExpires($date->format(DATE_RFC822));
+ $this->assertEquals($date->format('U'), $cookie->getExpires()->format('U'));
+
+ try {
+ $cookie->setExpires('this obviously is not a date');
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('InvalidArgumentException', $e);
+ }
+ }
+
+ public function testGetSetPath()
+ {
+ $cookie = new Cookie('name', 'value');
+ $cookie->setPath('/');
+
+ $this->assertEquals('/', $cookie->getPath());
+ }
+
+ public function testGetSetDomain()
+ {
+ $cookie = new Cookie('name', 'value');
+ $cookie->setDomain('example.com');
+
+ $this->assertEquals('example.com', $cookie->getDomain());
+ }
+
+ public function testGetSetSecure()
+ {
+ $cookie = new Cookie('name', 'value');
+
+ $cookie->setSecure(true);
+ $this->assertTrue($cookie->getSecure());
+
+ $cookie->setSecure(0);
+ $this->assertFalse($cookie->getSecure());
+
+ $cookie->setSecure('true');
+ $this->assertTrue($cookie->getSecure());
+ }
+
+ public function testGetSetHttpOnly()
+ {
+ $cookie = new Cookie('name', 'value');
+
+ $cookie->setHttpOnly(true);
+ $this->assertTrue($cookie->getHttpOnly());
+
+ $cookie->setHttpOnly(0);
+ $this->assertFalse($cookie->getHttpOnly());
+
+ $cookie->setHttpOnly('true');
+ $this->assertTrue($cookie->getHttpOnly());
+ }
+
+ public function testIsCleared()
+ {
+ $cookie = new Cookie('name', 'value');
+
+ $cookie->setExpires(new \DateTime('+2 days'));
+ $this->assertFalse($cookie->isCleared());
+
+ $cookie->setExpires(time() - 20);
+ $this->assertTrue($cookie->isCleared());
+ }
+
+ public function testToString()
+ {
+ $date = new \DateTime();
+
+ $cookie = new Cookie('name', 'value', array(
+ 'expires' => $date,
+ 'path' => '/path',
+ 'domain' => 'example.com',
+ 'secure' => true,
+ 'http_only' => true,
+ ));
+
+ $expected_value = 'name=value; expires=' . $date->format(DATE_COOKIE) . '; domain=example.com; path=/path; secure; httponly';
+ $this->assertEquals($expected_value, $cookie->toHeaderValue());
+ $this->assertEquals($expected_value, (string) $cookie);
+ }
+}
diff --git a/tests/Starlight/Component/Http/RequestTest.php b/tests/Starlight/Component/Http/RequestTest.php
index f02e87a..36ce510 100755
--- a/tests/Starlight/Component/Http/RequestTest.php
+++ b/tests/Starlight/Component/Http/RequestTest.php
@@ -1,298 +1,301 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\Request;
use Starlight\Component\Http\Request;
/**
*/
class RequestTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->post = array();
$this->get = array();
$this->cookies = array();
$this->files = array();
$this->server = array();
}
public function testClone()
{
$this->post['test'] = 'example';
$this->cookies['my_cookie'] = 'the value';
$request1 = $this->getRequest();
$request2 = clone $request1;
$this->assertEquals($request1->post->get('test'), $request2->post->get('test'));
$this->assertEquals($request1->cookies->get('my_cookie'), $request2->cookies->get('my_cookie'));
$request1->post->set('test', 'something new');
$this->assertNotEquals($request1->post->get('test'), $request2->post->get('test'));
}
public function testGet()
{
$this->cookies['check'] = 'cookies';
$this->post['check'] = 'post';
$this->get['check'] = 'get';
$this->assertEquals($this->getRequest()->get('check'), 'get');
unset($this->get['check']);
$this->assertEquals($this->getRequest()->get('check'), 'post');
unset($this->post['check']);
$this->assertEquals($this->getRequest()->get('check'), 'cookies');
unset($this->cookies['check']);
$this->assertNull($this->getRequest()->get('check'));
$this->assertEquals($this->getRequest()->get('check', 'default'), 'default');
}
public function testGetMethod()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->server['X_HTTP_METHOD_OVERRIDE'] = 'put';
$this->post['_method'] = 'get';
$this->assertEquals($this->getRequest()->getMethod(), 'get');
unset($this->post['_method']);
$this->assertEquals($this->getRequest()->getMethod(), 'put');
unset($this->server['X_HTTP_METHOD_OVERRIDE']);
$this->assertEquals($this->getRequest()->getMethod(), 'post');
unset($this->server['REQUEST_METHOD']);
$this->assertNull($this->getRequest()->getMethod());
}
public function testIsDelete()
{
$this->server['REQUEST_METHOD'] = 'delete';
$this->assertTrue($this->getRequest()->isDelete());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isDelete());
}
public function testIsGet()
{
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isGet());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isGet());
}
public function testIsPost()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->assertTrue($this->getRequest()->isPost());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertFalse($this->getRequest()->isPost());
}
public function testIsPut()
{
$this->server['REQUEST_METHOD'] = 'put';
$this->assertTrue($this->getRequest()->isPut());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isPut());
}
public function testIsHead()
{
$this->server['REQUEST_METHOD'] = 'head';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isHead());
}
public function testIsSsl()
{
$this->server['HTTPS'] = 'On';
$this->assertTrue($this->getRequest()->isSsl());
$this->server['HTTPS'] = '';
$this->assertFalse($this->getRequest()->isSsl());
}
public function testGetProtocol()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getProtocol(), 'https://');
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getProtocol(), 'http://');
}
public function testGetHost()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['HTTP_X_FORWARDED_HOST'] = 'forwarded.example.com';
$this->assertEquals($this->getRequest()->getHost(), 'forwarded.example.com');
unset($this->server['HTTP_X_FORWARDED_HOST']);
$this->assertEquals($this->getRequest()->getHost(), 'example.com');
}
public function testSetPortFromHost()
{
$this->server['HTTP_HOST'] = 'example.com:8080';
$request = $this->getRequest();
$request->getHost();
$this->assertEquals($request->getPort(), 8080);
}
public function testGetPort()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPort(), 8080);
}
public function testGetStandardPort()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getStandardPort(), 443);
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getStandardPort(), 80);
}
public function testGetPortString()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPortString(), ':8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getPortString(), '');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getPortString(), '');
}
public function testGetHostWithPort()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
}
public function testGetRemoteIp()
{
$this->server['REMOTE_ADDR'] = '127.0.0.3';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.3');
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.2');
unset($this->server['HTTP_CLIENT_IP']);
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.1');
}
public function testGetRemoteIpException()
{
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
- $this->setExpectedException('Starlight\\Component\\Http\\Exception\\IpSpoofingException');
- $this->getRequest()->getRemoteIp();
+ try {
+ $this->getRequest()->getRemoteIp();
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('Starlight\\Component\\Http\\Exception\\IpSpoofingException', $e);
+ }
}
public function testIsXmlHttpRequest()
{
$this->assertFalse($this->getRequest()->isXmlHttpRequest());
$this->server['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->assertTrue($this->getRequesT()->isXmlHttpRequest());
}
public function testGetServer()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com');
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com');
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com:8080');
}
public function testGetUri()
{
$this->server['REQUEST_URI'] = '/src/Starlight/Framework/bootloader.php';
$this->assertEquals($this->getRequest()->getUri(), '/src/Starlight/Framework/bootloader.php');
$this->server['REQUEST_URI'] = '';
$this->assertEquals($this->getRequest()->getUri(), '/');
}
public function testGetRoute()
{
$this->server['REQUEST_URI'] = '/photos/1/users';
$this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
$this->server['REQUEST_URI'] = '/photos/1/users?querystring=1';
$this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
$this->server['REQUEST_URI'] = '';
$this->assertEquals($this->getRequest()->getRoute(), '/');
}
public function testIsLocalStandard()
{
$this->server['REMOTE_ADDR'] = '127.0.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '127.0.0.2';
$this->assertFalse($this->getRequest()->isLocal());
}
public function testIsLocalCustom()
{
Request::$local_ips[] = '192.168.0.1';
$this->server['REMOTE_ADDR'] = '127.0.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '192.168.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '127.0.0.2';
$this->assertFalse($this->getRequest()->isLocal());
}
protected function getRequest()
{
return new Request($this->post, $this->get, $this->cookies, $this->files, $this->server);
}
}
diff --git a/tests/Starlight/Component/Routing/RouteParserTest.php b/tests/Starlight/Component/Routing/RouteParserTest.php
index 8f946b9..d82f7f7 100755
--- a/tests/Starlight/Component/Routing/RouteParserTest.php
+++ b/tests/Starlight/Component/Routing/RouteParserTest.php
@@ -1,154 +1,160 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\RouteParser;
/**
*/
class RouteParserTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->parser = new RouteParser();
}
public function testStaticSegment()
{
$this->parser->parse('sample');
$this->assertEquals('/\Asample\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testMultipleStaticSegments()
{
$this->parser->parse('sample/index.html');
$this->assertEquals('/\Asample\/index\.html\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testDynamicSegment()
{
$this->parser->parse(':subdomain.example.com');
$this->assertEquals('/\A(?<subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array('subdomain'), $this->parser->names);
}
public function testDynamicSegmentWithLedingUnderscore()
{
$this->parser->parse(':_subdomain.example.com');
$this->assertEquals('/\A(?<_subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array('_subdomain'), $this->parser->names);
}
public function testInvalidSegmentNames()
{
$this->assertEquals('/\A\:123\.example\.com\Z/', $this->parser->parse(':123.example.com'));
$this->assertEquals('/\A\:\$\.example\.com\Z/', $this->parser->parse(':$.example.com'));
}
public function testEscapedDynamicSegment()
{
$this->parser->parse('\:subdomain.example.com');
$this->assertEquals('/\A\:subdomain\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testDynamicSegmentWithSeparators()
{
$this->assertEquals('/\Afoo\/(?<bar>[^\/]+)\Z/', $this->parser->parse('foo/:bar', array(), array('/')));
}
public function testDynamicSegmentWithRequirements()
{
$this->assertEquals('/\Afoo\/(?<bar>[a-z]+)\Z/', $this->parser->parse('foo/:bar', array('bar' => '[a-z]+'), array('/')));
}
public function testDynamicSegmentInsideOptionalSegment()
{
$this->assertEquals('/\Afoo(?:\.(?<extension>[^\/\.]+))?\Z/', $this->parser->parse('foo(.:extension)'));
}
public function testGlobSegment()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files'));
}
public function testGlobIgnoresSeparators()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files', array(), array('/', '.', '?')));
}
public function testGlobSegmentAtBeginning()
{
$this->assertEquals('/\A(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('*files/foo.txt'));
}
public function testGlobSegmentInMiddle()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/foo.txt'));
}
public function testMultipleGlobSegments()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\/dir\/(?<morefiles>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/dir/*morefiles/foo.txt'));
}
public function testEscapedGlobSegment()
{
$this->parser->parse('src/\*files');
$this->assertEquals('/\Asrc\/\*files\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testOptionalSegment()
{
$this->assertEquals('/\A\/foo(?:\/bar)?\Z/', $this->parser->parse('/foo(/bar)'));
}
public function testConsecutiveOptionalSegments()
{
$this->assertEquals('/\A\/foo(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('/foo(/bar)(/baz)'));
}
public function testMultipleOptionalSegments()
{
$this->assertEquals('/\A(?:\/foo)?(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('(/foo)(/bar)(/baz)'));
}
public function testEscapesOptionalSegmentParenthesis()
{
$this->assertEquals('/\A\/foo\(\/bar\)\Z/', $this->parser->parse('/foo\(/bar\)'));
}
public function testEscapesOneOptionalSegmentParenthesis()
{
$this->assertEquals('/\A\/foo\((?:\/bar)?\Z/', $this->parser->parse('/foo\((/bar)'));
}
public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedFront()
{
- $this->setExpectedException('InvalidArgumentException');
- $this->parser->parse('/foo((/bar)');
+ try {
+ $this->parser->parse('/foo((/bar)');
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('InvalidArgumentException', $e);
+ }
}
public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedBack()
{
- $this->setExpectedException('InvalidArgumentException');
- $this->parser->parse('/foo(/bar))');
+ try {
+ $this->parser->parse('/foo(/bar))');
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('InvalidArgumentException', $e);
+ }
}
}
|
synewaves/starlight | 797c61420ad90574002fe803d0d3630c8ce52ebc | Reorganization and refactoring of buckets. Abstract out sessions and cookies | diff --git a/src/Starlight/Component/Http/Cookie.php b/src/Starlight/Component/Http/Cookie.php
new file mode 100755
index 0000000..ce0a09b
--- /dev/null
+++ b/src/Starlight/Component/Http/Cookie.php
@@ -0,0 +1,264 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Http;
+
+
+/**
+ * HTTP Cookie
+ */
+class Cookie
+{
+ protected $name;
+ protected $value;
+ protected $options;
+
+ /**
+ * Constructor
+ *
+ * Available options:
+ *
+ * * expires: Expiration date (string, int or \DateTime) (default: 0)
+ * * path: Path (default: null)
+ * * domain: Domain (default: null)
+ * * secure: Secure cookie (default: false)
+ * * http_only: HTTP only (default: true)
+ *
+ * @param string $name name
+ * @param mixed $value value
+ * @param array $options options hash
+ */
+ public function __construct($name, $value, array $options = array())
+ {
+ $options = array_merge(array(
+ 'expires' => 0,
+ 'path' => null,
+ 'domain' => null,
+ 'secure' => false,
+ 'http_only' => true,
+ ), $options);
+
+ $this->setName($name)
+ ->setValue($value)
+ ->setExpires($options['expires'])
+ ->setPath($options['path'])
+ ->setDomain($options['domain'])
+ ->setSecure($options['secure'])
+ ->setHttpOnly($options['http_only']);
+ }
+
+ /**
+ * Gets the name
+ * @return string name
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Sets the name
+ * @param string $name name
+ * @throws \InvalidArgumentException if invalid name
+ * @return Cookie this instance
+ */
+ public function setName($name)
+ {
+ // from PHP source code
+ if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
+ throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name));
+ }
+
+ if (empty($name)) {
+ throw new \InvalidArgumentException('The cookie name cannot be empty');
+ }
+
+ $this->name = $name;
+ return $this;
+ }
+
+ /**
+ * Gets the value
+ * @return string value
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * Sets the value
+ * @param string $value value
+ * @throws \InvalidArgumentException if invalid value
+ * @return Cookie this instance
+ */
+ public function setValue($value)
+ {
+ if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
+ throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $name));
+ }
+
+ $this->value = $value;
+ return $this;
+ }
+
+ /**
+ * Gets the expiration date
+ * @return int expiration date
+ */
+ public function getExpires()
+ {
+ return $this->options['expire'];
+ }
+
+ /**
+ * Sets the expiration date
+ * @param string|int|\DateTime $expires expiration date
+ * @return Cookie this instance
+ */
+ public function setExpires($expires)
+ {
+ if (is_numeric($expires)) {
+ $expires = (int) $expires;
+ } elseif ($expires instanceof \DateTime) {
+ $expires = $expires->getTimestamp();
+ } else {
+ $o_expires = $expires;
+ $expires = strtotime($expires);
+ if ($expires === false || $expires == -1) {
+ throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid: "%s".', $o_expires));
+ }
+ }
+
+ $this->options['expires'] = $expires;
+ return $this;
+ }
+
+ /**
+ * Gets the path
+ * @return string path
+ */
+ public function getPath()
+ {
+ return $this->options['path'];
+ }
+
+ /**
+ * Sets the path
+ * @param string $path path
+ * @return Cookie this instance
+ */
+ public function setPath($path)
+ {
+ $this->options['path'] = $path;
+ return $this;
+ }
+
+ /**
+ * Gets the domain
+ * @return string domain
+ */
+ public function getDomain()
+ {
+ return $this->options['domain'];
+ }
+
+ /**
+ * Sets the domain
+ * @param string $domain domain
+ * @return Cookie this instance
+ */
+ public function setDomain($domain)
+ {
+ $this->options['domain'] = $domain;
+ return $this;
+ }
+
+ /**
+ * Gets the secure flag
+ * @return boolean secure flag
+ */
+ public function getSecure()
+ {
+ return (bool) $this->options['secure'];
+ }
+
+ /**
+ * Sets the secure flag
+ * @param boolean $secure secure flag
+ * @return Cookie this instance
+ */
+ public function setSecure($secure)
+ {
+ $this->options['secure'] = (bool) $secure;
+ return $this;
+ }
+
+ /**
+ * Gets the http only flag
+ * @return boolean http only
+ */
+ public function getHttpOnly()
+ {
+ return (bool) $this->options['http_only'];
+ }
+
+ /**
+ * Sets the http only flag
+ * @param boolean $http_only http only flag
+ * @return Cookie this instance
+ */
+ public function setHttpOnly($http_only)
+ {
+ $this->options['http_only'] = (bool) $http_only;
+ return $this;
+ }
+
+ /**
+ * Is this cookie going to be cleared
+ * @return boolean is cleared
+ */
+ public function isCleared()
+ {
+ return $this->options['expires'] < time();
+ }
+
+ /**
+ * Get formatted cookie header value
+ * @return string formatted value
+ */
+ public function __toString()
+ {
+ $cookie = sprintf('%s=%s', $this->name, urlencode($this->value));
+
+ if ($options['expires'] !== null) {
+ $date = \DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'));
+ $cookie .= '; expires=' . substr($date->format('D, d-M-Y H:i:s T'), 0, -5);
+ }
+
+ if ($options['domain']) {
+ $cookie .= '; domain=' . $options['domain'];
+ }
+
+ if ($options['path'] && $options['path'] !== '/') {
+ $cookie .= '; path=' . $options['path'];
+ }
+
+ if ($options['secure']) {
+ $cookie .= '; secure';
+ }
+
+ if ($options['http_only']) {
+ $cookie .= '; httponly';
+ }
+
+ return $cookie;
+ }
+}
diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index 34240a7..53a6859 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,313 +1,305 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
+use Starlight\Component\StdLib\StorageBucket;
/**
* Wrapper class for request/response headers
*/
-class HeaderBucket implements \ArrayAccess, \IteratorAggregate
+class HeaderBucket extends StorageBucket
{
- /**
- * Headers
- * @var array
- */
- protected $headers;
+ protected $cookies = array();
+ protected $cache_control = array();
- /**
- * Type (request, response)
- * @var string
- */
- protected $type;
-
-
- /**
- * Constructor
- * @param array $headers An array of HTTP headers
- * @param string $type The type (null, request, or response)
- */
- public function __construct(array $headers = array(), $type = null)
- {
- $this->replace($headers);
-
- if ($type !== null && !in_array($type, array('request', 'response'))) {
- throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBucket.', $type));
- }
- $this->type = $type;
- }
-
- /**
- * Returns the headers
- * @return array An array of headers
- */
- public function all()
- {
- return $this->headers;
- }
-
- /**
- * Returns the parameter keys
- * @return array An array of parameter keys
- */
- public function keys()
- {
- return array_keys($this->headers);
- }
-
- /**
- * Replaces the current HTTP headers by a new set
- * @param array $headers An array of HTTP headers
- * @return HeaderBucket this instance
- */
- public function replace(array $headers = array())
- {
- $this->cache_control = null;
- $this->headers = array();
- foreach ($headers as $key => $values) {
- $this->set($key, $values);
- }
-
- return $this;
- }
-
/**
* Returns a header value by name
* @param string $key The header name
- * @param Boolean $first Whether to return the first value or all header values
+ * @param mixed $default default value if none found
+ * @param boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
- public function get($key, $first = true)
+ public function get($key, $default = null, $first = true)
{
- $key = static::normalizeHeaderName($key);
-
- if (!array_key_exists($key, $this->headers)) {
- return $first ? null : array();
+ $key = strtr(strtolower($key), '_', '-');
+
+ if (!array_key_exists($key, $this->contents)) {
+ if ($default === null) {
+ return $first ? null : array();
+ } else {
+ return $first ? $default : array($default);
+ }
}
if ($first) {
- return count($this->headers[$key]) ? $this->headers[$key][0] : '';
+ return count($this->contents[$key]) ? $this->contents[$key][0] : $default;
} else {
- return $this->headers[$key];
+ return $this->contents[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
- $key = static::normalizeHeaderName($key);
-
+ $key = strtr(strtolower($key), '_', '-');
+
if (!is_array($values)) {
$values = array($values);
}
-
- if ($replace === true || !isset($this->headers[$key])) {
- $this->headers[$key] = $values;
+
+ if ($replace === true || !isset($this->contents[$key])) {
+ $this->contents[$key] = $values;
} else {
- $this->headers[$key] = array_merge($this->headers[$key], $values);
+ $this->contents[$key] = array_merge($this->contents[$key], $values);
+ }
+
+ if ($key === 'cache-control') {
+ $this->cache_control = $this->parseCacheControl($values[0]);
}
return $this;
}
-
+
+ /**
+ * Replaces the current contents with a new set
+ * @param array $contents contents
+ * @return HeaderBucket this instance
+ */
+ public function replace(array $contents = array())
+ {
+ $this->contents = array();
+ $this->add($contents);
+
+ return $this;
+ }
+
/**
- * Returns true if the HTTP header is defined
- * @param string $key The HTTP header
- * @return Boolean true if the parameter exists, false otherwise
+ * Adds contents
+ * @param array $contents contents
+ * @return HeaderBucket this instance
+ */
+ public function add(array $contents = array())
+ {
+ foreach ($contents as $key => $value) {
+ $this->set($key, $value);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Returns true if the content is defined
+ * @param string $key The key
+ * @return boolean true if the contents exists, false otherwise
*/
public function has($key)
{
- return array_key_exists(static::normalizeHeaderName($key), $this->headers);
+ return parent::has(strtr(strtolower($key), '_', '-'));
}
-
+
/**
* Returns true if the given HTTP header contains the given value
- * @param string $key The HTTP header name
+ * @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
- return in_array($value, $this->get($key, false));
+ return in_array($value, $this->get($key, null, false));
}
-
+
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
- if ($this->has($key)) {
- unset($this->headers[static::normalizeHeaderName($key)]);
+ $key = strtr(strtolower($key), '_', '-');
+
+ parent::delete($key);
+
+ if ($key == 'cache-control') {
+ $this->cache_control = array();
}
return $this;
}
/**
- * Set cookie variable
- *
- * Available options:
- *
- * <ul>
- * <li><b>expires</b> <i>(integer)</i>: cookie expiration time (default: 0 [end of session])</li>
- * <li><b>path</b> <i>(string)</i>: path cookie is valid for (default: '')</li>
- * <li><b>domain</b> <i>(string)</i>: domain cookie is valid for (default: '')</li>
- * <li><b>secure/b> <i>(boolean)</i>: should cookie only be used on a secure connection (default: false)</li>
- * <li><b>http_only</b> <i>(string)</i>: cookie only valid over http? [not supported by all browsers] (default: true)</li>
- * <li><b>encode</b> <i>(boolean)</i>: urlencode cookie value (default: true)</li>
- * </ul>
- * @param string $key cookie key
- * @param mixed $value value
- * @param array $options options hash (see above)
+ * Sets a cookie
+ * @param Cookie $cookie
+ * @throws \InvalidArgumentException When the cookie expire parameter is not valid
* @return HeaderBucket this instance
*/
- public function setCookie($key, $value, $options = array())
+ public function setCookie(Cookie $cookie)
{
- $default_options = array(
- 'expires' => null,
- 'path' => null,
- 'domain' => null,
- 'secure' => false,
- 'http_only' => true,
- );
- $options += $default_options;
-
- if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
- throw new \InvalidArgumentException(sprintf('The cookie key "%s" contains invalid characters.', $key));
- }
-
- if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
- throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
- }
-
- if (trim($key) == '') {
- throw new \InvalidArgumentException('The cookie key cannot be empty');
- }
-
- $cookie = sprintf('%s=%s', $key, urlencode($value));
-
- if ($this->type == 'request') {
- $this->set('Cookie', $cookie);
- return;
- }
-
- if ($options['expires'] !== null) {
- if (is_numeric($options['expires'])) {
- $options['expires'] = (int) $options['expires'];
- } elseif ($options['expires'] instanceof \DateTime) {
- $options['expires'] = $options['expires']->getTimestamp();
- } else {
- $options['expires'] = strtotime($options['expires']);
- if ($options['expires'] === false || $options['expires'] == -1) {
- throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $options['expires']));
- }
- }
-
- $cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
- }
-
- if ($options['domain']) {
- $cookie .= '; domain=' . $options['domain'];
- }
-
- if ($options['path'] && $options['path'] !== '/') {
- $cookie .= '; path=' . $options['path'];
- }
-
- if ($options['secure']) {
- $cookie .= '; secure';
- }
-
- if ($options['http_only']) {
- $cookie .= '; httponly';
- }
-
- $this->set('Set-Cookie', $cookie, false);
-
+ $this->cookies[$cookie->getName()] = $cookie;
return $this;
}
-
+
/**
- * Expire a cookie variable
- * @param string $key cookie key
+ * Removes a cookie from the array, but does not unset it in the browser
+ * @param string $name
* @return HeaderBucket this instance
*/
- public function expireCookie($key)
+ public function removeCookie($name)
{
- if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
- throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
- }
-
- if (!$key) {
- throw new \InvalidArgumentException('The cookie name cannot be empty');
- }
+ unset($this->cookies[$name]);
+ return $this;
+ }
+
+ /**
+ * Whether the array contains any cookie with this name
+ * @param string $name
+ * @return boolean cookie exists
+ */
+ public function hasCookie($name)
+ {
+ return isset($this->cookies[$name]);
+ }
- if ($this->type == 'request') {
- return;
+ /**
+ * Returns a cookie
+ * @param string $name
+ * @throws \InvalidArgumentException if cookie not found
+ * @return Cookie cookie
+ */
+ public function getCookie($name)
+ {
+ if (!$this->hasCookie($name)) {
+ throw new \InvalidArgumentException(sprintf('There is no cookie with name "%s".', $name));
}
-
- $cookie = sprintf('%s=; expires=', $key, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
-
- $this->set('Set-Cookie', $cookie, false);
-
- return $this;
+
+ return $this->cookies[$name];
+ }
+
+ /**
+ * Returns an array with all cookies
+ * @return array all cookies
+ */
+ public function getCookies()
+ {
+ return $this->cookies;
}
+
+ /**
+ * Returns the HTTP header value converted to a date
+ * @param string $key The parameter key
+ * @param \DateTime $default The default value
+ * @throws \RuntimeException if cannot parse header
+ * @return \DateTime The filtered value
+ */
+ public function getDate($key, \DateTime $default = null)
+ {
+ if (($value = $this->get($key)) === null) {
+ return $default;
+ }
- // -----------
- // ArrayAccess
- // -----------
+ if (($date = \DateTime::createFromFormat(DATE_RFC2822, $value)) === false) {
+ throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
+ }
- public function offsetExists($offset)
+ return $date;
+ }
+
+ /**
+ * Adds the cache control headers
+ * @param string $key key
+ * @param mixed $value value
+ * @return HeaderBag this instance
+ */
+ public function addCacheControlDirective($key, $value = true)
{
- return $this->has($offset);
+ $this->cache_control[$key] = $value;
+ $this->set('Cache-Control', $this->getCacheControlHeader());
+
+ return $this;
}
-
- public function offsetGet($offset)
+
+ /**
+ * Is there a cache control directive present
+ * @param string $key key
+ * @return boolean is present
+ */
+ public function hasCacheControlDirective($key)
{
- return $this->get($offset);
+ return array_key_exists($key, $this->cache_control);
}
- public function offsetSet($offset, $value)
+ /**
+ * Gets the cache control directive header
+ * @param string $key key
+ * @return string cache control header
+ */
+ public function getCacheControlDirective($key)
{
- return $this->set($offset, $value);
+ return array_key_exists($key, $this->cache_control) ? $this->cache_control[$key] : null;
}
-
- public function offsetUnset($offset)
+
+ /**
+ * Removes the cache control directive header
+ * @param string $key key
+ * @return HeaderBag this instance
+ */
+ public function removeCacheControlDirective($key)
{
- return $this->delete($offset);
+ unset($this->cache_control[$key]);
+ $this->set('Cache-Control', $this->getCacheControlHeader());
+
+ return $this;
}
+
+ /**
+ * Generates the cache control header value
+ * @return string header value
+ */
+ protected function getCacheControlHeader()
+ {
+ $parts = array();
+ ksort($this->cache_control);
+ foreach ($this->cache_control as $key => $value) {
+ if ($value === true) {
+ $parts[] = $key;
+ } else {
+ if (preg_match('/[^a-zA-Z0-9._-]/', $value)) {
+ $value = '"' . $value . '"';
+ }
- // -----------------
- // IteratorAggregate
- // -----------------
+ $parts[] = "$key=$value";
+ }
+ }
- public function getIterator()
- {
- return new \ArrayIterator($this->all());
+ return implode(', ', $parts);
}
/**
- * Normalizes an HTTP header name
- * @param string $key The HTTP header name
- * @return string The normalized HTTP header name
+ * Parses a Cache-Control HTTP header
+ * @param string $header The value of the Cache-Control HTTP header
+ * @return array An array representing the attribute values
*/
- static public function normalizeHeaderName($key)
+ protected function parseCacheControl($header)
{
- return strtr(strtolower($key), '_', '-');
+ $cache_control = array();
+ preg_match_all('/([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?/', $header, $matches, PREG_SET_ORDER);
+ foreach ($matches as $match) {
+ $cache_control[strtolower($match[1])] = isset($match[2]) && $match[2] ? $match[2] : (isset($match[3]) ? $match[3] : true);
+ }
+
+ return $cache_control;
}
}
diff --git a/src/Starlight/Component/Http/ParameterBucket.php b/src/Starlight/Component/Http/ParameterBucket.php
index 314d74d..9164680 100755
--- a/src/Starlight/Component/Http/ParameterBucket.php
+++ b/src/Starlight/Component/Http/ParameterBucket.php
@@ -1,158 +1,64 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
+use Starlight\Component\StdLib\StorageBucket;
/**
* Wrapper class request parameters
* @see Request
*/
-class ParameterBucket implements \ArrayAccess, \IteratorAggregate
+class ParameterBucket extends StorageBucket
{
/**
- * Parameters
- * @var array
+ * Returns the alphabetic characters of the parameter value
+ * @param string $key The parameter key
+ * @param mixed $default The default value
+ * @return string The filtered value
*/
- protected $parameters;
-
-
- /**
- * Constructor
- * @param array $parameters Parameters
- */
- public function __construct(array $parameters = array())
- {
- $this->replace($parameters);
- }
-
- /**
- * Returns the parameters
- * @return array Parameters
- */
- public function all()
- {
- return $this->parameters;
- }
-
- /**
- * Returns the parameter keys
- * @return array Parameter keys
- */
- public function keys()
- {
- return array_keys($this->parameters);
- }
-
- /**
- * Replaces the current parameters by a new set
- * @param array $parameters parameters
- * @return HeaderBucket this instance
- */
- public function replace(array $parameters = array())
- {
- $this->parameters = $parameters;
-
- return $this;
- }
-
- /**
- * Adds parameters
- * @param array $parameters parameters
- * @return HeaderBucket this instance
- */
- public function add(array $parameters = array())
- {
- $this->parameters = array_replace($this->parameters, $parameters);
-
- return $this;
- }
-
- /**
- * Returns a parameter by name
- * @param string $key The key
- * @param mixed $default default value
- * @return mixed value
- */
- public function get($key, $default = null)
+ public function getAlpha($key, $default = '')
{
- return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
+ return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default));
}
/**
- * Sets a parameter by name
- * @param string $key The key
- * @param mixed $value value
- * @return HeaderBucket this instance
+ * Returns the alphabetic characters and digits of the parameter value
+ * @param string $key The parameter key
+ * @param mixed $default The default value
+ * @return string The filtered value
*/
- public function set($key, $value)
+ public function getAlnum($key, $default = '')
{
- $this->parameters[$key] = $value;
-
- return $this;
+ return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default));
}
/**
- * Returns true if the parameter is defined
- * @param string $key The key
- * @return boolean true if the parameter exists, false otherwise
+ * Returns the digits of the parameter value
+ * @param string $key The parameter key
+ * @param mixed $default The default value
+ * @return string The filtered value
*/
- public function has($key)
+ public function getDigits($key, $default = '')
{
- return array_key_exists($key, $this->parameters);
+ return preg_replace('/[^[:digit:]]/', '', $this->get($key, $default));
}
/**
- * Deletes a parameter
- * @param string $key key
- * @return HeaderBucket this instance
+ * Returns the parameter value converted to integer
+ * @param string $key The parameter key
+ * @param mixed $default The default value
+ * @return string The filtered value
*/
- public function delete($key)
- {
- if ($this->has($key)) {
- unset($this->parameters[$key]);
- }
-
- return $this;
- }
-
- //
- // ArrayAccess
- //
-
- public function offsetExists($offset)
- {
- return $this->has($offset);
- }
-
- public function offsetGet($offset)
- {
- return $this->get($offset);
- }
-
- public function offsetSet($offset, $value)
- {
- return $this->set($offset, $value);
- }
-
- public function offsetUnset($offset)
- {
- return $this->delete($offset);
- }
-
- //
- // IteratorAggregate
- //
-
- public function getIterator()
+ public function getInt($key, $default = 0)
{
- return new \ArrayIterator($this->all());
+ return (int) $this->get($key, $default);
}
}
diff --git a/src/Starlight/Component/Http/Session.php b/src/Starlight/Component/Http/Session.php
new file mode 100755
index 0000000..ef5e82e
--- /dev/null
+++ b/src/Starlight/Component/Http/Session.php
@@ -0,0 +1,274 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Http;
+use Starlight\Component\Http\SessionStorage;
+
+/**
+ * Session
+ */
+class Session implements \Serializable
+{
+ const FLASH_KEY = '_flash';
+ const SAVE_KEY = '_starlight';
+
+ protected $storage;
+ protected $options = array();
+ protected $attributes = array();
+ protected $old_flash_data = array();
+ protected $is_started = false;
+
+
+ /**
+ * Constructor
+ */
+ public function __construct(SessionStorageInterface $storage, array $options = array())
+ {
+ $this->storage = $storage;
+ $this->options = $options;
+ $this->attributes = array(self::FLASH_KEY => array());
+ $this->is_started = false;
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct()
+ {
+ $this->save();
+ }
+
+ /**
+ * Serialize
+ * @return string serialized data
+ */
+ public function serialize()
+ {
+ return serialize(array($this->storage, $this->options));
+ }
+
+ /**
+ * Unserialize
+ * @param string $serialized serialized data
+ */
+ public function unserialize($serialized)
+ {
+ list($this->storage, $this->options) = unserialize($serialized);
+ $this->attributes = array();
+ $this->is_started = false;
+ }
+
+ /**
+ * Save session
+ */
+ public function save()
+ {
+ if ($this->isStarted()) {
+ if (isset($this->attributes[self::FLASH_KEY])) {
+ $this->attributes[self::FLASH_KEY] = array_diff_key($this->attributes[self::FLASH_KEY], $this->old_flash_data);
+ }
+ $this->storage->write(self::SAVE_KEY, $this->attributes);
+ }
+ }
+
+ /**
+ * Start session and storage engine
+ */
+ public function start()
+ {
+ if ($this->isStarted()) {
+ return;
+ }
+
+ $this->storage->start();
+ $this->attributes = $this->storage->read(self::SAVE_KEY);
+
+ if (!isset($this->attributes[self::FLASH_KEY])) {
+ $this->attributes[self::FLASH_KEY] = array();
+ }
+
+ $this->old_flash_data = array_flip(array_keys($this->attributes[self::FLASH_KEY]));
+ $this->is_started = true;
+ }
+
+ /**
+ * Check if an attribute exists
+ * @param string $name attribute name
+ * @return boolean attribute exists
+ */
+ public function has($name)
+ {
+ return array_key_exists($name, $this->attributes);
+ }
+
+ /**
+ * Gets an attribute's value
+ * @param string $name attribute's name
+ * @param mixed $default default value if not found
+ * @return mixed
+ */
+ public function get($name, $default = null)
+ {
+ return $this->has($name) ? $this->attributes[$name] : $default;
+ }
+
+ /**
+ * Set an attribute's value
+ * @param string $name attribute name
+ * @param mixed $value attribute value
+ */
+ public function set($name, $value)
+ {
+ if (!$this->isStarted()) {
+ $this->start();
+ }
+
+ $this->attributes[$name] = $value;
+ }
+
+ /**
+ * Delete an attribute
+ * @param string $name attribute name
+ */
+ public function delete($name)
+ {
+ if (!$this->isStarted()) {
+ $this->start();
+ }
+
+ if ($this->has($name)) {
+ unset($this->attributes[$name]);
+ }
+ }
+
+ /**
+ * Clear all attributes
+ */
+ public function clear()
+ {
+ if (!$this->isStarted()) {
+ $this->start();
+ }
+
+ $this->attributes = array();
+ $this->clearFlashes();
+ }
+
+ /**
+ * Invalidates the session
+ */
+ public function invalidate()
+ {
+ $this->clear();
+ $this->storage->regenerate();
+ }
+
+ /**
+ * Migrates the session to a new session id, keeping existing attributes
+ */
+ public function migrate()
+ {
+ $this->storage->regenerate();
+ }
+
+ /**
+ * Gets the session id
+ * @return string id
+ */
+ public function id()
+ {
+ return $this->storage->id();
+ }
+
+ /**
+ * Gets all flash values
+ * @return array flash values
+ */
+ public function getFlashes()
+ {
+ return $this->attributes[self::FLASH_KEY];
+ }
+
+ /**
+ * Sets all flash values at once
+ * @param array $values flash values
+ */
+ public function setFlashes($values)
+ {
+ if (!$this->isStarted()) {
+ $this->start();
+ }
+
+ $this->attributes[self::FLASH_KEY] = $values;
+ }
+
+ /**
+ * Clears all flash data
+ */
+ public function clearFlashes()
+ {
+ $this->attributes[self::FLASH_KEY] = array();
+ }
+
+ /**
+ * Gets a flash value
+ * @param string $name flash name
+ * @param mixed $default default value if missing
+ * @return mixed value
+ */
+ public function getFlash($name, $default = null)
+ {
+ return $this->hasFlash($name) ? $this->attributes[self::FLASH_KEY][$name] : $default;
+ }
+
+ /**
+ * Sets a flash value
+ * @param string $name flash name
+ * @param mixed $value value
+ */
+ public function setFlash($name, $value)
+ {
+ if (!$this->isStarted()) {
+ $this->start();
+ }
+
+ $this->attributes[self::FLASH_KEY][$name] = $value;
+ }
+
+ /**
+ * Checks if a flash value exists
+ * @param string $name flash name
+ * @return boolean exists
+ */
+ public function hasFlash($name)
+ {
+ return array_key_exists($name, $this->attributes[self::FLASH_KEY]);
+ }
+
+ /**
+ * Deletes a flash value
+ * @param string $name flash name
+ */
+ public function deleteFlash($name)
+ {
+ if ($this->hasFlash($name)) {
+ unset($this->attributes[self::FLASH_KEY][$name]);
+ }
+ }
+
+ /**
+ * Is the current session started
+ * @return boolean session started
+ */
+ protected function isStarted()
+ {
+ return $this->is_started;
+ }
+}
diff --git a/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php b/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php
new file mode 100755
index 0000000..8a01a7d
--- /dev/null
+++ b/src/Starlight/Component/Http/SessionStorage/NativeSessionStorage.php
@@ -0,0 +1,156 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Http\SessionStorage;
+
+/**
+ * Native Session Storage
+ */
+class NativeSessionStorage implements SessionStorageInterface
+{
+ static protected $regenerated = false;
+ static protected $started = false;
+ protected $options;
+
+ /**
+ * Constructor
+ *
+ * Available options:
+ *
+ * * name: The cookie name (_SESS by default)
+ * * id: The session id (null by default)
+ * * lifetime: Cookie lifetime
+ * * path: Cookie path
+ * * domain: Cookie domain
+ * * secure: Cookie secure
+ * * httponly: Cookie http only
+ *
+ * The default values for most options are those returned by the session_get_cookie_params() function
+ * @param array $options An associative array of options
+ */
+ public function __construct(array $options = array())
+ {
+ $defaults = session_get_cookie_params();
+
+ $this->options = array_merge(array(
+ 'name' => '_SESS',
+ 'lifetime' => $defaults['lifetime'],
+ 'path' => $defaults['path'],
+ 'domain' => $defaults['domain'],
+ 'secure' => $defaults['secure'],
+ 'httponly' => isset($defaults['httponly']) ? $defaults['httponly'] : false,
+ ), $options);
+
+ session_name($this->options['name']);
+ }
+
+ /**
+ * Starts the session.
+ */
+ public function start()
+ {
+ if (self::$started) {
+ return;
+ }
+
+ session_set_cookie_params(
+ $this->options['lifetime'],
+ $this->options['path'],
+ $this->options['domain'],
+ $this->options['secure'],
+ $this->options['httponly']
+ );
+
+ // disable native cache limiter as this is managed by HeaderBag directly
+ // session_cache_limiter(false);
+
+ if (!ini_get('session.use_cookies') && $this->options['id'] && $this->options['id'] != session_id()) {
+ session_id($this->options['id']);
+ }
+
+ session_start();
+
+ self::$started = true;
+ }
+
+ /**
+ * Returns the session ID
+ * @return mixed The session ID
+ * @throws \RuntimeException If the session was not started yet
+ */
+ public function id()
+ {
+ if (!self::$started) {
+ throw new \RuntimeException('The session must be started before reading its ID');
+ }
+
+ return session_id();
+ }
+
+ /**
+ * Reads data from this storage
+ * The preferred format for a key is directory style so naming conflicts can be avoided.
+ * @param string $key A unique key identifying your data
+ * @return mixed Data associated with the key
+ * @throws \RuntimeException If an error occurs while reading data from this storage
+ */
+ public function read($key, $default = null)
+ {
+ return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
+ }
+
+ /**
+ * Removes data from this storage
+ * The preferred format for a key is directory style so naming conflicts can be avoided.
+ * @param string $key A unique key identifying your data
+ * @return mixed Data associated with the key
+ * @throws \RuntimeException If an error occurs while removing data from this storage
+ */
+ public function remove($key)
+ {
+ $rc = null;
+
+ if (isset($_SESSION[$key])) {
+ $rc = $_SESSION[$key];
+ unset($_SESSION[$key]);
+ }
+
+ return $rc;
+ }
+
+ /**
+ * Writes data to this storage
+ * The preferred format for a key is directory style so naming conflicts can be avoided.
+ * @param string $key A unique key identifying your data
+ * @param mixed $data Data associated with your key
+ * @throws \RuntimeException If an error occurs while writing to this storage
+ */
+ public function write($key, $data)
+ {
+ $_SESSION[$key] = $data;
+ }
+
+ /**
+ * Regenerates id that represents this storage
+ * @param Boolean $destroy Destroy session when regenerating?
+ * @return Boolean True if session regenerated, false if error
+ * @throws \RuntimeException If an error occurs while regenerating this storage
+ */
+ public function regenerate($destroy = false)
+ {
+ if (self::$regenerated) {
+ return;
+ }
+
+ session_regenerate_id($destroy);
+
+ self::$regenerated = true;
+ }
+}
diff --git a/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php b/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php
new file mode 100755
index 0000000..564a193
--- /dev/null
+++ b/src/Starlight/Component/Http/SessionStorage/SessionStorageInterface.php
@@ -0,0 +1,64 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Http\SessionStorage;
+
+/**
+ * Session Storage Interface
+ */
+interface SessionStorageInterface
+{
+ /**
+ * Starts the session.
+ */
+ function start();
+
+ /**
+ * Returns the session ID
+ * @return mixed The session ID
+ * @throws \RuntimeException If the session was not started yet
+ */
+ function id();
+
+ /**
+ * Reads data from this storage
+ * The preferred format for a key is directory style so naming conflicts can be avoided.
+ * @param string $key A unique key identifying your data
+ * @return mixed Data associated with the key
+ * @throws \RuntimeException If an error occurs while reading data from this storage
+ */
+ function read($key);
+
+ /**
+ * Removes data from this storage
+ * The preferred format for a key is directory style so naming conflicts can be avoided.
+ * @param string $key A unique key identifying your data
+ * @return mixed Data associated with the key
+ * @throws \RuntimeException If an error occurs while removing data from this storage
+ */
+ function remove($key);
+
+ /**
+ * Writes data to this storage
+ * The preferred format for a key is directory style so naming conflicts can be avoided.
+ * @param string $key A unique key identifying your data
+ * @param mixed $data Data associated with your key
+ * @throws \RuntimeException If an error occurs while writing to this storage
+ */
+ function write($key, $data);
+
+ /**
+ * Regenerates id that represents this storage
+ * @param Boolean $destroy Destroy session when regenerating?
+ * @return Boolean True if session regenerated, false if error
+ * @throws \RuntimeException If an error occurs while regenerating this storage
+ */
+ function regenerate($destroy = false);
+}
diff --git a/src/Starlight/Component/StdLib/StorageBucket.php b/src/Starlight/Component/StdLib/StorageBucket.php
new file mode 100755
index 0000000..cfb29e8
--- /dev/null
+++ b/src/Starlight/Component/StdLib/StorageBucket.php
@@ -0,0 +1,157 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\StdLib;
+
+
+/**
+ * Generic storage bucket
+ */
+class StorageBucket implements \ArrayAccess, \IteratorAggregate
+{
+ /**
+ * Bucket contents
+ * @var array
+ */
+ protected $contents;
+
+
+ /**
+ * Constructor
+ * @param array $contents contents
+ */
+ public function __construct(array $contents = array())
+ {
+ $this->replace($contents);
+ }
+
+ /**
+ * Returns the contents
+ * @return array contents
+ */
+ public function all()
+ {
+ return $this->contents;
+ }
+
+ /**
+ * Returns the contents keys
+ * @return array contents keys
+ */
+ public function keys()
+ {
+ return array_keys($this->contents);
+ }
+
+ /**
+ * Replaces the current contents with a new set
+ * @param array $contents contents
+ * @return StorageBucket this instance
+ */
+ public function replace(array $contents = array())
+ {
+ $this->contents = $contents;
+
+ return $this;
+ }
+
+ /**
+ * Adds contents
+ * @param array $contents contents
+ * @return StorageBucket this instance
+ */
+ public function add(array $contents = array())
+ {
+ $this->contents = array_replace($this->contents, $contents);
+
+ return $this;
+ }
+
+ /**
+ * Returns content by name
+ * @param string $key The key
+ * @param mixed $default default value
+ * @return mixed value
+ */
+ public function get($key, $default = null)
+ {
+ return array_key_exists($key, $this->contents) ? $this->contents[$key] : $default;
+ }
+
+ /**
+ * Sets content by name
+ * @param string $key The key
+ * @param mixed $value value
+ * @return StorageBucket this instance
+ */
+ public function set($key, $value)
+ {
+ $this->contents[$key] = $value;
+
+ return $this;
+ }
+
+ /**
+ * Returns true if the content is defined
+ * @param string $key The key
+ * @return boolean true if the contents exists, false otherwise
+ */
+ public function has($key)
+ {
+ return array_key_exists($key, $this->contents);
+ }
+
+ /**
+ * Deletes a content
+ * @param string $key key
+ * @return StorageBucket this instance
+ */
+ public function delete($key)
+ {
+ if ($this->has($key)) {
+ unset($this->contents[$key]);
+ }
+
+ return $this;
+ }
+
+ // --------------------------
+ // ArrayAccess implementation
+ // --------------------------
+
+ public function offsetExists($offset)
+ {
+ return $this->has($offset);
+ }
+
+ public function offsetGet($offset)
+ {
+ return $this->get($offset);
+ }
+
+ public function offsetSet($offset, $value)
+ {
+ return $this->set($offset, $value);
+ }
+
+ public function offsetUnset($offset)
+ {
+ return $this->delete($offset);
+ }
+
+ // --------------------------------
+ // IteratorAggregate implementation
+ // --------------------------------
+
+ public function getIterator()
+ {
+ return new \ArrayIterator($this->all());
+ }
+}
diff --git a/tests/Starlight/Component/Http/HeaderBucketTest.php b/tests/Starlight/Component/Http/HeaderBucketTest.php
index 9a8d242..51583c1 100755
--- a/tests/Starlight/Component/Http/HeaderBucketTest.php
+++ b/tests/Starlight/Component/Http/HeaderBucketTest.php
@@ -1,317 +1,110 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\HeaderBucket;
use Starlight\Component\Http\HeaderBucket;
/**
*/
class HeaderBucketTest extends \PHPUnit_Framework_TestCase
{
- public function setup()
- {
- $this->headers = array(
- 'HTTP_HOST' => 'localhost:80',
- 'HTTP_CONNECTION' => 'keep-alive',
- 'HTTP_REFERER' => 'http://localhost:80/',
- 'HTTP_ACCEPT' => 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
- 'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.59 Safari/534.3',
- 'HTTP_ACCEPT_ENCODING' => 'gzip,deflate,sdch',
- 'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
- 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
- );
-
- $this->type = 'request';
-
- $this->normalized_headers = array();
- foreach ($this->headers as $header => $value) {
- $this->normalized_headers[HeaderBucket::normalizeHeaderName($header)] = array($value);
- }
- }
-
- public function testArguments()
- {
- $this->type = 'madeup';
- $this->setExpectedException('InvalidArgumentException');
-
- $this->getBucket();
- }
-
- public function testAll()
- {
- $this->assertEquals($this->getBucket()->all(), $this->normalized_headers);
- }
-
- public function testKeys()
- {
- $this->assertEquals($this->getBucket()->keys(), array_keys($this->normalized_headers));
- }
-
- public function testReplace()
+ public function testHas()
{
- $bucket = $this->getBucket();
- $this->assertEquals($bucket->all(), $this->normalized_headers);
-
- $new_headers = array(
- 'HTTP_HOST' => 'localhost:80',
- );
- $normalized = array(
- 'http-host' => array('localhost:80'),
- );
- $bucket->replace($new_headers);
- $this->assertNotEquals($bucket->all(), $this->normalized_headers);
- $this->assertEquals($bucket->all(), $normalized);
+ $bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
+ $this->assertEquals(true, $bucket->has('foo'));
+ $this->assertEquals(true, $bucket->has('FoO'));
+ $this->assertEquals(false, $bucket->has('bizz'));
}
public function testGet()
{
- $this->assertEquals($this->getBucket()->get('HTTP_HOST'), 'localhost:80');
- $this->assertEquals($this->getBucket()->get('HTTP_HOST', false), array('localhost:80'));
- $this->assertNull($this->getBucket()->get('MADE_UP'));
- $this->assertEquals($this->getBucket()->get('MADE_UP', false), array());
- }
+ $bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
+ $this->assertEquals('bar', $bucket->get('foo'), '->get return current value');
+ $this->assertEquals('bar', $bucket->get('FoO'), '->get key in case insensitive');
+ $this->assertEquals(array('bar'), $bucket->get('foo', 'nope', false), '->get return the value as array');
- public function testSet()
- {
- $bucket = $this->getBucket();
-
- $bucket->set('MADE_UP', 'Value');
- $this->assertEquals($bucket->get('MADE_UP'), 'Value');
-
- $bucket->set('MADE_uP', 'Value 2');
- $this->assertEquals($bucket->get('MADE_UP'), 'Value 2');
-
- $bucket->set('MADE_UP', 'Value 1', false);
- $this->assertEquals($bucket->get('MADE_UP', false), array('Value 2', 'Value 1'));
- }
+ // defaults
+ $this->assertNull($bucket->get('none'), '->get unknown values returns null');
+ $this->assertEquals('default', $bucket->get('none', 'default'), '->get unknown values returns default');
+ $this->assertEquals(array('default'), $bucket->get('none', 'default', false), '->get unknown values returns default as array');
- public function testHas()
- {
- $this->assertTrue($this->getBucket()->has('HTTP_HOST'));
- $this->assertFalse($this->getBucket()->has('MADE_UP'));
+ $bucket->set('foo', 'bor', false);
+ $this->assertEquals('bar', $bucket->get('foo'), '->get return first value');
+ $this->assertEquals(array('bar', 'bor'), $bucket->get('foo', 'nope', false), '->get return all values as array');
}
public function testContains()
{
- $this->assertTrue($this->getBucket()->contains('HTTP_HOST', 'localhost:80'));
- $this->assertFalse($this->getBucket()->contains('HTTP_HOST', 'localhost'));
- $this->assertFalse($this->getBucket()->contains('MADE_UP', 'made up value'));
- }
-
- public function testDelete()
- {
- $bucket = $this->getBucket();
+ $bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
+ $this->assertTrue($bucket->contains('foo', 'bar'), '->contains first value');
+ $this->assertTrue($bucket->contains('fuzz', 'bizz'), '->contains second value');
+ $this->assertFalse($bucket->contains('nope', 'nope'), '->contains unknown value');
+ $this->assertFalse($bucket->contains('foo', 'nope'), '->contains unknown value');
- $this->assertTrue($bucket->has('HTTP_HOST'));
- $bucket->delete('HTTP_HOST');
- $this->assertFalse($bucket->has('HTTP_HOST'));
-
- $this->assertFalse($bucket->has('MADE_UP'));
- $bucket->delete('MADE_UP');
- $this->assertFalse($bucket->has('MADE_UP'));
- }
-
- public function testSetCookieInvalidKey()
- {
- $this->setExpectedException('InvalidArgumentException');
- $this->getBucket()->setCookie('Invalid_cookie=', 'value');
+ // Multiple values
+ $bucket->set('foo', 'bor', false);
+ $this->assertTrue($bucket->contains('foo', 'bar'), '->contains first value');
+ $this->assertTrue($bucket->contains('foo', 'bor'), '->contains second value');
+ $this->assertFalse($bucket->contains('foo', 'nope'), '->contains unknown value');
}
- public function testSetCookieInvalidValue()
- {
- $this->setExpectedException('InvalidArgumentException');
- $this->getBucket()->setCookie('Invalid_cookie', 'value;');
- }
-
- public function testSetCookieEmptyKey()
- {
- $this->setExpectedException('InvalidArgumentException');
- $this->getBucket()->setCookie('', 'value');
- }
-
- public function testSetCookieRequest()
- {
- $this->type = 'request';
- $bucket = $this->getBucket();
-
- $bucket->setCookie('cookie_key', 'cookie_value');
- $this->assertEquals($bucket->get('Cookie'), 'cookie_key=cookie_value');
- }
-
- public function testSetCookieWithExpirationDateInteger()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
- $expires = new \DateTime('+7 days');
-
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'expires' => $expires->getTimestamp(),
- 'http_only' => false,
- ));
-
- $this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
- }
-
- public function testSetCookieWithExpirationDateString()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
- $expires = 'January 1, 2000 12:00:00';
-
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'expires' => $expires,
- 'http_only' => false,
- ));
-
- $this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
- }
-
- public function testSetCookieWithExpirationDateInvalidString()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
- $expires = 'This is not a date';
-
- $this->setExpectedException('InvalidArgumentException');
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'expires' => $expires,
- 'http_only' => false,
- ));
- }
-
- public function testSetCookieWithExpirationDateDateTime()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
- $expires = new \DateTime('+7 days');
-
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'expires' => $expires,
- 'http_only' => false,
- ));
-
- $this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
- }
-
- public function testSetCookieWithPath()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
- $path = '/some/awesome/path';
-
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'path' => $path,
- 'http_only' => false,
- ));
- $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; path=' . $path);
- }
-
- public function testSetCookieWithDomain()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
- $domain = 'example.com';
-
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'domain' => $domain,
- 'http_only' => false,
- ));
- $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; domain=' . $domain);
- }
-
- public function testSetCookieWithSecure()
+ public function testDelete()
{
- $this->type = 'response';
- $bucket = $this->getBucket();
+ $bucket = new HeaderBucket(array('foo' => 'bar', 'fuzz' => 'bizz'));
+ $bucket->delete('foo');
+ $bucket->delete('FuZZ');
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'secure' => true,
- 'http_only' => false,
- ));
- $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; secure');
+ $this->assertFalse($bucket->has('foo'));
+ $this->assertFalse($bucket->has('Fuzz'));
}
- public function testSetCookieWithHttpOnly()
+ public function testCacheControlDirectiveAccessors()
{
- $this->type = 'response';
- $bucket = $this->getBucket();
+ $bucket = new HeaderBucket();
+ $bucket->addCacheControlDirective('public');
- $bucket->setCookie('cookie_key', 'cookie_value', array(
- 'http_only' => true,
- ));
- $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; httponly');
- }
-
- public function testExpireCookieInvalidKey()
- {
- $this->setExpectedException('InvalidArgumentException');
- $this->getBucket()->expireCookie('Invalid_cookie=', 'value');
- }
-
- public function testExpireCookieEmptyKey()
- {
- $this->setExpectedException('InvalidArgumentException');
- $this->getBucket()->expireCookie('', 'value;');
- }
-
- public function testExpireCookie()
- {
- $this->type = 'response';
- $bucket = $this->getBucket();
+ $this->assertTrue($bucket->hasCacheControlDirective('public'));
+ $this->assertEquals(true, $bucket->getCacheControlDirective('public'));
+ $this->assertEquals('public', $bucket->get('cache-control'));
- $bucket->expireCookie('cookie_key');
- $this->assertRegExp('/^cookie\_key\=\; expires\=/i', $bucket->get('Set-Cookie'));
- }
-
- public function testExpireCookieRequest()
- {
- $bucket = $this->getBucket();
+ $bucket->addCacheControlDirective('max-age', 10);
+ $this->assertTrue($bucket->hasCacheControlDirective('max-age'));
+ $this->assertEquals(10, $bucket->getCacheControlDirective('max-age'));
+ $this->assertEquals('max-age=10, public', $bucket->get('cache-control'));
- $bucket->expireCookie('cookie_key');
- $this->assertNull($bucket->get('Set-Cookie'));
+ $bucket->removeCacheControlDirective('max-age');
+ $this->assertFalse($bucket->hasCacheControlDirective('max-age'));
}
- public function testArrayAccess()
+ public function testCacheControlDirectiveParsing()
{
- $bucket = $this->getBucket();
+ $bucket = new HeaderBucket(array('cache-control' => 'public, max-age=10'));
+ $this->assertTrue($bucket->hasCacheControlDirective('public'));
+ $this->assertEquals(true, $bucket->getCacheControlDirective('public'));
- $this->assertTrue(isset($bucket['HTTP_HOST']));
- $this->assertEquals($bucket['HTTP_HOST'], 'localhost:80');
+ $this->assertTrue($bucket->hasCacheControlDirective('max-age'));
+ $this->assertEquals(10, $bucket->getCacheControlDirective('max-age'));
- $bucket['MADE_UP'] = 'anything';
- $this->assertTrue(isset($bucket['MADE_UP']));
-
- unset($bucket['MADE_UP']);
- $this->assertFalse(isset($bucket['MADE_UP']));
+ $bucket->addCacheControlDirective('s-maxage', 100);
+ $this->assertEquals('max-age=10, public, s-maxage=100', $bucket->get('cache-control'));
}
- public function testIteratorAggreate()
+ public function testCacheControlDirectiveOverrideWithReplace()
{
- $bucket = $this->getBucket();
+ $bucket = new HeaderBucket(array('cache-control' => 'private, max-age=100'));
+ $bucket->replace(array('cache-control' => 'public, max-age=10'));
+ $this->assertTrue($bucket->hasCacheControlDirective('public'));
+ $this->assertEquals(true, $bucket->getCacheControlDirective('public'));
- foreach ($bucket as $key => $value) {
- $this->assertEquals($value, $this->normalized_headers[$key]);
- }
- }
-
- public function testNormalizeHeaderName()
- {
- $this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_HOST'), 'http-host');
- $this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_hoST'), 'http-host');
- $this->assertEquals(HeaderBucket::normalizeHeaderName('http-host'), 'http-host');
- }
-
-
- protected function getBucket()
- {
- return new HeaderBucket($this->headers, $this->type);
+ $this->assertTrue($bucket->hasCacheControlDirective('max-age'));
+ $this->assertEquals(10, $bucket->getCacheControlDirective('max-age'));
}
}
diff --git a/tests/Starlight/Component/Http/ParameterBucketTest.php b/tests/Starlight/Component/Http/ParameterBucketTest.php
index 965baa5..9a4c3e9 100755
--- a/tests/Starlight/Component/Http/ParameterBucketTest.php
+++ b/tests/Starlight/Component/Http/ParameterBucketTest.php
@@ -1,124 +1,67 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\ParameterBucket;
use Starlight\Component\Http\ParameterBucket;
/**
*/
class ParameterBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->params = array(
'test_1' => 'value_1',
'test_2' => 'value_2',
'test_3' => 'value_3',
+ 'test_4' => 12321,
+ 'test_5' => '12341',
+ 'test_6' => 'value_1matt23_again',
);
}
- public function testAll()
+ public function testGetAlpha()
{
- $this->assertEquals($this->getBucket()->all(), $this->params);
+ $this->assertEquals($this->getBucket()->getAlpha('test_1'), 'value');
+ $this->assertEquals($this->getBucket()->getAlpha('test_4'), '');
+ $this->assertEquals($this->getBucket()->getAlpha('test_5'), '');
+ $this->assertEquals($this->getBucket()->getAlpha('test_6'), 'valuemattagain');
}
- public function testKeys()
+ public function testGetAlnum()
{
- $this->assertEquals($this->getBucket()->keys(), array_keys($this->params));
+ $this->assertEquals($this->getBucket()->getAlnum('test_1'), 'value1');
+ $this->assertEquals($this->getBucket()->getAlnum('test_4'), '12321');
+ $this->assertEquals($this->getBucket()->getAlnum('test_5'), '12341');
+ $this->assertEquals($this->getBucket()->getAlnum('test_6'), 'value1matt23again');
}
- public function testReplace()
+ public function testGetDigits()
{
- $bucket = $this->getBucket();
- $new_parameters = array('test_4' => 'value_4');
- $bucket->replace($new_parameters);
-
- $this->assertEquals($bucket->all(), $new_parameters);
- $this->assertNotEquals($bucket->all(), $this->params);
+ $this->assertEquals($this->getBucket()->getDigits('test_1'), '1');
+ $this->assertEquals($this->getBucket()->getDigits('test_4'), '12321');
+ $this->assertEquals($this->getBucket()->getDigits('test_5'), '12341');
+ $this->assertEquals($this->getBucket()->getDigits('test_6'), '123');
}
- public function testAdd()
+ public function testGetInt()
{
- $bucket = $this->getBucket();
- $new_parameters = array('test_4' => 'value_4');
- $bucket->add($new_parameters);
-
- $this->assertEquals($bucket->all(), array_replace($this->params, $new_parameters));
- $this->assertNotEquals($bucket->all(), $this->params);
- }
-
- public function testGet()
- {
- $this->assertEquals($this->getBucket()->get('test_1'), 'value_1');
- $this->assertNull($this->getBucket()->get('test_4'));
- $this->assertEquals($this->getBucket()->get('test_4', 'value_4'), 'value_4');
- }
-
- public function testSet()
- {
- $bucket = $this->getBucket();
-
- $this->assertNull($bucket->get('test_4'));
- $bucket->set('test_4', 'value_4');
- $this->assertEquals($bucket->get('test_4'), 'value_4');
-
- $this->assertEquals($bucket->get('test_2'), 'value_2');
- $bucket->set('test_2', 'value_22');
- $this->assertEquals($bucket->get('test_2'), 'value_22');
- }
-
- public function testHas()
- {
- $this->assertTrue($this->getBucket()->has('test_1'));
- $this->assertFalse($this->getBucket()->has('test_4'));
- }
-
- public function testDelete()
- {
- $bucket = $this->getBucket();
-
- $this->assertTrue($bucket->has('test_1'));
- $bucket->delete('test_1');
- $this->assertFalse($bucket->has('test_1'));
-
- $this->assertFalse($bucket->has('test_4'));
- $bucket->delete('test_4');
- $this->assertFalse($bucket->has('test_4'));
- }
-
- public function testArrayAccess()
- {
- $bucket = $this->getBucket();
-
- $this->assertTrue(isset($bucket['test_1']));
- $this->assertEquals($bucket['test_1'], 'value_1');
-
- $bucket['test_4'] = 'anything';
- $this->assertTrue(isset($bucket['test_4']));
-
- unset($bucket['test_4']);
- $this->assertFalse(isset($bucket['test_4']));
- }
-
- public function testIteratorAggreate()
- {
- $bucket = $this->getBucket();
-
- foreach ($bucket as $key => $value) {
- $this->assertEquals($value, $this->params[$key]);
- }
+ $this->assertEquals($this->getBucket()->getInt('test_1'), 0);
+ $this->assertEquals($this->getBucket()->getInt('test_4'), 12321);
+ $this->assertEquals($this->getBucket()->getInt('test_5'), 12341);
+ $this->assertEquals($this->getBucket()->getInt('test_6'), 0);
}
protected function getBucket()
{
return new ParameterBucket($this->params);
}
}
diff --git a/tests/Starlight/Component/StdLib/StorageBucketTest.php b/tests/Starlight/Component/StdLib/StorageBucketTest.php
new file mode 100755
index 0000000..6513d07
--- /dev/null
+++ b/tests/Starlight/Component/StdLib/StorageBucketTest.php
@@ -0,0 +1,124 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\StdLib\StorageBucket;
+use Starlight\Component\StdLib\StorageBucket;
+
+
+/**
+ */
+class StorageBucketTest extends \PHPUnit_Framework_TestCase
+{
+ public function setup()
+ {
+ $this->params = array(
+ 'test_1' => 'value_1',
+ 'test_2' => 'value_2',
+ 'test_3' => 'value_3',
+ );
+ }
+
+ public function testAll()
+ {
+ $this->assertEquals($this->getBucket()->all(), $this->params);
+ }
+
+ public function testKeys()
+ {
+ $this->assertEquals($this->getBucket()->keys(), array_keys($this->params));
+ }
+
+ public function testReplace()
+ {
+ $bucket = $this->getBucket();
+ $new_parameters = array('test_4' => 'value_4');
+ $bucket->replace($new_parameters);
+
+ $this->assertEquals($bucket->all(), $new_parameters);
+ $this->assertNotEquals($bucket->all(), $this->params);
+ }
+
+ public function testAdd()
+ {
+ $bucket = $this->getBucket();
+ $new_parameters = array('test_4' => 'value_4');
+ $bucket->add($new_parameters);
+
+ $this->assertEquals($bucket->all(), array_replace($this->params, $new_parameters));
+ $this->assertNotEquals($bucket->all(), $this->params);
+ }
+
+ public function testGet()
+ {
+ $this->assertEquals($this->getBucket()->get('test_1'), 'value_1');
+ $this->assertNull($this->getBucket()->get('test_4'));
+ $this->assertEquals($this->getBucket()->get('test_4', 'value_4'), 'value_4');
+ }
+
+ public function testSet()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertNull($bucket->get('test_4'));
+ $bucket->set('test_4', 'value_4');
+ $this->assertEquals($bucket->get('test_4'), 'value_4');
+
+ $this->assertEquals($bucket->get('test_2'), 'value_2');
+ $bucket->set('test_2', 'value_22');
+ $this->assertEquals($bucket->get('test_2'), 'value_22');
+ }
+
+ public function testHas()
+ {
+ $this->assertTrue($this->getBucket()->has('test_1'));
+ $this->assertFalse($this->getBucket()->has('test_4'));
+ }
+
+ public function testDelete()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertTrue($bucket->has('test_1'));
+ $bucket->delete('test_1');
+ $this->assertFalse($bucket->has('test_1'));
+
+ $this->assertFalse($bucket->has('test_4'));
+ $bucket->delete('test_4');
+ $this->assertFalse($bucket->has('test_4'));
+ }
+
+ public function testArrayAccess()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertTrue(isset($bucket['test_1']));
+ $this->assertEquals($bucket['test_1'], 'value_1');
+
+ $bucket['test_4'] = 'anything';
+ $this->assertTrue(isset($bucket['test_4']));
+
+ unset($bucket['test_4']);
+ $this->assertFalse(isset($bucket['test_4']));
+ }
+
+ public function testIteratorAggreate()
+ {
+ $bucket = $this->getBucket();
+
+ foreach ($bucket as $key => $value) {
+ $this->assertEquals($value, $this->params[$key]);
+ }
+ }
+
+ protected function getBucket()
+ {
+ return new StorageBucket($this->params);
+ }
+}
|
synewaves/starlight | 8fda0481d941fb128f68e00e8c0d183f40be8e37 | Standardize null checks | diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index 3a6da01..34240a7 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,318 +1,313 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class for request/response headers
*/
class HeaderBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Headers
* @var array
*/
protected $headers;
- // /**
- // * Wrapper class for request/response headers
- // */
- // protected $cache_control;
-
/**
* Type (request, response)
* @var string
*/
protected $type;
/**
* Constructor
* @param array $headers An array of HTTP headers
* @param string $type The type (null, request, or response)
*/
public function __construct(array $headers = array(), $type = null)
{
$this->replace($headers);
if ($type !== null && !in_array($type, array('request', 'response'))) {
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBucket.', $type));
}
$this->type = $type;
}
/**
* Returns the headers
* @return array An array of headers
*/
public function all()
{
return $this->headers;
}
/**
* Returns the parameter keys
* @return array An array of parameter keys
*/
public function keys()
{
return array_keys($this->headers);
}
/**
* Replaces the current HTTP headers by a new set
* @param array $headers An array of HTTP headers
* @return HeaderBucket this instance
*/
public function replace(array $headers = array())
{
$this->cache_control = null;
$this->headers = array();
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
return $this;
}
/**
* Returns a header value by name
* @param string $key The header name
* @param Boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function get($key, $first = true)
{
$key = static::normalizeHeaderName($key);
if (!array_key_exists($key, $this->headers)) {
return $first ? null : array();
}
if ($first) {
return count($this->headers[$key]) ? $this->headers[$key][0] : '';
} else {
return $this->headers[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
$key = static::normalizeHeaderName($key);
if (!is_array($values)) {
$values = array($values);
}
if ($replace === true || !isset($this->headers[$key])) {
$this->headers[$key] = $values;
} else {
$this->headers[$key] = array_merge($this->headers[$key], $values);
}
return $this;
}
/**
* Returns true if the HTTP header is defined
* @param string $key The HTTP header
* @return Boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists(static::normalizeHeaderName($key), $this->headers);
}
/**
* Returns true if the given HTTP header contains the given value
* @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, false));
}
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->headers[static::normalizeHeaderName($key)]);
}
return $this;
}
/**
* Set cookie variable
*
* Available options:
*
* <ul>
* <li><b>expires</b> <i>(integer)</i>: cookie expiration time (default: 0 [end of session])</li>
* <li><b>path</b> <i>(string)</i>: path cookie is valid for (default: '')</li>
* <li><b>domain</b> <i>(string)</i>: domain cookie is valid for (default: '')</li>
* <li><b>secure/b> <i>(boolean)</i>: should cookie only be used on a secure connection (default: false)</li>
* <li><b>http_only</b> <i>(string)</i>: cookie only valid over http? [not supported by all browsers] (default: true)</li>
* <li><b>encode</b> <i>(boolean)</i>: urlencode cookie value (default: true)</li>
* </ul>
* @param string $key cookie key
* @param mixed $value value
* @param array $options options hash (see above)
* @return HeaderBucket this instance
*/
public function setCookie($key, $value, $options = array())
{
$default_options = array(
'expires' => null,
'path' => null,
'domain' => null,
'secure' => false,
'http_only' => true,
);
$options += $default_options;
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie key "%s" contains invalid characters.', $key));
}
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
if (trim($key) == '') {
throw new \InvalidArgumentException('The cookie key cannot be empty');
}
$cookie = sprintf('%s=%s', $key, urlencode($value));
if ($this->type == 'request') {
$this->set('Cookie', $cookie);
return;
}
if ($options['expires'] !== null) {
if (is_numeric($options['expires'])) {
$options['expires'] = (int) $options['expires'];
} elseif ($options['expires'] instanceof \DateTime) {
$options['expires'] = $options['expires']->getTimestamp();
} else {
$options['expires'] = strtotime($options['expires']);
if ($options['expires'] === false || $options['expires'] == -1) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $options['expires']));
}
}
$cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($options['domain']) {
$cookie .= '; domain=' . $options['domain'];
}
if ($options['path'] && $options['path'] !== '/') {
$cookie .= '; path=' . $options['path'];
}
if ($options['secure']) {
$cookie .= '; secure';
}
if ($options['http_only']) {
$cookie .= '; httponly';
}
$this->set('Set-Cookie', $cookie, false);
return $this;
}
/**
* Expire a cookie variable
* @param string $key cookie key
* @return HeaderBucket this instance
*/
public function expireCookie($key)
{
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
}
if (!$key) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
if ($this->type == 'request') {
return;
}
$cookie = sprintf('%s=; expires=', $key, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
$this->set('Set-Cookie', $cookie, false);
return $this;
}
// -----------
// ArrayAccess
// -----------
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
public function offsetUnset($offset)
{
return $this->delete($offset);
}
// -----------------
// IteratorAggregate
// -----------------
public function getIterator()
{
return new \ArrayIterator($this->all());
}
/**
* Normalizes an HTTP header name
* @param string $key The HTTP header name
* @return string The normalized HTTP header name
*/
static public function normalizeHeaderName($key)
{
return strtr(strtolower($key), '_', '-');
}
}
diff --git a/src/Starlight/Component/Http/Request.php b/src/Starlight/Component/Http/Request.php
index c5f5ef5..dd6dcab 100755
--- a/src/Starlight/Component/Http/Request.php
+++ b/src/Starlight/Component/Http/Request.php
@@ -1,315 +1,317 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Request
*/
class Request
{
public static $local_ips = array('127.0.0.1');
public $post;
public $get;
public $cookies;
public $files;
public $server;
public $headers;
protected $host;
protected $port;
protected $remote_ip;
protected $url;
/**
* Constructor
* @param array $post POST values
* @param array $get GET values
* @param array $cookies COOKIE values
* @param array $files FILES values
* @param array $server SERVER values
*/
public function __construct(array $post = null, array $get = null, array $cookies = null, array $files = null, array $server = null)
{
$this->post = new ParameterBucket($post ?: $_POST);
$this->get = new ParameterBucket($get ?: $_GET);
$this->cookies = new ParameterBucket($cookies ?: $_COOKIE);
$this->files = new ParameterBucket($files ?: $_FILES);
$this->server = new ParameterBucket($server ?: $_SERVER);
$this->headers = new HeaderBucket($this->initializeHeaders(), 'request');
}
/**
* Clone
*/
public function __clone()
{
$this->post = clone $this->post;
$this->get = clone $this->get;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Get a value from the request
*
* Order or precedence: GET, POST, COOKIE
*/
public function get($key, $default = null)
{
return $this->get->get($key, $this->post->get($key, $this->cookies->get($key, $default)));
}
/**
* Gets request method, lowercased
*
* Method can come from three places in this order:
* <ol>
* <li>$_POST[_method]</li>
* <li>$_SERVER[X_HTTP_METHOD_OVERRIDE]</li>
* <li>$_SERVER[REQUEST_METHOD]</li>
* </ol>
* @return string request method
*/
public function getMethod()
{
$method = $this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD')));
- return !is_null($method) ? strtolower($method) : null;
+ return $method !== null ? strtolower($method) : null;
}
/**
* Is this a DELETE request
* @return boolean is DELETE request
*/
public function isDelete()
{
return $this->getMethod() == 'delete';
}
/**
* Is this a GET request
* @see head()
* @return boolean is GET request
*/
public function isGet()
{
return $this->isHead();
}
/**
* Is this a POST request
* @return boolean is POST request
*/
public function isPost()
{
return $this->getMethod() == 'post';
}
/**
* Is this a HEAD request
*
* Functionally equivalent to get()
* @return boolean is HEAD request
*/
public function isHead()
{
return $this->getMethod() == 'head' || $this->getMethod() == 'get';
}
/**
* Is this a PUT request
* @return boolean is PUT request
*/
public function isPut()
{
return $this->getMethod() == 'put';
}
/**
* Is this an SSL request
* @return boolean is SSL request
*/
public function isSsl()
{
return strtolower($this->server->get('HTTPS')) == 'on';
}
/**
* Gets server protocol
* @return string protocol
*/
public function getProtocol()
{
return $this->isSsl() ? 'https://' : 'http://';
}
/**
* Gets the server host
* @return string host
*/
public function getHost()
{
- if (is_null($this->host)) {
+ if ($this->host === null) {
$host = $this->server->get('HTTP_X_FORWARDED_HOST', $this->server->get('HTTP_HOST'));
$pos = strpos($host, ':');
if ($pos !== false) {
$this->host = substr($host, 0, $pos);
- $this->port = is_null($this->port) ? (int) substr($host, $pos + 1) : null;
+ if ($this->port === null) {
+ $this->port = (int) substr($host, $pos + 1);
+ }
} else {
$this->host = $host;
}
}
return $this->host;
}
/**
* Gets the server port
* @return integer port
*/
public function getPort()
{
- if (is_null($this->port)) {
+ if ($this->port === null) {
$this->port = (int) $this->server->get('SERVER_PORT', $this->getStandardPort());
}
return $this->port;
}
/**
* Gets the standard port number for the current protocol
* @return integer port (443, 80)
*/
public function getStandardPort()
{
return $this->isSsl() ? 443 : 80;
}
/**
* Gets the port string with colon delimiter if not standard port
* @return string port
*/
public function getPortString()
{
return (in_array($this->getPort(), array(443, 80))) ? '' : ':' . $this->getPort();
}
/**
* Gets the host with the port
* @return string host with port
*/
public function getHostWithPort()
{
return $this->getHost() . $this->getPortString();
}
/**
* Gets the client's remote ip
* @return string IP
*/
public function getRemoteIp()
{
- if (is_null($this->remote_ip)) {
+ if ($this->remote_ip === null) {
$remote_ips = null;
if ($x_forward = $this->server->get('HTTP_X_FORWARDED_FOR')) {
$remote_ips = array_map('trim', explode(',', $x_forward));
}
$client_ip = $this->server->get('HTTP_CLIENT_IP');
if ($client_ip) {
if (is_array($remote_ips) && !in_array($client_ip, $remote_ips)) {
// don't know which came from the proxy, and which from the user
throw new Exception\IpSpoofingException(sprintf("IP spoofing attack?!\nHTTP_CLIENT_IP=%s\nHTTP_X_FORWARDED_FOR=%s", $this->server->get('HTTP_CLIENT_IP'), $this->server->get('HTTP_X_FORWARDED_FOR')));
}
$this->remote_ip = $client_ip;
} elseif (is_array($remote_ips)) {
$this->remote_ip = $remote_ips[0];
} else {
$this->remote_ip = $this->server->get('REMOTE_ADDR');
}
}
return $this->remote_ip;
}
/**
* Is this request local?
* @return boolean local
*/
public function isLocal()
{
return in_array($this->getRemoteIp(), static::$local_ips);
}
/**
* Check if the request is an XMLHttpRequest (AJAX)
* @return boolean is XHR (AJAX) request
*/
public function isXmlHttpRequest()
{
return (bool) preg_match('/XMLHttpRequest/i', $this->server->get('HTTP_X_REQUESTED_WITH'));
}
/**
* Gets the full server url with protocol and port
* @return string server path
*/
public function getServer()
{
return $this->getProtocol() . $this->getHostWithPort();
}
/**
* Gets the requested URI path without domain or script name
* @return string uri
*/
public function getUri()
{
$url = $this->server->get('REQUEST_URI');
return trim($url) != '' ? $url : '/';
}
/**
* Gets the requested route from the URI
* @return string route
*/
public function getRoute()
{
$route = $this->getUri();
// remove query string
if (($qs = strpos($route, '?')) !== false) {
$route = substr($route, 0, $qs);
}
return $route;
}
/**
* Initialize request headers for HeaderBucket
* @return array headers
*/
protected function initializeHeaders()
{
$headers = array();
foreach ($this->server->all() as $key => $value) {
if (strtolower(substr($key, 0, 5)) === 'http_') {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
}
diff --git a/src/Starlight/Component/Routing/ResourceRoute.php b/src/Starlight/Component/Routing/ResourceRoute.php
index f2e7921..161f1fe 100755
--- a/src/Starlight/Component/Routing/ResourceRoute.php
+++ b/src/Starlight/Component/Routing/ResourceRoute.php
@@ -1,327 +1,327 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Inflector\Inflector;
/**
* ResourceRoute
*/
class ResourceRoute implements CompilableInterface
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%p', 'verb' => 'get', 'url' => '(.:format)'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'create' => array('name' => '%p', 'verb' => 'post', 'url' => '(.:format)'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id(.:format)'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action(.:format)'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id(.:format)'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id(.:format)'),
);
/**
* Default path names
* @var array
*/
protected static $resource_names = array(
'add' => 'add',
'edit' => 'edit',
'delete' => 'delete',
);
public $resource;
public $controller;
public $except;
public $only;
public $constraints;
public $singular;
public $plural;
public $path_names;
public $module;
public $path_prefix;
public $name_prefix;
public $member = array();
public $collection = array();
public $map_member_collection_scope = null;
/**
* Constructor
* @param string $resource resource name
* @param array $options options hash
*/
public function __construct($resource = null, array $options = array())
{
- if (!is_null($resource)) {
+ if ($resource !== null) {
$this->resource = $resource;
$this->controller = $this->plural = Inflector::pluralize($this->resource);
$this->singular = Inflector::singularize($this->controller);
if (count($options) > 0) {
foreach ($options as $key => $value) {
$this->$key($value);
}
}
}
}
/**
* Set except routes from $resources_map
* @param array $except except resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function except(array $except)
{
$this->only = null;
$this->except = $except;
return $this;
}
/**
* Set only routes from $resources_map
* @param array $only only resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function only(array $only)
{
$this->except = null;
$this->only = $only;
return $this;
}
/**
* Set controller
* @param string $controller controller name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function controller($controller)
{
$this->controller = $controller;
return $this;
}
/**
* Set contraints
* @param mixed $constraints constraints
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set name for route paths
* @param string $name path name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function name($name)
{
$single = explode(' ', strtolower(Inflector::humanize($name)));
$plural = $single;
$count = count($single);
$single[$count - 1] = Inflector::singularize($single[$count - 1]);
$plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
$this->singular = implode('_', $single);
$this->plural = implode('_', $plural);
return $this;
}
/**
* Set path names for special routes
* @param array $names path name overrides
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function pathNames(array $names)
{
$this->path_names = $names;
return $this;
}
/**
* Set module/namespace for resource
* @param string $module module/namespace name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Set member routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function member(\Closure $callback)
{
$this->map_member_collection_scope = 'member';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set collection routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function collection(\Closure $callback)
{
$this->map_member_collection_scope = 'collection';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set an extra route which responds to GET requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function get($path, $options = array())
{
return $this->mapMethod('get', $path, $options);
}
/**
* Set an extra route which responds to PUT requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function put($path, $options = array())
{
return $this->mapMethod('put', $path, $options);
}
/**
* Set an extra route which responds to POST requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function post($path, $options = array())
{
return $this->mapMethod('post', $path, $options);
}
/**
* Set an extra route which responds to DELETE requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function delete($path, $options = array())
{
return $this->mapMethod('delete', $path, $options);
}
/**
* Map extra routes through a common interface
* @param string $method HTTP method
* @param string $path path
* @param array $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
protected function mapMethod($method, $path, $options = array())
{
$on = isset($options['on']) ? $options['on'] : $this->map_member_collection_scope;
if (!$on || ($on != 'member' && $on != 'collection')) {
throw new \InvalidArgumentException('You must pass a valid "on" option (collection/method) to ' . $method);
}
array_push($this->$on, array($path, strtoupper($method)));
return $this;
}
/**
* Compiles this resource route into individual \Starlight\Component\Routing\Route
* @return array array of \Starlight\Component\Routing\Route routes
*/
public function compile()
{
$generators = static::$resources_map;
if ($this->except) {
$generators = array_diff_key($generators, array_fill_keys($this->except, true));
} elseif ($this->only) {
$generators = array_intersect_key($generators, array_fill_keys($this->only, true));
}
if (is_array($this->path_names)) {
$this->path_names += static::$resource_names;
} else {
$this->path_names = static::$resource_names;
}
if ($this->module) {
$this->controller = $this->module . '\\' . $this->controller;
}
if (count($this->member) > 0) {
foreach ($this->member as $member) {
list($name, $verb) = $member;
$generators[$name] = array('name' => $name . '_%s', 'verb' => $verb, 'url' => '/:id/' . $name . '(.:format)');
}
}
if (count($this->collection) > 0) {
foreach ($this->collection as $collection) {
list($name, $verb) = $collection;
$generators[$name] = array('name' => $name . '_%p', 'verb' => $verb, 'url' => '/' . $name . '(.:format)');
}
}
$routes = array();
foreach ($generators as $action => $parts) {
$path = $parts['url'];
if (strpos($path, ':action') !== false) {
$path = str_replace(':action', $this->path_names[$action], $path);
}
$r = new Route($this->path_prefix . '/' . $this->resource . $path, $this->controller . '::' . $action);
$r->methods(array($parts['verb']));
$name = str_replace('%s', $this->name_prefix . $this->singular, $parts['name']);
$name = str_replace('%p', $this->name_prefix . $this->plural, $name);
$r->name($name);
if ($this->constraints) {
$r->constraints($this->constraints);
}
$routes[] = $r->compile();
}
return $routes;
}
}
|
synewaves/starlight | 9cac8167b9d56ce7bb7b552577af45ded154c42d | Added event dispatcher and tests | diff --git a/src/Starlight/Component/EventDispatcher/Event.php b/src/Starlight/Component/EventDispatcher/Event.php
index a6f9170..7826478 100755
--- a/src/Starlight/Component/EventDispatcher/Event.php
+++ b/src/Starlight/Component/EventDispatcher/Event.php
@@ -1,134 +1,138 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\EventDispatcher;
/**
* Event
*/
class Event implements EventInterface
{
- protected $value = null;
- protected $processed = false;
- protected $subject;
- protected $name;
- protected $parameters;
-
- /**
- * Constructs a new Event.
- *
- * @param mixed $subject The subject
- * @param string $name The event name
- * @param array $parameters An array of parameters
- */
- public function __construct($subject, $name, $parameters = array())
- {
- $this->subject = $subject;
- $this->name = $name;
- $this->parameters = $parameters;
- }
-
- /**
- * Returns the subject.
- *
- * @return mixed The subject
- */
- public function getSubject()
- {
- return $this->subject;
- }
-
- /**
- * Returns the event name.
- *
- * @return string The event name
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Sets the processed flag to true.
- *
- * This method must be called by listeners when
- * it has processed the event (it is only meaninful
- * when the event has been notified with the notifyUntil()
- * dispatcher method.
- */
- public function setProcessed()
- {
- $this->processed = true;
- }
-
- /**
- * Returns whether the event has been processed by a listener or not.
- *
- * This method is only meaningful for events notified
- * with notifyUntil().
- *
- * @return Boolean true if the event has been processed, false otherwise
- */
- public function isProcessed()
- {
- return $this->processed;
- }
-
- /**
- * Returns the event parameters.
- *
- * @return array The event parameters
- */
- public function all()
- {
- return $this->parameters;
- }
-
- /**
- * Returns true if the parameter exists.
- *
- * @param string $name The parameter name
- *
- * @return Boolean true if the parameter exists, false otherwise
- */
- public function has($name)
- {
- return array_key_exists($name, $this->parameters);
- }
-
- /**
- * Returns a parameter value.
- *
- * @param string $name The parameter name
- *
- * @return mixed The parameter value
- *
- * @throws \InvalidArgumentException When parameter doesn't exists for this event
- */
- public function get($name)
- {
- if (!array_key_exists($name, $this->parameters)) {
- throw new \InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name));
- }
-
- return $this->parameters[$name];
- }
-
- /**
- * Sets a parameter.
- *
- * @param string $name The parameter name
- * @param mixed $value The parameter value
- */
- public function set($name, $value)
- {
- $this->parameters[$name] = $value;
- }
+ /**
+ * Is processed flag
+ * @var boolean
+ */
+ protected $processed = false;
+
+ /**
+ * Subeject
+ * @var mixed
+ */
+ protected $subject;
+
+ /**
+ * Unique idenfitier
+ * @var string
+ */
+ protected $name;
+
+ /**
+ * Parameters
+ * @var array
+ */
+ protected $parameters;
+
+
+ /**
+ * Constructor
+ * @param mixed $subject The subject
+ * @param string $name The event name
+ * @param array $parameters An array of parameters
+ */
+ public function __construct($subject, $name, $parameters = array())
+ {
+ $this->subject = $subject;
+ $this->name = $name;
+ $this->parameters = $parameters;
+ }
+
+ /**
+ * Returns the event's subject
+ * @return mixed subject
+ */
+ public function getSubject()
+ {
+ return $this->subject;
+ }
+
+ /**
+ * Returns the event's name
+ * @return string name
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Sets the event's processed flag to true
+ *
+ * This method must be called by listeners after the listener has processed the event.
+ * (This is only used when calling notifyUntil() in the event manager)
+ */
+ public function setProcessed()
+ {
+ $this->processed = true;
+ }
+
+ /**
+ * Returns whether the event has been processed by a listener or not
+ * @see setProcessed()
+ * @return boolean true if the event has been processed
+ */
+ public function isProcessed()
+ {
+ return $this->processed;
+ }
+
+ /**
+ * Returns the event's parameters
+ * @return array parameters
+ */
+ public function all()
+ {
+ return $this->parameters;
+ }
+
+ /**
+ * Returns true if the parameter exists
+ * @param string $name The parameter name
+ * @return boolean true if the parameter exists
+ */
+ public function has($name)
+ {
+ return array_key_exists($name, $this->parameters);
+ }
+
+ /**
+ * Returns a parameter value
+ * @param string $name The parameter name
+ * @return mixed The parameter value
+ * @throws \InvalidArgumentException When parameter doesn't exist
+ */
+ public function get($name)
+ {
+ if (!array_key_exists($name, $this->parameters)) {
+ throw new \InvalidArgumentException(sprintf('The event "%s" doesn\'t have a "%s" parameter', $this->name, $name));
+ }
+
+ return $this->parameters[$name];
+ }
+
+ /**
+ * Sets a parameter
+ * @param string $name The parameter name
+ * @param mixed $value The parameter value
+ */
+ public function set($name, $value)
+ {
+ $this->parameters[$name] = $value;
+ }
}
diff --git a/src/Starlight/Component/EventDispatcher/EventDispatcher.php b/src/Starlight/Component/EventDispatcher/EventDispatcher.php
new file mode 100755
index 0000000..42196e0
--- /dev/null
+++ b/src/Starlight/Component/EventDispatcher/EventDispatcher.php
@@ -0,0 +1,142 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\EventDispatcher;
+
+/**
+ * EventDispatcher
+ */
+class EventDispatcher implements EventDispatcherInterface
+{
+ /**
+ * Registered event listeners
+ * @var array
+ */
+ protected $listeners = array();
+
+
+ /**
+ * Connects a listener to a given event name
+ * Listeners with a higher priority are executed first
+ * @param string $name An event name
+ * @param mixed $listener A PHP callable
+ * @param integer $priority The priority (between -10 and 10 -- defaults to 0)
+ */
+ public function connect($name, $listener, $priority = 0)
+ {
+ if (!isset($this->listeners[$name][$priority])) {
+ if (!isset($this->listeners[$name])) {
+ $this->listeners[$name] = array();
+ }
+ $this->listeners[$name][$priority] = array();
+ }
+
+ $this->listeners[$name][$priority][] = $listener;
+ }
+
+ /**
+ * Disconnects one, or all listeners for the given event name
+ * @param string $name An event name
+ * @param mixed|null $listener The listener to remove, or null to remove all
+ */
+ public function disconnect($name, $listener = null)
+ {
+ if (!isset($this->listeners[$name])) {
+ return;
+ }
+
+ if ($listener === null) {
+ unset($this->listeners[$name]);
+ return;
+ }
+
+ foreach ($this->listeners[$name] as $priority => $callables) {
+ foreach ($callables as $i => $callable) {
+ if ($listener === $callable) {
+ unset($this->listeners[$name][$priority][$i]);
+ }
+ }
+ }
+ }
+
+ /**
+ * Notifies all listeners of a given event
+ * @param EventInterface $event An EventInterface instance
+ */
+ public function notify(EventInterface $event)
+ {
+ foreach ($this->getListeners($event->getName()) as $listener) {
+ call_user_func($listener, $event);
+ }
+ }
+
+ /**
+ * Notifies all listeners of a given event until one processes the event
+ * A listener tells the dispatcher that it has processed the event by calling the setProcessed() method on it.
+ * It can then return a value that will be fowarded to the caller.
+ * @param EventInterface $event An EventInterface instance
+ * @return mixed The returned value of the listener that processed the event
+ */
+ public function notifyUntil(EventInterface $event)
+ {
+ foreach ($this->getListeners($event->getName()) as $listener) {
+ $ret = call_user_func($listener, $event);
+ if ($event->isProcessed()) {
+ return $ret;
+ }
+ }
+ }
+
+ /**
+ * Filters a value by calling all listeners of a given event
+ * @param EventInterface $event An EventInterface instance
+ * @param mixed $value The value to be filtered
+ * @return mixed The filtered value
+ */
+ public function filter(EventInterface $event, $value)
+ {
+ foreach ($this->getListeners($event->getName()) as $listener) {
+ $value = call_user_func($listener, $event, $value);
+ }
+
+ return $value;
+ }
+
+ /**
+ * Returns true if the given event name has some listeners
+ * @param string $name The event name
+ * @return Boolean true if some listeners are connected, false otherwise
+ */
+ public function hasListeners($name)
+ {
+ return (Boolean) count($this->getListeners($name));
+ }
+
+ /**
+ * Returns all listeners associated with a given event name
+ * @param string $name The event name
+ * @return array An array of listeners
+ */
+ public function getListeners($name)
+ {
+ if (!isset($this->listeners[$name])) {
+ return array();
+ }
+
+ $listeners = array();
+ $all = $this->listeners[$name];
+ krsort($all);
+ foreach ($all as $l) {
+ $listeners = array_merge($listeners, $l);
+ }
+
+ return $listeners;
+ }
+}
diff --git a/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php b/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php
new file mode 100755
index 0000000..57f8964
--- /dev/null
+++ b/src/Starlight/Component/EventDispatcher/EventDispatcherInterface.php
@@ -0,0 +1,71 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\EventDispatcher;
+
+/**
+ * EventDispatcherInterface describes an event dispatcher class
+ * @see http://developer.apple.com/documentation/Cocoa/Conceptual/Notifications/index.html Apple's Cocoa framework
+ */
+interface EventDispatcherInterface
+{
+ /**
+ * Connects a listener to a given event name
+ * Listeners with a higher priority are executed first
+ * @param string $name An event name
+ * @param mixed $listener A PHP callable
+ * @param integer $priority The priority (between -10 and 10 -- defaults to 0)
+ */
+ function connect($name, $listener, $priority = 0);
+
+ /**
+ * Disconnects one, or all listeners for the given event name
+ * @param string $name An event name
+ * @param mixed|null $listener The listener to remove, or null to remove all
+ */
+ function disconnect($name, $listener = null);
+
+ /**
+ * Notifies all listeners of a given event
+ * @param EventInterface $event An EventInterface instance
+ */
+ function notify(EventInterface $event);
+
+ /**
+ * Notifies all listeners of a given event until one processes the event
+ * A listener tells the dispatcher that it has processed the event by calling the setProcessed() method on it.
+ * It can then return a value that will be fowarded to the caller.
+ * @param EventInterface $event An EventInterface instance
+ * @return mixed The returned value of the listener that processed the event
+ */
+ function notifyUntil(EventInterface $event);
+
+ /**
+ * Filters a value by calling all listeners of a given event
+ * @param EventInterface $event An EventInterface instance
+ * @param mixed $value The value to be filtered
+ * @return mixed The filtered value
+ */
+ function filter(EventInterface $event, $value);
+
+ /**
+ * Returns true if the given event name has some listeners
+ * @param string $name The event name
+ * @return Boolean true if some listeners are connected, false otherwise
+ */
+ function hasListeners($name);
+
+ /**
+ * Returns all listeners associated with a given event name
+ * @param string $name The event name
+ * @return array An array of listeners
+ */
+ function getListeners($name);
+}
diff --git a/src/Starlight/Component/EventDispatcher/EventInterface.php b/src/Starlight/Component/EventDispatcher/EventInterface.php
new file mode 100755
index 0000000..b38947c
--- /dev/null
+++ b/src/Starlight/Component/EventDispatcher/EventInterface.php
@@ -0,0 +1,72 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\EventDispatcher;
+
+/**
+ * EventInterface
+ */
+interface EventInterface
+{
+ /**
+ * Returns the event's subject
+ * @return mixed subject
+ */
+ function getSubject();
+
+ /**
+ * Returns the event's name
+ * @return string name
+ */
+ function getName();
+
+ /**
+ * Sets the event's processed flag to true
+ *
+ * This method must be called by listeners after the listener has processed the event.
+ * (This is only used when calling notifyUntil() in the event manager)
+ */
+ function setProcessed();
+
+ /**
+ * Returns whether the event has been processed by a listener or not
+ * @see setProcessed()
+ * @return boolean true if the event has been processed
+ */
+ function isProcessed();
+
+ /**
+ * Returns the event's parameters
+ * @return array parameters
+ */
+ function all();
+
+ /**
+ * Returns true if the parameter exists
+ * @param string $name The parameter name
+ * @return boolean true if the parameter exists
+ */
+ function has($name);
+
+ /**
+ * Returns a parameter value
+ * @param string $name The parameter name
+ * @return mixed The parameter value
+ * @throws \InvalidArgumentException When parameter doesn't exist
+ */
+ function get($name);
+
+ /**
+ * Sets a parameter
+ * @param string $name The parameter name
+ * @param mixed $value The parameter value
+ */
+ function set($name, $value);
+}
diff --git a/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php b/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php
new file mode 100755
index 0000000..06b53af
--- /dev/null
+++ b/tests/Starlight/Component/EventDispatcher/EventDispatcherTest.php
@@ -0,0 +1,136 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\EventDispatcher;
+use Starlight\Component\EventDispatcher\EventDispatcher;
+
+/**
+ */
+class EventDispatcherTest extends \PHPUnit_Framework_TestCase
+{
+ public function testConnectAndDisconnect()
+ {
+ $dispatcher = new EventDispatcher();
+
+ $dispatcher->connect('bar', 'listenToBar');
+ $this->assertEquals(array('listenToBar'), $dispatcher->getListeners('bar'), '->connect() connects a listener to an event name');
+ $dispatcher->connect('bar', 'listenToBarBar');
+ $this->assertEquals(array('listenToBar', 'listenToBarBar'), $dispatcher->getListeners('bar'), '->connect() can connect several listeners for the same event name');
+
+ $dispatcher->connect('barbar', 'listenToBarBar');
+
+ $dispatcher->disconnect('bar');
+ $this->assertEquals(array(), $dispatcher->getListeners('bar'), '->disconnect() without a listener disconnects all listeners of for an event name');
+ $this->assertEquals(array('listenToBarBar'), $dispatcher->getListeners('barbar'), '->disconnect() without a listener disconnects all listeners of for an event name');
+ }
+
+ public function testGetHasListeners()
+ {
+ $dispatcher = new EventDispatcher();
+
+ $this->assertFalse($dispatcher->hasListeners('foo'), '->hasListeners() returns false if the event has no listener');
+ $dispatcher->connect('foo', 'listenToFoo');
+ $this->assertEquals(true, $dispatcher->hasListeners('foo'), '->hasListeners() returns true if the event has some listeners');
+ $dispatcher->disconnect('foo', 'listenToFoo');
+ $this->assertFalse($dispatcher->hasListeners('foo'), '->hasListeners() returns false if the event has no listener');
+
+ $dispatcher->connect('bar', 'listenToBar');
+ $this->assertEquals(array('listenToBar'), $dispatcher->getListeners('bar'), '->getListeners() returns an array of listeners connected to the given event name');
+ $this->assertEquals(array(), $dispatcher->getListeners('foobar'), '->getListeners() returns an empty array if no listener are connected to the given event name');
+ }
+
+ public function testNotify()
+ {
+ $listener = new TestListener();
+ $dispatcher = new EventDispatcher();
+ $dispatcher->connect('foo', array($listener, 'listenToFoo'));
+ $dispatcher->connect('foo', array($listener, 'listenToFooBis'));
+ $e = $dispatcher->notify($event = new Event(new \stdClass(), 'foo'));
+ $this->assertEquals('listenToFoolistenToFooBis', $listener->getValue(), '->notify() notifies all registered listeners in order');
+
+ $listener->reset();
+ $dispatcher = new EventDispatcher();
+ $dispatcher->connect('foo', array($listener, 'listenToFooBis'));
+ $dispatcher->connect('foo', array($listener, 'listenToFoo'));
+ $dispatcher->notify(new Event(new \stdClass(), 'foo'));
+ $this->assertEquals('listenToFooBislistenToFoo', $listener->getValue(), '->notify() notifies all registered listeners in order');
+ }
+
+ public function testNotifyUntil()
+ {
+ $listener = new TestListener();
+ $dispatcher = new EventDispatcher();
+ $dispatcher->connect('foo', array($listener, 'listenToFoo'));
+ $dispatcher->connect('foo', array($listener, 'listenToFooBis'));
+ $dispatcher->notifyUntil($event = new Event(new \stdClass(), 'foo'));
+ $this->assertEquals('listenToFoolistenToFooBis', $listener->getValue(), '->notifyUntil() notifies all registered listeners in order and stops when the event is processed');
+
+ $listener->reset();
+ $dispatcher = new EventDispatcher();
+ $dispatcher->connect('foo', array($listener, 'listenToFooBis'));
+ $dispatcher->connect('foo', array($listener, 'listenToFoo'));
+ $dispatcher->notifyUntil($event = new Event(new \stdClass(), 'foo'));
+ $this->assertEquals('listenToFooBis', $listener->getValue(), '->notifyUntil() notifies all registered listeners in order and stops when the event is processed');
+ }
+
+ public function testFilter()
+ {
+ $listener = new TestListener();
+ $dispatcher = new EventDispatcher();
+ $dispatcher->connect('foo', array($listener, 'filterFoo'));
+ $dispatcher->connect('foo', array($listener, 'filterFooBis'));
+ $ret = $dispatcher->filter($event = new Event(new \stdClass(), 'foo'), 'foo');
+ $this->assertEquals('-*foo*-', $ret, '->filter() returns the filtered value');
+
+ $listener->reset();
+ $dispatcher = new EventDispatcher();
+ $dispatcher->connect('foo', array($listener, 'filterFooBis'));
+ $dispatcher->connect('foo', array($listener, 'filterFoo'));
+ $ret = $dispatcher->filter($event = new Event(new \stdClass(), 'foo'), 'foo');
+ $this->assertEquals('*-foo-*', $ret, '->filter() returns the filtered value');
+ }
+}
+
+
+class TestListener
+{
+ protected $value = '';
+
+ function filterFoo(Event $event, $foo)
+ {
+ return "*$foo*";
+ }
+
+ function filterFooBis(Event $event, $foo)
+ {
+ return "-$foo-";
+ }
+
+ function listenToFoo(Event $event)
+ {
+ $this->value .= 'listenToFoo';
+ }
+
+ function listenToFooBis(Event $event)
+ {
+ $this->value .= 'listenToFooBis';
+ $event->setProcessed();
+ }
+
+ function getValue()
+ {
+ return $this->value;
+ }
+
+ function reset()
+ {
+ $this->value = '';
+ }
+}
diff --git a/tests/Starlight/Component/EventDispatcher/EventTest.php b/tests/Starlight/Component/EventDispatcher/EventTest.php
new file mode 100755
index 0000000..dad1f2a
--- /dev/null
+++ b/tests/Starlight/Component/EventDispatcher/EventTest.php
@@ -0,0 +1,68 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\EventDispatcher;
+use Starlight\Component\EventDispatcher\Event;
+
+/**
+ */
+class EventTest extends \PHPUnit_Framework_TestCase
+{
+ protected $subject;
+ protected $parameters;
+
+ public function testGetSubject()
+ {
+ $event = $this->createEvent();
+ $this->assertEquals($this->subject, $event->getSubject(), '->getSubject() returns the event subject');
+ }
+
+ public function testGetName()
+ {
+ $this->assertEquals('name', $this->createEvent()->getName(), '->getName() returns the event name');
+ }
+
+ public function testParameters()
+ {
+ $event = $this->createEvent();
+
+ $this->assertEquals($this->parameters, $event->all(), '->all() returns the event parameters');
+ $this->assertEquals('bar', $event->get('foo'), '->get() returns the value of a parameter');
+ $event->set('foo', 'foo');
+ $this->assertEquals('foo', $event->get('foo'), '->set() changes the value of a parameter');
+ $this->assertTrue($event->has('foo'), '->has() returns true if the parameter is defined');
+ $this->assertFalse($event->has('oof'), '->has() returns false if the parameter is not defined');
+
+ try {
+ $event->get('foobar');
+ $this->fail('->get() throws an \InvalidArgumentException exception when the parameter does not exist');
+ } catch (\Exception $e) {
+ $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws an \InvalidArgumentException exception when the parameter does not exist');
+ $this->assertEquals('The event "name" doesn\'t have a "foobar" parameter', $e->getMessage(), '->get() throws an \InvalidArgumentException exception when the parameter does not exist');
+ }
+ $event = new Event($this->subject, 'name', $this->parameters);
+ }
+
+ public function testSetIsProcessed()
+ {
+ $event = $this->createEvent();
+ $this->assertFalse($event->isProcessed(), '->isProcessed() returns false by default');
+ $event->setProcessed();
+ $this->assertTrue($event->isProcessed(), '->isProcessed() returns true if the event has been processed');
+ }
+
+ protected function createEvent()
+ {
+ $this->subject = new \stdClass();
+ $this->parameters = array('foo' => 'bar');
+
+ return new Event($this->subject, 'name', $this->parameters);
+ }
+}
|
synewaves/starlight | 344458965b701b38535d5851b2adccde29e8d9c2 | Cleaned up bootloader logic and interface naming conventions | diff --git a/.gitignore b/.gitignore
index a75b755..f8440b2 100755
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
.eprj
phpunit.xml
autoload.php
-coverage
\ No newline at end of file
+coverage
+test.php
\ No newline at end of file
diff --git a/src/Starlight/Component/EventDispatcher/Event.php b/src/Starlight/Component/EventDispatcher/Event.php
new file mode 100755
index 0000000..a6f9170
--- /dev/null
+++ b/src/Starlight/Component/EventDispatcher/Event.php
@@ -0,0 +1,134 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\EventDispatcher;
+
+/**
+ * Event
+ */
+class Event implements EventInterface
+{
+ protected $value = null;
+ protected $processed = false;
+ protected $subject;
+ protected $name;
+ protected $parameters;
+
+ /**
+ * Constructs a new Event.
+ *
+ * @param mixed $subject The subject
+ * @param string $name The event name
+ * @param array $parameters An array of parameters
+ */
+ public function __construct($subject, $name, $parameters = array())
+ {
+ $this->subject = $subject;
+ $this->name = $name;
+ $this->parameters = $parameters;
+ }
+
+ /**
+ * Returns the subject.
+ *
+ * @return mixed The subject
+ */
+ public function getSubject()
+ {
+ return $this->subject;
+ }
+
+ /**
+ * Returns the event name.
+ *
+ * @return string The event name
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Sets the processed flag to true.
+ *
+ * This method must be called by listeners when
+ * it has processed the event (it is only meaninful
+ * when the event has been notified with the notifyUntil()
+ * dispatcher method.
+ */
+ public function setProcessed()
+ {
+ $this->processed = true;
+ }
+
+ /**
+ * Returns whether the event has been processed by a listener or not.
+ *
+ * This method is only meaningful for events notified
+ * with notifyUntil().
+ *
+ * @return Boolean true if the event has been processed, false otherwise
+ */
+ public function isProcessed()
+ {
+ return $this->processed;
+ }
+
+ /**
+ * Returns the event parameters.
+ *
+ * @return array The event parameters
+ */
+ public function all()
+ {
+ return $this->parameters;
+ }
+
+ /**
+ * Returns true if the parameter exists.
+ *
+ * @param string $name The parameter name
+ *
+ * @return Boolean true if the parameter exists, false otherwise
+ */
+ public function has($name)
+ {
+ return array_key_exists($name, $this->parameters);
+ }
+
+ /**
+ * Returns a parameter value.
+ *
+ * @param string $name The parameter name
+ *
+ * @return mixed The parameter value
+ *
+ * @throws \InvalidArgumentException When parameter doesn't exists for this event
+ */
+ public function get($name)
+ {
+ if (!array_key_exists($name, $this->parameters)) {
+ throw new \InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name));
+ }
+
+ return $this->parameters[$name];
+ }
+
+ /**
+ * Sets a parameter.
+ *
+ * @param string $name The parameter name
+ * @param mixed $value The parameter value
+ */
+ public function set($name, $value)
+ {
+ $this->parameters[$name] = $value;
+ }
+}
diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index f249e63..3a6da01 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,332 +1,318 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class for request/response headers
*/
class HeaderBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Headers
* @var array
*/
protected $headers;
// /**
// * Wrapper class for request/response headers
// */
// protected $cache_control;
/**
* Type (request, response)
* @var string
*/
protected $type;
/**
* Constructor
* @param array $headers An array of HTTP headers
* @param string $type The type (null, request, or response)
*/
public function __construct(array $headers = array(), $type = null)
{
$this->replace($headers);
if ($type !== null && !in_array($type, array('request', 'response'))) {
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBucket.', $type));
}
$this->type = $type;
}
/**
* Returns the headers
* @return array An array of headers
*/
public function all()
{
return $this->headers;
}
/**
* Returns the parameter keys
* @return array An array of parameter keys
*/
public function keys()
{
return array_keys($this->headers);
}
/**
* Replaces the current HTTP headers by a new set
* @param array $headers An array of HTTP headers
* @return HeaderBucket this instance
*/
public function replace(array $headers = array())
{
$this->cache_control = null;
$this->headers = array();
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
return $this;
}
/**
* Returns a header value by name
* @param string $key The header name
* @param Boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function get($key, $first = true)
{
$key = static::normalizeHeaderName($key);
if (!array_key_exists($key, $this->headers)) {
return $first ? null : array();
}
if ($first) {
return count($this->headers[$key]) ? $this->headers[$key][0] : '';
} else {
return $this->headers[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
$key = static::normalizeHeaderName($key);
if (!is_array($values)) {
$values = array($values);
}
if ($replace === true || !isset($this->headers[$key])) {
$this->headers[$key] = $values;
} else {
$this->headers[$key] = array_merge($this->headers[$key], $values);
}
return $this;
}
/**
* Returns true if the HTTP header is defined
* @param string $key The HTTP header
* @return Boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists(static::normalizeHeaderName($key), $this->headers);
}
/**
* Returns true if the given HTTP header contains the given value
* @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, false));
}
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->headers[static::normalizeHeaderName($key)]);
}
return $this;
}
-
- // /**
- // * Returns an instance able to manage the Cache-Control header.
- // *
- // * @return CacheControl A CacheControl instance
- // */
- // public function getCacheControl()
- // {
- // if (null === $this->cacheControl) {
- // $this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type);
- // }
- //
- // return $this->cacheControl;
- // }
/**
* Set cookie variable
*
* Available options:
*
* <ul>
* <li><b>expires</b> <i>(integer)</i>: cookie expiration time (default: 0 [end of session])</li>
* <li><b>path</b> <i>(string)</i>: path cookie is valid for (default: '')</li>
* <li><b>domain</b> <i>(string)</i>: domain cookie is valid for (default: '')</li>
* <li><b>secure/b> <i>(boolean)</i>: should cookie only be used on a secure connection (default: false)</li>
* <li><b>http_only</b> <i>(string)</i>: cookie only valid over http? [not supported by all browsers] (default: true)</li>
* <li><b>encode</b> <i>(boolean)</i>: urlencode cookie value (default: true)</li>
* </ul>
* @param string $key cookie key
* @param mixed $value value
* @param array $options options hash (see above)
* @return HeaderBucket this instance
*/
public function setCookie($key, $value, $options = array())
{
$default_options = array(
'expires' => null,
'path' => null,
'domain' => null,
'secure' => false,
'http_only' => true,
);
$options += $default_options;
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie key "%s" contains invalid characters.', $key));
}
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
if (trim($key) == '') {
throw new \InvalidArgumentException('The cookie key cannot be empty');
}
$cookie = sprintf('%s=%s', $key, urlencode($value));
if ($this->type == 'request') {
$this->set('Cookie', $cookie);
return;
}
if ($options['expires'] !== null) {
if (is_numeric($options['expires'])) {
$options['expires'] = (int) $options['expires'];
} elseif ($options['expires'] instanceof \DateTime) {
$options['expires'] = $options['expires']->getTimestamp();
} else {
$options['expires'] = strtotime($options['expires']);
if ($options['expires'] === false || $options['expires'] == -1) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $options['expires']));
}
}
$cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($options['domain']) {
$cookie .= '; domain=' . $options['domain'];
}
if ($options['path'] && $options['path'] !== '/') {
$cookie .= '; path=' . $options['path'];
}
if ($options['secure']) {
$cookie .= '; secure';
}
if ($options['http_only']) {
$cookie .= '; httponly';
}
$this->set('Set-Cookie', $cookie, false);
return $this;
}
/**
* Expire a cookie variable
* @param string $key cookie key
* @return HeaderBucket this instance
*/
public function expireCookie($key)
{
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
}
if (!$key) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
if ($this->type == 'request') {
return;
}
$cookie = sprintf('%s=; expires=', $key, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
$this->set('Set-Cookie', $cookie, false);
return $this;
}
- //
+ // -----------
// ArrayAccess
- //
+ // -----------
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
public function offsetUnset($offset)
{
return $this->delete($offset);
}
- //
+ // -----------------
// IteratorAggregate
- //
+ // -----------------
public function getIterator()
{
return new \ArrayIterator($this->all());
}
/**
* Normalizes an HTTP header name
* @param string $key The HTTP header name
* @return string The normalized HTTP header name
*/
static public function normalizeHeaderName($key)
{
return strtr(strtolower($key), '_', '-');
}
}
diff --git a/src/Starlight/Component/Routing/Compilable.php b/src/Starlight/Component/Routing/Compilable.php
old mode 100644
new mode 100755
diff --git a/src/Starlight/Component/Routing/CompilableInterface.php b/src/Starlight/Component/Routing/CompilableInterface.php
new file mode 100755
index 0000000..1e91719
--- /dev/null
+++ b/src/Starlight/Component/Routing/CompilableInterface.php
@@ -0,0 +1,23 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Routing;
+
+
+/**
+ * Compilable interface
+ */
+interface CompilableInterface
+{
+ /**
+ * Compile
+ */
+ public function compile();
+}
diff --git a/src/Starlight/Component/Routing/ResourceRoute.php b/src/Starlight/Component/Routing/ResourceRoute.php
old mode 100644
new mode 100755
index 4b617a7..f2e7921
--- a/src/Starlight/Component/Routing/ResourceRoute.php
+++ b/src/Starlight/Component/Routing/ResourceRoute.php
@@ -1,327 +1,327 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Inflector\Inflector;
/**
* ResourceRoute
*/
-class ResourceRoute implements Compilable
+class ResourceRoute implements CompilableInterface
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%p', 'verb' => 'get', 'url' => '(.:format)'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
'create' => array('name' => '%p', 'verb' => 'post', 'url' => '(.:format)'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id(.:format)'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action(.:format)'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id(.:format)'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id(.:format)'),
);
/**
* Default path names
* @var array
*/
protected static $resource_names = array(
'add' => 'add',
'edit' => 'edit',
'delete' => 'delete',
);
public $resource;
public $controller;
public $except;
public $only;
public $constraints;
public $singular;
public $plural;
public $path_names;
public $module;
public $path_prefix;
public $name_prefix;
public $member = array();
public $collection = array();
public $map_member_collection_scope = null;
/**
* Constructor
* @param string $resource resource name
* @param array $options options hash
*/
public function __construct($resource = null, array $options = array())
{
if (!is_null($resource)) {
$this->resource = $resource;
$this->controller = $this->plural = Inflector::pluralize($this->resource);
$this->singular = Inflector::singularize($this->controller);
if (count($options) > 0) {
foreach ($options as $key => $value) {
$this->$key($value);
}
}
}
}
/**
* Set except routes from $resources_map
* @param array $except except resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function except(array $except)
{
$this->only = null;
$this->except = $except;
return $this;
}
/**
* Set only routes from $resources_map
* @param array $only only resources
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function only(array $only)
{
$this->except = null;
$this->only = $only;
return $this;
}
/**
* Set controller
* @param string $controller controller name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function controller($controller)
{
$this->controller = $controller;
return $this;
}
/**
* Set contraints
* @param mixed $constraints constraints
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set name for route paths
* @param string $name path name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function name($name)
{
$single = explode(' ', strtolower(Inflector::humanize($name)));
$plural = $single;
$count = count($single);
$single[$count - 1] = Inflector::singularize($single[$count - 1]);
$plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
$this->singular = implode('_', $single);
$this->plural = implode('_', $plural);
return $this;
}
/**
* Set path names for special routes
* @param array $names path name overrides
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function pathNames(array $names)
{
$this->path_names = $names;
return $this;
}
/**
* Set module/namespace for resource
* @param string $module module/namespace name
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Set member routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function member(\Closure $callback)
{
$this->map_member_collection_scope = 'member';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set collection routes
* @param \Closure $callback callback method
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function collection(\Closure $callback)
{
$this->map_member_collection_scope = 'collection';
$callback($this);
$this->map_member_collection_scope = null;
return $this;
}
/**
* Set an extra route which responds to GET requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function get($path, $options = array())
{
return $this->mapMethod('get', $path, $options);
}
/**
* Set an extra route which responds to PUT requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function put($path, $options = array())
{
return $this->mapMethod('put', $path, $options);
}
/**
* Set an extra route which responds to POST requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function post($path, $options = array())
{
return $this->mapMethod('post', $path, $options);
}
/**
* Set an extra route which responds to DELETE requests
* @param string $path path
* @param string $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
public function delete($path, $options = array())
{
return $this->mapMethod('delete', $path, $options);
}
/**
* Map extra routes through a common interface
* @param string $method HTTP method
* @param string $path path
* @param array $options options hash
* @return \Starlight\Component\Routing\ResourceRoute this resource route
*/
protected function mapMethod($method, $path, $options = array())
{
$on = isset($options['on']) ? $options['on'] : $this->map_member_collection_scope;
if (!$on || ($on != 'member' && $on != 'collection')) {
throw new \InvalidArgumentException('You must pass a valid "on" option (collection/method) to ' . $method);
}
array_push($this->$on, array($path, strtoupper($method)));
return $this;
}
/**
* Compiles this resource route into individual \Starlight\Component\Routing\Route
* @return array array of \Starlight\Component\Routing\Route routes
*/
public function compile()
{
$generators = static::$resources_map;
if ($this->except) {
$generators = array_diff_key($generators, array_fill_keys($this->except, true));
} elseif ($this->only) {
$generators = array_intersect_key($generators, array_fill_keys($this->only, true));
}
if (is_array($this->path_names)) {
$this->path_names += static::$resource_names;
} else {
$this->path_names = static::$resource_names;
}
if ($this->module) {
$this->controller = $this->module . '\\' . $this->controller;
}
if (count($this->member) > 0) {
foreach ($this->member as $member) {
list($name, $verb) = $member;
$generators[$name] = array('name' => $name . '_%s', 'verb' => $verb, 'url' => '/:id/' . $name . '(.:format)');
}
}
if (count($this->collection) > 0) {
foreach ($this->collection as $collection) {
list($name, $verb) = $collection;
$generators[$name] = array('name' => $name . '_%p', 'verb' => $verb, 'url' => '/' . $name . '(.:format)');
}
}
$routes = array();
foreach ($generators as $action => $parts) {
$path = $parts['url'];
if (strpos($path, ':action') !== false) {
$path = str_replace(':action', $this->path_names[$action], $path);
}
$r = new Route($this->path_prefix . '/' . $this->resource . $path, $this->controller . '::' . $action);
$r->methods(array($parts['verb']));
$name = str_replace('%s', $this->name_prefix . $this->singular, $parts['name']);
$name = str_replace('%p', $this->name_prefix . $this->plural, $name);
$r->name($name);
if ($this->constraints) {
$r->constraints($this->constraints);
}
$routes[] = $r->compile();
}
return $routes;
}
}
diff --git a/src/Starlight/Component/Routing/Routable.php b/src/Starlight/Component/Routing/Routable.php
old mode 100644
new mode 100755
diff --git a/src/Starlight/Component/Routing/RoutableInterface.php b/src/Starlight/Component/Routing/RoutableInterface.php
new file mode 100755
index 0000000..b879653
--- /dev/null
+++ b/src/Starlight/Component/Routing/RoutableInterface.php
@@ -0,0 +1,25 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Routing;
+use Starlight\Component\Http\Request;
+
+
+/**
+ * Routable interface
+ */
+interface RoutableInterface
+{
+ /**
+ * Match a request
+ * @param \Starlight\Component\Http\Request $request current request
+ */
+ public function match(Request $request);
+}
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index 98b8064..fd0284e 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,185 +1,181 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
-class Route implements Routable, Compilable
+class Route implements RoutableInterface, CompilableInterface
{
/**
* Base default values for route parameters
* @var array
*/
protected static $base_parameter_defaults = array(
'controller' => null,
'action' => null,
'id' => null,
);
public $path;
public $endpoint;
public $regex;
public $parameters = array();
public $constraints;
public $methods = array();
public $name;
public $module;
public $path_prefix;
public $name_prefix;
/**
* Constructor
* @param string $path url path
- * @param mixed $endpoint route endpoint
+ * @param mixed $endpoint route endpoint - "controller::action" or a valid callback
*/
public function __construct($path, $endpoint)
{
$this->path = static::normalize($path);
$this->endpoint = $endpoint;
}
/**
* Set route parameter defaults
* @param array $defaults default values hash
* @return \Starlight\Component\Routing\Route this instance
*/
public function defaults(array $defaults)
{
foreach ($defaults as $key => $value) {
if (!isset($this->parameters[$key]) || trim($this->parameters[$key]) == '') {
$this->parameters[$key] = $value;
}
}
return $this;
}
/**
* Set route constraints
* @param mixed $constraints constraints (hash or \Closure)
* @return \Starlight\Component\Routing\Route this instance
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* Set HTTP methods/verbs route should respond to
* @param array $methods HTTP methods
* @return \Starlight\Component\Routing\Route this instance
*/
public function methods($methods)
{
if (!is_array($methods)) {
$methods = array($methods);
}
$this->methods = $methods;
return $this;
}
/**
* Set route name for generated helpers
* @param string $name route name
* @return \Starlight\Component\Routing\Route this instance
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
* Set module/namespace for the controller
* @param string $module module/namespace
* @return \Starlight\Component\Routing\Route this instance
*/
public function module($module)
{
$this->module = $module;
return $this;
}
/**
* Compiles the route
* @return \Starlight\Component\Routing\Route this compiled instance
*/
public function compile()
{
$parser = new RouteParser();
$constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
if ($this->path_prefix) {
$this->path = $this->path_prefix . $this->path;
}
$this->regex = $parser->parse($this->path, $constraints);
$this->parameters = array_merge(static::$base_parameter_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
// get endpoint if string:
- if (is_string($this->endpoint) && strpos($this->endpoint, '::') !== false) {
- // apply module:
- if ($this->module) {
- $this->endpoint = $this->module . '\\' . $this->endpoint;
+ if (is_string($this->endpoint)) {
+ if (strpos($this->endpoint, '::') !== false) {
+ // apply module:
+ if ($this->module) {
+ $this->endpoint = $this->module . '\\' . $this->endpoint;
+ }
+
+ list($this->parameters['controller'], $this->parameters['action']) = explode('::', $this->endpoint);
}
-
- list($this->parameters['controller'], $this->parameters['action']) = explode('::', $this->endpoint);
+ } else {
+ // should be a callback
+ // TODO: handle callbacks
}
// set name/prefix if available:
if ($this->name && $this->name_prefix) {
$this->name = $this->name_prefix . $this->name;
}
return $this;
}
/**
* Match a request
* @param \Starlight\Component\Http\Request $request current request
*/
public function match(Request $request)
{
}
/**
* Normalizes path - removes trailing slashes and prepends single slash
* @param string $path original path
* @return string normalized path
*/
protected function normalize($path)
{
$path = trim($path, '/');
$path = '/' . $path;
return $path;
}
-
- /**
- * Nice output version for this route
- * @return string nice output
- */
- public function __toString()
- {
- return sprintf("%-6s %-40s %s", strtoupper(implode(',', $this->methods)), $this->path, json_encode($this->parameters));
- }
}
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
old mode 100644
new mode 100755
index 72f3e4f..0a7e92a
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,385 +1,388 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
use Starlight\Component\Inflector\Inflector;
/**
* Router
*/
-class Router implements Compilable
+class Router implements CompilableInterface
{
protected $routes = array();
protected $current = array();
protected $current_type = null;
protected $compiled = array();
protected $has_compiled = false;
protected $scopes = array();
/**
* Draw routes - router gateway
* @param \Closure $callback callback
* @return \Starlight\Component\Routing\Router this instance
*/
public function draw(\Closure $callback)
{
// TODO: check for cached version before redrawing these
$callback($this);
return $this;
}
/**
* Maps a single route
* @param string $path url path
* @param mixed $endpoint controller::action pair or callback
* @return \Starlight\Component\Routing\Route route
*/
public function map($path, $endpoint)
{
if ($this->current_type == 'resource') {
throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context.');
}
if (!preg_match('/\(\.:format\)$/', $path)) {
// auto append format option to path:
$path .= '(.:format)';
}
$this->routes[] = new Route($path, $endpoint);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'route';
$this->applyScopes();
array_pop($this->current);
$this->current_type = '';
return $this->routes[count($this->routes) - 1];
}
/**
* Maps RESTful resources routes
*/
public function resources()
{
$args = func_get_args();
$count = count($args);
$callback = null;
$options = array();
if (is_callable($args[$count - 1])) {
$callback = array_pop($args);
$count--;
}
if (is_array($args[$count - 1])) {
$options = array_pop($args);
$count--;
}
// map each resource separately (if multiple)
foreach ($args as $resource) {
if ($resource == Inflector::pluralize($resource)) {
$klass = 'Starlight\Component\Routing\ResourceRoute';
} else {
$klass = 'Starlight\Component\Routing\SingularResourceRoute';
}
$this->routes[] = new $klass($resource, $options);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'resource';
$route = $this->routes[count($this->routes) - 1];
$this->applyScopes();
if ($callback) {
$callback($this, $route);
}
array_pop($this->current);
$this->current_type = 'route';
}
return $route;
}
/**
* Maps singular RESTful resource
*/
public function resource()
{
return call_user_func_array(array($this, 'resources'), func_get_args());
}
/**
*
*/
public function redirect($path)
{
// TOOD: handle inline redirection
if (is_string($path)) {
- return function() {
-
+ return function() use ($path) {
+ return $path;
};
+ } else {
+ // already a callback, need to lazy evaluate later:
+ return $path;
}
}
/**
* Scope routes
* @param array $scopes scopes to apply
* @param \Closure $callback callback
*/
public function scope(array $scopes, \Closure $callback)
{
$this->addScopes($scopes);
$callback($this);
$this->removeScopes($scopes);
}
/**
* Compile all routes
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
// /**
// *
// */
// public function match(Request $request)
// {
// foreach ($this->compiled as $r) {
// if ($r->match($request)) {
// //
// return;
// }
// }
//
// // nothing matched:
// }
/**
* Pretty version of routes
* @return string nice string
*/
public function __toString()
{
$parts = array();
$mn = $mv = $mp = 0;
foreach ($this->compiled as $r) {
$p = array(
'name' => $r->name,
'verb' => strtoupper(implode(',', $r->methods)),
'path' => $r->path,
'endp' => is_callable($r->endpoint) ? '{callback}' : $r->endpoint,
);
if (strlen($p['name']) > $mn) {
$mn = strlen($p['name']);
}
if (strlen($p['verb']) > $mv) {
$mv = strlen($p['verb']);
}
if (strlen($p['path']) > $mp) {
$mp = strlen($p['path']);
}
$parts[] = $p;
}
$rc = '<pre>';
foreach ($parts as $p) {
$rc .= sprintf("%" . $mn . "s %-" . $mv . "s %-" . $mp . "s %s\n", $p['name'], $p['verb'], $p['path'], $p['endp']);
}
$rc .= '</pre>';
return $rc;
}
/**
* Apply current scopes to currently scoped routes
*/
protected function applyScopes()
{
$count = count($this->current);
$current = $this->current[$count - 1];
$previous = isset($this->current[$count - 2]) ? $this->routes[$this->current[$count - 2]] : null;
$this->routes[$current] = $this->applyScope($this->routes[$current], $previous);
}
/**
* Apply scopes to single route
* @param mixed $route resource or route to scope
* @param \Starlight\Component\Routing\ResourceRoute $nested current parent route (if present)
* @return mixed resource or route which was scoped
*/
protected function applyScope($route, $nested = null)
{
// nested resource
if ($nested) {
$route->path_prefix .= $nested->path_prefix . '/' . $nested->plural . '/:' . $nested->singular . '_id';
$route->name_prefix .= $nested->name_prefix . $nested->singular . '_';
}
// constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
$constraints = array_merge($constraints, $c);
}
$route->constraints($constraints);
}
// name
if (isset($this->scopes['name'])) {
$count = count($this->scopes['name']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
} else {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
}
// module
if (isset($this->scopes['module'])) {
$route->module(implode('\\', $this->scopes['module']));
}
// path
if (isset($this->scopes['path'])) {
$count = count($this->scopes['path']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
} else {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
}
if ($this->current_type == 'route') {
// route only cases
// HTTP methods/verbs
if (isset($this->scopes['methods'])) {
// only consider the last on the stack:
$route->methods($this->scopes['methods'][count($this->scopes['methods']) - 1]);
}
// parameter defaults
if (isset($this->scopes['defaults'])) {
$defaults = array();
foreach ($this->scopes['defaults'] as $d) {
$defaults = array_merge($defaults, $d);
}
$route->defaults($d);
}
} elseif ($this->current_type == 'resource') {
// resource only cases
// except
if (isset($this->scopes['except'])) {
// only consider the last on the stack:
$route->except($this->scopes['except'][count($this->scopes['except']) - 1]);
}
// only
if (isset($this->scopes['only'])) {
// only consider the last on the stack:
$route->only($this->scopes['only'][count($this->scopes['only']) - 1]);
}
// path_names
if (isset($this->scopes['path_names'])) {
// only consider the last on the stack:
$route->pathNames($this->scopes['path_names'][count($this->scopes['path_names']) - 1]);
}
}
return $route;
}
/**
* Add scopes to parse tree
* @param array $scopes scopes to add
*/
protected function addScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->addScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
$this->scopes[$scope][] = $options;
} else {
$this->scopes[$scope] = array($options);
}
}
}
/**
* Remove scopes from parse tree
* @param array $scopes scopes to remove
*/
protected function removeScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->removeScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
if (($position = array_search($options, $this->scopes[$scope])) !== false) {
unset($this->scopes[$scope][$position]);
if (count($this->scopes[$scope]) == 0) {
unset($this->scopes[$scope]);
}
}
}
}
}
}
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index 261eadb..d26ee6e 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,40 +1,9 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
- */
-
-
-error_reporting(-1);
-
-require_once __DIR__ . '/Support/UniversalClassLoader.php';
-
-$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
-$autoloader->registerNamespaces(array(
- 'Starlight' => __DIR__ . '/../../',
-));
-$autoloader->register();
-
-
-function dump()
-{
- foreach (func_get_args() as $arg) {
- echo '<pre>' . htmlspecialchars(print_r($arg, true)) . '</pre>';
- echo '<hr />';
- }
-}
-
-
-$r = new \Starlight\Component\Routing\Router();
-$r->draw(function($r){
-
- $r->map('users', $r->redirect('/users/anything'));
-
-})->compile();
-
-echo $r;
-dump($r);
\ No newline at end of file
+ */
\ No newline at end of file
|
synewaves/starlight | 4ff22c548f6d2b37a48c7cef8f1c0a223d6ef991 | Begin work on inline redirection / route callbacks | diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index 226e86b..72f3e4f 100644
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,367 +1,385 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
use Starlight\Component\Inflector\Inflector;
/**
* Router
*/
class Router implements Compilable
{
protected $routes = array();
protected $current = array();
protected $current_type = null;
protected $compiled = array();
protected $has_compiled = false;
protected $scopes = array();
/**
* Draw routes - router gateway
* @param \Closure $callback callback
* @return \Starlight\Component\Routing\Router this instance
*/
public function draw(\Closure $callback)
{
// TODO: check for cached version before redrawing these
$callback($this);
return $this;
}
/**
* Maps a single route
* @param string $path url path
* @param mixed $endpoint controller::action pair or callback
* @return \Starlight\Component\Routing\Route route
*/
public function map($path, $endpoint)
{
if ($this->current_type == 'resource') {
throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context.');
}
+ if (!preg_match('/\(\.:format\)$/', $path)) {
+ // auto append format option to path:
+ $path .= '(.:format)';
+ }
+
$this->routes[] = new Route($path, $endpoint);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'route';
$this->applyScopes();
array_pop($this->current);
$this->current_type = '';
return $this->routes[count($this->routes) - 1];
}
/**
* Maps RESTful resources routes
*/
public function resources()
{
$args = func_get_args();
$count = count($args);
$callback = null;
$options = array();
if (is_callable($args[$count - 1])) {
$callback = array_pop($args);
$count--;
}
if (is_array($args[$count - 1])) {
$options = array_pop($args);
$count--;
}
// map each resource separately (if multiple)
foreach ($args as $resource) {
if ($resource == Inflector::pluralize($resource)) {
$klass = 'Starlight\Component\Routing\ResourceRoute';
} else {
$klass = 'Starlight\Component\Routing\SingularResourceRoute';
}
$this->routes[] = new $klass($resource, $options);
$this->current[] = count($this->routes) - 1;
$this->current_type = 'resource';
$route = $this->routes[count($this->routes) - 1];
$this->applyScopes();
if ($callback) {
$callback($this, $route);
}
array_pop($this->current);
$this->current_type = 'route';
}
return $route;
}
/**
* Maps singular RESTful resource
*/
public function resource()
{
return call_user_func_array(array($this, 'resources'), func_get_args());
}
+ /**
+ *
+ */
+ public function redirect($path)
+ {
+ // TOOD: handle inline redirection
+ if (is_string($path)) {
+ return function() {
+
+ };
+ }
+ }
+
/**
* Scope routes
* @param array $scopes scopes to apply
* @param \Closure $callback callback
*/
public function scope(array $scopes, \Closure $callback)
{
$this->addScopes($scopes);
$callback($this);
$this->removeScopes($scopes);
}
/**
* Compile all routes
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
// /**
// *
// */
// public function match(Request $request)
// {
// foreach ($this->compiled as $r) {
// if ($r->match($request)) {
// //
// return;
// }
// }
//
// // nothing matched:
// }
/**
* Pretty version of routes
* @return string nice string
*/
public function __toString()
{
$parts = array();
$mn = $mv = $mp = 0;
foreach ($this->compiled as $r) {
$p = array(
'name' => $r->name,
'verb' => strtoupper(implode(',', $r->methods)),
'path' => $r->path,
- 'endp' => $r->endpoint,
+ 'endp' => is_callable($r->endpoint) ? '{callback}' : $r->endpoint,
);
if (strlen($p['name']) > $mn) {
$mn = strlen($p['name']);
}
if (strlen($p['verb']) > $mv) {
$mv = strlen($p['verb']);
}
if (strlen($p['path']) > $mp) {
$mp = strlen($p['path']);
}
$parts[] = $p;
}
$rc = '<pre>';
foreach ($parts as $p) {
$rc .= sprintf("%" . $mn . "s %-" . $mv . "s %-" . $mp . "s %s\n", $p['name'], $p['verb'], $p['path'], $p['endp']);
}
$rc .= '</pre>';
return $rc;
}
/**
* Apply current scopes to currently scoped routes
*/
protected function applyScopes()
{
$count = count($this->current);
$current = $this->current[$count - 1];
$previous = isset($this->current[$count - 2]) ? $this->routes[$this->current[$count - 2]] : null;
$this->routes[$current] = $this->applyScope($this->routes[$current], $previous);
}
/**
* Apply scopes to single route
* @param mixed $route resource or route to scope
* @param \Starlight\Component\Routing\ResourceRoute $nested current parent route (if present)
* @return mixed resource or route which was scoped
*/
protected function applyScope($route, $nested = null)
{
// nested resource
if ($nested) {
$route->path_prefix .= $nested->path_prefix . '/' . $nested->plural . '/:' . $nested->singular . '_id';
$route->name_prefix .= $nested->name_prefix . $nested->singular . '_';
}
// constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
$constraints = array_merge($constraints, $c);
}
$route->constraints($constraints);
}
// name
if (isset($this->scopes['name'])) {
$count = count($this->scopes['name']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
} else {
$route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
}
}
// module
if (isset($this->scopes['module'])) {
$route->module(implode('\\', $this->scopes['module']));
}
// path
if (isset($this->scopes['path'])) {
$count = count($this->scopes['path']);
if ($this->current_type == 'resource') {
if (!$nested || $count > 1) {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
} else {
$route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
}
}
if ($this->current_type == 'route') {
// route only cases
// HTTP methods/verbs
if (isset($this->scopes['methods'])) {
// only consider the last on the stack:
$route->methods($this->scopes['methods'][count($this->scopes['methods']) - 1]);
}
// parameter defaults
if (isset($this->scopes['defaults'])) {
$defaults = array();
foreach ($this->scopes['defaults'] as $d) {
$defaults = array_merge($defaults, $d);
}
$route->defaults($d);
}
} elseif ($this->current_type == 'resource') {
// resource only cases
// except
if (isset($this->scopes['except'])) {
// only consider the last on the stack:
$route->except($this->scopes['except'][count($this->scopes['except']) - 1]);
}
// only
if (isset($this->scopes['only'])) {
// only consider the last on the stack:
$route->only($this->scopes['only'][count($this->scopes['only']) - 1]);
}
// path_names
if (isset($this->scopes['path_names'])) {
// only consider the last on the stack:
$route->pathNames($this->scopes['path_names'][count($this->scopes['path_names']) - 1]);
}
}
return $route;
}
/**
* Add scopes to parse tree
* @param array $scopes scopes to add
*/
protected function addScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->addScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
$this->scopes[$scope][] = $options;
} else {
$this->scopes[$scope] = array($options);
}
}
}
/**
* Remove scopes from parse tree
* @param array $scopes scopes to remove
*/
protected function removeScopes(array $scopes)
{
foreach ($scopes as $scope => $options) {
if ($scope == 'namespace') {
$this->removeScopes(array(
'name' => $options,
'path' => $options,
'module' => $options,
));
continue;
}
if (isset($this->scopes[$scope])) {
if (($position = array_search($options, $this->scopes[$scope])) !== false) {
unset($this->scopes[$scope][$position]);
if (count($this->scopes[$scope]) == 0) {
unset($this->scopes[$scope]);
}
}
}
}
}
}
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index 704e6db..261eadb 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,29 +1,40 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
error_reporting(-1);
require_once __DIR__ . '/Support/UniversalClassLoader.php';
$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
$autoloader->registerNamespaces(array(
'Starlight' => __DIR__ . '/../../',
));
$autoloader->register();
function dump()
{
foreach (func_get_args() as $arg) {
echo '<pre>' . htmlspecialchars(print_r($arg, true)) . '</pre>';
echo '<hr />';
}
}
+
+
+$r = new \Starlight\Component\Routing\Router();
+$r->draw(function($r){
+
+ $r->map('users', $r->redirect('/users/anything'));
+
+})->compile();
+
+echo $r;
+dump($r);
\ No newline at end of file
|
synewaves/starlight | 71d73205fd8e32aa2b7259dcc9566f82d18da8e5 | Finish routing API basics | diff --git a/src/Starlight/Component/Routing/Compilable.php b/src/Starlight/Component/Routing/Compilable.php
index 1835bda..cee7e6a 100644
--- a/src/Starlight/Component/Routing/Compilable.php
+++ b/src/Starlight/Component/Routing/Compilable.php
@@ -1,20 +1,23 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
* Compilable interface
*/
interface Compilable
{
+ /**
+ * Compile
+ */
public function compile();
-}
\ No newline at end of file
+}
diff --git a/src/Starlight/Component/Routing/Resource.php b/src/Starlight/Component/Routing/Resource.php
deleted file mode 100644
index 74c4d3d..0000000
--- a/src/Starlight/Component/Routing/Resource.php
+++ /dev/null
@@ -1,192 +0,0 @@
-<?php
-/*
- * This file is part of the Starlight framework.
- *
- * (c) Matthew Vince <[email protected]>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
-
-namespace Starlight\Component\Routing;
-use Starlight\Component\Inflector\Inflector;
-
-
-/**
- * Resource
- */
-class Resource implements Compilable
-{
- /**
- * RESTful routing map; maps actions to methods
- * @var array
- */
- protected static $resources_map = array(
- 'index' => array('name' => '%p', 'verb' => 'get', 'url' => '/'),
- 'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action'),
- 'create' => array('name' => '%p', 'verb' => 'post', 'url' => '/'),
- 'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id'),
- 'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action'),
- 'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id'),
- 'delete' => array('name' => 'delete_%s', 'verb' => 'get', 'url' => '/:id/:action'),
- 'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id'),
- );
-
- protected static $resource_names = array(
- 'add' => 'add',
- 'edit' => 'edit',
- 'delete' => 'delete',
- );
-
-
- public $resource;
- public $except;
- public $only;
- public $controller;
- public $constraints;
- public $name;
- public $path_names;
- public $namespace;
- // member, collection, resources (nested)
-
-
- /**
- *
- */
- public function __construct($resource)
- {
- $this->resource = $resource;
- $this->controller = Inflector::pluralize($this->resource);
- }
-
- /**
- *
- */
- public function except(array $except)
- {
- $this->only = null;
- $this->except = $except;
-
- return $this;
- }
-
- /**
- *
- */
- public function only(array $only)
- {
- $this->except = null;
- $this->only = $only;
-
- return $this;
- }
-
- /**
- *
- */
- public function controller($controller)
- {
- $this->controller = $controller;
-
- return $this;
- }
-
- /**
- *
- */
- public function constraints($constraints)
- {
- $this->constraints = $constraints;
-
- return $this;
- }
-
- /**
- * (as)
- */
- public function name($name)
- {
- $single = explode(' ', strtolower(Inflector::humanize($name)));
- $plural = $single;
- $count = count($single);
-
- $single[$count - 1] = Inflector::singularize($single[$count - 1]);
- $plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
-
- $this->name = array(
- implode('_', $single),
- implode('_', $plural),
- );
-
- return $this;
- }
-
- /**
- *
- */
- public function pathNames(array $names)
- {
- $this->path_names = $names;
-
- return $this;
- }
-
- /**
- *
- */
- public function namespaced($namespace)
- {
- $this->namespace = $namespace;
-
- return $this;
- }
-
- /**
- *
- */
- public function compile()
- {
- $generators = static::$resources_map;
- if ($this->except) {
- $generators = array_diff_key($generators, array_fill_keys($this->except, true));
- } elseif ($this->only) {
- $generators = array_intersect_key($generators, array_fill_keys($this->only, true));
- }
-
- if (is_array($this->path_names)) {
- $this->path_names += static::$resource_names;
- } else {
- $this->path_names = static::$resource_names;
- }
-
- $routes = array();
- foreach ($generators as $action => $parts) {
- $path = $parts['url'];
- if (strpos($path, ':action') !== false) {
- $path = str_replace(':action', $this->path_names[$action], $path);
- }
-
- $r = new Route('/' . $this->resource . $path, $this->controller . '#' . $action);
- $r->methods(array($parts['verb']));
-
- $single = isset($this->name[0]) ? $this->name[0] : Inflector::singularize($this->resource);
- $plural = isset($this->name[1]) ? $this->name[1] : Inflector::pluralize($this->resource);
-
- $name = str_replace('%s', $single, $parts['name']);
- $name = str_replace('%p', $plural, $name);
- $r->name($name);
-
- if ($this->constraints) {
- $r->constraints($this->constraints);
- }
-
- if ($this->namespace) {
- $r->namespaced($this->namespace);
- }
-
- $routes[] = $r->compile();
- }
-
- return $routes;
- }
-}
diff --git a/src/Starlight/Component/Routing/ResourceRoute.php b/src/Starlight/Component/Routing/ResourceRoute.php
new file mode 100644
index 0000000..4b617a7
--- /dev/null
+++ b/src/Starlight/Component/Routing/ResourceRoute.php
@@ -0,0 +1,327 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Routing;
+use Starlight\Component\Inflector\Inflector;
+
+
+/**
+ * ResourceRoute
+ */
+class ResourceRoute implements Compilable
+{
+ /**
+ * RESTful routing map; maps actions to methods
+ * @var array
+ */
+ protected static $resources_map = array(
+ 'index' => array('name' => '%p', 'verb' => 'get', 'url' => '(.:format)'),
+ 'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
+ 'create' => array('name' => '%p', 'verb' => 'post', 'url' => '(.:format)'),
+ 'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id(.:format)'),
+ 'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action(.:format)'),
+ 'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id(.:format)'),
+ 'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id(.:format)'),
+ );
+
+ /**
+ * Default path names
+ * @var array
+ */
+ protected static $resource_names = array(
+ 'add' => 'add',
+ 'edit' => 'edit',
+ 'delete' => 'delete',
+ );
+
+
+ public $resource;
+ public $controller;
+ public $except;
+ public $only;
+ public $constraints;
+ public $singular;
+ public $plural;
+ public $path_names;
+ public $module;
+ public $path_prefix;
+ public $name_prefix;
+ public $member = array();
+ public $collection = array();
+ public $map_member_collection_scope = null;
+
+
+ /**
+ * Constructor
+ * @param string $resource resource name
+ * @param array $options options hash
+ */
+ public function __construct($resource = null, array $options = array())
+ {
+ if (!is_null($resource)) {
+ $this->resource = $resource;
+
+ $this->controller = $this->plural = Inflector::pluralize($this->resource);
+ $this->singular = Inflector::singularize($this->controller);
+
+ if (count($options) > 0) {
+ foreach ($options as $key => $value) {
+ $this->$key($value);
+ }
+ }
+ }
+ }
+
+ /**
+ * Set except routes from $resources_map
+ * @param array $except except resources
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function except(array $except)
+ {
+ $this->only = null;
+ $this->except = $except;
+
+ return $this;
+ }
+
+ /**
+ * Set only routes from $resources_map
+ * @param array $only only resources
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function only(array $only)
+ {
+ $this->except = null;
+ $this->only = $only;
+
+ return $this;
+ }
+
+ /**
+ * Set controller
+ * @param string $controller controller name
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function controller($controller)
+ {
+ $this->controller = $controller;
+
+ return $this;
+ }
+
+ /**
+ * Set contraints
+ * @param mixed $constraints constraints
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function constraints($constraints)
+ {
+ $this->constraints = $constraints;
+
+ return $this;
+ }
+
+ /**
+ * Set name for route paths
+ * @param string $name path name
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function name($name)
+ {
+ $single = explode(' ', strtolower(Inflector::humanize($name)));
+ $plural = $single;
+ $count = count($single);
+
+ $single[$count - 1] = Inflector::singularize($single[$count - 1]);
+ $plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
+
+ $this->singular = implode('_', $single);
+ $this->plural = implode('_', $plural);
+
+ return $this;
+ }
+
+ /**
+ * Set path names for special routes
+ * @param array $names path name overrides
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function pathNames(array $names)
+ {
+ $this->path_names = $names;
+
+ return $this;
+ }
+
+ /**
+ * Set module/namespace for resource
+ * @param string $module module/namespace name
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function module($module)
+ {
+ $this->module = $module;
+
+ return $this;
+ }
+
+ /**
+ * Set member routes
+ * @param \Closure $callback callback method
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function member(\Closure $callback)
+ {
+ $this->map_member_collection_scope = 'member';
+ $callback($this);
+ $this->map_member_collection_scope = null;
+
+ return $this;
+ }
+
+ /**
+ * Set collection routes
+ * @param \Closure $callback callback method
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function collection(\Closure $callback)
+ {
+ $this->map_member_collection_scope = 'collection';
+ $callback($this);
+ $this->map_member_collection_scope = null;
+
+ return $this;
+ }
+
+ /**
+ * Set an extra route which responds to GET requests
+ * @param string $path path
+ * @param string $options options hash
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function get($path, $options = array())
+ {
+ return $this->mapMethod('get', $path, $options);
+ }
+
+ /**
+ * Set an extra route which responds to PUT requests
+ * @param string $path path
+ * @param string $options options hash
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function put($path, $options = array())
+ {
+ return $this->mapMethod('put', $path, $options);
+ }
+
+ /**
+ * Set an extra route which responds to POST requests
+ * @param string $path path
+ * @param string $options options hash
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function post($path, $options = array())
+ {
+ return $this->mapMethod('post', $path, $options);
+ }
+
+ /**
+ * Set an extra route which responds to DELETE requests
+ * @param string $path path
+ * @param string $options options hash
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ public function delete($path, $options = array())
+ {
+ return $this->mapMethod('delete', $path, $options);
+ }
+
+ /**
+ * Map extra routes through a common interface
+ * @param string $method HTTP method
+ * @param string $path path
+ * @param array $options options hash
+ * @return \Starlight\Component\Routing\ResourceRoute this resource route
+ */
+ protected function mapMethod($method, $path, $options = array())
+ {
+ $on = isset($options['on']) ? $options['on'] : $this->map_member_collection_scope;
+ if (!$on || ($on != 'member' && $on != 'collection')) {
+ throw new \InvalidArgumentException('You must pass a valid "on" option (collection/method) to ' . $method);
+ }
+
+ array_push($this->$on, array($path, strtoupper($method)));
+
+ return $this;
+ }
+
+ /**
+ * Compiles this resource route into individual \Starlight\Component\Routing\Route
+ * @return array array of \Starlight\Component\Routing\Route routes
+ */
+ public function compile()
+ {
+ $generators = static::$resources_map;
+ if ($this->except) {
+ $generators = array_diff_key($generators, array_fill_keys($this->except, true));
+ } elseif ($this->only) {
+ $generators = array_intersect_key($generators, array_fill_keys($this->only, true));
+ }
+
+ if (is_array($this->path_names)) {
+ $this->path_names += static::$resource_names;
+ } else {
+ $this->path_names = static::$resource_names;
+ }
+
+ if ($this->module) {
+ $this->controller = $this->module . '\\' . $this->controller;
+ }
+
+ if (count($this->member) > 0) {
+ foreach ($this->member as $member) {
+ list($name, $verb) = $member;
+ $generators[$name] = array('name' => $name . '_%s', 'verb' => $verb, 'url' => '/:id/' . $name . '(.:format)');
+ }
+ }
+
+ if (count($this->collection) > 0) {
+ foreach ($this->collection as $collection) {
+ list($name, $verb) = $collection;
+ $generators[$name] = array('name' => $name . '_%p', 'verb' => $verb, 'url' => '/' . $name . '(.:format)');
+ }
+ }
+
+ $routes = array();
+ foreach ($generators as $action => $parts) {
+ $path = $parts['url'];
+ if (strpos($path, ':action') !== false) {
+ $path = str_replace(':action', $this->path_names[$action], $path);
+ }
+
+ $r = new Route($this->path_prefix . '/' . $this->resource . $path, $this->controller . '::' . $action);
+ $r->methods(array($parts['verb']));
+
+ $name = str_replace('%s', $this->name_prefix . $this->singular, $parts['name']);
+ $name = str_replace('%p', $this->name_prefix . $this->plural, $name);
+ $r->name($name);
+
+ if ($this->constraints) {
+ $r->constraints($this->constraints);
+ }
+
+ $routes[] = $r->compile();
+ }
+
+ return $routes;
+ }
+}
diff --git a/src/Starlight/Component/Routing/Routable.php b/src/Starlight/Component/Routing/Routable.php
index 5ff7697..1dc0309 100644
--- a/src/Starlight/Component/Routing/Routable.php
+++ b/src/Starlight/Component/Routing/Routable.php
@@ -1,21 +1,25 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
- * Route
+ * Routable interface
*/
interface Routable
{
+ /**
+ * Match a request
+ * @param \Starlight\Component\Http\Request $request current request
+ */
public function match(Request $request);
}
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index d2d626a..98b8064 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,141 +1,185 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements Routable, Compilable
{
/**
* Base default values for route parameters
* @var array
*/
protected static $base_parameter_defaults = array(
'controller' => null,
'action' => null,
'id' => null,
);
public $path;
public $endpoint;
public $regex;
- public $parameters;
+ public $parameters = array();
public $constraints;
- public $methods;
+ public $methods = array();
public $name;
+ public $module;
+ public $path_prefix;
+ public $name_prefix;
/**
* Constructor
* @param string $path url path
* @param mixed $endpoint route endpoint
*/
public function __construct($path, $endpoint)
{
$this->path = static::normalize($path);
$this->endpoint = $endpoint;
}
/**
* Set route parameter defaults
* @param array $defaults default values hash
- * @return Route this instance
+ * @return \Starlight\Component\Routing\Route this instance
*/
public function defaults(array $defaults)
{
foreach ($defaults as $key => $value) {
- if (trim($this->parameters[$key]) == '') {
+ if (!isset($this->parameters[$key]) || trim($this->parameters[$key]) == '') {
$this->parameters[$key] = $value;
}
}
return $this;
}
/**
- * Set route constraints
- * @param mixed $constraints constraints (hash or Closure)
- * @return Route this instance
+ * Set route constraints
+ * @param mixed $constraints constraints (hash or \Closure)
+ * @return \Starlight\Component\Routing\Route this instance
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
- * Set HTTP methods/verbs route should respond to
- * @param array $methods HTTP methods
- * @return Route this instance
+ * Set HTTP methods/verbs route should respond to
+ * @param array $methods HTTP methods
+ * @return \Starlight\Component\Routing\Route this instance
*/
- public function methods(array $methods)
+ public function methods($methods)
{
+ if (!is_array($methods)) {
+ $methods = array($methods);
+ }
+
$this->methods = $methods;
return $this;
}
/**
- * Set route name for generated helpers
- * @param string $name route name
- * @return Route this instance
+ * Set route name for generated helpers
+ * @param string $name route name
+ * @return \Starlight\Component\Routing\Route this instance
*/
public function name($name)
{
$this->name = $name;
return $this;
}
+ /**
+ * Set module/namespace for the controller
+ * @param string $module module/namespace
+ * @return \Starlight\Component\Routing\Route this instance
+ */
+ public function module($module)
+ {
+ $this->module = $module;
+
+ return $this;
+ }
+
/**
* Compiles the route
+ * @return \Starlight\Component\Routing\Route this compiled instance
*/
public function compile()
{
$parser = new RouteParser();
$constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
+ if ($this->path_prefix) {
+ $this->path = $this->path_prefix . $this->path;
+ }
+
$this->regex = $parser->parse($this->path, $constraints);
$this->parameters = array_merge(static::$base_parameter_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
- // get endpoint:
- if (strpos($this->endpoint, '#') !== false) {
- list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
+ // get endpoint if string:
+ if (is_string($this->endpoint) && strpos($this->endpoint, '::') !== false) {
+ // apply module:
+ if ($this->module) {
+ $this->endpoint = $this->module . '\\' . $this->endpoint;
+ }
+
+ list($this->parameters['controller'], $this->parameters['action']) = explode('::', $this->endpoint);
+ }
+
+ // set name/prefix if available:
+ if ($this->name && $this->name_prefix) {
+ $this->name = $this->name_prefix . $this->name;
}
return $this;
}
/**
- *
+ * Match a request
+ * @param \Starlight\Component\Http\Request $request current request
*/
public function match(Request $request)
{
}
/**
* Normalizes path - removes trailing slashes and prepends single slash
* @param string $path original path
* @return string normalized path
*/
protected function normalize($path)
{
$path = trim($path, '/');
$path = '/' . $path;
return $path;
}
+
+ /**
+ * Nice output version for this route
+ * @return string nice output
+ */
+ public function __toString()
+ {
+ return sprintf("%-6s %-40s %s", strtoupper(implode(',', $this->methods)), $this->path, json_encode($this->parameters));
+ }
}
diff --git a/src/Starlight/Component/Routing/RouteParser.php b/src/Starlight/Component/Routing/RouteParser.php
index e31ae66..2fe8107 100755
--- a/src/Starlight/Component/Routing/RouteParser.php
+++ b/src/Starlight/Component/Routing/RouteParser.php
@@ -1,145 +1,151 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
- * Route
+ * RouteParser
*/
class RouteParser
{
/**
* URL path separators
* '\' and '.'
* @var string
*/
protected static $default_separators = array('/', '.');
-
public $path;
public $regex;
public $requirements;
public $separators;
public $names = array();
protected $quoted_separators;
/**
- *
+ * Parse a route path into a regular expression
+ * @param string $path original url path
+ * @param array $requirements requirements hash
+ * @param array $separators path separators
+ * @return string regular expression
*/
public function parse($path, array $requirements = array(), array $separators = array())
{
$this->regex = '';
$this->path = trim($path);
$this->requirements = $requirements;
$this->separators = count($separators) > 0 ? $separators : static::$default_separators;
$this->quoted_separators = $this->quote(implode('', $this->separators));
$this->regex = $this->reduce();
return $this->regex;
}
/**
- *
+ * Reduce the path into the regular expression
+ * @return string reduced path
*/
protected function reduce()
{
$balance = 0;
$prev = $next = $literal = '';
$length = strlen($this->path);
$segments = array();
for ($i=0; $i<$length; $i++)
{
$curr = $this->path[$i];
$next = isset($this->path[$i + 1]) ? $this->path[$i + 1] : '';
$prev = ($i > 0) ? $this->path[$i - 1] : '';
if ($curr == '\\') {
if (preg_match('/[\(|\)|\:|\*]/', $next)) {
// escaped special character
$i++;
$literal .= $next;
} else {
// literal
$literal .= $curr;
}
} else {
if (preg_match('/[\(|\)]/', $curr)) {
// parenthesis
if ($literal != '') {
$segments[] = $this->quote($literal);
$literal = '';
}
if ($curr == '(') {
$balance += 1;
$segments[] = '(?:';
} else {
$balance -= 1;
$segments[] = ')?';
}
} elseif (preg_match('/[\:|\*]/', $curr)) {
// identifier
preg_match('/(\:|\*){1}[a-z\_]+/i', $this->path, $matches, PREG_OFFSET_CAPTURE, $i);
if (isset($matches[0]) && count($matches[0]) > 0) {
if ($literal != '') {
$segments[] = $this->quote($literal);
$literal = '';
}
$id = substr($matches[0][0], 0, 1);
$key = substr($matches[0][0], 1);
if (isset($this->requirements[$key])) {
// custom requirements
$regex = $this->requirements[$key];
} elseif ($id == '*') {
// glob
$regex = '.+';
} else {
// standard segments
$regex = '[^' . $this->quoted_separators . ']+';
}
$segments[] = '(?<' . $key . '>' . $regex . ')';
$this->names[] = $key;
$i += strlen($key);
} else {
// invalid identifier:
$literal .= $curr;
}
} else {
// just normal text
$literal .= $curr;
}
}
}
if ($literal != '') {
$segments[] = $this->quote($literal);
}
if ($balance != 0) {
throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
}
return '/\A' . implode('', $segments) . '\Z/';
}
/**
- *
+ * Quote string for preg parsing
+ * @param string $string string to quote
+ * @return string quoted string
*/
protected function quote($string)
{
return preg_quote($string, '/');
}
}
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index bce66cb..226e86b 100644
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,176 +1,367 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
+use Starlight\Component\Inflector\Inflector;
/**
* Router
*/
-class Router
+class Router implements Compilable
{
protected $routes = array();
+ protected $current = array();
+ protected $current_type = null;
protected $compiled = array();
- protected $scopes = array();
protected $has_compiled = false;
+ protected $scopes = array();
/**
- *
+ * Draw routes - router gateway
+ * @param \Closure $callback callback
+ * @return \Starlight\Component\Routing\Router this instance
*/
public function draw(\Closure $callback)
{
- // todo: check for cached version before redrawing these
+ // TODO: check for cached version before redrawing these
$callback($this);
+
+ return $this;
}
-
/**
- *
+ * Maps a single route
+ * @param string $path url path
+ * @param mixed $endpoint controller::action pair or callback
+ * @return \Starlight\Component\Routing\Route route
*/
public function map($path, $endpoint)
{
+ if ($this->current_type == 'resource') {
+ throw new \RuntimeException('Cannot use ' . __CLASS__ . '::map within a resource context.');
+ }
+
$this->routes[] = new Route($path, $endpoint);
+ $this->current[] = count($this->routes) - 1;
+ $this->current_type = 'route';
- return $this->applyScopes($this->routes[count($this->routes) - 1]);
- }
-
- /**
- *
- */
- public function resources($resource)
- {
- $this->routes[] = new Resource($resource);
+ $this->applyScopes();
- return $this->applyScopes($this->routes[count($this->routes) - 1]);
+ array_pop($this->current);
+ $this->current_type = '';
+
+ return $this->routes[count($this->routes) - 1];
}
/**
- *
+ * Maps RESTful resources routes
*/
- public function resource($resource)
+ public function resources()
{
- $this->routes[] = new SingularResource($resource);
+ $args = func_get_args();
+ $count = count($args);
+ $callback = null;
+ $options = array();
+
+ if (is_callable($args[$count - 1])) {
+ $callback = array_pop($args);
+ $count--;
+ }
- return $this->applyScopes($this->routes[count($this->routes) - 1]);
+ if (is_array($args[$count - 1])) {
+ $options = array_pop($args);
+ $count--;
+ }
+
+ // map each resource separately (if multiple)
+ foreach ($args as $resource) {
+ if ($resource == Inflector::pluralize($resource)) {
+ $klass = 'Starlight\Component\Routing\ResourceRoute';
+ } else {
+ $klass = 'Starlight\Component\Routing\SingularResourceRoute';
+ }
+
+ $this->routes[] = new $klass($resource, $options);
+ $this->current[] = count($this->routes) - 1;
+ $this->current_type = 'resource';
+
+ $route = $this->routes[count($this->routes) - 1];
+
+ $this->applyScopes();
+
+ if ($callback) {
+ $callback($this, $route);
+ }
+
+ array_pop($this->current);
+ $this->current_type = 'route';
+ }
+
+ return $route;
}
/**
- *
+ * Maps singular RESTful resource
*/
- public function namespaced($namespace, $callback)
+ public function resource()
{
- $this->scope('namespace', $namespace, $callback);
+ return call_user_func_array(array($this, 'resources'), func_get_args());
}
/**
- *
+ * Scope routes
+ * @param array $scopes scopes to apply
+ * @param \Closure $callback callback
*/
- public function constraints($constraints, $callback)
+ public function scope(array $scopes, \Closure $callback)
{
- $this->scope('constraints', $constraints, $callback);
+ $this->addScopes($scopes);
+ $callback($this);
+ $this->removeScopes($scopes);
}
/**
- *
+ * Compile all routes
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
+ // /**
+ // *
+ // */
+ // public function match(Request $request)
+ // {
+ // foreach ($this->compiled as $r) {
+ // if ($r->match($request)) {
+ // //
+ // return;
+ // }
+ // }
+ //
+ // // nothing matched:
+ // }
+
/**
- *
+ * Pretty version of routes
+ * @return string nice string
*/
- public function match(Request $request)
+ public function __toString()
{
+ $parts = array();
+ $mn = $mv = $mp = 0;
foreach ($this->compiled as $r) {
- if ($r->match($request)) {
- //
- return;
+ $p = array(
+ 'name' => $r->name,
+ 'verb' => strtoupper(implode(',', $r->methods)),
+ 'path' => $r->path,
+ 'endp' => $r->endpoint,
+ );
+
+ if (strlen($p['name']) > $mn) {
+ $mn = strlen($p['name']);
}
+ if (strlen($p['verb']) > $mv) {
+ $mv = strlen($p['verb']);
+ }
+ if (strlen($p['path']) > $mp) {
+ $mp = strlen($p['path']);
+ }
+
+ $parts[] = $p;
+ }
+
+
+ $rc = '<pre>';
+ foreach ($parts as $p) {
+ $rc .= sprintf("%" . $mn . "s %-" . $mv . "s %-" . $mp . "s %s\n", $p['name'], $p['verb'], $p['path'], $p['endp']);
}
+ $rc .= '</pre>';
- // nothing matched:
+ return $rc;
}
/**
- *
+ * Apply current scopes to currently scoped routes
*/
- public function scope($type, $value, $callback)
+ protected function applyScopes()
{
- $this->addScope($type, $value);
- $callback($this);
- $this->removeScope($type, $value);
+ $count = count($this->current);
+ $current = $this->current[$count - 1];
+ $previous = isset($this->current[$count - 2]) ? $this->routes[$this->current[$count - 2]] : null;
+
+ $this->routes[$current] = $this->applyScope($this->routes[$current], $previous);
}
/**
- *
+ * Apply scopes to single route
+ * @param mixed $route resource or route to scope
+ * @param \Starlight\Component\Routing\ResourceRoute $nested current parent route (if present)
+ * @return mixed resource or route which was scoped
*/
- protected function applyScopes($route)
+ protected function applyScope($route, $nested = null)
{
- // scoped namespace
- if (isset($this->scopes['namespace'])) {
- $route->namespaced(implode('/', $this->scopes['namespace']));
+ // nested resource
+ if ($nested) {
+ $route->path_prefix .= $nested->path_prefix . '/' . $nested->plural . '/:' . $nested->singular . '_id';
+ $route->name_prefix .= $nested->name_prefix . $nested->singular . '_';
}
- // scoped constraints
+ // constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
$constraints = array_merge($constraints, $c);
}
$route->constraints($constraints);
}
+ // name
+ if (isset($this->scopes['name'])) {
+ $count = count($this->scopes['name']);
+ if ($this->current_type == 'resource') {
+ if (!$nested || $count > 1) {
+ $route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
+ }
+ } else {
+ $route->name_prefix .= $this->scopes['name'][$count - 1] . '_';
+ }
+ }
+
+ // module
+ if (isset($this->scopes['module'])) {
+ $route->module(implode('\\', $this->scopes['module']));
+ }
+
+ // path
+ if (isset($this->scopes['path'])) {
+ $count = count($this->scopes['path']);
+ if ($this->current_type == 'resource') {
+ if (!$nested || $count > 1) {
+ $route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
+ }
+ } else {
+ $route->path_prefix .= '/' . $this->scopes['path'][$count - 1];
+ }
+ }
+
+
+ if ($this->current_type == 'route') {
+ // route only cases
+
+ // HTTP methods/verbs
+ if (isset($this->scopes['methods'])) {
+ // only consider the last on the stack:
+ $route->methods($this->scopes['methods'][count($this->scopes['methods']) - 1]);
+ }
+
+ // parameter defaults
+ if (isset($this->scopes['defaults'])) {
+ $defaults = array();
+ foreach ($this->scopes['defaults'] as $d) {
+ $defaults = array_merge($defaults, $d);
+ }
+ $route->defaults($d);
+ }
+
+ } elseif ($this->current_type == 'resource') {
+ // resource only cases
+
+ // except
+ if (isset($this->scopes['except'])) {
+ // only consider the last on the stack:
+ $route->except($this->scopes['except'][count($this->scopes['except']) - 1]);
+ }
+
+ // only
+ if (isset($this->scopes['only'])) {
+ // only consider the last on the stack:
+ $route->only($this->scopes['only'][count($this->scopes['only']) - 1]);
+ }
+
+ // path_names
+ if (isset($this->scopes['path_names'])) {
+ // only consider the last on the stack:
+ $route->pathNames($this->scopes['path_names'][count($this->scopes['path_names']) - 1]);
+ }
+ }
+
return $route;
}
/**
- *
+ * Add scopes to parse tree
+ * @param array $scopes scopes to add
*/
- protected function addScope($key, $value = null)
+ protected function addScopes(array $scopes)
{
- if (isset($this->scopes[$key])) {
- $this->scopes[$key][] = $value;
- } else {
- $this->scopes[$key] = array($value);
+ foreach ($scopes as $scope => $options) {
+ if ($scope == 'namespace') {
+ $this->addScopes(array(
+ 'name' => $options,
+ 'path' => $options,
+ 'module' => $options,
+ ));
+ continue;
+ }
+
+ if (isset($this->scopes[$scope])) {
+ $this->scopes[$scope][] = $options;
+ } else {
+ $this->scopes[$scope] = array($options);
+ }
}
}
/**
- *
+ * Remove scopes from parse tree
+ * @param array $scopes scopes to remove
*/
- protected function removeScope($key, $value)
+ protected function removeScopes(array $scopes)
{
- if (isset($this->scopes[$key])) {
- $position = array_search($value, $this->scopes[$key]);
- if ($position !== false) {
- unset($this->scopes[$key][$position]);
+ foreach ($scopes as $scope => $options) {
+ if ($scope == 'namespace') {
+ $this->removeScopes(array(
+ 'name' => $options,
+ 'path' => $options,
+ 'module' => $options,
+ ));
+ continue;
+ }
+ if (isset($this->scopes[$scope])) {
+ if (($position = array_search($options, $this->scopes[$scope])) !== false) {
+ unset($this->scopes[$scope][$position]);
+ if (count($this->scopes[$scope]) == 0) {
+ unset($this->scopes[$scope]);
+ }
+ }
}
}
}
}
diff --git a/src/Starlight/Component/Routing/SingularResource.php b/src/Starlight/Component/Routing/SingularResourceRoute.php
similarity index 76%
rename from src/Starlight/Component/Routing/SingularResource.php
rename to src/Starlight/Component/Routing/SingularResourceRoute.php
index 1664357..c33e679 100644
--- a/src/Starlight/Component/Routing/SingularResource.php
+++ b/src/Starlight/Component/Routing/SingularResourceRoute.php
@@ -1,33 +1,32 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
* Singular resource
*/
-class SingularResource extends Resource
+class SingularResourceRoute extends ResourceRoute
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
- 'index' => array('name' => '%s', 'verb' => 'get', 'url' => '/'),
- 'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action'),
- 'create' => array('name' => '%s', 'verb' => 'post', 'url' => '/'),
- 'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/'),
- 'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:action'),
- 'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/'),
- 'delete' => array('name' => 'delete_%s', 'verb' => 'get', 'url' => '/:action'),
- 'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/'),
+ 'index' => array('name' => '%s', 'verb' => 'get', 'url' => '(.:format)'),
+ 'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
+ 'create' => array('name' => '%s', 'verb' => 'post', 'url' => '(.:format)'),
+ 'show' => array('name' => '%s', 'verb' => 'get', 'url' => '(.:format)'),
+ 'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:action(.:format)'),
+ 'update' => array('name' => '%s', 'verb' => 'put', 'url' => '(.:format)'),
+ 'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '(.:format)'),
);
}
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index 0a2f302..704e6db 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,76 +1,29 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
error_reporting(-1);
require_once __DIR__ . '/Support/UniversalClassLoader.php';
$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
$autoloader->registerNamespaces(array(
'Starlight' => __DIR__ . '/../../',
));
$autoloader->register();
function dump()
{
foreach (func_get_args() as $arg) {
echo '<pre>' . htmlspecialchars(print_r($arg, true)) . '</pre>';
echo '<hr />';
}
}
-
-
-// // $context = new \Starlight\Component\Http\HttpContext();
-// // $dispatcher = new \Starlight\Component\Http\HttpDispatcher($context);
-// // $dispatcher->dispatch();
-//
-// $router = new \Starlight\Component\Routing\Router();
-// $router->draw(function($r){
-// // $r->map('/:controller(/:action(/:id))(.:format)', 'session#add');
-// // $r->map(':controller/:id', 'session#add')->constraints(array('id' => '[0-9]+'))->namespaced('admin');
-// // $r->map('*anything', 'session#add');
-// // $r->map('/login/:screenname', 'session#add')
-// // ->defaults(array('id' => 27))
-// // ->methods(array('get', 'post', 'delete'))
-// // ->name('login')
-// // ->namespaced('admin')
-// // ->constraints(array('id' => '/27/i'))
-// // ;
-//
-// // $r->constraints(array('id' => 27), function($r){
-// // $r->namespaced('admin', function($r){
-// // // $r->map('/login', 'session#new');
-// // // $r->map('/logout', 'session#destroy');
-// // $r->namespaced('anything', function($r){
-// // $r->map('whee', 'session#new');
-// // });
-// // });
-// // });
-//
-// $r->resources('photo')
-// ->name('image')
-// ->controller('images')
-// ->namespaced('admin')
-// ;
-// });
-// $router->compile();
-//
-// dump($router);
-
-$parser = new Starlight\Component\Routing\RouteParser();
-// $parser->parse('foo/bar');
-// $parser->parse('/foo(/bar))');
-// $parser->parse('/foo/bar)');
-// $parser->parse('/foo(/bar(/:format)/download)');
-$parser->parse('/\\foo\\((/:bar)(/baz)');
-// $parser->parse('/foo.:format');
-// $parser->parse('/foo/bar');
\ No newline at end of file
diff --git a/tests/Starlight/Component/Routing/RouteTest.php b/tests/Starlight/Component/Routing/RouteTest.php
index 65e3ce8..3a542f2 100755
--- a/tests/Starlight/Component/Routing/RouteTest.php
+++ b/tests/Starlight/Component/Routing/RouteTest.php
@@ -1,100 +1,100 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\Route;
/**
*/
class RouteTest extends \PHPUnit_Framework_TestCase
{
public function testRouteIsNormalized()
{
- $route = new Route('some/path', 'controller#action');
+ $route = new Route('some/path', 'controller::action');
$this->assertEquals('/some/path', $route->path);
}
public function testSetDefaults()
{
$route = $this->getRoute();
$defaults = array('id' => 24);
$return = $route->defaults($defaults);
$this->assertEquals($defaults, $route->parameters);
$this->assertEquals($return, $route);
}
public function testDefaultsDontOverrideSetParameters()
{
$route = $this->getRoute();
$defaults = array('id' => 24);
$route->parameters = array('id' => 25);
$return = $route->defaults($defaults);
$this->assertEquals(25, $route->parameters['id']);
$this->assertEquals($return, $route);
}
public function testSetConstraints()
{
$route = $this->getRoute();
$constraints = array('id' => '[0-9]+');
$return = $route->constraints($constraints);
$this->assertEquals($constraints, $route->constraints);
$this->assertEquals($return, $route);
}
public function testSetMethods()
{
$route = $this->getRoute();
$methods = array('get', 'post');
$return = $route->methods($methods);
$this->assertEquals($methods, $route->methods);
$this->assertEquals($return, $route);
}
public function testSetName()
{
$route = $this->getRoute();
$name = 'login';
$return = $route->name($name);
$this->assertEquals($name, $route->name);
$this->assertEquals($return, $route);
}
public function testDetermineControllerActionFromEndpoint()
{
- $route = $this->getRoute(array('endpoint' => 'users#view'));
+ $route = $this->getRoute(array('endpoint' => 'users::view'));
$route->compile();
$this->assertEquals('users', $route->parameters['controller']);
$this->assertEquals('view', $route->parameters['action']);
}
protected function getRoute(array $options = array())
{
$defaults = array(
'path' => '/:controller/:action/:id',
- 'endpoint' => 'controller#action',
+ 'endpoint' => 'controller::action',
);
$options = array_merge($defaults, $options);
return new Route($options['path'], $options['endpoint']);
}
}
|
synewaves/starlight | 676170166562ec234c62eeaa6b7519ea500f47de | Base route definitions | diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index e16cfdf..d2d626a 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,144 +1,141 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements Routable, Compilable
{
- // /**
- // * Base default values for route parameters
- // * @var array
- // */
- // protected static $base_defaults = array(
- // 'controller' => null,
- // 'action' => null,
- // 'id' => null,
- // );
- //
- //
- // public $path;
- // public $endpoint;
- // public $regex;
- // public $parameters;
- // public $constraints;
- // public $methods;
- // public $name;
- // public $namespace;
- //
- //
- // /**
- // *
- // */
- // public function __construct($path, $endpoint)
- // {
- // $this->path = static::normalize($path);
- // $this->endpoint = $endpoint;
- // }
- //
- // /**
- // *
- // */
- // public function defaults(array $defaults)
- // {
- // foreach ($defaults as $key => $value) {
- // if (trim($this->parameters[$key]) == '') {
- // $this->parameters[$key] = $value;
- // }
- // }
- //
- // return $this;
- // }
- //
- // /**
- // *
- // */
- // public function constraints($constraints)
- // {
- // $this->constraints = $constraints;
- //
- // return $this;
- // }
- //
- // /**
- // *
- // */
- // public function methods(array $methods)
- // {
- // $this->methods = $methods;
- //
- // return $this;
- // }
- //
- // /**
- // *
- // */
- // public function name($name)
- // {
- // $this->name = $name;
- //
- // return $this;
- // }
- //
- // /**
- // *
- // */
- // public function namespaced($namespace)
- // {
- // $this->namespace = $namespace;
- //
- // return $this;
- // }
- //
- // /**
- // *
- // */
- // public function compile()
- // {
- // $parser = new RouteParser();
- // $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
- //
- // if ($this->namespace) {
- // $this->path = '/' . $this->namespace . $this->path;
- // if ($this->name != '') {
- // $this->name = $this->namespace . '_' . $this->name;
- // }
- // $this->endpoint = $this->namespace . '/' . $this->endpoint;
- // }
- //
- // $this->regex = $parser->parse($this->path, $constraints);
- // $this->parameters = array_merge(static::$base_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
- // list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
- //
- // return $this;
- // }
- //
- // /**
- // *
- // */
- // public function match(Request $request)
- // {
- // }
- //
- // /**
- // *
- // */
- // protected function normalize($path)
- // {
- // $path = trim($path, '/');
- // $path = '/' . $path;
- //
- // return $path;
- // }
+ /**
+ * Base default values for route parameters
+ * @var array
+ */
+ protected static $base_parameter_defaults = array(
+ 'controller' => null,
+ 'action' => null,
+ 'id' => null,
+ );
+
+
+ public $path;
+ public $endpoint;
+ public $regex;
+ public $parameters;
+ public $constraints;
+ public $methods;
+ public $name;
+
+
+ /**
+ * Constructor
+ * @param string $path url path
+ * @param mixed $endpoint route endpoint
+ */
+ public function __construct($path, $endpoint)
+ {
+ $this->path = static::normalize($path);
+ $this->endpoint = $endpoint;
+ }
+
+ /**
+ * Set route parameter defaults
+ * @param array $defaults default values hash
+ * @return Route this instance
+ */
+ public function defaults(array $defaults)
+ {
+ foreach ($defaults as $key => $value) {
+ if (trim($this->parameters[$key]) == '') {
+ $this->parameters[$key] = $value;
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Set route constraints
+ * @param mixed $constraints constraints (hash or Closure)
+ * @return Route this instance
+ */
+ public function constraints($constraints)
+ {
+ $this->constraints = $constraints;
+
+ return $this;
+ }
+
+ /**
+ * Set HTTP methods/verbs route should respond to
+ * @param array $methods HTTP methods
+ * @return Route this instance
+ */
+ public function methods(array $methods)
+ {
+ $this->methods = $methods;
+
+ return $this;
+ }
+
+ /**
+ * Set route name for generated helpers
+ * @param string $name route name
+ * @return Route this instance
+ */
+ public function name($name)
+ {
+ $this->name = $name;
+
+ return $this;
+ }
+
+ /**
+ * Compiles the route
+ */
+ public function compile()
+ {
+ $parser = new RouteParser();
+ $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
+
+ $this->regex = $parser->parse($this->path, $constraints);
+ $this->parameters = array_merge(static::$base_parameter_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
+
+ // get endpoint:
+ if (strpos($this->endpoint, '#') !== false) {
+ list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
+ }
+
+ return $this;
+ }
+
+ /**
+ *
+ */
+ public function match(Request $request)
+ {
+ }
+
+ /**
+ * Normalizes path - removes trailing slashes and prepends single slash
+ * @param string $path original path
+ * @return string normalized path
+ */
+ protected function normalize($path)
+ {
+ $path = trim($path, '/');
+ $path = '/' . $path;
+
+ return $path;
+ }
}
diff --git a/tests/Starlight/Component/Routing/RouteParserTest.php b/tests/Starlight/Component/Routing/RouteParserTest.php
index 97d35e4..8f946b9 100755
--- a/tests/Starlight/Component/Routing/RouteParserTest.php
+++ b/tests/Starlight/Component/Routing/RouteParserTest.php
@@ -1,155 +1,154 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\RouteParser;
/**
- * @group Routing
*/
class RouteParserTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->parser = new RouteParser();
}
public function testStaticSegment()
{
$this->parser->parse('sample');
$this->assertEquals('/\Asample\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testMultipleStaticSegments()
{
$this->parser->parse('sample/index.html');
$this->assertEquals('/\Asample\/index\.html\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testDynamicSegment()
{
$this->parser->parse(':subdomain.example.com');
$this->assertEquals('/\A(?<subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array('subdomain'), $this->parser->names);
}
public function testDynamicSegmentWithLedingUnderscore()
{
$this->parser->parse(':_subdomain.example.com');
$this->assertEquals('/\A(?<_subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array('_subdomain'), $this->parser->names);
}
public function testInvalidSegmentNames()
{
$this->assertEquals('/\A\:123\.example\.com\Z/', $this->parser->parse(':123.example.com'));
$this->assertEquals('/\A\:\$\.example\.com\Z/', $this->parser->parse(':$.example.com'));
}
public function testEscapedDynamicSegment()
{
$this->parser->parse('\:subdomain.example.com');
$this->assertEquals('/\A\:subdomain\.example\.com\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testDynamicSegmentWithSeparators()
{
$this->assertEquals('/\Afoo\/(?<bar>[^\/]+)\Z/', $this->parser->parse('foo/:bar', array(), array('/')));
}
public function testDynamicSegmentWithRequirements()
{
$this->assertEquals('/\Afoo\/(?<bar>[a-z]+)\Z/', $this->parser->parse('foo/:bar', array('bar' => '[a-z]+'), array('/')));
}
public function testDynamicSegmentInsideOptionalSegment()
{
$this->assertEquals('/\Afoo(?:\.(?<extension>[^\/\.]+))?\Z/', $this->parser->parse('foo(.:extension)'));
}
public function testGlobSegment()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files'));
}
public function testGlobIgnoresSeparators()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files', array(), array('/', '.', '?')));
}
public function testGlobSegmentAtBeginning()
{
$this->assertEquals('/\A(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('*files/foo.txt'));
}
public function testGlobSegmentInMiddle()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/foo.txt'));
}
public function testMultipleGlobSegments()
{
$this->assertEquals('/\Asrc\/(?<files>.+)\/dir\/(?<morefiles>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/dir/*morefiles/foo.txt'));
}
public function testEscapedGlobSegment()
{
$this->parser->parse('src/\*files');
$this->assertEquals('/\Asrc\/\*files\Z/', $this->parser->regex);
$this->assertEquals(array(), $this->parser->names);
}
public function testOptionalSegment()
{
$this->assertEquals('/\A\/foo(?:\/bar)?\Z/', $this->parser->parse('/foo(/bar)'));
}
public function testConsecutiveOptionalSegments()
{
$this->assertEquals('/\A\/foo(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('/foo(/bar)(/baz)'));
}
public function testMultipleOptionalSegments()
{
$this->assertEquals('/\A(?:\/foo)?(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('(/foo)(/bar)(/baz)'));
}
public function testEscapesOptionalSegmentParenthesis()
{
$this->assertEquals('/\A\/foo\(\/bar\)\Z/', $this->parser->parse('/foo\(/bar\)'));
}
public function testEscapesOneOptionalSegmentParenthesis()
{
$this->assertEquals('/\A\/foo\((?:\/bar)?\Z/', $this->parser->parse('/foo\((/bar)'));
}
public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedFront()
{
$this->setExpectedException('InvalidArgumentException');
$this->parser->parse('/foo((/bar)');
}
public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedBack()
{
$this->setExpectedException('InvalidArgumentException');
$this->parser->parse('/foo(/bar))');
}
}
diff --git a/tests/Starlight/Component/Routing/RouteTest.php b/tests/Starlight/Component/Routing/RouteTest.php
index 1c5830d..65e3ce8 100755
--- a/tests/Starlight/Component/Routing/RouteTest.php
+++ b/tests/Starlight/Component/Routing/RouteTest.php
@@ -1,20 +1,100 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\Route;
/**
*/
class RouteTest extends \PHPUnit_Framework_TestCase
{
+ public function testRouteIsNormalized()
+ {
+ $route = new Route('some/path', 'controller#action');
+ $this->assertEquals('/some/path', $route->path);
+ }
+ public function testSetDefaults()
+ {
+ $route = $this->getRoute();
+
+ $defaults = array('id' => 24);
+ $return = $route->defaults($defaults);
+
+ $this->assertEquals($defaults, $route->parameters);
+ $this->assertEquals($return, $route);
+ }
+
+ public function testDefaultsDontOverrideSetParameters()
+ {
+ $route = $this->getRoute();
+
+ $defaults = array('id' => 24);
+ $route->parameters = array('id' => 25);
+ $return = $route->defaults($defaults);
+
+ $this->assertEquals(25, $route->parameters['id']);
+ $this->assertEquals($return, $route);
+ }
+
+ public function testSetConstraints()
+ {
+ $route = $this->getRoute();
+
+ $constraints = array('id' => '[0-9]+');
+ $return = $route->constraints($constraints);
+
+ $this->assertEquals($constraints, $route->constraints);
+ $this->assertEquals($return, $route);
+ }
+
+ public function testSetMethods()
+ {
+ $route = $this->getRoute();
+
+ $methods = array('get', 'post');
+ $return = $route->methods($methods);
+
+ $this->assertEquals($methods, $route->methods);
+ $this->assertEquals($return, $route);
+ }
+
+ public function testSetName()
+ {
+ $route = $this->getRoute();
+
+ $name = 'login';
+ $return = $route->name($name);
+
+ $this->assertEquals($name, $route->name);
+ $this->assertEquals($return, $route);
+ }
+
+ public function testDetermineControllerActionFromEndpoint()
+ {
+ $route = $this->getRoute(array('endpoint' => 'users#view'));
+ $route->compile();
+
+ $this->assertEquals('users', $route->parameters['controller']);
+ $this->assertEquals('view', $route->parameters['action']);
+ }
+
+ protected function getRoute(array $options = array())
+ {
+ $defaults = array(
+ 'path' => '/:controller/:action/:id',
+ 'endpoint' => 'controller#action',
+ );
+ $options = array_merge($defaults, $options);
+
+ return new Route($options['path'], $options['endpoint']);
+ }
}
|
synewaves/starlight | 261a764f9af60098ab77fd29de7d3fffea2f56de | Fixed ending semicolons on classes | diff --git a/src/Starlight/Component/Dispatcher/Context/Context.php b/src/Starlight/Component/Dispatcher/Context/Context.php
index 27195a6..6aed097 100644
--- a/src/Starlight/Component/Dispatcher/Context/Context.php
+++ b/src/Starlight/Component/Dispatcher/Context/Context.php
@@ -1,16 +1,16 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Dispatcher\Context;
class Context
{
-};
+}
diff --git a/src/Starlight/Component/Dispatcher/Dispatcher.php b/src/Starlight/Component/Dispatcher/Dispatcher.php
index 6b4d5a2..2172f67 100644
--- a/src/Starlight/Component/Dispatcher/Dispatcher.php
+++ b/src/Starlight/Component/Dispatcher/Dispatcher.php
@@ -1,25 +1,25 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Dispatcher;
use Starlight\Component\Dispatcher\Context\Context;
abstract class Dispatcher
{
public $context;
public function __construct(Context $context)
{
$this->context = $context;
}
abstract public function dispatch();
-};
+}
diff --git a/src/Starlight/Component/Http/Exception/IpSpoofingException.php b/src/Starlight/Component/Http/Exception/IpSpoofingException.php
index 9d799d2..fbfde02 100755
--- a/src/Starlight/Component/Http/Exception/IpSpoofingException.php
+++ b/src/Starlight/Component/Http/Exception/IpSpoofingException.php
@@ -1,20 +1,20 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http\Exception;
/**
* IP Spoofing exception
* @see \Starlight\Component\Http\Request::getRemoteIp()
*/
class IpSpoofingException extends \Exception
{
-};
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index 46aeac0..f249e63 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,332 +1,332 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class for request/response headers
*/
class HeaderBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Headers
* @var array
*/
protected $headers;
// /**
// * Wrapper class for request/response headers
// */
// protected $cache_control;
/**
* Type (request, response)
* @var string
*/
protected $type;
/**
* Constructor
* @param array $headers An array of HTTP headers
* @param string $type The type (null, request, or response)
*/
public function __construct(array $headers = array(), $type = null)
{
$this->replace($headers);
if ($type !== null && !in_array($type, array('request', 'response'))) {
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBucket.', $type));
}
$this->type = $type;
}
/**
* Returns the headers
* @return array An array of headers
*/
public function all()
{
return $this->headers;
}
/**
* Returns the parameter keys
* @return array An array of parameter keys
*/
public function keys()
{
return array_keys($this->headers);
}
/**
* Replaces the current HTTP headers by a new set
* @param array $headers An array of HTTP headers
* @return HeaderBucket this instance
*/
public function replace(array $headers = array())
{
$this->cache_control = null;
$this->headers = array();
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
return $this;
}
/**
* Returns a header value by name
* @param string $key The header name
* @param Boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function get($key, $first = true)
{
$key = static::normalizeHeaderName($key);
if (!array_key_exists($key, $this->headers)) {
return $first ? null : array();
}
if ($first) {
return count($this->headers[$key]) ? $this->headers[$key][0] : '';
} else {
return $this->headers[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
$key = static::normalizeHeaderName($key);
if (!is_array($values)) {
$values = array($values);
}
if ($replace === true || !isset($this->headers[$key])) {
$this->headers[$key] = $values;
} else {
$this->headers[$key] = array_merge($this->headers[$key], $values);
}
return $this;
}
/**
* Returns true if the HTTP header is defined
* @param string $key The HTTP header
* @return Boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists(static::normalizeHeaderName($key), $this->headers);
}
/**
* Returns true if the given HTTP header contains the given value
* @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, false));
}
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->headers[static::normalizeHeaderName($key)]);
}
return $this;
}
// /**
// * Returns an instance able to manage the Cache-Control header.
// *
// * @return CacheControl A CacheControl instance
// */
// public function getCacheControl()
// {
// if (null === $this->cacheControl) {
// $this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type);
// }
//
// return $this->cacheControl;
// }
/**
* Set cookie variable
*
* Available options:
*
* <ul>
* <li><b>expires</b> <i>(integer)</i>: cookie expiration time (default: 0 [end of session])</li>
* <li><b>path</b> <i>(string)</i>: path cookie is valid for (default: '')</li>
* <li><b>domain</b> <i>(string)</i>: domain cookie is valid for (default: '')</li>
* <li><b>secure/b> <i>(boolean)</i>: should cookie only be used on a secure connection (default: false)</li>
* <li><b>http_only</b> <i>(string)</i>: cookie only valid over http? [not supported by all browsers] (default: true)</li>
* <li><b>encode</b> <i>(boolean)</i>: urlencode cookie value (default: true)</li>
* </ul>
* @param string $key cookie key
* @param mixed $value value
* @param array $options options hash (see above)
* @return HeaderBucket this instance
*/
public function setCookie($key, $value, $options = array())
{
$default_options = array(
'expires' => null,
'path' => null,
'domain' => null,
'secure' => false,
'http_only' => true,
);
$options += $default_options;
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie key "%s" contains invalid characters.', $key));
}
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
if (trim($key) == '') {
throw new \InvalidArgumentException('The cookie key cannot be empty');
}
$cookie = sprintf('%s=%s', $key, urlencode($value));
if ($this->type == 'request') {
$this->set('Cookie', $cookie);
return;
}
if ($options['expires'] !== null) {
if (is_numeric($options['expires'])) {
$options['expires'] = (int) $options['expires'];
} elseif ($options['expires'] instanceof \DateTime) {
$options['expires'] = $options['expires']->getTimestamp();
} else {
$options['expires'] = strtotime($options['expires']);
if ($options['expires'] === false || $options['expires'] == -1) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $options['expires']));
}
}
$cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($options['domain']) {
$cookie .= '; domain=' . $options['domain'];
}
if ($options['path'] && $options['path'] !== '/') {
$cookie .= '; path=' . $options['path'];
}
if ($options['secure']) {
$cookie .= '; secure';
}
if ($options['http_only']) {
$cookie .= '; httponly';
}
$this->set('Set-Cookie', $cookie, false);
return $this;
}
/**
* Expire a cookie variable
* @param string $key cookie key
* @return HeaderBucket this instance
*/
public function expireCookie($key)
{
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
}
if (!$key) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
if ($this->type == 'request') {
return;
}
$cookie = sprintf('%s=; expires=', $key, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
$this->set('Set-Cookie', $cookie, false);
return $this;
}
//
// ArrayAccess
//
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
public function offsetUnset($offset)
{
return $this->delete($offset);
}
//
// IteratorAggregate
//
public function getIterator()
{
return new \ArrayIterator($this->all());
}
/**
* Normalizes an HTTP header name
* @param string $key The HTTP header name
* @return string The normalized HTTP header name
*/
static public function normalizeHeaderName($key)
{
return strtr(strtolower($key), '_', '-');
}
-};
+}
diff --git a/src/Starlight/Component/Http/HttpContext.php b/src/Starlight/Component/Http/HttpContext.php
index d45f120..9e96c6c 100644
--- a/src/Starlight/Component/Http/HttpContext.php
+++ b/src/Starlight/Component/Http/HttpContext.php
@@ -1,26 +1,26 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
use Starlight\Component\Dispatcher\Context\Context;
class HttpContext extends Context
{
public $request;
public $response;
public function __construct()
{
$this->request = new Request();
$this->response = new Response();
}
-};
+}
diff --git a/src/Starlight/Component/Http/HttpDispatcher.php b/src/Starlight/Component/Http/HttpDispatcher.php
index caf68aa..4d84521 100755
--- a/src/Starlight/Component/Http/HttpDispatcher.php
+++ b/src/Starlight/Component/Http/HttpDispatcher.php
@@ -1,21 +1,21 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
use Starlight\Component\Dispatcher\Dispatcher;
class HttpDispatcher extends Dispatcher
{
public function dispatch()
{
dump($this->context->request);
}
-};
+}
diff --git a/src/Starlight/Component/Http/ParameterBucket.php b/src/Starlight/Component/Http/ParameterBucket.php
index 8fbd49c..314d74d 100755
--- a/src/Starlight/Component/Http/ParameterBucket.php
+++ b/src/Starlight/Component/Http/ParameterBucket.php
@@ -1,158 +1,158 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class request parameters
* @see Request
*/
class ParameterBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Parameters
* @var array
*/
protected $parameters;
/**
* Constructor
* @param array $parameters Parameters
*/
public function __construct(array $parameters = array())
{
$this->replace($parameters);
}
/**
* Returns the parameters
* @return array Parameters
*/
public function all()
{
return $this->parameters;
}
/**
* Returns the parameter keys
* @return array Parameter keys
*/
public function keys()
{
return array_keys($this->parameters);
}
/**
* Replaces the current parameters by a new set
* @param array $parameters parameters
* @return HeaderBucket this instance
*/
public function replace(array $parameters = array())
{
$this->parameters = $parameters;
return $this;
}
/**
* Adds parameters
* @param array $parameters parameters
* @return HeaderBucket this instance
*/
public function add(array $parameters = array())
{
$this->parameters = array_replace($this->parameters, $parameters);
return $this;
}
/**
* Returns a parameter by name
* @param string $key The key
* @param mixed $default default value
* @return mixed value
*/
public function get($key, $default = null)
{
return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}
/**
* Sets a parameter by name
* @param string $key The key
* @param mixed $value value
* @return HeaderBucket this instance
*/
public function set($key, $value)
{
$this->parameters[$key] = $value;
return $this;
}
/**
* Returns true if the parameter is defined
* @param string $key The key
* @return boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists($key, $this->parameters);
}
/**
* Deletes a parameter
* @param string $key key
* @return HeaderBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->parameters[$key]);
}
return $this;
}
//
// ArrayAccess
//
public function offsetExists($offset)
{
return $this->has($offset);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
public function offsetUnset($offset)
{
return $this->delete($offset);
}
//
// IteratorAggregate
//
public function getIterator()
{
return new \ArrayIterator($this->all());
}
-};
+}
diff --git a/src/Starlight/Component/Http/Request.php b/src/Starlight/Component/Http/Request.php
index 9759497..c5f5ef5 100755
--- a/src/Starlight/Component/Http/Request.php
+++ b/src/Starlight/Component/Http/Request.php
@@ -1,315 +1,315 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Request
*/
class Request
{
public static $local_ips = array('127.0.0.1');
public $post;
public $get;
public $cookies;
public $files;
public $server;
public $headers;
protected $host;
protected $port;
protected $remote_ip;
protected $url;
/**
* Constructor
* @param array $post POST values
* @param array $get GET values
* @param array $cookies COOKIE values
* @param array $files FILES values
* @param array $server SERVER values
*/
public function __construct(array $post = null, array $get = null, array $cookies = null, array $files = null, array $server = null)
{
$this->post = new ParameterBucket($post ?: $_POST);
$this->get = new ParameterBucket($get ?: $_GET);
$this->cookies = new ParameterBucket($cookies ?: $_COOKIE);
$this->files = new ParameterBucket($files ?: $_FILES);
$this->server = new ParameterBucket($server ?: $_SERVER);
$this->headers = new HeaderBucket($this->initializeHeaders(), 'request');
}
/**
* Clone
*/
public function __clone()
{
$this->post = clone $this->post;
$this->get = clone $this->get;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Get a value from the request
*
* Order or precedence: GET, POST, COOKIE
*/
public function get($key, $default = null)
{
return $this->get->get($key, $this->post->get($key, $this->cookies->get($key, $default)));
}
/**
* Gets request method, lowercased
*
* Method can come from three places in this order:
* <ol>
* <li>$_POST[_method]</li>
* <li>$_SERVER[X_HTTP_METHOD_OVERRIDE]</li>
* <li>$_SERVER[REQUEST_METHOD]</li>
* </ol>
* @return string request method
*/
public function getMethod()
{
$method = $this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD')));
return !is_null($method) ? strtolower($method) : null;
}
/**
* Is this a DELETE request
* @return boolean is DELETE request
*/
public function isDelete()
{
return $this->getMethod() == 'delete';
}
/**
* Is this a GET request
* @see head()
* @return boolean is GET request
*/
public function isGet()
{
return $this->isHead();
}
/**
* Is this a POST request
* @return boolean is POST request
*/
public function isPost()
{
return $this->getMethod() == 'post';
}
/**
* Is this a HEAD request
*
* Functionally equivalent to get()
* @return boolean is HEAD request
*/
public function isHead()
{
return $this->getMethod() == 'head' || $this->getMethod() == 'get';
}
/**
* Is this a PUT request
* @return boolean is PUT request
*/
public function isPut()
{
return $this->getMethod() == 'put';
}
/**
* Is this an SSL request
* @return boolean is SSL request
*/
public function isSsl()
{
return strtolower($this->server->get('HTTPS')) == 'on';
}
/**
* Gets server protocol
* @return string protocol
*/
public function getProtocol()
{
return $this->isSsl() ? 'https://' : 'http://';
}
/**
* Gets the server host
* @return string host
*/
public function getHost()
{
if (is_null($this->host)) {
$host = $this->server->get('HTTP_X_FORWARDED_HOST', $this->server->get('HTTP_HOST'));
$pos = strpos($host, ':');
if ($pos !== false) {
$this->host = substr($host, 0, $pos);
$this->port = is_null($this->port) ? (int) substr($host, $pos + 1) : null;
} else {
$this->host = $host;
}
}
return $this->host;
}
/**
* Gets the server port
* @return integer port
*/
public function getPort()
{
if (is_null($this->port)) {
$this->port = (int) $this->server->get('SERVER_PORT', $this->getStandardPort());
}
return $this->port;
}
/**
* Gets the standard port number for the current protocol
* @return integer port (443, 80)
*/
public function getStandardPort()
{
return $this->isSsl() ? 443 : 80;
}
/**
* Gets the port string with colon delimiter if not standard port
* @return string port
*/
public function getPortString()
{
return (in_array($this->getPort(), array(443, 80))) ? '' : ':' . $this->getPort();
}
/**
* Gets the host with the port
* @return string host with port
*/
public function getHostWithPort()
{
return $this->getHost() . $this->getPortString();
}
/**
* Gets the client's remote ip
* @return string IP
*/
public function getRemoteIp()
{
if (is_null($this->remote_ip)) {
$remote_ips = null;
if ($x_forward = $this->server->get('HTTP_X_FORWARDED_FOR')) {
$remote_ips = array_map('trim', explode(',', $x_forward));
}
$client_ip = $this->server->get('HTTP_CLIENT_IP');
if ($client_ip) {
if (is_array($remote_ips) && !in_array($client_ip, $remote_ips)) {
// don't know which came from the proxy, and which from the user
throw new Exception\IpSpoofingException(sprintf("IP spoofing attack?!\nHTTP_CLIENT_IP=%s\nHTTP_X_FORWARDED_FOR=%s", $this->server->get('HTTP_CLIENT_IP'), $this->server->get('HTTP_X_FORWARDED_FOR')));
}
$this->remote_ip = $client_ip;
} elseif (is_array($remote_ips)) {
$this->remote_ip = $remote_ips[0];
} else {
$this->remote_ip = $this->server->get('REMOTE_ADDR');
}
}
return $this->remote_ip;
}
/**
* Is this request local?
* @return boolean local
*/
public function isLocal()
{
return in_array($this->getRemoteIp(), static::$local_ips);
}
/**
* Check if the request is an XMLHttpRequest (AJAX)
* @return boolean is XHR (AJAX) request
*/
public function isXmlHttpRequest()
{
return (bool) preg_match('/XMLHttpRequest/i', $this->server->get('HTTP_X_REQUESTED_WITH'));
}
/**
* Gets the full server url with protocol and port
* @return string server path
*/
public function getServer()
{
return $this->getProtocol() . $this->getHostWithPort();
}
/**
* Gets the requested URI path without domain or script name
* @return string uri
*/
public function getUri()
{
$url = $this->server->get('REQUEST_URI');
return trim($url) != '' ? $url : '/';
}
/**
* Gets the requested route from the URI
* @return string route
*/
public function getRoute()
{
$route = $this->getUri();
// remove query string
if (($qs = strpos($route, '?')) !== false) {
$route = substr($route, 0, $qs);
}
return $route;
}
/**
* Initialize request headers for HeaderBucket
* @return array headers
*/
protected function initializeHeaders()
{
$headers = array();
foreach ($this->server->all() as $key => $value) {
if (strtolower(substr($key, 0, 5)) === 'http_') {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
-};
+}
diff --git a/src/Starlight/Component/Http/Response.php b/src/Starlight/Component/Http/Response.php
index 973b4a0..d272df6 100644
--- a/src/Starlight/Component/Http/Response.php
+++ b/src/Starlight/Component/Http/Response.php
@@ -1,98 +1,98 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Response
*/
class Response
{
/**
* Standard HTTP status codes and default messages
* @link http://www.iana.org/assignments/http-status-codes
* @var array
*/
protected static $status_codes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
507 => 'Insufficient Storage',
510 => 'Not Extended'
);
protected $content;
protected $status;
public function __construct($content = '', $status = 200)
{
$this->content($content)->status($status);
}
public function content($content)
{
$this->content = $content;
return $this;
}
public function status($status)
{
$this->status = $status;
return $this;
}
-};
+}
diff --git a/src/Starlight/Component/Inflector/Inflector.php b/src/Starlight/Component/Inflector/Inflector.php
index 1f3b6be..cf3da6a 100644
--- a/src/Starlight/Component/Inflector/Inflector.php
+++ b/src/Starlight/Component/Inflector/Inflector.php
@@ -1,312 +1,312 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Inflector;
/**
* Inflector
*/
class Inflector
{
/**
* Plural inflections
* @var array
*/
protected static $plurals = array();
/**
* Singular inflections
* @var array
*/
protected static $singulars = array();
/**
* Uncountable item reflections
* @var array
*/
protected static $uncountables = array();
/**
* Adds a plural inflection
* @param string $rule regex rule
* @param string $replacement regex replacement
*/
public static function plural($rule, $replacement)
{
if (!preg_match('/^\//', $rule)) {
// looks like a string
// TODO: make string vs regex detection better
static::$uncountables = array_diff(static::$uncountables, array($rule));
$rule = '/' . $rule . '/i';
}
static::$uncountables = array_diff(static::$uncountables, array($replacement));
array_unshift(static::$plurals, array($rule, $replacement));
}
/**
* Adds a singular inflection
* @param string $rule regex rule
* @param string $replacement regex replacement
*/
public static function singular($rule, $replacement)
{
if (!preg_match('/^\//', $rule)) {
// looks like a string
// TODO: make string vs regex detection better
static::$uncountables = array_diff(static::$uncountables, array($rule));
$rule = '/' . $rule . '/i';
}
static::$uncountables = array_diff(static::$uncountables, array($replacement));
array_unshift(static::$singulars, array($rule, $replacement));
}
/**
* Adds an irregular inflection
* @param string $singular singular rule
* @param string $plural plural rule
*/
public static function irregular($singular, $plural)
{
static::plural('/(' . $singular[0] . ')' . substr($singular, 1) . '$/i', '\1' . substr($plural, 1));
static::singular('/(' . $plural[0] . ')' . substr($plural, 1) . '$/i', '\1' . substr($singular, 1));
}
/**
* Adds an uncountable word(s)
* @param string|array single word or array of words
*/
public static function uncountable($words)
{
static::$uncountables += !is_array($words) ? array($words) : $words;
}
/**
* Pluralizes a word
* @param string $str word
* @return string pluralized word
*/
public static function pluralize($str)
{
$str = strval($str);
if (!in_array(strtolower($str), static::$uncountables) && $str != '') {
foreach (static::$plurals as $pair) {
if (preg_match($pair[0], $str)) {
return preg_replace($pair[0], $pair[1], $str);
}
}
}
return $str;
}
/**
* Singularizes a word
* @param string $str word
* @return string singularized word
*/
public static function singularize($str)
{
$str = strval($str);
if (!in_array(strtolower($str), static::$uncountables) && $str != '') {
foreach (static::$singulars as $pair) {
if (preg_match($pair[0], $str)) {
return preg_replace($pair[0], $pair[1], $str);
}
}
}
return $str;
}
/**
* Normalizes a string for a url
*
* This removes any non alphanumeric character, dash, space or underscore
* with supplied separator
*
* <code>
* echo Inflector::normalize('This is an example');
* > this-is-an-example
* </code>
* @param string $str string to normalize
* @param string $sep string separator
* @return normalized string
*/
public static function normalize($str, $sep = '-')
{
return strtolower(preg_replace(array('/[^a-zA-Z0-9\_ \-]/', '/\s+/',), array('', $sep), strval($str)));
}
/**
* Humanizes an underscored string
*
* <code>
* echo Inflector::humanize('this_is_an_example');
* > This is an example
* </code>
* @param string $str string to humanize (underscored)
* @return string humanized string
*/
public static function humanize($str)
{
return ucfirst(strtolower(preg_replace('/_/', ' ', preg_replace('/_id$/', '', strval($str)))));
}
/**
* Titleizes an underscored string
*
* <code>
* echo Inflector::titleize('this_is_an_example');
* > This Is An Example
* </code>
* @param string $str string to titleize (underscored)
* @return string titleized string
*/
public static function titleize($str)
{
return ucwords(static::humanize(static::underscore($str)));
}
/**
* Creates a table name from a class name
*
* <code>
* echo Inflector::tableize('ExampleWord');
* > example_words
* </code>
* @param string $str string to tableize (underscored)
* @return string humanized string
*/
public static function tableize($str)
{
return static::pluralize(static::underscore($str));
}
/**
* Creates a class name from a table name
*
* <code>
* echo Inflector::classify('example_words');
* > ExampleWord
* </code>
* @param string $str string to classify (camel-cased, pluralized)
* @return string classified string
*/
public static function classify($str)
{
return static::camelize(static::singularize(preg_replace('/.*\./', '', $str)));
}
/**
* Camelizes a string
*
* <code>
* echo Inflector::camelize('This is an example');
* > ThisIsAnExample
* </code>
* @param string $str string to camelize
* @param boolean $uc_first uppercase first letter
* @return camelized string
*/
public static function camelize($str, $uc_first = true)
{
$base = str_replace(' ', '', ucwords(str_replace('_', ' ', strval($str))));
return !$uc_first ? strtolower(substr($base, 0, 1)) . substr($base, 1) : $base;
}
/**
* Underscores a camelized string
*
* <code>
* echo Inflector::underscore('thisIsAnExample');
* > this_is_an_example
* </code>
* @param string $str string to underscore (camelized)
* @return string underscored string
*/
public static function underscore($str)
{
$str = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\\1_\\2', strval($str));
$str = preg_replace('/([a-z\d])([A-Z])/', '\\1_\\2', $str);
$str = str_replace('-', '_', $str);
return strtolower($str);
}
/**
* Dasherizes a string
*
* <code>
* echo Inflector::dasherize('this_is_an_example');
* > this-is-an-example
* </code>
* @param string $str string to dasherize
* @return dasherized string
*/
public static function dasherize($str)
{
return str_replace('_', '-', strval($str));
}
/**
* Ordinalizes a number
*
* <code>
* echo Inflector::ordinalize(10);
* > 10th
* </code>
* @param integer $number number
* @return string ordinalized number
*/
public static function ordinalize($number)
{
if (in_array(($number % 100), array(11, 12, 13))) {
return $number . 'th';
} else {
$mod = $number % 10;
if ($mod == 1) {
return $number . 'st';
} elseif ($mod == 2) {
return $number . 'nd';
} elseif ($mod == 3) {
return $number . 'rd';
} else {
return $number . 'th';
}
}
}
/**
* Creates a foreign key name from a class name
*
* <code>
* echo Inflector::foreignKey('Example');
* > example_id
* </code>
* @param string $str string to make foreign key for
* @param boolean $underscore use underscore delimiter
* @return string foreign key string
*/
public static function foreignKey($str, $underscore = true)
{
return static::underscore($str) . ($underscore ? '_id' : 'id');
}
-};
+}
// include default inflections
require_once __DIR__ . '/inflections.php';
diff --git a/src/Starlight/Component/Routing/Compilable.php b/src/Starlight/Component/Routing/Compilable.php
index 0aa1c82..1835bda 100644
--- a/src/Starlight/Component/Routing/Compilable.php
+++ b/src/Starlight/Component/Routing/Compilable.php
@@ -1,20 +1,20 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
* Compilable interface
*/
interface Compilable
{
public function compile();
-};
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/src/Starlight/Component/Routing/Resource.php b/src/Starlight/Component/Routing/Resource.php
index 189e527..74c4d3d 100644
--- a/src/Starlight/Component/Routing/Resource.php
+++ b/src/Starlight/Component/Routing/Resource.php
@@ -1,192 +1,192 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Inflector\Inflector;
/**
* Resource
*/
class Resource implements Compilable
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%p', 'verb' => 'get', 'url' => '/'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action'),
'create' => array('name' => '%p', 'verb' => 'post', 'url' => '/'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id'),
'delete' => array('name' => 'delete_%s', 'verb' => 'get', 'url' => '/:id/:action'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id'),
);
protected static $resource_names = array(
'add' => 'add',
'edit' => 'edit',
'delete' => 'delete',
);
public $resource;
public $except;
public $only;
public $controller;
public $constraints;
public $name;
public $path_names;
public $namespace;
// member, collection, resources (nested)
/**
*
*/
public function __construct($resource)
{
$this->resource = $resource;
$this->controller = Inflector::pluralize($this->resource);
}
/**
*
*/
public function except(array $except)
{
$this->only = null;
$this->except = $except;
return $this;
}
/**
*
*/
public function only(array $only)
{
$this->except = null;
$this->only = $only;
return $this;
}
/**
*
*/
public function controller($controller)
{
$this->controller = $controller;
return $this;
}
/**
*
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* (as)
*/
public function name($name)
{
$single = explode(' ', strtolower(Inflector::humanize($name)));
$plural = $single;
$count = count($single);
$single[$count - 1] = Inflector::singularize($single[$count - 1]);
$plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
$this->name = array(
implode('_', $single),
implode('_', $plural),
);
return $this;
}
/**
*
*/
public function pathNames(array $names)
{
$this->path_names = $names;
return $this;
}
/**
*
*/
public function namespaced($namespace)
{
$this->namespace = $namespace;
return $this;
}
/**
*
*/
public function compile()
{
$generators = static::$resources_map;
if ($this->except) {
$generators = array_diff_key($generators, array_fill_keys($this->except, true));
} elseif ($this->only) {
$generators = array_intersect_key($generators, array_fill_keys($this->only, true));
}
if (is_array($this->path_names)) {
$this->path_names += static::$resource_names;
} else {
$this->path_names = static::$resource_names;
}
$routes = array();
foreach ($generators as $action => $parts) {
$path = $parts['url'];
if (strpos($path, ':action') !== false) {
$path = str_replace(':action', $this->path_names[$action], $path);
}
$r = new Route('/' . $this->resource . $path, $this->controller . '#' . $action);
$r->methods(array($parts['verb']));
$single = isset($this->name[0]) ? $this->name[0] : Inflector::singularize($this->resource);
$plural = isset($this->name[1]) ? $this->name[1] : Inflector::pluralize($this->resource);
$name = str_replace('%s', $single, $parts['name']);
$name = str_replace('%p', $plural, $name);
$r->name($name);
if ($this->constraints) {
$r->constraints($this->constraints);
}
if ($this->namespace) {
$r->namespaced($this->namespace);
}
$routes[] = $r->compile();
}
return $routes;
}
-};
+}
diff --git a/src/Starlight/Component/Routing/Routable.php b/src/Starlight/Component/Routing/Routable.php
index c2300f3..5ff7697 100644
--- a/src/Starlight/Component/Routing/Routable.php
+++ b/src/Starlight/Component/Routing/Routable.php
@@ -1,21 +1,21 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
interface Routable
{
public function match(Request $request);
-};
+}
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index 8b6428b..e16cfdf 100755
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,144 +1,144 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements Routable, Compilable
{
// /**
// * Base default values for route parameters
// * @var array
// */
// protected static $base_defaults = array(
// 'controller' => null,
// 'action' => null,
// 'id' => null,
// );
//
//
// public $path;
// public $endpoint;
// public $regex;
// public $parameters;
// public $constraints;
// public $methods;
// public $name;
// public $namespace;
//
//
// /**
// *
// */
// public function __construct($path, $endpoint)
// {
// $this->path = static::normalize($path);
// $this->endpoint = $endpoint;
// }
//
// /**
// *
// */
// public function defaults(array $defaults)
// {
// foreach ($defaults as $key => $value) {
// if (trim($this->parameters[$key]) == '') {
// $this->parameters[$key] = $value;
// }
// }
//
// return $this;
// }
//
// /**
// *
// */
// public function constraints($constraints)
// {
// $this->constraints = $constraints;
//
// return $this;
// }
//
// /**
// *
// */
// public function methods(array $methods)
// {
// $this->methods = $methods;
//
// return $this;
// }
//
// /**
// *
// */
// public function name($name)
// {
// $this->name = $name;
//
// return $this;
// }
//
// /**
// *
// */
// public function namespaced($namespace)
// {
// $this->namespace = $namespace;
//
// return $this;
// }
//
// /**
// *
// */
// public function compile()
// {
// $parser = new RouteParser();
// $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
//
// if ($this->namespace) {
// $this->path = '/' . $this->namespace . $this->path;
// if ($this->name != '') {
// $this->name = $this->namespace . '_' . $this->name;
// }
// $this->endpoint = $this->namespace . '/' . $this->endpoint;
// }
//
// $this->regex = $parser->parse($this->path, $constraints);
// $this->parameters = array_merge(static::$base_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
// list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
//
// return $this;
// }
//
// /**
// *
// */
// public function match(Request $request)
// {
// }
//
// /**
// *
// */
// protected function normalize($path)
// {
// $path = trim($path, '/');
// $path = '/' . $path;
//
// return $path;
// }
-};
+}
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index b0f620e..bce66cb 100644
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,176 +1,176 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Router
*/
class Router
{
protected $routes = array();
protected $compiled = array();
protected $scopes = array();
protected $has_compiled = false;
/**
*
*/
public function draw(\Closure $callback)
{
// todo: check for cached version before redrawing these
$callback($this);
}
/**
*
*/
public function map($path, $endpoint)
{
$this->routes[] = new Route($path, $endpoint);
return $this->applyScopes($this->routes[count($this->routes) - 1]);
}
/**
*
*/
public function resources($resource)
{
$this->routes[] = new Resource($resource);
return $this->applyScopes($this->routes[count($this->routes) - 1]);
}
/**
*
*/
public function resource($resource)
{
$this->routes[] = new SingularResource($resource);
return $this->applyScopes($this->routes[count($this->routes) - 1]);
}
/**
*
*/
public function namespaced($namespace, $callback)
{
$this->scope('namespace', $namespace, $callback);
}
/**
*
*/
public function constraints($constraints, $callback)
{
$this->scope('constraints', $constraints, $callback);
}
/**
*
*/
public function compile()
{
if ($this->has_compiled) {
return;
}
$this->compiled = array();
foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
$this->compiled = array_merge($this->compiled, $c);
} else {
$this->compiled[] = $c;
}
}
$this->has_compiled = true;
}
/**
*
*/
public function match(Request $request)
{
foreach ($this->compiled as $r) {
if ($r->match($request)) {
//
return;
}
}
// nothing matched:
}
/**
*
*/
public function scope($type, $value, $callback)
{
$this->addScope($type, $value);
$callback($this);
$this->removeScope($type, $value);
}
/**
*
*/
protected function applyScopes($route)
{
// scoped namespace
if (isset($this->scopes['namespace'])) {
$route->namespaced(implode('/', $this->scopes['namespace']));
}
// scoped constraints
if (isset($this->scopes['constraints'])) {
$constraints = array();
foreach ($this->scopes['constraints'] as $c) {
$constraints = array_merge($constraints, $c);
}
$route->constraints($constraints);
}
return $route;
}
/**
*
*/
protected function addScope($key, $value = null)
{
if (isset($this->scopes[$key])) {
$this->scopes[$key][] = $value;
} else {
$this->scopes[$key] = array($value);
}
}
/**
*
*/
protected function removeScope($key, $value)
{
if (isset($this->scopes[$key])) {
$position = array_search($value, $this->scopes[$key]);
if ($position !== false) {
unset($this->scopes[$key][$position]);
}
}
}
-};
+}
diff --git a/src/Starlight/Component/Routing/SingularResource.php b/src/Starlight/Component/Routing/SingularResource.php
index 2411a91..1664357 100644
--- a/src/Starlight/Component/Routing/SingularResource.php
+++ b/src/Starlight/Component/Routing/SingularResource.php
@@ -1,33 +1,33 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
* Singular resource
*/
class SingularResource extends Resource
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
'index' => array('name' => '%s', 'verb' => 'get', 'url' => '/'),
'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action'),
'create' => array('name' => '%s', 'verb' => 'post', 'url' => '/'),
'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/'),
'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:action'),
'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/'),
'delete' => array('name' => 'delete_%s', 'verb' => 'get', 'url' => '/:action'),
'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/'),
);
-};
+}
diff --git a/tests/Starlight/Component/Http/HeaderBucketTest.php b/tests/Starlight/Component/Http/HeaderBucketTest.php
index acdb317..9a8d242 100755
--- a/tests/Starlight/Component/Http/HeaderBucketTest.php
+++ b/tests/Starlight/Component/Http/HeaderBucketTest.php
@@ -1,317 +1,317 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\HeaderBucket;
use Starlight\Component\Http\HeaderBucket;
/**
*/
class HeaderBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->headers = array(
'HTTP_HOST' => 'localhost:80',
'HTTP_CONNECTION' => 'keep-alive',
'HTTP_REFERER' => 'http://localhost:80/',
'HTTP_ACCEPT' => 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.59 Safari/534.3',
'HTTP_ACCEPT_ENCODING' => 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
);
$this->type = 'request';
$this->normalized_headers = array();
foreach ($this->headers as $header => $value) {
$this->normalized_headers[HeaderBucket::normalizeHeaderName($header)] = array($value);
}
}
public function testArguments()
{
$this->type = 'madeup';
$this->setExpectedException('InvalidArgumentException');
$this->getBucket();
}
public function testAll()
{
$this->assertEquals($this->getBucket()->all(), $this->normalized_headers);
}
public function testKeys()
{
$this->assertEquals($this->getBucket()->keys(), array_keys($this->normalized_headers));
}
public function testReplace()
{
$bucket = $this->getBucket();
$this->assertEquals($bucket->all(), $this->normalized_headers);
$new_headers = array(
'HTTP_HOST' => 'localhost:80',
);
$normalized = array(
'http-host' => array('localhost:80'),
);
$bucket->replace($new_headers);
$this->assertNotEquals($bucket->all(), $this->normalized_headers);
$this->assertEquals($bucket->all(), $normalized);
}
public function testGet()
{
$this->assertEquals($this->getBucket()->get('HTTP_HOST'), 'localhost:80');
$this->assertEquals($this->getBucket()->get('HTTP_HOST', false), array('localhost:80'));
$this->assertNull($this->getBucket()->get('MADE_UP'));
$this->assertEquals($this->getBucket()->get('MADE_UP', false), array());
}
public function testSet()
{
$bucket = $this->getBucket();
$bucket->set('MADE_UP', 'Value');
$this->assertEquals($bucket->get('MADE_UP'), 'Value');
$bucket->set('MADE_uP', 'Value 2');
$this->assertEquals($bucket->get('MADE_UP'), 'Value 2');
$bucket->set('MADE_UP', 'Value 1', false);
$this->assertEquals($bucket->get('MADE_UP', false), array('Value 2', 'Value 1'));
}
public function testHas()
{
$this->assertTrue($this->getBucket()->has('HTTP_HOST'));
$this->assertFalse($this->getBucket()->has('MADE_UP'));
}
public function testContains()
{
$this->assertTrue($this->getBucket()->contains('HTTP_HOST', 'localhost:80'));
$this->assertFalse($this->getBucket()->contains('HTTP_HOST', 'localhost'));
$this->assertFalse($this->getBucket()->contains('MADE_UP', 'made up value'));
}
public function testDelete()
{
$bucket = $this->getBucket();
$this->assertTrue($bucket->has('HTTP_HOST'));
$bucket->delete('HTTP_HOST');
$this->assertFalse($bucket->has('HTTP_HOST'));
$this->assertFalse($bucket->has('MADE_UP'));
$bucket->delete('MADE_UP');
$this->assertFalse($bucket->has('MADE_UP'));
}
public function testSetCookieInvalidKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->setCookie('Invalid_cookie=', 'value');
}
public function testSetCookieInvalidValue()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->setCookie('Invalid_cookie', 'value;');
}
public function testSetCookieEmptyKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->setCookie('', 'value');
}
public function testSetCookieRequest()
{
$this->type = 'request';
$bucket = $this->getBucket();
$bucket->setCookie('cookie_key', 'cookie_value');
$this->assertEquals($bucket->get('Cookie'), 'cookie_key=cookie_value');
}
public function testSetCookieWithExpirationDateInteger()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = new \DateTime('+7 days');
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires->getTimestamp(),
'http_only' => false,
));
$this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testSetCookieWithExpirationDateString()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = 'January 1, 2000 12:00:00';
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires,
'http_only' => false,
));
$this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testSetCookieWithExpirationDateInvalidString()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = 'This is not a date';
$this->setExpectedException('InvalidArgumentException');
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires,
'http_only' => false,
));
}
public function testSetCookieWithExpirationDateDateTime()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = new \DateTime('+7 days');
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires,
'http_only' => false,
));
$this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testSetCookieWithPath()
{
$this->type = 'response';
$bucket = $this->getBucket();
$path = '/some/awesome/path';
$bucket->setCookie('cookie_key', 'cookie_value', array(
'path' => $path,
'http_only' => false,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; path=' . $path);
}
public function testSetCookieWithDomain()
{
$this->type = 'response';
$bucket = $this->getBucket();
$domain = 'example.com';
$bucket->setCookie('cookie_key', 'cookie_value', array(
'domain' => $domain,
'http_only' => false,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; domain=' . $domain);
}
public function testSetCookieWithSecure()
{
$this->type = 'response';
$bucket = $this->getBucket();
$bucket->setCookie('cookie_key', 'cookie_value', array(
'secure' => true,
'http_only' => false,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; secure');
}
public function testSetCookieWithHttpOnly()
{
$this->type = 'response';
$bucket = $this->getBucket();
$bucket->setCookie('cookie_key', 'cookie_value', array(
'http_only' => true,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; httponly');
}
public function testExpireCookieInvalidKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->expireCookie('Invalid_cookie=', 'value');
}
public function testExpireCookieEmptyKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->expireCookie('', 'value;');
}
public function testExpireCookie()
{
$this->type = 'response';
$bucket = $this->getBucket();
$bucket->expireCookie('cookie_key');
$this->assertRegExp('/^cookie\_key\=\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testExpireCookieRequest()
{
$bucket = $this->getBucket();
$bucket->expireCookie('cookie_key');
$this->assertNull($bucket->get('Set-Cookie'));
}
public function testArrayAccess()
{
$bucket = $this->getBucket();
$this->assertTrue(isset($bucket['HTTP_HOST']));
$this->assertEquals($bucket['HTTP_HOST'], 'localhost:80');
$bucket['MADE_UP'] = 'anything';
$this->assertTrue(isset($bucket['MADE_UP']));
unset($bucket['MADE_UP']);
$this->assertFalse(isset($bucket['MADE_UP']));
}
public function testIteratorAggreate()
{
$bucket = $this->getBucket();
foreach ($bucket as $key => $value) {
$this->assertEquals($value, $this->normalized_headers[$key]);
}
}
public function testNormalizeHeaderName()
{
$this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_HOST'), 'http-host');
$this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_hoST'), 'http-host');
$this->assertEquals(HeaderBucket::normalizeHeaderName('http-host'), 'http-host');
}
protected function getBucket()
{
return new HeaderBucket($this->headers, $this->type);
}
-};
+}
diff --git a/tests/Starlight/Component/Http/ParameterBucketTest.php b/tests/Starlight/Component/Http/ParameterBucketTest.php
index a881c10..965baa5 100755
--- a/tests/Starlight/Component/Http/ParameterBucketTest.php
+++ b/tests/Starlight/Component/Http/ParameterBucketTest.php
@@ -1,124 +1,124 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\ParameterBucket;
use Starlight\Component\Http\ParameterBucket;
/**
*/
class ParameterBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->params = array(
'test_1' => 'value_1',
'test_2' => 'value_2',
'test_3' => 'value_3',
);
}
public function testAll()
{
$this->assertEquals($this->getBucket()->all(), $this->params);
}
public function testKeys()
{
$this->assertEquals($this->getBucket()->keys(), array_keys($this->params));
}
public function testReplace()
{
$bucket = $this->getBucket();
$new_parameters = array('test_4' => 'value_4');
$bucket->replace($new_parameters);
$this->assertEquals($bucket->all(), $new_parameters);
$this->assertNotEquals($bucket->all(), $this->params);
}
public function testAdd()
{
$bucket = $this->getBucket();
$new_parameters = array('test_4' => 'value_4');
$bucket->add($new_parameters);
$this->assertEquals($bucket->all(), array_replace($this->params, $new_parameters));
$this->assertNotEquals($bucket->all(), $this->params);
}
public function testGet()
{
$this->assertEquals($this->getBucket()->get('test_1'), 'value_1');
$this->assertNull($this->getBucket()->get('test_4'));
$this->assertEquals($this->getBucket()->get('test_4', 'value_4'), 'value_4');
}
public function testSet()
{
$bucket = $this->getBucket();
$this->assertNull($bucket->get('test_4'));
$bucket->set('test_4', 'value_4');
$this->assertEquals($bucket->get('test_4'), 'value_4');
$this->assertEquals($bucket->get('test_2'), 'value_2');
$bucket->set('test_2', 'value_22');
$this->assertEquals($bucket->get('test_2'), 'value_22');
}
public function testHas()
{
$this->assertTrue($this->getBucket()->has('test_1'));
$this->assertFalse($this->getBucket()->has('test_4'));
}
public function testDelete()
{
$bucket = $this->getBucket();
$this->assertTrue($bucket->has('test_1'));
$bucket->delete('test_1');
$this->assertFalse($bucket->has('test_1'));
$this->assertFalse($bucket->has('test_4'));
$bucket->delete('test_4');
$this->assertFalse($bucket->has('test_4'));
}
public function testArrayAccess()
{
$bucket = $this->getBucket();
$this->assertTrue(isset($bucket['test_1']));
$this->assertEquals($bucket['test_1'], 'value_1');
$bucket['test_4'] = 'anything';
$this->assertTrue(isset($bucket['test_4']));
unset($bucket['test_4']);
$this->assertFalse(isset($bucket['test_4']));
}
public function testIteratorAggreate()
{
$bucket = $this->getBucket();
foreach ($bucket as $key => $value) {
$this->assertEquals($value, $this->params[$key]);
}
}
protected function getBucket()
{
return new ParameterBucket($this->params);
}
-};
+}
diff --git a/tests/Starlight/Component/Http/RequestTest.php b/tests/Starlight/Component/Http/RequestTest.php
index e02d397..f02e87a 100755
--- a/tests/Starlight/Component/Http/RequestTest.php
+++ b/tests/Starlight/Component/Http/RequestTest.php
@@ -1,298 +1,298 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\Request;
use Starlight\Component\Http\Request;
/**
*/
class RequestTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->post = array();
$this->get = array();
$this->cookies = array();
$this->files = array();
$this->server = array();
}
public function testClone()
{
$this->post['test'] = 'example';
$this->cookies['my_cookie'] = 'the value';
$request1 = $this->getRequest();
$request2 = clone $request1;
$this->assertEquals($request1->post->get('test'), $request2->post->get('test'));
$this->assertEquals($request1->cookies->get('my_cookie'), $request2->cookies->get('my_cookie'));
$request1->post->set('test', 'something new');
$this->assertNotEquals($request1->post->get('test'), $request2->post->get('test'));
}
public function testGet()
{
$this->cookies['check'] = 'cookies';
$this->post['check'] = 'post';
$this->get['check'] = 'get';
$this->assertEquals($this->getRequest()->get('check'), 'get');
unset($this->get['check']);
$this->assertEquals($this->getRequest()->get('check'), 'post');
unset($this->post['check']);
$this->assertEquals($this->getRequest()->get('check'), 'cookies');
unset($this->cookies['check']);
$this->assertNull($this->getRequest()->get('check'));
$this->assertEquals($this->getRequest()->get('check', 'default'), 'default');
}
public function testGetMethod()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->server['X_HTTP_METHOD_OVERRIDE'] = 'put';
$this->post['_method'] = 'get';
$this->assertEquals($this->getRequest()->getMethod(), 'get');
unset($this->post['_method']);
$this->assertEquals($this->getRequest()->getMethod(), 'put');
unset($this->server['X_HTTP_METHOD_OVERRIDE']);
$this->assertEquals($this->getRequest()->getMethod(), 'post');
unset($this->server['REQUEST_METHOD']);
$this->assertNull($this->getRequest()->getMethod());
}
public function testIsDelete()
{
$this->server['REQUEST_METHOD'] = 'delete';
$this->assertTrue($this->getRequest()->isDelete());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isDelete());
}
public function testIsGet()
{
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isGet());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isGet());
}
public function testIsPost()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->assertTrue($this->getRequest()->isPost());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertFalse($this->getRequest()->isPost());
}
public function testIsPut()
{
$this->server['REQUEST_METHOD'] = 'put';
$this->assertTrue($this->getRequest()->isPut());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isPut());
}
public function testIsHead()
{
$this->server['REQUEST_METHOD'] = 'head';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isHead());
}
public function testIsSsl()
{
$this->server['HTTPS'] = 'On';
$this->assertTrue($this->getRequest()->isSsl());
$this->server['HTTPS'] = '';
$this->assertFalse($this->getRequest()->isSsl());
}
public function testGetProtocol()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getProtocol(), 'https://');
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getProtocol(), 'http://');
}
public function testGetHost()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['HTTP_X_FORWARDED_HOST'] = 'forwarded.example.com';
$this->assertEquals($this->getRequest()->getHost(), 'forwarded.example.com');
unset($this->server['HTTP_X_FORWARDED_HOST']);
$this->assertEquals($this->getRequest()->getHost(), 'example.com');
}
public function testSetPortFromHost()
{
$this->server['HTTP_HOST'] = 'example.com:8080';
$request = $this->getRequest();
$request->getHost();
$this->assertEquals($request->getPort(), 8080);
}
public function testGetPort()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPort(), 8080);
}
public function testGetStandardPort()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getStandardPort(), 443);
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getStandardPort(), 80);
}
public function testGetPortString()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPortString(), ':8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getPortString(), '');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getPortString(), '');
}
public function testGetHostWithPort()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
}
public function testGetRemoteIp()
{
$this->server['REMOTE_ADDR'] = '127.0.0.3';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.3');
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.2');
unset($this->server['HTTP_CLIENT_IP']);
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.1');
}
public function testGetRemoteIpException()
{
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
$this->setExpectedException('Starlight\\Component\\Http\\Exception\\IpSpoofingException');
$this->getRequest()->getRemoteIp();
}
public function testIsXmlHttpRequest()
{
$this->assertFalse($this->getRequest()->isXmlHttpRequest());
$this->server['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->assertTrue($this->getRequesT()->isXmlHttpRequest());
}
public function testGetServer()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com');
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com');
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com:8080');
}
public function testGetUri()
{
$this->server['REQUEST_URI'] = '/src/Starlight/Framework/bootloader.php';
$this->assertEquals($this->getRequest()->getUri(), '/src/Starlight/Framework/bootloader.php');
$this->server['REQUEST_URI'] = '';
$this->assertEquals($this->getRequest()->getUri(), '/');
}
public function testGetRoute()
{
$this->server['REQUEST_URI'] = '/photos/1/users';
$this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
$this->server['REQUEST_URI'] = '/photos/1/users?querystring=1';
$this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
$this->server['REQUEST_URI'] = '';
$this->assertEquals($this->getRequest()->getRoute(), '/');
}
public function testIsLocalStandard()
{
$this->server['REMOTE_ADDR'] = '127.0.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '127.0.0.2';
$this->assertFalse($this->getRequest()->isLocal());
}
public function testIsLocalCustom()
{
Request::$local_ips[] = '192.168.0.1';
$this->server['REMOTE_ADDR'] = '127.0.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '192.168.0.1';
$this->assertTrue($this->getRequest()->isLocal());
$this->server['REMOTE_ADDR'] = '127.0.0.2';
$this->assertFalse($this->getRequest()->isLocal());
}
protected function getRequest()
{
return new Request($this->post, $this->get, $this->cookies, $this->files, $this->server);
}
-};
+}
diff --git a/tests/Starlight/Component/Inflector/InflectorTest.php b/tests/Starlight/Component/Inflector/InflectorTest.php
index 08bbacc..9f153a0 100644
--- a/tests/Starlight/Component/Inflector/InflectorTest.php
+++ b/tests/Starlight/Component/Inflector/InflectorTest.php
@@ -1,367 +1,367 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Inflector;
use Starlight\Component\Inflector\Inflector;
/**
*/
class InflectorTest extends \PHPUnit_Framework_TestCase
{
protected static $singular_to_plural = array(
'search' => 'searches',
'switch' => 'switches',
'fix' => 'fixes',
'box' => 'boxes',
'process' => 'processes',
'address' => 'addresses',
'case' => 'cases',
'stack' => 'stacks',
'wish' => 'wishes',
'fish' => 'fish',
'category' => 'categories',
'query' => 'queries',
'ability' => 'abilities',
'agency' => 'agencies',
'movie' => 'movies',
'archive' => 'archives',
'index' => 'indices',
'wife' => 'wives',
'safe' => 'saves',
'half' => 'halves',
'move' => 'moves',
'salesperson' => 'salespeople',
'person' => 'people',
'spokesman' => 'spokesmen',
'man' => 'men',
'woman' => 'women',
'basis' => 'bases',
'diagnosis' => 'diagnoses',
'diagnosis_a' => 'diagnosis_as',
'datum' => 'data',
'medium' => 'media',
'analysis' => 'analyses',
'node_child' => 'node_children',
'child' => 'children',
'experience' => 'experiences',
'day' => 'days',
'comment' => 'comments',
'foobar' => 'foobars',
'newsletter' => 'newsletters',
'old_news' => 'old_news',
'news' => 'news',
'series' => 'series',
'species' => 'species',
'quiz' => 'quizzes',
'perspective' => 'perspectives',
'ox' => 'oxen',
'photo' => 'photos',
'buffalo' => 'buffaloes',
'tomato' => 'tomatoes',
'dwarf' => 'dwarves',
'elf' => 'elves',
'information' => 'information',
'equipment' => 'equipment',
'bus' => 'buses',
'status' => 'statuses',
'status_code' => 'status_codes',
'mouse' => 'mice',
'louse' => 'lice',
'house' => 'houses',
'octopus' => 'octopi',
'virus' => 'viri',
'alias' => 'aliases',
'portfolio' => 'portfolios',
'vertex' => 'vertices',
'matrix' => 'matrices',
'matrix_fu' => 'matrix_fus',
'axis' => 'axes',
'testis' => 'testes',
'crisis' => 'crises',
'rice' => 'rice',
'shoe' => 'shoes',
'horse' => 'horses',
'prize' => 'prizes',
'edge' => 'edges',
'cow' => 'cattle',
'database' => 'databases',
);
protected static $string_to_normalized = array(
'Donald E. Knuth' => 'donald-e-knuth',
'Random text with *(bad)* characters' => 'random-text-with-bad-characters',
'Allow_Under_Scores' => 'allow_under_scores',
'Trailing bad characters!@#' => 'trailing-bad-characters',
'!@#Leading bad characters' => 'leading-bad-characters',
'Squeeze separators' => 'squeeze-separators',
);
protected static $string_to_normalized_no_sep = array(
'Donald E. Knuth' => 'donaldeknuth',
'Random text with *(bad)* characters' => 'randomtextwithbadcharacters',
'Trailing bad characters!@#' => 'trailingbadcharacters',
'!@#Leading bad characters' => 'leadingbadcharacters',
'Squeeze separators' => 'squeezeseparators',
);
protected static $string_to_normalized_with_underscore = array(
'Donald E. Knuth' => 'donald_e_knuth',
'Random text with *(bad)* characters' => 'random_text_with_bad_characters',
'Trailing bad characters!@#' => 'trailing_bad_characters',
'!@#Leading bad characters' => 'leading_bad_characters',
'Squeeze separators' => 'squeeze_separators',
);
protected static $string_to_title = array(
'starlight_base' => 'Starlight Base',
'StarlightBase' => 'Starlight Base',
'starlight base code' => 'Starlight Base Code',
'Starlight base Code' => 'Starlight Base Code',
'Starlight Base Code' => 'Starlight Base Code',
'starlightbasecode' => 'Starlightbasecode',
'Starlightbasecode' => 'Starlightbasecode',
'Person\'s stuff' => 'Person\'s Stuff',
'person\'s Stuff' => 'Person\'s Stuff',
'Person\'s Stuff' => 'Person\'s Stuff',
);
protected static $camel_to_underscore = array(
'Product' => 'product',
'SpecialGuest' => 'special_guest',
'ApplicationController' => 'application_controller',
'Area51Controller' => 'area51_controller',
);
protected static $camel_to_underscore_wo_rev = array(
'HTMLTidy' => 'html_tidy',
'HTMLTidyGenerator' => 'html_tidy_generator',
'FreeBSD' => 'free_bsd',
'HTML' => 'html',
);
protected static $class_to_fk_underscore = array(
'Person' => 'person_id',
);
protected static $class_to_fk_no_underscore = array(
'Person' => 'personid',
);
protected static $class_to_table = array(
'PrimarySpokesman' => 'primary_spokesmen',
'NodeChild' => 'node_children',
);
protected static $underscore_to_human = array(
'employee_salary' => 'Employee salary',
'employee_id' => 'Employee',
'underground' => 'Underground',
);
protected static $ordinals = array(
'0' => '0th',
'1' => '1st',
'2' => '2nd',
'3' => '3rd',
'4' => '4th',
'5' => '5th',
'6' => '6th',
'7' => '7th',
'8' => '8th',
'9' => '9th',
'10' => '10th',
'11' => '11th',
'12' => '12th',
'13' => '13th',
'14' => '14th',
'20' => '20th',
'21' => '21st',
'22' => '22nd',
'23' => '23rd',
'24' => '24th',
'100' => '100th',
'101' => '101st',
'102' => '102nd',
'103' => '103rd',
'104' => '104th',
'110' => '110th',
'111' => '111th',
'112' => '112th',
'113' => '113th',
'1000' => '1000th',
'1001' => '1001st',
);
protected static $underscores_to_dashes = array(
'street' => 'street',
'street_address' => 'street-address',
'person_street_address' => 'person-street-address',
);
protected static $underscores_to_lower_camel = array(
'product' => 'product',
'special_guest' => 'specialGuest',
'application_controller' => 'applicationController',
'area51_controller' => 'area51Controller',
);
public function testPluralizePlurals()
{
$this->assertEquals('plurals', Inflector::pluralize('plurals'));
$this->assertEquals('Plurals', Inflector::pluralize('Plurals'));
}
public function testPluralizeEmptyString()
{
$this->assertEquals('', Inflector::pluralize(''));
}
public function testSingularToPlural()
{
foreach (self::$singular_to_plural as $singular => $plural) {
$this->assertEquals($plural, Inflector::pluralize($singular));
$this->assertEquals(ucfirst($plural), Inflector::pluralize(ucfirst($singular)));
$this->assertEquals($singular, Inflector::singularize($plural));
$this->assertEquals(ucfirst($singular), Inflector::singularize(ucfirst($plural)));
}
}
public function testCamelize()
{
foreach (self::$camel_to_underscore as $camel => $underscore) {
$this->assertEquals($camel, Inflector::camelize($underscore));
}
}
public function testOverwritePreviousInflectors()
{
$this->assertEquals('series', Inflector::singularize('series'));
Inflector::singular('series', 'serie');
$this->assertEquals('serie', Inflector::singularize('series'));
Inflector::uncountable('series');
$this->assertEquals('series', Inflector::pluralize('series'));
Inflector::plural('series', 'seria');
$this->assertEquals('seria', Inflector::pluralize('series'));
Inflector::uncountable('series');
$this->assertEquals('dies', Inflector::pluralize('die'));
Inflector::irregular('die', 'dice');
$this->assertEquals('dice', Inflector::pluralize('die'));
$this->assertEquals('die', Inflector::singularize('dice'));
}
public function testTitleize()
{
foreach (self::$string_to_title as $before => $title) {
$this->assertEquals($title, Inflector::titleize($before));
}
}
public function testNormalize()
{
foreach (self::$string_to_normalized as $string => $normalized) {
$this->assertEquals($normalized, Inflector::normalize($string));
}
}
public function testNormalizeWithNoSeparator()
{
foreach (self::$string_to_normalized_no_sep as $string => $normalized) {
$this->assertEquals($normalized, Inflector::normalize($string, ''));
}
}
public function testNormalizeWithUnderscore()
{
foreach (self::$string_to_normalized_with_underscore as $string => $normalized) {
$this->assertEquals($normalized, Inflector::normalize($string, '_'));
}
}
public function testCamelizeLowercasesFirstLetter()
{
$this->assertEquals('capitalPlayersLeague', Inflector::camelize('Capital_players_League', false));
}
public function testUnderscore()
{
foreach (self::$camel_to_underscore as $camel => $underscore) {
$this->assertEquals($underscore, Inflector::underscore($camel));
}
foreach (self::$camel_to_underscore_wo_rev as $camel => $underscore) {
$this->assertEquals($underscore, Inflector::underscore($camel));
}
}
public function testforeignKey()
{
foreach (self::$class_to_fk_underscore as $klass => $fk) {
$this->assertEquals($fk, Inflector::foreignKey($klass));
}
foreach (self::$class_to_fk_no_underscore as $klass => $fk) {
$this->assertEquals($fk, Inflector::foreignKey($klass, false));
}
}
public function testTableize()
{
foreach (self::$class_to_table as $klass => $table) {
$this->assertEquals($table, Inflector::tableize($klass));
}
}
public function testClassify()
{
foreach (self::$class_to_table as $klass => $table) {
$this->assertEquals($klass, Inflector::classify($table));
$this->assertEquals($klass, Inflector::classify('prefix.' . $table));
}
}
public function testHumanize()
{
foreach (self::$underscore_to_human as $underscore => $human) {
$this->assertEquals($human, Inflector::humanize($underscore));
}
}
public function testOrdinal()
{
foreach (self::$ordinals as $number => $ordinal) {
$this->assertEquals($ordinal, Inflector::ordinalize($number));
}
}
public function testDasherize()
{
foreach (self::$underscores_to_dashes as $underscored => $dashes) {
$this->assertEquals($dashes, Inflector::dasherize($underscored));
}
}
public function testUnderscoreAsReverseOfDasherize()
{
foreach (self::$underscores_to_dashes as $underscored => $dashes) {
$this->assertEquals($underscored, Inflector::underscore(Inflector::dasherize($underscored)));
}
}
public function testUnderscoreToLowerCamel()
{
foreach (self::$underscores_to_lower_camel as $underscored => $lower_camel) {
$this->assertEquals($lower_camel, Inflector::camelize($underscored, false));
}
}
-};
+}
diff --git a/tests/Starlight/Component/Routing/RouteTest.php b/tests/Starlight/Component/Routing/RouteTest.php
index 511809e..1c5830d 100755
--- a/tests/Starlight/Component/Routing/RouteTest.php
+++ b/tests/Starlight/Component/Routing/RouteTest.php
@@ -1,19 +1,20 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\Route;
/**
*/
class RouteTest extends \PHPUnit_Framework_TestCase
{
-};
+
+}
|
synewaves/starlight | e90a3b29eb537b70170aea1534277525e011e2ce | Much improved RouteParser based on Rack::Mount::Strexp | diff --git a/src/Starlight/Component/Routing/RouteParser.php b/src/Starlight/Component/Routing/RouteParser.php
index 5d3ac95..e31ae66 100755
--- a/src/Starlight/Component/Routing/RouteParser.php
+++ b/src/Starlight/Component/Routing/RouteParser.php
@@ -1,216 +1,145 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
* Route
*/
class RouteParser
{
/**
* URL path separators
* '\' and '.'
* @var string
*/
protected static $default_separators = array('/', '.');
public $path;
public $regex;
public $requirements;
public $separators;
public $names = array();
protected $quoted_separators;
+
/**
*
*/
public function parse($path, array $requirements = array(), array $separators = array())
{
$this->regex = '';
$this->path = trim($path);
$this->requirements = $requirements;
$this->separators = count($separators) > 0 ? $separators : static::$default_separators;
$this->quoted_separators = $this->quote(implode('', $this->separators));
- $this->segments = $this->reduce($this->path);
- $this->regex = '/\A' . $this->expand($this->segments) . '\Z/';
+ $this->regex = $this->reduce();
return $this->regex;
}
- protected function reduce($path)
+ /**
+ *
+ */
+ protected function reduce()
{
+ $balance = 0;
+ $prev = $next = $literal = '';
+ $length = strlen($this->path);
$segments = array();
- $start = 0;
- $length = strlen($path);
-
- $open = strpos($path, '(');
- $close = $last_close = $last_open = -1;
-
- // if (($open !== false && $close_test === false) || ($open === false && $close_test !== false)) {
- // // something is unbalanced:
- // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
- // }
-
- // if ($open === false) {
- // // check for unbalanced-ness:
- // $c = $this->findMatchingParen(0, $path);
- // if ($close !== false) {
- // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
- // }
- //
- // $segments[] = $path;
- // } elseif ($start != $open) {
- // $segments[] = substr($path, $start, $open);
- // }
-
- // while ($open !== false && $open <= $end) {
- // if (($close = $this->findMatchingParen($open, $path)) !== false) {
- // $segment = array(
- // 'content_before' => '',
- // 'content_after' => '',
- // 'children' => array(),
- // );
- //
- // $segment_content = substr($path, $open + 1, $close - $open - 1);
- // $segment_inner_paren_open = strpos($segment_content, '(', 0);
- // if ($segment_inner_paren_open !== false) {
- // $segment_inner_paren_close = $this->findMatchingParen($segment_inner_paren_open, $segment_content);
- // if ($segment_inner_paren_close !== false) {
- // $segment['content_before'] = substr($segment_content, 0, $segment_inner_paren_open);
- // $segment['content_after'] = substr($segment_content, $segment_inner_paren_close + 1);
- // $segment['children'] = $this->reduce(substr($segment_content, $segment_inner_paren_open, strlen($segment_content) - $segment_inner_paren_close - 1));
- // } else {
- // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
- // }
- // } else {
- // $segment['content_before'] = $segment_content;
- // }
- //
- // $segments[] = $segment;
- // $last_open = $open;
- // $last_close = $close;
- // $open = strpos($path, '(', $close + 1);
- // } else {
- // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
- // }
- // }
-
- return $segments;
- }
-
-
- protected function findMatchingParen($open, $path)
- {
- $close = false;
- $balance = -1;
- $len = strlen($path);
-
- for ($i=$open+1; $i<$len; $i++) {
- $char = $path{$i};
- if ('(' == $char) {
- $balance -= 1;
- }
- if (')' == $char) {
- $balance += 1;
- }
- if (0 == $balance) {
- $close = $i;
- $i = $len;
- }
- }
-
- return $close;
- }
-
-
- protected function expand($segments)
- {
- dump($this->path);
- dump($segments); die;
-
- $regex = '';
-
- foreach ($segments as $segment) {
- if (is_array($segment)) {
- $regex .= '(?:';
- $regex .= $this->parseSegmentPart($segment['content_before']);
- $regex .= $this->expand($segment['children']);
- $regex .= $this->parseSegmentPart($segment['content_after']);
- $regex .= ')?';
- } else {
- $regex .= $this->parseSegmentPart($segment);
- }
- }
-
- return $regex;
- }
-
-
- protected function parseSegmentPart($path)
- {
- $parsed = '';
-
- preg_match_all('/((\:|\*){1}[a-z\_]+)/i', $path, $matches, PREG_OFFSET_CAPTURE);
- if (isset($matches[0]) && count($matches[0]) > 0) {
+ for ($i=0; $i<$length; $i++)
+ {
+ $curr = $this->path[$i];
+ $next = isset($this->path[$i + 1]) ? $this->path[$i + 1] : '';
+ $prev = ($i > 0) ? $this->path[$i - 1] : '';
- $t_regex = '';
- $t_offset = 0;
-
- foreach ($matches[0] as $segment) {
- list($key, $offset) = $segment;
-
- if (($offset > 0 && substr($path, $offset - 1, 1) == '\\')) {
- $t_regex .= $this->quote(substr($path, $t_offset, $offset - $t_offset - 1));
- $t_regex .= '\\' . substr($path, $offset, 1);
- $t_regex .= $this->quote(substr($path, $offset + 1, strlen($key) - 1));
+ if ($curr == '\\') {
+ if (preg_match('/[\(|\)|\:|\*]/', $next)) {
+ // escaped special character
+ $i++;
+ $literal .= $next;
} else {
- $t_regex .= $this->quote(substr($path, $t_offset, $offset - $t_offset));
-
- $identifier = substr($key, 0, 1);
- $name = substr($key, 1);
+ // literal
+ $literal .= $curr;
+ }
+ } else {
+ if (preg_match('/[\(|\)]/', $curr)) {
+ // parenthesis
+ if ($literal != '') {
+ $segments[] = $this->quote($literal);
+ $literal = '';
+ }
- $regex = '';
- if (isset($this->requirements[$name])) {
- // custom requirements
- $regex = $this->requirements[$name];
- } elseif ($identifier == '*') {
- // glob character
- $regex = '.+';
+ if ($curr == '(') {
+ $balance += 1;
+ $segments[] = '(?:';
} else {
- // standard segment
- $regex = '[^' . $this->quoted_separators . ']+';
+ $balance -= 1;
+ $segments[] = ')?';
}
-
- $t_regex .= '(?<' . $name . '>' . $regex . ')';
- $this->names[] = $name;
+ } elseif (preg_match('/[\:|\*]/', $curr)) {
+ // identifier
+ preg_match('/(\:|\*){1}[a-z\_]+/i', $this->path, $matches, PREG_OFFSET_CAPTURE, $i);
+ if (isset($matches[0]) && count($matches[0]) > 0) {
+ if ($literal != '') {
+ $segments[] = $this->quote($literal);
+ $literal = '';
+ }
+
+ $id = substr($matches[0][0], 0, 1);
+ $key = substr($matches[0][0], 1);
+
+ if (isset($this->requirements[$key])) {
+ // custom requirements
+ $regex = $this->requirements[$key];
+ } elseif ($id == '*') {
+ // glob
+ $regex = '.+';
+ } else {
+ // standard segments
+ $regex = '[^' . $this->quoted_separators . ']+';
+ }
+
+ $segments[] = '(?<' . $key . '>' . $regex . ')';
+ $this->names[] = $key;
+ $i += strlen($key);
+ } else {
+ // invalid identifier:
+ $literal .= $curr;
+ }
+ } else {
+ // just normal text
+ $literal .= $curr;
}
-
- $t_offset = $offset + strlen($key);
}
-
- $t_regex .= $this->quote(substr($path, $t_offset), '/');
- $parsed = $t_regex;
-
- } else {
- $parsed = $this->quote($path);
}
- return $parsed;
+ if ($literal != '') {
+ $segments[] = $this->quote($literal);
+ }
+
+ if ($balance != 0) {
+ throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
+ }
+
+ return '/\A' . implode('', $segments) . '\Z/';
}
+ /**
+ *
+ */
protected function quote($string)
{
return preg_quote($string, '/');
}
}
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index 4012aed..0a2f302 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,75 +1,76 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
error_reporting(-1);
require_once __DIR__ . '/Support/UniversalClassLoader.php';
$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
$autoloader->registerNamespaces(array(
'Starlight' => __DIR__ . '/../../',
));
$autoloader->register();
function dump()
{
foreach (func_get_args() as $arg) {
echo '<pre>' . htmlspecialchars(print_r($arg, true)) . '</pre>';
echo '<hr />';
}
}
// // $context = new \Starlight\Component\Http\HttpContext();
// // $dispatcher = new \Starlight\Component\Http\HttpDispatcher($context);
// // $dispatcher->dispatch();
//
// $router = new \Starlight\Component\Routing\Router();
// $router->draw(function($r){
// // $r->map('/:controller(/:action(/:id))(.:format)', 'session#add');
// // $r->map(':controller/:id', 'session#add')->constraints(array('id' => '[0-9]+'))->namespaced('admin');
// // $r->map('*anything', 'session#add');
// // $r->map('/login/:screenname', 'session#add')
// // ->defaults(array('id' => 27))
// // ->methods(array('get', 'post', 'delete'))
// // ->name('login')
// // ->namespaced('admin')
// // ->constraints(array('id' => '/27/i'))
// // ;
//
// // $r->constraints(array('id' => 27), function($r){
// // $r->namespaced('admin', function($r){
// // // $r->map('/login', 'session#new');
// // // $r->map('/logout', 'session#destroy');
// // $r->namespaced('anything', function($r){
// // $r->map('whee', 'session#new');
// // });
// // });
// // });
//
// $r->resources('photo')
// ->name('image')
// ->controller('images')
// ->namespaced('admin')
// ;
// });
// $router->compile();
//
// dump($router);
$parser = new Starlight\Component\Routing\RouteParser();
+// $parser->parse('foo/bar');
// $parser->parse('/foo(/bar))');
-$parser->parse('/foo/bar)');
+// $parser->parse('/foo/bar)');
// $parser->parse('/foo(/bar(/:format)/download)');
-// dump($parser->parse('/foo(/bar)(/baz)'));
-// dump($parser->parse('/foo.:format'));
-// dump($parser->parse('/foo/bar'));
\ No newline at end of file
+$parser->parse('/\\foo\\((/:bar)(/baz)');
+// $parser->parse('/foo.:format');
+// $parser->parse('/foo/bar');
\ No newline at end of file
diff --git a/tests/Starlight/Component/Routing/RouteParserTest.php b/tests/Starlight/Component/Routing/RouteParserTest.php
index 2b100b1..97d35e4 100755
--- a/tests/Starlight/Component/Routing/RouteParserTest.php
+++ b/tests/Starlight/Component/Routing/RouteParserTest.php
@@ -1,157 +1,155 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Component\Routing;
use Starlight\Component\Routing\RouteParser;
/**
* @group Routing
*/
class RouteParserTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->parser = new RouteParser();
}
- // public function testStaticSegment()
- // {
- // $this->parser->parse('sample');
- //
- // $this->assertEquals('/\Asample\Z/', $this->parser->regex);
- // $this->assertEquals(array(), $this->parser->names);
- // }
- //
- // public function testMultipleStaticSegments()
- // {
- // $this->parser->parse('sample/index.html');
- //
- // $this->assertEquals('/\Asample\/index\.html\Z/', $this->parser->regex);
- // $this->assertEquals(array(), $this->parser->names);
- // }
- //
- // public function testDynamicSegment()
- // {
- // $this->parser->parse(':subdomain.example.com');
- //
- // $this->assertEquals('/\A(?<subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
- // $this->assertEquals(array('subdomain'), $this->parser->names);
- // }
- //
- // public function testDynamicSegmentWithLedingUnderscore()
- // {
- // $this->parser->parse(':_subdomain.example.com');
- //
- // $this->assertEquals('/\A(?<_subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
- // $this->assertEquals(array('_subdomain'), $this->parser->names);
- // }
- //
- // public function testInvalidSegmentNames()
- // {
- // $this->assertEquals('/\A\:123\.example\.com\Z/', $this->parser->parse(':123.example.com'));
- // $this->assertEquals('/\A\:\$\.example\.com\Z/', $this->parser->parse(':$.example.com'));
- // }
- //
- // public function testEscapedDynamicSegment()
- // {
- // $this->parser->parse('\:subdomain.example.com');
- //
- // $this->assertEquals('/\A\:subdomain\.example\.com\Z/', $this->parser->regex);
- // $this->assertEquals(array(), $this->parser->names);
- // }
- //
- // public function testDynamicSegmentWithSeparators()
- // {
- // $this->assertEquals('/\Afoo\/(?<bar>[^\/]+)\Z/', $this->parser->parse('foo/:bar', array(), array('/')));
- // }
- //
- // public function testDynamicSegmentWithRequirements()
- // {
- // $this->assertEquals('/\Afoo\/(?<bar>[a-z]+)\Z/', $this->parser->parse('foo/:bar', array('bar' => '[a-z]+'), array('/')));
- // }
- //
- // public function testDynamicSegmentInsideOptionalSegment()
- // {
- // $this->assertEquals('/\Afoo(?:\.(?<extension>[^\/\.]+))?\Z/', $this->parser->parse('foo(.:extension)'));
- // }
- //
- // public function testGlobSegment()
- // {
- // $this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files'));
- // }
- //
- // public function testGlobIgnoresSeparators()
- // {
- // $this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files', array(), array('/', '.', '?')));
- // }
- //
- // public function testGlobSegmentAtBeginning()
- // {
- // $this->assertEquals('/\A(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('*files/foo.txt'));
- // }
- //
- // public function testGlobSegmentInMiddle()
- // {
- // $this->assertEquals('/\Asrc\/(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/foo.txt'));
- // }
- //
- // public function testMultipleGlobSegments()
- // {
- // $this->assertEquals('/\Asrc\/(?<files>.+)\/dir\/(?<morefiles>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/dir/*morefiles/foo.txt'));
- // }
- //
- // public function testEscapedGlobSegment()
- // {
- // $this->parser->parse('src/\*files');
- //
- // $this->assertEquals('/\Asrc\/\*files\Z/', $this->parser->regex);
- // $this->assertEquals(array(), $this->parser->names);
- // }
- //
- // public function testOptionalSegment()
- // {
- // $this->assertEquals('/\A\/foo(?:\/bar)?\Z/', $this->parser->parse('/foo(/bar)'));
- // }
- //
- // public function testConsecutiveOptionalSegments()
- // {
- // $this->assertEquals('/\A\/foo(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('/foo(/bar)(/baz)'));
- // }
- //
- // public function testMultipleOptionalSegments()
- // {
- // $this->assertEquals('/\A(?:\/foo)?(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('(/foo)(/bar)(/baz)'));
- // }
-
- // public function testEscapesOptionalSegmentParenthesis()
- // {
- // $this->assertEquals('/\A\/foo\(\/bar\)\Z/', $this->parser->parse('/foo\(/bar\)'));
- // }
-
- // public function testEscapesOneOptionalSegmentParenthesis()
- // {
- // $this->assertEquals('/\A\/foo\((?:\/bar)?\Z/', $this->parser->parse('/foo\((/bar\)'));
- // }
-
- public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalanced()
+ public function testStaticSegment()
{
+ $this->parser->parse('sample');
+
+ $this->assertEquals('/\Asample\Z/', $this->parser->regex);
+ $this->assertEquals(array(), $this->parser->names);
+ }
+
+ public function testMultipleStaticSegments()
+ {
+ $this->parser->parse('sample/index.html');
+
+ $this->assertEquals('/\Asample\/index\.html\Z/', $this->parser->regex);
+ $this->assertEquals(array(), $this->parser->names);
+ }
+
+ public function testDynamicSegment()
+ {
+ $this->parser->parse(':subdomain.example.com');
+
+ $this->assertEquals('/\A(?<subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
+ $this->assertEquals(array('subdomain'), $this->parser->names);
+ }
+
+ public function testDynamicSegmentWithLedingUnderscore()
+ {
+ $this->parser->parse(':_subdomain.example.com');
+
+ $this->assertEquals('/\A(?<_subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
+ $this->assertEquals(array('_subdomain'), $this->parser->names);
+ }
+
+ public function testInvalidSegmentNames()
+ {
+ $this->assertEquals('/\A\:123\.example\.com\Z/', $this->parser->parse(':123.example.com'));
+ $this->assertEquals('/\A\:\$\.example\.com\Z/', $this->parser->parse(':$.example.com'));
+ }
+
+ public function testEscapedDynamicSegment()
+ {
+ $this->parser->parse('\:subdomain.example.com');
+
+ $this->assertEquals('/\A\:subdomain\.example\.com\Z/', $this->parser->regex);
+ $this->assertEquals(array(), $this->parser->names);
+ }
+
+ public function testDynamicSegmentWithSeparators()
+ {
+ $this->assertEquals('/\Afoo\/(?<bar>[^\/]+)\Z/', $this->parser->parse('foo/:bar', array(), array('/')));
+ }
+
+ public function testDynamicSegmentWithRequirements()
+ {
+ $this->assertEquals('/\Afoo\/(?<bar>[a-z]+)\Z/', $this->parser->parse('foo/:bar', array('bar' => '[a-z]+'), array('/')));
+ }
+
+ public function testDynamicSegmentInsideOptionalSegment()
+ {
+ $this->assertEquals('/\Afoo(?:\.(?<extension>[^\/\.]+))?\Z/', $this->parser->parse('foo(.:extension)'));
+ }
+
+ public function testGlobSegment()
+ {
+ $this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files'));
+ }
+
+ public function testGlobIgnoresSeparators()
+ {
+ $this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files', array(), array('/', '.', '?')));
+ }
+
+ public function testGlobSegmentAtBeginning()
+ {
+ $this->assertEquals('/\A(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('*files/foo.txt'));
+ }
+
+ public function testGlobSegmentInMiddle()
+ {
+ $this->assertEquals('/\Asrc\/(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/foo.txt'));
+ }
+
+ public function testMultipleGlobSegments()
+ {
+ $this->assertEquals('/\Asrc\/(?<files>.+)\/dir\/(?<morefiles>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/dir/*morefiles/foo.txt'));
+ }
+
+ public function testEscapedGlobSegment()
+ {
+ $this->parser->parse('src/\*files');
+
+ $this->assertEquals('/\Asrc\/\*files\Z/', $this->parser->regex);
+ $this->assertEquals(array(), $this->parser->names);
+ }
+
+ public function testOptionalSegment()
+ {
+ $this->assertEquals('/\A\/foo(?:\/bar)?\Z/', $this->parser->parse('/foo(/bar)'));
+ }
+
+ public function testConsecutiveOptionalSegments()
+ {
+ $this->assertEquals('/\A\/foo(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('/foo(/bar)(/baz)'));
+ }
+
+ public function testMultipleOptionalSegments()
+ {
+ $this->assertEquals('/\A(?:\/foo)?(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('(/foo)(/bar)(/baz)'));
+ }
+
+ public function testEscapesOptionalSegmentParenthesis()
+ {
+ $this->assertEquals('/\A\/foo\(\/bar\)\Z/', $this->parser->parse('/foo\(/bar\)'));
+ }
+
+ public function testEscapesOneOptionalSegmentParenthesis()
+ {
+ $this->assertEquals('/\A\/foo\((?:\/bar)?\Z/', $this->parser->parse('/foo\((/bar)'));
+ }
+
+ public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedFront()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ $this->parser->parse('/foo((/bar)');
+ }
+
+ public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalancedBack()
+ {
$this->setExpectedException('InvalidArgumentException');
- // $this->parser->parse('/foo(/bar');
- // $this->parser->parse('/foo((/bar)');
- echo $this->parser->parse('/foo(/bar))');
+ $this->parser->parse('/foo(/bar))');
}
}
-
-
- // def test_raises_regexp_error_if_optional_segment_parenthesises_are_unblanced
- // assert_raise(RegexpError) { Strexp.compile('/foo((/bar)') }
- // assert_raise(RegexpError) { Strexp.compile('/foo(/bar))') }
- // end
\ No newline at end of file
|
synewaves/starlight | 0af1b114ec79ce3f1b3fa1225fa2e351345f4da3 | Work on path parser for Routing | diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
old mode 100644
new mode 100755
index 2acd9db..8b6428b
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,144 +1,144 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements Routable, Compilable
{
- /**
- * Base default values for route parameters
- * @var array
- */
- protected static $base_defaults = array(
- 'controller' => null,
- 'action' => null,
- 'id' => null,
- );
-
-
- public $path;
- public $endpoint;
- public $regex;
- public $parameters;
- public $constraints;
- public $methods;
- public $name;
- public $namespace;
-
-
- /**
- *
- */
- public function __construct($path, $endpoint)
- {
- $this->path = static::normalize($path);
- $this->endpoint = $endpoint;
- }
-
- /**
- *
- */
- public function defaults(array $defaults)
- {
- foreach ($defaults as $key => $value) {
- if (trim($this->parameters[$key]) == '') {
- $this->parameters[$key] = $value;
- }
- }
-
- return $this;
- }
-
- /**
- *
- */
- public function constraints($constraints)
- {
- $this->constraints = $constraints;
-
- return $this;
- }
-
- /**
- *
- */
- public function methods(array $methods)
- {
- $this->methods = $methods;
-
- return $this;
- }
-
- /**
- *
- */
- public function name($name)
- {
- $this->name = $name;
-
- return $this;
- }
-
- /**
- *
- */
- public function namespaced($namespace)
- {
- $this->namespace = $namespace;
-
- return $this;
- }
-
- /**
- *
- */
- public function compile()
- {
- $parser = new RouteParser();
- $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
-
- if ($this->namespace) {
- $this->path = '/' . $this->namespace . $this->path;
- if ($this->name != '') {
- $this->name = $this->namespace . '_' . $this->name;
- }
- $this->endpoint = $this->namespace . '/' . $this->endpoint;
- }
-
- $this->regex = $parser->parse($this->path, $constraints);
- $this->parameters = array_merge(static::$base_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
- list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
-
- return $this;
- }
-
- /**
- *
- */
- public function match(Request $request)
- {
- }
-
- /**
- *
- */
- protected function normalize($path)
- {
- $path = trim($path, '/');
- $path = '/' . $path;
-
- return $path;
- }
+ // /**
+ // * Base default values for route parameters
+ // * @var array
+ // */
+ // protected static $base_defaults = array(
+ // 'controller' => null,
+ // 'action' => null,
+ // 'id' => null,
+ // );
+ //
+ //
+ // public $path;
+ // public $endpoint;
+ // public $regex;
+ // public $parameters;
+ // public $constraints;
+ // public $methods;
+ // public $name;
+ // public $namespace;
+ //
+ //
+ // /**
+ // *
+ // */
+ // public function __construct($path, $endpoint)
+ // {
+ // $this->path = static::normalize($path);
+ // $this->endpoint = $endpoint;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function defaults(array $defaults)
+ // {
+ // foreach ($defaults as $key => $value) {
+ // if (trim($this->parameters[$key]) == '') {
+ // $this->parameters[$key] = $value;
+ // }
+ // }
+ //
+ // return $this;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function constraints($constraints)
+ // {
+ // $this->constraints = $constraints;
+ //
+ // return $this;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function methods(array $methods)
+ // {
+ // $this->methods = $methods;
+ //
+ // return $this;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function name($name)
+ // {
+ // $this->name = $name;
+ //
+ // return $this;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function namespaced($namespace)
+ // {
+ // $this->namespace = $namespace;
+ //
+ // return $this;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function compile()
+ // {
+ // $parser = new RouteParser();
+ // $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
+ //
+ // if ($this->namespace) {
+ // $this->path = '/' . $this->namespace . $this->path;
+ // if ($this->name != '') {
+ // $this->name = $this->namespace . '_' . $this->name;
+ // }
+ // $this->endpoint = $this->namespace . '/' . $this->endpoint;
+ // }
+ //
+ // $this->regex = $parser->parse($this->path, $constraints);
+ // $this->parameters = array_merge(static::$base_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
+ // list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
+ //
+ // return $this;
+ // }
+ //
+ // /**
+ // *
+ // */
+ // public function match(Request $request)
+ // {
+ // }
+ //
+ // /**
+ // *
+ // */
+ // protected function normalize($path)
+ // {
+ // $path = trim($path, '/');
+ // $path = '/' . $path;
+ //
+ // return $path;
+ // }
};
diff --git a/src/Starlight/Component/Routing/RouteParser.php b/src/Starlight/Component/Routing/RouteParser.php
old mode 100644
new mode 100755
index 07b9672..5d3ac95
--- a/src/Starlight/Component/Routing/RouteParser.php
+++ b/src/Starlight/Component/Routing/RouteParser.php
@@ -1,80 +1,216 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
/**
* Route
*/
class RouteParser
{
/**
- * URL path separators (regex escaped)
+ * URL path separators
* '\' and '.'
* @var string
*/
- protected static $default_separators = array('\/', '\.');
+ protected static $default_separators = array('/', '.');
public $path;
public $regex;
public $requirements;
public $separators;
public $names = array();
+ protected $quoted_separators;
/**
*
*/
public function parse($path, array $requirements = array(), array $separators = array())
{
+ $this->regex = '';
$this->path = trim($path);
$this->requirements = $requirements;
$this->separators = count($separators) > 0 ? $separators : static::$default_separators;
+ $this->quoted_separators = $this->quote(implode('', $this->separators));
- $this->regex = $this->path;
- $this->regex = str_replace(')', ')?', $this->regex);
- $this->regex = str_replace('/', '\\/', $this->regex);
- $this->regex = str_replace('.', '\\.', $this->regex);
+ $this->segments = $this->reduce($this->path);
+ $this->regex = '/\A' . $this->expand($this->segments) . '\Z/';
- preg_match_all('/((\:|\\*)[a-z]+)/i', $this->regex, $matches, PREG_OFFSET_CAPTURE);
- if (isset($matches[0])) {
+ return $this->regex;
+ }
+
+ protected function reduce($path)
+ {
+ $segments = array();
+
+ $start = 0;
+ $length = strlen($path);
+
+ $open = strpos($path, '(');
+ $close = $last_close = $last_open = -1;
+
+ // if (($open !== false && $close_test === false) || ($open === false && $close_test !== false)) {
+ // // something is unbalanced:
+ // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
+ // }
+
+ // if ($open === false) {
+ // // check for unbalanced-ness:
+ // $c = $this->findMatchingParen(0, $path);
+ // if ($close !== false) {
+ // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
+ // }
+ //
+ // $segments[] = $path;
+ // } elseif ($start != $open) {
+ // $segments[] = substr($path, $start, $open);
+ // }
+
+ // while ($open !== false && $open <= $end) {
+ // if (($close = $this->findMatchingParen($open, $path)) !== false) {
+ // $segment = array(
+ // 'content_before' => '',
+ // 'content_after' => '',
+ // 'children' => array(),
+ // );
+ //
+ // $segment_content = substr($path, $open + 1, $close - $open - 1);
+ // $segment_inner_paren_open = strpos($segment_content, '(', 0);
+ // if ($segment_inner_paren_open !== false) {
+ // $segment_inner_paren_close = $this->findMatchingParen($segment_inner_paren_open, $segment_content);
+ // if ($segment_inner_paren_close !== false) {
+ // $segment['content_before'] = substr($segment_content, 0, $segment_inner_paren_open);
+ // $segment['content_after'] = substr($segment_content, $segment_inner_paren_close + 1);
+ // $segment['children'] = $this->reduce(substr($segment_content, $segment_inner_paren_open, strlen($segment_content) - $segment_inner_paren_close - 1));
+ // } else {
+ // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
+ // }
+ // } else {
+ // $segment['content_before'] = $segment_content;
+ // }
+ //
+ // $segments[] = $segment;
+ // $last_open = $open;
+ // $last_close = $close;
+ // $open = strpos($path, '(', $close + 1);
+ // } else {
+ // throw new \InvalidArgumentException('Optional segment parenthesis are unbalanced.');
+ // }
+ // }
+
+ return $segments;
+ }
+
+
+ protected function findMatchingParen($open, $path)
+ {
+ $close = false;
+ $balance = -1;
+ $len = strlen($path);
+
+ for ($i=$open+1; $i<$len; $i++) {
+ $char = $path{$i};
+ if ('(' == $char) {
+ $balance -= 1;
+ }
+ if (')' == $char) {
+ $balance += 1;
+ }
+ if (0 == $balance) {
+ $close = $i;
+ $i = $len;
+ }
+ }
+
+ return $close;
+ }
+
+
+ protected function expand($segments)
+ {
+ dump($this->path);
+ dump($segments); die;
+
+ $regex = '';
+
+ foreach ($segments as $segment) {
+ if (is_array($segment)) {
+ $regex .= '(?:';
+ $regex .= $this->parseSegmentPart($segment['content_before']);
+ $regex .= $this->expand($segment['children']);
+ $regex .= $this->parseSegmentPart($segment['content_after']);
+ $regex .= ')?';
+ } else {
+ $regex .= $this->parseSegmentPart($segment);
+ }
+ }
+
+ return $regex;
+ }
+
+
+ protected function parseSegmentPart($path)
+ {
+ $parsed = '';
+
+ preg_match_all('/((\:|\*){1}[a-z\_]+)/i', $path, $matches, PREG_OFFSET_CAPTURE);
+ if (isset($matches[0]) && count($matches[0]) > 0) {
+
$t_regex = '';
$t_offset = 0;
- $separators = implode('', $this->separators);
- foreach ($matches[0] as $match) {
- list($key, $offset) = $match;
-
- $t_regex .= substr($this->regex, $t_offset, $offset - $t_offset);
-
- $identifier = substr($key, 0, 1);
- $name = substr($key, 1);
+
+ foreach ($matches[0] as $segment) {
+ list($key, $offset) = $segment;
- $regex = '';
- if (isset($this->requirements[$name])) {
- $regex = $this->requirements[$name];
- } elseif ($identifier == '*') {
- $regex = '.+';
+ if (($offset > 0 && substr($path, $offset - 1, 1) == '\\')) {
+ $t_regex .= $this->quote(substr($path, $t_offset, $offset - $t_offset - 1));
+ $t_regex .= '\\' . substr($path, $offset, 1);
+ $t_regex .= $this->quote(substr($path, $offset + 1, strlen($key) - 1));
} else {
- $regex = '[^' . $separators . ']+';
+ $t_regex .= $this->quote(substr($path, $t_offset, $offset - $t_offset));
+
+ $identifier = substr($key, 0, 1);
+ $name = substr($key, 1);
+
+ $regex = '';
+ if (isset($this->requirements[$name])) {
+ // custom requirements
+ $regex = $this->requirements[$name];
+ } elseif ($identifier == '*') {
+ // glob character
+ $regex = '.+';
+ } else {
+ // standard segment
+ $regex = '[^' . $this->quoted_separators . ']+';
+ }
+
+ $t_regex .= '(?<' . $name . '>' . $regex . ')';
+ $this->names[] = $name;
}
- $t_regex .= '(?<' . $name . '>' . $regex . ')';
$t_offset = $offset + strlen($key);
-
- $this->names[] = $name;
}
+
+ $t_regex .= $this->quote(substr($path, $t_offset), '/');
+ $parsed = $t_regex;
- $t_regex .= substr($this->regex, $t_offset);
- $this->regex = $t_regex;
+ } else {
+ $parsed = $this->quote($path);
}
- return '/\\A' . $this->regex . '\\Z/';
+ return $parsed;
+ }
+
+ protected function quote($string)
+ {
+ return preg_quote($string, '/');
}
-};
+}
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index fc6e1d1..4012aed 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,67 +1,75 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
error_reporting(-1);
require_once __DIR__ . '/Support/UniversalClassLoader.php';
$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
$autoloader->registerNamespaces(array(
'Starlight' => __DIR__ . '/../../',
));
$autoloader->register();
function dump()
{
foreach (func_get_args() as $arg) {
echo '<pre>' . htmlspecialchars(print_r($arg, true)) . '</pre>';
echo '<hr />';
}
}
-// $context = new \Starlight\Component\Http\HttpContext();
-// $dispatcher = new \Starlight\Component\Http\HttpDispatcher($context);
-// $dispatcher->dispatch();
+// // $context = new \Starlight\Component\Http\HttpContext();
+// // $dispatcher = new \Starlight\Component\Http\HttpDispatcher($context);
+// // $dispatcher->dispatch();
+//
+// $router = new \Starlight\Component\Routing\Router();
+// $router->draw(function($r){
+// // $r->map('/:controller(/:action(/:id))(.:format)', 'session#add');
+// // $r->map(':controller/:id', 'session#add')->constraints(array('id' => '[0-9]+'))->namespaced('admin');
+// // $r->map('*anything', 'session#add');
+// // $r->map('/login/:screenname', 'session#add')
+// // ->defaults(array('id' => 27))
+// // ->methods(array('get', 'post', 'delete'))
+// // ->name('login')
+// // ->namespaced('admin')
+// // ->constraints(array('id' => '/27/i'))
+// // ;
+//
+// // $r->constraints(array('id' => 27), function($r){
+// // $r->namespaced('admin', function($r){
+// // // $r->map('/login', 'session#new');
+// // // $r->map('/logout', 'session#destroy');
+// // $r->namespaced('anything', function($r){
+// // $r->map('whee', 'session#new');
+// // });
+// // });
+// // });
+//
+// $r->resources('photo')
+// ->name('image')
+// ->controller('images')
+// ->namespaced('admin')
+// ;
+// });
+// $router->compile();
+//
+// dump($router);
-$router = new \Starlight\Component\Routing\Router();
-$router->draw(function($r){
- // $r->map('/:controller(/:action(/:id))(.:format)', 'session#add');
- // $r->map(':controller/:id', 'session#add')->constraints(array('id' => '[0-9]+'))->namespaced('admin');
- // $r->map('*anything', 'session#add');
- // $r->map('/login/:screenname', 'session#add')
- // ->defaults(array('id' => 27))
- // ->methods(array('get', 'post', 'delete'))
- // ->name('login')
- // ->namespaced('admin')
- // ->constraints(array('id' => '/27/i'))
- // ;
-
- // $r->constraints(array('id' => 27), function($r){
- // $r->namespaced('admin', function($r){
- // // $r->map('/login', 'session#new');
- // // $r->map('/logout', 'session#destroy');
- // $r->namespaced('anything', function($r){
- // $r->map('whee', 'session#new');
- // });
- // });
- // });
-
- $r->resources('photo')
- ->name('image')
- ->controller('images')
- ->namespaced('admin')
- ;
-});
-$router->compile();
-
-dump($router);
\ No newline at end of file
+$parser = new Starlight\Component\Routing\RouteParser();
+// $parser->parse('/foo(/bar))');
+$parser->parse('/foo/bar)');
+// $parser->parse('/foo(/bar(/:format)/download)');
+// dump($parser->parse('/foo(/bar)(/baz)'));
+// dump($parser->parse('/foo.:format'));
+// dump($parser->parse('/foo/bar'));
\ No newline at end of file
diff --git a/tests/Starlight/Component/Routing/RouteParserTest.php b/tests/Starlight/Component/Routing/RouteParserTest.php
new file mode 100755
index 0000000..2b100b1
--- /dev/null
+++ b/tests/Starlight/Component/Routing/RouteParserTest.php
@@ -0,0 +1,157 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\Component\Routing;
+use Starlight\Component\Routing\RouteParser;
+
+
+/**
+ * @group Routing
+ */
+class RouteParserTest extends \PHPUnit_Framework_TestCase
+{
+ public function setup()
+ {
+ $this->parser = new RouteParser();
+ }
+
+ // public function testStaticSegment()
+ // {
+ // $this->parser->parse('sample');
+ //
+ // $this->assertEquals('/\Asample\Z/', $this->parser->regex);
+ // $this->assertEquals(array(), $this->parser->names);
+ // }
+ //
+ // public function testMultipleStaticSegments()
+ // {
+ // $this->parser->parse('sample/index.html');
+ //
+ // $this->assertEquals('/\Asample\/index\.html\Z/', $this->parser->regex);
+ // $this->assertEquals(array(), $this->parser->names);
+ // }
+ //
+ // public function testDynamicSegment()
+ // {
+ // $this->parser->parse(':subdomain.example.com');
+ //
+ // $this->assertEquals('/\A(?<subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
+ // $this->assertEquals(array('subdomain'), $this->parser->names);
+ // }
+ //
+ // public function testDynamicSegmentWithLedingUnderscore()
+ // {
+ // $this->parser->parse(':_subdomain.example.com');
+ //
+ // $this->assertEquals('/\A(?<_subdomain>[^\/\.]+)\.example\.com\Z/', $this->parser->regex);
+ // $this->assertEquals(array('_subdomain'), $this->parser->names);
+ // }
+ //
+ // public function testInvalidSegmentNames()
+ // {
+ // $this->assertEquals('/\A\:123\.example\.com\Z/', $this->parser->parse(':123.example.com'));
+ // $this->assertEquals('/\A\:\$\.example\.com\Z/', $this->parser->parse(':$.example.com'));
+ // }
+ //
+ // public function testEscapedDynamicSegment()
+ // {
+ // $this->parser->parse('\:subdomain.example.com');
+ //
+ // $this->assertEquals('/\A\:subdomain\.example\.com\Z/', $this->parser->regex);
+ // $this->assertEquals(array(), $this->parser->names);
+ // }
+ //
+ // public function testDynamicSegmentWithSeparators()
+ // {
+ // $this->assertEquals('/\Afoo\/(?<bar>[^\/]+)\Z/', $this->parser->parse('foo/:bar', array(), array('/')));
+ // }
+ //
+ // public function testDynamicSegmentWithRequirements()
+ // {
+ // $this->assertEquals('/\Afoo\/(?<bar>[a-z]+)\Z/', $this->parser->parse('foo/:bar', array('bar' => '[a-z]+'), array('/')));
+ // }
+ //
+ // public function testDynamicSegmentInsideOptionalSegment()
+ // {
+ // $this->assertEquals('/\Afoo(?:\.(?<extension>[^\/\.]+))?\Z/', $this->parser->parse('foo(.:extension)'));
+ // }
+ //
+ // public function testGlobSegment()
+ // {
+ // $this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files'));
+ // }
+ //
+ // public function testGlobIgnoresSeparators()
+ // {
+ // $this->assertEquals('/\Asrc\/(?<files>.+)\Z/', $this->parser->parse('src/*files', array(), array('/', '.', '?')));
+ // }
+ //
+ // public function testGlobSegmentAtBeginning()
+ // {
+ // $this->assertEquals('/\A(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('*files/foo.txt'));
+ // }
+ //
+ // public function testGlobSegmentInMiddle()
+ // {
+ // $this->assertEquals('/\Asrc\/(?<files>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/foo.txt'));
+ // }
+ //
+ // public function testMultipleGlobSegments()
+ // {
+ // $this->assertEquals('/\Asrc\/(?<files>.+)\/dir\/(?<morefiles>.+)\/foo\.txt\Z/', $this->parser->parse('src/*files/dir/*morefiles/foo.txt'));
+ // }
+ //
+ // public function testEscapedGlobSegment()
+ // {
+ // $this->parser->parse('src/\*files');
+ //
+ // $this->assertEquals('/\Asrc\/\*files\Z/', $this->parser->regex);
+ // $this->assertEquals(array(), $this->parser->names);
+ // }
+ //
+ // public function testOptionalSegment()
+ // {
+ // $this->assertEquals('/\A\/foo(?:\/bar)?\Z/', $this->parser->parse('/foo(/bar)'));
+ // }
+ //
+ // public function testConsecutiveOptionalSegments()
+ // {
+ // $this->assertEquals('/\A\/foo(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('/foo(/bar)(/baz)'));
+ // }
+ //
+ // public function testMultipleOptionalSegments()
+ // {
+ // $this->assertEquals('/\A(?:\/foo)?(?:\/bar)?(?:\/baz)?\Z/', $this->parser->parse('(/foo)(/bar)(/baz)'));
+ // }
+
+ // public function testEscapesOptionalSegmentParenthesis()
+ // {
+ // $this->assertEquals('/\A\/foo\(\/bar\)\Z/', $this->parser->parse('/foo\(/bar\)'));
+ // }
+
+ // public function testEscapesOneOptionalSegmentParenthesis()
+ // {
+ // $this->assertEquals('/\A\/foo\((?:\/bar)?\Z/', $this->parser->parse('/foo\((/bar\)'));
+ // }
+
+ public function testThrowsExceptionIfOptionalSegmentParenthesisAreUnbalanced()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ // $this->parser->parse('/foo(/bar');
+ // $this->parser->parse('/foo((/bar)');
+ echo $this->parser->parse('/foo(/bar))');
+ }
+}
+
+
+ // def test_raises_regexp_error_if_optional_segment_parenthesises_are_unblanced
+ // assert_raise(RegexpError) { Strexp.compile('/foo((/bar)') }
+ // assert_raise(RegexpError) { Strexp.compile('/foo(/bar))') }
+ // end
\ No newline at end of file
diff --git a/tests/Starlight/Component/Routing/RouteTest.php b/tests/Starlight/Component/Routing/RouteTest.php
new file mode 100755
index 0000000..511809e
--- /dev/null
+++ b/tests/Starlight/Component/Routing/RouteTest.php
@@ -0,0 +1,19 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\Component\Routing;
+use Starlight\Component\Routing\Route;
+
+
+/**
+ */
+class RouteTest extends \PHPUnit_Framework_TestCase
+{
+};
|
synewaves/starlight | 7ff574716bb8db7534b3b2effac8269b3323fd5c | Getting router into a usable state | diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index a5c04bf..a09b5c1 100755
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
- backupStaticAttributes="true"
+ backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
- processIsolation="true"
+ processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="Starlight Test Suite">
<directory>./tests/Starlight/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./src/Starlight/</directory>
</whitelist>
</filter>
</phpunit>
diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index 4b23734..46aeac0 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,299 +1,332 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class for request/response headers
*/
-class HeaderBucket
+class HeaderBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Headers
* @var array
*/
protected $headers;
// /**
// * Wrapper class for request/response headers
// */
// protected $cache_control;
/**
* Type (request, response)
* @var string
*/
protected $type;
/**
* Constructor
* @param array $headers An array of HTTP headers
* @param string $type The type (null, request, or response)
*/
public function __construct(array $headers = array(), $type = null)
{
$this->replace($headers);
if ($type !== null && !in_array($type, array('request', 'response'))) {
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBucket.', $type));
}
$this->type = $type;
}
/**
* Returns the headers
* @return array An array of headers
*/
public function all()
{
return $this->headers;
}
/**
* Returns the parameter keys
* @return array An array of parameter keys
*/
public function keys()
{
return array_keys($this->headers);
}
/**
* Replaces the current HTTP headers by a new set
* @param array $headers An array of HTTP headers
* @return HeaderBucket this instance
*/
public function replace(array $headers = array())
{
$this->cache_control = null;
$this->headers = array();
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
return $this;
}
/**
* Returns a header value by name
* @param string $key The header name
* @param Boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function get($key, $first = true)
{
$key = static::normalizeHeaderName($key);
if (!array_key_exists($key, $this->headers)) {
return $first ? null : array();
}
if ($first) {
return count($this->headers[$key]) ? $this->headers[$key][0] : '';
} else {
return $this->headers[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
$key = static::normalizeHeaderName($key);
if (!is_array($values)) {
$values = array($values);
}
if ($replace === true || !isset($this->headers[$key])) {
$this->headers[$key] = $values;
} else {
$this->headers[$key] = array_merge($this->headers[$key], $values);
}
return $this;
}
/**
* Returns true if the HTTP header is defined
* @param string $key The HTTP header
* @return Boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists(static::normalizeHeaderName($key), $this->headers);
}
/**
* Returns true if the given HTTP header contains the given value
* @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, false));
}
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->headers[static::normalizeHeaderName($key)]);
}
return $this;
}
// /**
// * Returns an instance able to manage the Cache-Control header.
// *
// * @return CacheControl A CacheControl instance
// */
// public function getCacheControl()
// {
// if (null === $this->cacheControl) {
// $this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type);
// }
//
// return $this->cacheControl;
// }
/**
* Set cookie variable
*
* Available options:
*
* <ul>
* <li><b>expires</b> <i>(integer)</i>: cookie expiration time (default: 0 [end of session])</li>
* <li><b>path</b> <i>(string)</i>: path cookie is valid for (default: '')</li>
* <li><b>domain</b> <i>(string)</i>: domain cookie is valid for (default: '')</li>
* <li><b>secure/b> <i>(boolean)</i>: should cookie only be used on a secure connection (default: false)</li>
* <li><b>http_only</b> <i>(string)</i>: cookie only valid over http? [not supported by all browsers] (default: true)</li>
* <li><b>encode</b> <i>(boolean)</i>: urlencode cookie value (default: true)</li>
* </ul>
* @param string $key cookie key
* @param mixed $value value
* @param array $options options hash (see above)
* @return HeaderBucket this instance
*/
public function setCookie($key, $value, $options = array())
{
$default_options = array(
'expires' => null,
'path' => null,
'domain' => null,
'secure' => false,
'http_only' => true,
);
$options += $default_options;
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie key "%s" contains invalid characters.', $key));
}
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
if (trim($key) == '') {
throw new \InvalidArgumentException('The cookie key cannot be empty');
}
$cookie = sprintf('%s=%s', $key, urlencode($value));
if ($this->type == 'request') {
$this->set('Cookie', $cookie);
return;
}
if ($options['expires'] !== null) {
if (is_numeric($options['expires'])) {
$options['expires'] = (int) $options['expires'];
} elseif ($options['expires'] instanceof \DateTime) {
$options['expires'] = $options['expires']->getTimestamp();
} else {
$options['expires'] = strtotime($options['expires']);
if ($options['expires'] === false || $options['expires'] == -1) {
throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $options['expires']));
}
}
$cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($options['domain']) {
$cookie .= '; domain=' . $options['domain'];
}
if ($options['path'] && $options['path'] !== '/') {
$cookie .= '; path=' . $options['path'];
}
if ($options['secure']) {
$cookie .= '; secure';
}
if ($options['http_only']) {
$cookie .= '; httponly';
}
$this->set('Set-Cookie', $cookie, false);
return $this;
}
/**
* Expire a cookie variable
* @param string $key cookie key
* @return HeaderBucket this instance
*/
public function expireCookie($key)
{
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
}
if (!$key) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
if ($this->type == 'request') {
return;
}
$cookie = sprintf('%s=; expires=', $key, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
$this->set('Set-Cookie', $cookie, false);
return $this;
}
+
+ //
+ // ArrayAccess
+ //
+
+ public function offsetExists($offset)
+ {
+ return $this->has($offset);
+ }
+
+ public function offsetGet($offset)
+ {
+ return $this->get($offset);
+ }
+
+ public function offsetSet($offset, $value)
+ {
+ return $this->set($offset, $value);
+ }
+
+ public function offsetUnset($offset)
+ {
+ return $this->delete($offset);
+ }
+
+ //
+ // IteratorAggregate
+ //
+
+ public function getIterator()
+ {
+ return new \ArrayIterator($this->all());
+ }
/**
* Normalizes an HTTP header name
* @param string $key The HTTP header name
* @return string The normalized HTTP header name
*/
static public function normalizeHeaderName($key)
{
return strtr(strtolower($key), '_', '-');
}
};
diff --git a/src/Starlight/Component/Dispatcher/HttpDispatcher.php b/src/Starlight/Component/Http/HttpDispatcher.php
similarity index 72%
rename from src/Starlight/Component/Dispatcher/HttpDispatcher.php
rename to src/Starlight/Component/Http/HttpDispatcher.php
index 2b0bb51..caf68aa 100755
--- a/src/Starlight/Component/Dispatcher/HttpDispatcher.php
+++ b/src/Starlight/Component/Http/HttpDispatcher.php
@@ -1,19 +1,21 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
-namespace Starlight\Component\Dispatcher;
+namespace Starlight\Component\Http;
+use Starlight\Component\Dispatcher\Dispatcher;
class HttpDispatcher extends Dispatcher
{
public function dispatch()
{
+ dump($this->context->request);
}
};
diff --git a/src/Starlight/Component/Http/ParameterBucket.php b/src/Starlight/Component/Http/ParameterBucket.php
index 1818bdc..8fbd49c 100755
--- a/src/Starlight/Component/Http/ParameterBucket.php
+++ b/src/Starlight/Component/Http/ParameterBucket.php
@@ -1,125 +1,158 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class request parameters
* @see Request
*/
-class ParameterBucket
+class ParameterBucket implements \ArrayAccess, \IteratorAggregate
{
/**
* Parameters
* @var array
*/
protected $parameters;
/**
* Constructor
* @param array $parameters Parameters
*/
public function __construct(array $parameters = array())
{
$this->replace($parameters);
}
/**
* Returns the parameters
* @return array Parameters
*/
public function all()
{
return $this->parameters;
}
/**
* Returns the parameter keys
* @return array Parameter keys
*/
public function keys()
{
return array_keys($this->parameters);
}
/**
* Replaces the current parameters by a new set
* @param array $parameters parameters
* @return HeaderBucket this instance
*/
public function replace(array $parameters = array())
{
$this->parameters = $parameters;
return $this;
}
/**
* Adds parameters
* @param array $parameters parameters
* @return HeaderBucket this instance
*/
public function add(array $parameters = array())
{
$this->parameters = array_replace($this->parameters, $parameters);
return $this;
}
/**
* Returns a parameter by name
* @param string $key The key
* @param mixed $default default value
* @return mixed value
*/
public function get($key, $default = null)
{
return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}
/**
* Sets a parameter by name
* @param string $key The key
* @param mixed $value value
* @return HeaderBucket this instance
*/
public function set($key, $value)
{
$this->parameters[$key] = $value;
return $this;
}
/**
* Returns true if the parameter is defined
* @param string $key The key
* @return boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists($key, $this->parameters);
}
/**
* Deletes a parameter
* @param string $key key
* @return HeaderBucket this instance
*/
public function delete($key)
{
if ($this->has($key)) {
unset($this->parameters[$key]);
}
return $this;
}
+
+ //
+ // ArrayAccess
+ //
+
+ public function offsetExists($offset)
+ {
+ return $this->has($offset);
+ }
+
+ public function offsetGet($offset)
+ {
+ return $this->get($offset);
+ }
+
+ public function offsetSet($offset, $value)
+ {
+ return $this->set($offset, $value);
+ }
+
+ public function offsetUnset($offset)
+ {
+ return $this->delete($offset);
+ }
+
+ //
+ // IteratorAggregate
+ //
+
+ public function getIterator()
+ {
+ return new \ArrayIterator($this->all());
+ }
};
diff --git a/src/Starlight/Component/Http/Request.php b/src/Starlight/Component/Http/Request.php
index 65f7dcf..9759497 100755
--- a/src/Starlight/Component/Http/Request.php
+++ b/src/Starlight/Component/Http/Request.php
@@ -1,277 +1,315 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Request
*/
class Request
{
+ public static $local_ips = array('127.0.0.1');
+
public $post;
public $get;
public $cookies;
public $files;
public $server;
public $headers;
protected $host;
protected $port;
protected $remote_ip;
+ protected $url;
/**
* Constructor
* @param array $post POST values
* @param array $get GET values
* @param array $cookies COOKIE values
* @param array $files FILES values
* @param array $server SERVER values
*/
public function __construct(array $post = null, array $get = null, array $cookies = null, array $files = null, array $server = null)
{
$this->post = new ParameterBucket($post ?: $_POST);
$this->get = new ParameterBucket($get ?: $_GET);
$this->cookies = new ParameterBucket($cookies ?: $_COOKIE);
$this->files = new ParameterBucket($files ?: $_FILES);
$this->server = new ParameterBucket($server ?: $_SERVER);
$this->headers = new HeaderBucket($this->initializeHeaders(), 'request');
}
/**
* Clone
*/
public function __clone()
{
$this->post = clone $this->post;
$this->get = clone $this->get;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Get a value from the request
*
* Order or precedence: GET, POST, COOKIE
*/
public function get($key, $default = null)
{
return $this->get->get($key, $this->post->get($key, $this->cookies->get($key, $default)));
}
/**
* Gets request method, lowercased
*
* Method can come from three places in this order:
* <ol>
* <li>$_POST[_method]</li>
* <li>$_SERVER[X_HTTP_METHOD_OVERRIDE]</li>
* <li>$_SERVER[REQUEST_METHOD]</li>
* </ol>
* @return string request method
*/
public function getMethod()
{
$method = $this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD')));
return !is_null($method) ? strtolower($method) : null;
}
/**
* Is this a DELETE request
* @return boolean is DELETE request
*/
public function isDelete()
{
return $this->getMethod() == 'delete';
}
/**
* Is this a GET request
* @see head()
* @return boolean is GET request
*/
public function isGet()
{
return $this->isHead();
}
/**
* Is this a POST request
* @return boolean is POST request
*/
public function isPost()
{
return $this->getMethod() == 'post';
}
/**
* Is this a HEAD request
*
* Functionally equivalent to get()
* @return boolean is HEAD request
*/
public function isHead()
{
return $this->getMethod() == 'head' || $this->getMethod() == 'get';
}
/**
* Is this a PUT request
* @return boolean is PUT request
*/
public function isPut()
{
return $this->getMethod() == 'put';
}
/**
* Is this an SSL request
* @return boolean is SSL request
*/
public function isSsl()
{
return strtolower($this->server->get('HTTPS')) == 'on';
}
/**
* Gets server protocol
* @return string protocol
*/
public function getProtocol()
{
return $this->isSsl() ? 'https://' : 'http://';
}
/**
* Gets the server host
* @return string host
*/
public function getHost()
{
if (is_null($this->host)) {
$host = $this->server->get('HTTP_X_FORWARDED_HOST', $this->server->get('HTTP_HOST'));
$pos = strpos($host, ':');
if ($pos !== false) {
$this->host = substr($host, 0, $pos);
$this->port = is_null($this->port) ? (int) substr($host, $pos + 1) : null;
} else {
$this->host = $host;
}
}
return $this->host;
}
/**
* Gets the server port
* @return integer port
*/
public function getPort()
{
if (is_null($this->port)) {
$this->port = (int) $this->server->get('SERVER_PORT', $this->getStandardPort());
}
return $this->port;
}
/**
* Gets the standard port number for the current protocol
* @return integer port (443, 80)
*/
public function getStandardPort()
{
return $this->isSsl() ? 443 : 80;
}
/**
* Gets the port string with colon delimiter if not standard port
* @return string port
*/
public function getPortString()
{
return (in_array($this->getPort(), array(443, 80))) ? '' : ':' . $this->getPort();
}
/**
* Gets the host with the port
* @return string host with port
*/
public function getHostWithPort()
{
return $this->getHost() . $this->getPortString();
}
/**
* Gets the client's remote ip
* @return string IP
*/
public function getRemoteIp()
{
if (is_null($this->remote_ip)) {
$remote_ips = null;
if ($x_forward = $this->server->get('HTTP_X_FORWARDED_FOR')) {
$remote_ips = array_map('trim', explode(',', $x_forward));
}
$client_ip = $this->server->get('HTTP_CLIENT_IP');
if ($client_ip) {
if (is_array($remote_ips) && !in_array($client_ip, $remote_ips)) {
// don't know which came from the proxy, and which from the user
throw new Exception\IpSpoofingException(sprintf("IP spoofing attack?!\nHTTP_CLIENT_IP=%s\nHTTP_X_FORWARDED_FOR=%s", $this->server->get('HTTP_CLIENT_IP'), $this->server->get('HTTP_X_FORWARDED_FOR')));
}
$this->remote_ip = $client_ip;
} elseif (is_array($remote_ips)) {
$this->remote_ip = $remote_ips[0];
} else {
$this->remote_ip = $this->server->get('REMOTE_ADDR');
}
}
return $this->remote_ip;
}
+ /**
+ * Is this request local?
+ * @return boolean local
+ */
+ public function isLocal()
+ {
+ return in_array($this->getRemoteIp(), static::$local_ips);
+ }
+
/**
* Check if the request is an XMLHttpRequest (AJAX)
* @return boolean is XHR (AJAX) request
*/
public function isXmlHttpRequest()
{
return (bool) preg_match('/XMLHttpRequest/i', $this->server->get('HTTP_X_REQUESTED_WITH'));
}
/**
* Gets the full server url with protocol and port
* @return string server path
*/
public function getServer()
{
return $this->getProtocol() . $this->getHostWithPort();
}
+ /**
+ * Gets the requested URI path without domain or script name
+ * @return string uri
+ */
+ public function getUri()
+ {
+ $url = $this->server->get('REQUEST_URI');
+ return trim($url) != '' ? $url : '/';
+ }
+
+ /**
+ * Gets the requested route from the URI
+ * @return string route
+ */
+ public function getRoute()
+ {
+ $route = $this->getUri();
+
+ // remove query string
+ if (($qs = strpos($route, '?')) !== false) {
+ $route = substr($route, 0, $qs);
+ }
+
+ return $route;
+ }
+
/**
* Initialize request headers for HeaderBucket
* @return array headers
*/
protected function initializeHeaders()
{
$headers = array();
foreach ($this->server->all() as $key => $value) {
if (strtolower(substr($key, 0, 5)) === 'http_') {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
};
diff --git a/src/Starlight/Component/Routing/Resource.php b/src/Starlight/Component/Routing/Resource.php
index 27e122e..189e527 100644
--- a/src/Starlight/Component/Routing/Resource.php
+++ b/src/Starlight/Component/Routing/Resource.php
@@ -1,152 +1,192 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
use Starlight\Component\Inflector\Inflector;
/**
- * Route
+ * Resource
*/
class Resource implements Compilable
{
/**
* RESTful routing map; maps actions to methods
* @var array
*/
protected static $resources_map = array(
- 'index' => array('method' => 'get', 'path' => '/'),
- 'add' => array('method' => 'get', 'path' => '/:action'),
- 'create' => array('method' => 'post', 'path' => '/'),
- 'show' => array('method' => 'get', 'path' => '/:id'),
- 'edit' => array('method' => 'get', 'path' => '/:id/:action'),
- 'update' => array('method' => 'put', 'path' => '/:id'),
- 'delete' => array('method' => 'get', 'path' => '/:id/:action'),
- 'destroy' => array('method' => 'delete', 'path' => '/:id'),
+ 'index' => array('name' => '%p', 'verb' => 'get', 'url' => '/'),
+ 'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action'),
+ 'create' => array('name' => '%p', 'verb' => 'post', 'url' => '/'),
+ 'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/:id'),
+ 'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:id/:action'),
+ 'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/:id'),
+ 'delete' => array('name' => 'delete_%s', 'verb' => 'get', 'url' => '/:id/:action'),
+ 'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/:id'),
);
protected static $resource_names = array(
'add' => 'add',
'edit' => 'edit',
'delete' => 'delete',
);
public $resource;
public $except;
public $only;
public $controller;
public $constraints;
public $name;
public $path_names;
+ public $namespace;
// member, collection, resources (nested)
/**
*
*/
public function __construct($resource)
{
$this->resource = $resource;
- $this->controller = $this->resource;
+ $this->controller = Inflector::pluralize($this->resource);
}
/**
*
*/
public function except(array $except)
{
$this->only = null;
$this->except = $except;
return $this;
}
/**
*
*/
public function only(array $only)
{
$this->except = null;
$this->only = $only;
return $this;
}
/**
*
*/
public function controller($controller)
{
$this->controller = $controller;
return $this;
}
/**
*
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
* (as)
*/
public function name($name)
{
- $this->name = $name;
+ $single = explode(' ', strtolower(Inflector::humanize($name)));
+ $plural = $single;
+ $count = count($single);
+
+ $single[$count - 1] = Inflector::singularize($single[$count - 1]);
+ $plural[$count - 1] = Inflector::pluralize($plural[$count - 1]);
+
+ $this->name = array(
+ implode('_', $single),
+ implode('_', $plural),
+ );
return $this;
}
/**
*
*/
public function pathNames(array $names)
{
$this->path_names = $names;
return $this;
}
+ /**
+ *
+ */
+ public function namespaced($namespace)
+ {
+ $this->namespace = $namespace;
+
+ return $this;
+ }
/**
*
*/
public function compile()
{
- $generators = self::$resources_map;
+ $generators = static::$resources_map;
if ($this->except) {
$generators = array_diff_key($generators, array_fill_keys($this->except, true));
} elseif ($this->only) {
$generators = array_intersect_key($generators, array_fill_keys($this->only, true));
}
- $this->path_names += self::$resource_names;
+ if (is_array($this->path_names)) {
+ $this->path_names += static::$resource_names;
+ } else {
+ $this->path_names = static::$resource_names;
+ }
$routes = array();
foreach ($generators as $action => $parts) {
- $path = $parts['path'];
+ $path = $parts['url'];
if (strpos($path, ':action') !== false) {
$path = str_replace(':action', $this->path_names[$action], $path);
}
$r = new Route('/' . $this->resource . $path, $this->controller . '#' . $action);
- $r->methods(array($parts['method']))->name($this->name);
- $routes[] = $r;
+ $r->methods(array($parts['verb']));
+
+ $single = isset($this->name[0]) ? $this->name[0] : Inflector::singularize($this->resource);
+ $plural = isset($this->name[1]) ? $this->name[1] : Inflector::pluralize($this->resource);
+
+ $name = str_replace('%s', $single, $parts['name']);
+ $name = str_replace('%p', $plural, $name);
+ $r->name($name);
+
+ if ($this->constraints) {
+ $r->constraints($this->constraints);
+ }
+
+ if ($this->namespace) {
+ $r->namespaced($this->namespace);
+ }
+
+ $routes[] = $r->compile();
}
-
- dump($routes);
+
+ return $routes;
}
};
diff --git a/src/Starlight/Component/Routing/Routable.php b/src/Starlight/Component/Routing/Routable.php
index 0bebc32..c2300f3 100644
--- a/src/Starlight/Component/Routing/Routable.php
+++ b/src/Starlight/Component/Routing/Routable.php
@@ -1,20 +1,21 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
+use Starlight\Component\Http\Request;
/**
* Route
*/
interface Routable
{
- public function match($path);
+ public function match(Request $request);
};
diff --git a/src/Starlight/Component/Routing/Route.php b/src/Starlight/Component/Routing/Route.php
index 5ff1dff..2acd9db 100644
--- a/src/Starlight/Component/Routing/Route.php
+++ b/src/Starlight/Component/Routing/Route.php
@@ -1,167 +1,144 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
+use Starlight\Component\Http\Request;
/**
* Route
*/
class Route implements Routable, Compilable
{
- /**
- * URL path separators regex
- * '\' and '.'
- * @var string
- */
- protected static $separators = array('\/', '\.');
-
/**
* Base default values for route parameters
* @var array
*/
protected static $base_defaults = array(
'controller' => null,
'action' => null,
'id' => null,
);
public $path;
public $endpoint;
public $regex;
public $parameters;
public $constraints;
public $methods;
public $name;
public $namespace;
/**
*
*/
public function __construct($path, $endpoint)
{
- $this->path = $path;
+ $this->path = static::normalize($path);
$this->endpoint = $endpoint;
}
/**
*
*/
public function defaults(array $defaults)
{
foreach ($defaults as $key => $value) {
if (trim($this->parameters[$key]) == '') {
$this->parameters[$key] = $value;
}
}
return $this;
}
/**
*
*/
public function constraints($constraints)
{
$this->constraints = $constraints;
return $this;
}
/**
*
*/
public function methods(array $methods)
{
$this->methods = $methods;
return $this;
}
/**
*
*/
public function name($name)
{
$this->name = $name;
return $this;
}
/**
*
*/
public function namespaced($namespace)
{
$this->namespace = $namespace;
- //
return $this;
}
/**
*
*/
public function compile()
{
- $elements = preg_split('/([' . implode(static::$separators) . '])/i', trim($this->path, '/'), -1, PREG_SPLIT_DELIM_CAPTURE);
- if (count($elements) == 0) {
- return;
- }
-
- array_unshift($elements, '/');
- $patterns = array();
- $count = count($elements);
- $names = array();
-
- for ($i=0; $i<$count; $i = $i+2) {
- $sep = $elements[$i];
- $elm = $elements[$i+1];
-
- if (preg_match('/^\*(.+)$/', $elm, $match)) {
- // glob character:
- $patterns[] = '(?:\\' . $sep . '(.*+))?';
- $names[$match[1]] = null;
- } elseif (preg_match('/^:(.+)$/', $elm, $match)) {
- // named element:
- $patterns[] = '(?:\\' . $sep . '([^\/\.]+))?';
- $names[$match[1]] = null;
- } else {
- // normal element:
- $patterns[] = '\\' . $sep . $elm;
- }
- }
+ $parser = new RouteParser();
+ $constraints = !is_callable($this->constraints) ? (array) $this->constraints : array();
if ($this->namespace) {
- array_unshift($patterns, '\\/' . $this->namespace);
+ $this->path = '/' . $this->namespace . $this->path;
if ($this->name != '') {
$this->name = $this->namespace . '_' . $this->name;
}
+ $this->endpoint = $this->namespace . '/' . $this->endpoint;
}
- $this->regex = '/^' . implode($patterns) . '\/?$/i';
- $this->parameters = static::$base_defaults + $names;
+ $this->regex = $parser->parse($this->path, $constraints);
+ $this->parameters = array_merge(static::$base_defaults, array_fill_keys($parser->names, ''), (array) $this->parameters);
list($this->parameters['controller'], $this->parameters['action']) = explode('#', $this->endpoint);
return $this;
}
/**
*
*/
- public function match($context)
+ public function match(Request $request)
{
- // if (preg_match($this->regex, $path, $matches)) {
- // dump($matches);
- // }
+ }
+
+ /**
+ *
+ */
+ protected function normalize($path)
+ {
+ $path = trim($path, '/');
+ $path = '/' . $path;
+
+ return $path;
}
};
diff --git a/src/Starlight/Component/Routing/RouteParser.php b/src/Starlight/Component/Routing/RouteParser.php
new file mode 100644
index 0000000..07b9672
--- /dev/null
+++ b/src/Starlight/Component/Routing/RouteParser.php
@@ -0,0 +1,80 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Routing;
+
+
+/**
+ * Route
+ */
+class RouteParser
+{
+ /**
+ * URL path separators (regex escaped)
+ * '\' and '.'
+ * @var string
+ */
+ protected static $default_separators = array('\/', '\.');
+
+ public $path;
+ public $regex;
+ public $requirements;
+ public $separators;
+ public $names = array();
+
+ /**
+ *
+ */
+ public function parse($path, array $requirements = array(), array $separators = array())
+ {
+ $this->path = trim($path);
+ $this->requirements = $requirements;
+ $this->separators = count($separators) > 0 ? $separators : static::$default_separators;
+
+ $this->regex = $this->path;
+ $this->regex = str_replace(')', ')?', $this->regex);
+ $this->regex = str_replace('/', '\\/', $this->regex);
+ $this->regex = str_replace('.', '\\.', $this->regex);
+
+ preg_match_all('/((\:|\\*)[a-z]+)/i', $this->regex, $matches, PREG_OFFSET_CAPTURE);
+ if (isset($matches[0])) {
+ $t_regex = '';
+ $t_offset = 0;
+ $separators = implode('', $this->separators);
+ foreach ($matches[0] as $match) {
+ list($key, $offset) = $match;
+
+ $t_regex .= substr($this->regex, $t_offset, $offset - $t_offset);
+
+ $identifier = substr($key, 0, 1);
+ $name = substr($key, 1);
+
+ $regex = '';
+ if (isset($this->requirements[$name])) {
+ $regex = $this->requirements[$name];
+ } elseif ($identifier == '*') {
+ $regex = '.+';
+ } else {
+ $regex = '[^' . $separators . ']+';
+ }
+
+ $t_regex .= '(?<' . $name . '>' . $regex . ')';
+ $t_offset = $offset + strlen($key);
+
+ $this->names[] = $name;
+ }
+
+ $t_regex .= substr($this->regex, $t_offset);
+ $this->regex = $t_regex;
+ }
+
+ return '/\\A' . $this->regex . '\\Z/';
+ }
+};
diff --git a/src/Starlight/Component/Routing/Router.php b/src/Starlight/Component/Routing/Router.php
index 8416d0e..b0f620e 100644
--- a/src/Starlight/Component/Routing/Router.php
+++ b/src/Starlight/Component/Routing/Router.php
@@ -1,63 +1,176 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Routing;
+use Starlight\Component\Http\Request;
/**
* Router
*/
class Router
{
- protected static $routes = array();
- protected static $compiled = array();
+ protected $routes = array();
+ protected $compiled = array();
+ protected $scopes = array();
+ protected $has_compiled = false;
- public static function map($path, $endpoint)
+ /**
+ *
+ */
+ public function draw(\Closure $callback)
{
- static::$routes[] = new Route($path, $endpoint);
+ // todo: check for cached version before redrawing these
+ $callback($this);
+ }
+
+
+ /**
+ *
+ */
+ public function map($path, $endpoint)
+ {
+ $this->routes[] = new Route($path, $endpoint);
- return static::$routes[count(static::$routes) - 1];
+ return $this->applyScopes($this->routes[count($this->routes) - 1]);
}
+ /**
+ *
+ */
+ public function resources($resource)
+ {
+ $this->routes[] = new Resource($resource);
+
+ return $this->applyScopes($this->routes[count($this->routes) - 1]);
+ }
- public static function resources($resource)
+ /**
+ *
+ */
+ public function resource($resource)
{
- static::$routes[] = new Resource($resource);
+ $this->routes[] = new SingularResource($resource);
- return static::$routes[count(static::$routes) - 1];
+ return $this->applyScopes($this->routes[count($this->routes) - 1]);
+ }
+
+ /**
+ *
+ */
+ public function namespaced($namespace, $callback)
+ {
+ $this->scope('namespace', $namespace, $callback);
}
- public static function compile()
+ /**
+ *
+ */
+ public function constraints($constraints, $callback)
{
- static::$compiled = array();
+ $this->scope('constraints', $constraints, $callback);
+ }
+
+ /**
+ *
+ */
+ public function compile()
+ {
+ if ($this->has_compiled) {
+ return;
+ }
- foreach (self::$routes as $route) {
+ $this->compiled = array();
+
+ foreach ($this->routes as $route) {
$c = $route->compile();
if (is_array($c)) {
- static::$compiled += $c;
+ $this->compiled = array_merge($this->compiled, $c);
} else {
- static::$compiled [] = $c;
+ $this->compiled[] = $c;
}
}
+
+ $this->has_compiled = true;
}
- public static function match($url)
+ /**
+ *
+ */
+ public function match(Request $request)
{
- foreach (static::$compiled as $r) {
- if ($r->match($url)) {
+ foreach ($this->compiled as $r) {
+ if ($r->match($request)) {
//
return;
}
}
// nothing matched:
}
+
+ /**
+ *
+ */
+ public function scope($type, $value, $callback)
+ {
+ $this->addScope($type, $value);
+ $callback($this);
+ $this->removeScope($type, $value);
+ }
+
+ /**
+ *
+ */
+ protected function applyScopes($route)
+ {
+ // scoped namespace
+ if (isset($this->scopes['namespace'])) {
+ $route->namespaced(implode('/', $this->scopes['namespace']));
+ }
+
+ // scoped constraints
+ if (isset($this->scopes['constraints'])) {
+ $constraints = array();
+ foreach ($this->scopes['constraints'] as $c) {
+ $constraints = array_merge($constraints, $c);
+ }
+ $route->constraints($constraints);
+ }
+
+ return $route;
+ }
+
+ /**
+ *
+ */
+ protected function addScope($key, $value = null)
+ {
+ if (isset($this->scopes[$key])) {
+ $this->scopes[$key][] = $value;
+ } else {
+ $this->scopes[$key] = array($value);
+ }
+ }
+
+ /**
+ *
+ */
+ protected function removeScope($key, $value)
+ {
+ if (isset($this->scopes[$key])) {
+ $position = array_search($value, $this->scopes[$key]);
+ if ($position !== false) {
+ unset($this->scopes[$key][$position]);
+ }
+ }
+ }
};
diff --git a/src/Starlight/Component/Routing/SingularResource.php b/src/Starlight/Component/Routing/SingularResource.php
new file mode 100644
index 0000000..2411a91
--- /dev/null
+++ b/src/Starlight/Component/Routing/SingularResource.php
@@ -0,0 +1,33 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Component\Routing;
+
+
+/**
+ * Singular resource
+ */
+class SingularResource extends Resource
+{
+ /**
+ * RESTful routing map; maps actions to methods
+ * @var array
+ */
+ protected static $resources_map = array(
+ 'index' => array('name' => '%s', 'verb' => 'get', 'url' => '/'),
+ 'add' => array('name' => 'add_%s', 'verb' => 'get', 'url' => '/:action'),
+ 'create' => array('name' => '%s', 'verb' => 'post', 'url' => '/'),
+ 'show' => array('name' => '%s', 'verb' => 'get', 'url' => '/'),
+ 'edit' => array('name' => 'edit_%s', 'verb' => 'get', 'url' => '/:action'),
+ 'update' => array('name' => '%s', 'verb' => 'put', 'url' => '/'),
+ 'delete' => array('name' => 'delete_%s', 'verb' => 'get', 'url' => '/:action'),
+ 'destroy' => array('name' => '%s', 'verb' => 'delete', 'url' => '/'),
+ );
+};
diff --git a/src/Starlight/Framework/bootloader.php b/src/Starlight/Framework/bootloader.php
index 9dfb433..fc6e1d1 100755
--- a/src/Starlight/Framework/bootloader.php
+++ b/src/Starlight/Framework/bootloader.php
@@ -1,64 +1,67 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
+
error_reporting(-1);
require_once __DIR__ . '/Support/UniversalClassLoader.php';
$autoloader = new \Starlight\Framework\Support\UniversalClassLoader();
$autoloader->registerNamespaces(array(
'Starlight' => __DIR__ . '/../../',
));
$autoloader->register();
+
function dump()
{
foreach (func_get_args() as $arg) {
- echo '<pre>' . print_r($arg, true) . '</pre>';
+ echo '<pre>' . htmlspecialchars(print_r($arg, true)) . '</pre>';
echo '<hr />';
}
}
-$dispatcher = new \Starlight\Component\Dispatcher\HttpDispatcher(new \Starlight\Component\Http\HttpContext());
-$dispatcher->dispatch();
-
-
-// $dispatcher = new \Starlight\Component\Dispatcher\HttpDispatcher();
-// $dispatcher->dispatch(new \Starlight\Component\Http\Request());
-// dump($dispatcher);
-
-//\Starlight\Framework\Kernel::initialize();
-
-// $r->match('/some/url/to/match', 'controller#hellyeah');
-
-// $route = \Starlight\Component\Routing\Router::map('/pages/:id', 'pages#view')
-// // ->defaults(array('controller' => 'anything'))
-// // ->methods(array('post', 'get'))
-// // ->constraints(array('id' => '/[0-9]+/i'))
-// // ->name('junk_stuff')
-// // ->namespaced('admin')
-// ;
-// // ->constraints(function($request){
-// // return false;
-// // });
+// $context = new \Starlight\Component\Http\HttpContext();
+// $dispatcher = new \Starlight\Component\Http\HttpDispatcher($context);
+// $dispatcher->dispatch();
-// $route = \Starlight\Component\Routing\Router::resources('photos')
-// ->only(array('edit'))
-// ->pathNames(array('edit' => 'editon'))
-// ->controller('images')
-// ->name('images')
-// ;
-//
-// $route->compile();
+$router = new \Starlight\Component\Routing\Router();
+$router->draw(function($r){
+ // $r->map('/:controller(/:action(/:id))(.:format)', 'session#add');
+ // $r->map(':controller/:id', 'session#add')->constraints(array('id' => '[0-9]+'))->namespaced('admin');
+ // $r->map('*anything', 'session#add');
+ // $r->map('/login/:screenname', 'session#add')
+ // ->defaults(array('id' => 27))
+ // ->methods(array('get', 'post', 'delete'))
+ // ->name('login')
+ // ->namespaced('admin')
+ // ->constraints(array('id' => '/27/i'))
+ // ;
+
+ // $r->constraints(array('id' => 27), function($r){
+ // $r->namespaced('admin', function($r){
+ // // $r->map('/login', 'session#new');
+ // // $r->map('/logout', 'session#destroy');
+ // $r->namespaced('anything', function($r){
+ // $r->map('whee', 'session#new');
+ // });
+ // });
+ // });
+
+ $r->resources('photo')
+ ->name('image')
+ ->controller('images')
+ ->namespaced('admin')
+ ;
+});
+$router->compile();
-// \Starlight\Component\Routing\Router::compile();
-// //\Starlight\Component\Routing\Router::match('/pages/this-is-some-junk/and-some-more-junk/adsf/anything/100asd');
-// \Starlight\Component\Routing\Router::match('/pages/100asd');
+dump($router);
\ No newline at end of file
diff --git a/tests/Starlight/Component/Http/HeaderBucketTest.php b/tests/Starlight/Component/Http/HeaderBucketTest.php
index f220ebd..acdb317 100755
--- a/tests/Starlight/Component/Http/HeaderBucketTest.php
+++ b/tests/Starlight/Component/Http/HeaderBucketTest.php
@@ -1,294 +1,317 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\HeaderBucket;
use Starlight\Component\Http\HeaderBucket;
/**
*/
class HeaderBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->headers = array(
'HTTP_HOST' => 'localhost:80',
'HTTP_CONNECTION' => 'keep-alive',
'HTTP_REFERER' => 'http://localhost:80/',
'HTTP_ACCEPT' => 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.59 Safari/534.3',
'HTTP_ACCEPT_ENCODING' => 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
);
$this->type = 'request';
$this->normalized_headers = array();
foreach ($this->headers as $header => $value) {
$this->normalized_headers[HeaderBucket::normalizeHeaderName($header)] = array($value);
}
}
public function testArguments()
{
$this->type = 'madeup';
$this->setExpectedException('InvalidArgumentException');
$this->getBucket();
}
public function testAll()
{
$this->assertEquals($this->getBucket()->all(), $this->normalized_headers);
}
public function testKeys()
{
$this->assertEquals($this->getBucket()->keys(), array_keys($this->normalized_headers));
}
public function testReplace()
{
$bucket = $this->getBucket();
$this->assertEquals($bucket->all(), $this->normalized_headers);
$new_headers = array(
'HTTP_HOST' => 'localhost:80',
);
$normalized = array(
'http-host' => array('localhost:80'),
);
$bucket->replace($new_headers);
$this->assertNotEquals($bucket->all(), $this->normalized_headers);
$this->assertEquals($bucket->all(), $normalized);
}
public function testGet()
{
$this->assertEquals($this->getBucket()->get('HTTP_HOST'), 'localhost:80');
$this->assertEquals($this->getBucket()->get('HTTP_HOST', false), array('localhost:80'));
$this->assertNull($this->getBucket()->get('MADE_UP'));
$this->assertEquals($this->getBucket()->get('MADE_UP', false), array());
}
public function testSet()
{
$bucket = $this->getBucket();
$bucket->set('MADE_UP', 'Value');
$this->assertEquals($bucket->get('MADE_UP'), 'Value');
$bucket->set('MADE_uP', 'Value 2');
$this->assertEquals($bucket->get('MADE_UP'), 'Value 2');
$bucket->set('MADE_UP', 'Value 1', false);
$this->assertEquals($bucket->get('MADE_UP', false), array('Value 2', 'Value 1'));
}
public function testHas()
{
$this->assertTrue($this->getBucket()->has('HTTP_HOST'));
$this->assertFalse($this->getBucket()->has('MADE_UP'));
}
public function testContains()
{
$this->assertTrue($this->getBucket()->contains('HTTP_HOST', 'localhost:80'));
$this->assertFalse($this->getBucket()->contains('HTTP_HOST', 'localhost'));
$this->assertFalse($this->getBucket()->contains('MADE_UP', 'made up value'));
}
public function testDelete()
{
$bucket = $this->getBucket();
$this->assertTrue($bucket->has('HTTP_HOST'));
$bucket->delete('HTTP_HOST');
$this->assertFalse($bucket->has('HTTP_HOST'));
$this->assertFalse($bucket->has('MADE_UP'));
$bucket->delete('MADE_UP');
$this->assertFalse($bucket->has('MADE_UP'));
}
public function testSetCookieInvalidKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->setCookie('Invalid_cookie=', 'value');
}
public function testSetCookieInvalidValue()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->setCookie('Invalid_cookie', 'value;');
}
public function testSetCookieEmptyKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->setCookie('', 'value');
}
public function testSetCookieRequest()
{
$this->type = 'request';
$bucket = $this->getBucket();
$bucket->setCookie('cookie_key', 'cookie_value');
$this->assertEquals($bucket->get('Cookie'), 'cookie_key=cookie_value');
}
public function testSetCookieWithExpirationDateInteger()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = new \DateTime('+7 days');
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires->getTimestamp(),
'http_only' => false,
));
$this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testSetCookieWithExpirationDateString()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = 'January 1, 2000 12:00:00';
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires,
'http_only' => false,
));
$this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testSetCookieWithExpirationDateInvalidString()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = 'This is not a date';
$this->setExpectedException('InvalidArgumentException');
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires,
'http_only' => false,
));
}
public function testSetCookieWithExpirationDateDateTime()
{
$this->type = 'response';
$bucket = $this->getBucket();
$expires = new \DateTime('+7 days');
$bucket->setCookie('cookie_key', 'cookie_value', array(
'expires' => $expires,
'http_only' => false,
));
$this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testSetCookieWithPath()
{
$this->type = 'response';
$bucket = $this->getBucket();
$path = '/some/awesome/path';
$bucket->setCookie('cookie_key', 'cookie_value', array(
'path' => $path,
'http_only' => false,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; path=' . $path);
}
public function testSetCookieWithDomain()
{
$this->type = 'response';
$bucket = $this->getBucket();
$domain = 'example.com';
$bucket->setCookie('cookie_key', 'cookie_value', array(
'domain' => $domain,
'http_only' => false,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; domain=' . $domain);
}
public function testSetCookieWithSecure()
{
$this->type = 'response';
$bucket = $this->getBucket();
$bucket->setCookie('cookie_key', 'cookie_value', array(
'secure' => true,
'http_only' => false,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; secure');
}
public function testSetCookieWithHttpOnly()
{
$this->type = 'response';
$bucket = $this->getBucket();
$bucket->setCookie('cookie_key', 'cookie_value', array(
'http_only' => true,
));
$this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; httponly');
}
public function testExpireCookieInvalidKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->expireCookie('Invalid_cookie=', 'value');
}
public function testExpireCookieEmptyKey()
{
$this->setExpectedException('InvalidArgumentException');
$this->getBucket()->expireCookie('', 'value;');
}
public function testExpireCookie()
{
$this->type = 'response';
$bucket = $this->getBucket();
$bucket->expireCookie('cookie_key');
$this->assertRegExp('/^cookie\_key\=\; expires\=/i', $bucket->get('Set-Cookie'));
}
public function testExpireCookieRequest()
{
$bucket = $this->getBucket();
$bucket->expireCookie('cookie_key');
$this->assertNull($bucket->get('Set-Cookie'));
}
+ public function testArrayAccess()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertTrue(isset($bucket['HTTP_HOST']));
+ $this->assertEquals($bucket['HTTP_HOST'], 'localhost:80');
+
+ $bucket['MADE_UP'] = 'anything';
+ $this->assertTrue(isset($bucket['MADE_UP']));
+
+ unset($bucket['MADE_UP']);
+ $this->assertFalse(isset($bucket['MADE_UP']));
+ }
+
+ public function testIteratorAggreate()
+ {
+ $bucket = $this->getBucket();
+
+ foreach ($bucket as $key => $value) {
+ $this->assertEquals($value, $this->normalized_headers[$key]);
+ }
+ }
+
public function testNormalizeHeaderName()
{
$this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_HOST'), 'http-host');
$this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_hoST'), 'http-host');
$this->assertEquals(HeaderBucket::normalizeHeaderName('http-host'), 'http-host');
}
protected function getBucket()
{
return new HeaderBucket($this->headers, $this->type);
}
};
diff --git a/tests/Starlight/Component/Http/ParameterBucketTest.php b/tests/Starlight/Component/Http/ParameterBucketTest.php
index 1ba7117..a881c10 100755
--- a/tests/Starlight/Component/Http/ParameterBucketTest.php
+++ b/tests/Starlight/Component/Http/ParameterBucketTest.php
@@ -1,101 +1,124 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\ParameterBucket;
use Starlight\Component\Http\ParameterBucket;
/**
*/
class ParameterBucketTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->params = array(
'test_1' => 'value_1',
'test_2' => 'value_2',
'test_3' => 'value_3',
);
}
public function testAll()
{
$this->assertEquals($this->getBucket()->all(), $this->params);
}
public function testKeys()
{
$this->assertEquals($this->getBucket()->keys(), array_keys($this->params));
}
public function testReplace()
{
$bucket = $this->getBucket();
$new_parameters = array('test_4' => 'value_4');
$bucket->replace($new_parameters);
$this->assertEquals($bucket->all(), $new_parameters);
$this->assertNotEquals($bucket->all(), $this->params);
}
public function testAdd()
{
$bucket = $this->getBucket();
$new_parameters = array('test_4' => 'value_4');
$bucket->add($new_parameters);
$this->assertEquals($bucket->all(), array_replace($this->params, $new_parameters));
$this->assertNotEquals($bucket->all(), $this->params);
}
public function testGet()
{
$this->assertEquals($this->getBucket()->get('test_1'), 'value_1');
$this->assertNull($this->getBucket()->get('test_4'));
$this->assertEquals($this->getBucket()->get('test_4', 'value_4'), 'value_4');
}
public function testSet()
{
$bucket = $this->getBucket();
$this->assertNull($bucket->get('test_4'));
$bucket->set('test_4', 'value_4');
$this->assertEquals($bucket->get('test_4'), 'value_4');
$this->assertEquals($bucket->get('test_2'), 'value_2');
$bucket->set('test_2', 'value_22');
$this->assertEquals($bucket->get('test_2'), 'value_22');
}
public function testHas()
{
$this->assertTrue($this->getBucket()->has('test_1'));
$this->assertFalse($this->getBucket()->has('test_4'));
}
public function testDelete()
{
$bucket = $this->getBucket();
$this->assertTrue($bucket->has('test_1'));
$bucket->delete('test_1');
$this->assertFalse($bucket->has('test_1'));
$this->assertFalse($bucket->has('test_4'));
$bucket->delete('test_4');
$this->assertFalse($bucket->has('test_4'));
}
+ public function testArrayAccess()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertTrue(isset($bucket['test_1']));
+ $this->assertEquals($bucket['test_1'], 'value_1');
+
+ $bucket['test_4'] = 'anything';
+ $this->assertTrue(isset($bucket['test_4']));
+
+ unset($bucket['test_4']);
+ $this->assertFalse(isset($bucket['test_4']));
+ }
+
+ public function testIteratorAggreate()
+ {
+ $bucket = $this->getBucket();
+
+ foreach ($bucket as $key => $value) {
+ $this->assertEquals($value, $this->params[$key]);
+ }
+ }
+
protected function getBucket()
{
return new ParameterBucket($this->params);
}
};
diff --git a/tests/Starlight/Component/Http/RequestTest.php b/tests/Starlight/Component/Http/RequestTest.php
index a5920e3..e02d397 100755
--- a/tests/Starlight/Component/Http/RequestTest.php
+++ b/tests/Starlight/Component/Http/RequestTest.php
@@ -1,254 +1,298 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Tests\Http\Request;
use Starlight\Component\Http\Request;
/**
*/
class RequestTest extends \PHPUnit_Framework_TestCase
{
public function setup()
{
$this->post = array();
$this->get = array();
$this->cookies = array();
$this->files = array();
$this->server = array();
}
public function testClone()
{
$this->post['test'] = 'example';
$this->cookies['my_cookie'] = 'the value';
$request1 = $this->getRequest();
$request2 = clone $request1;
$this->assertEquals($request1->post->get('test'), $request2->post->get('test'));
$this->assertEquals($request1->cookies->get('my_cookie'), $request2->cookies->get('my_cookie'));
$request1->post->set('test', 'something new');
$this->assertNotEquals($request1->post->get('test'), $request2->post->get('test'));
}
public function testGet()
{
$this->cookies['check'] = 'cookies';
$this->post['check'] = 'post';
$this->get['check'] = 'get';
$this->assertEquals($this->getRequest()->get('check'), 'get');
unset($this->get['check']);
$this->assertEquals($this->getRequest()->get('check'), 'post');
unset($this->post['check']);
$this->assertEquals($this->getRequest()->get('check'), 'cookies');
unset($this->cookies['check']);
$this->assertNull($this->getRequest()->get('check'));
$this->assertEquals($this->getRequest()->get('check', 'default'), 'default');
}
public function testGetMethod()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->server['X_HTTP_METHOD_OVERRIDE'] = 'put';
$this->post['_method'] = 'get';
$this->assertEquals($this->getRequest()->getMethod(), 'get');
unset($this->post['_method']);
$this->assertEquals($this->getRequest()->getMethod(), 'put');
unset($this->server['X_HTTP_METHOD_OVERRIDE']);
$this->assertEquals($this->getRequest()->getMethod(), 'post');
unset($this->server['REQUEST_METHOD']);
$this->assertNull($this->getRequest()->getMethod());
}
public function testIsDelete()
{
$this->server['REQUEST_METHOD'] = 'delete';
$this->assertTrue($this->getRequest()->isDelete());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isDelete());
}
public function testIsGet()
{
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isGet());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isGet());
}
public function testIsPost()
{
$this->server['REQUEST_METHOD'] = 'post';
$this->assertTrue($this->getRequest()->isPost());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertFalse($this->getRequest()->isPost());
}
public function testIsPut()
{
$this->server['REQUEST_METHOD'] = 'put';
$this->assertTrue($this->getRequest()->isPut());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isPut());
}
public function testIsHead()
{
$this->server['REQUEST_METHOD'] = 'head';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'get';
$this->assertTrue($this->getRequest()->isHead());
$this->server['REQUEST_METHOD'] = 'post';
$this->assertFalse($this->getRequest()->isHead());
}
public function testIsSsl()
{
$this->server['HTTPS'] = 'On';
$this->assertTrue($this->getRequest()->isSsl());
$this->server['HTTPS'] = '';
$this->assertFalse($this->getRequest()->isSsl());
}
public function testGetProtocol()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getProtocol(), 'https://');
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getProtocol(), 'http://');
}
public function testGetHost()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['HTTP_X_FORWARDED_HOST'] = 'forwarded.example.com';
$this->assertEquals($this->getRequest()->getHost(), 'forwarded.example.com');
unset($this->server['HTTP_X_FORWARDED_HOST']);
$this->assertEquals($this->getRequest()->getHost(), 'example.com');
}
public function testSetPortFromHost()
{
$this->server['HTTP_HOST'] = 'example.com:8080';
$request = $this->getRequest();
$request->getHost();
$this->assertEquals($request->getPort(), 8080);
}
public function testGetPort()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPort(), 8080);
}
public function testGetStandardPort()
{
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getStandardPort(), 443);
$this->server['HTTPS'] = '';
$this->assertEquals($this->getRequest()->getStandardPort(), 80);
}
public function testGetPortString()
{
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getPortString(), ':8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getPortString(), '');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getPortString(), '');
}
public function testGetHostWithPort()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
$this->server['SERVER_PORT'] = '443';
$this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
}
public function testGetRemoteIp()
{
$this->server['REMOTE_ADDR'] = '127.0.0.3';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.3');
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.2');
unset($this->server['HTTP_CLIENT_IP']);
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
$this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.1');
}
public function testGetRemoteIpException()
{
$this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
$this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
$this->setExpectedException('Starlight\\Component\\Http\\Exception\\IpSpoofingException');
$this->getRequest()->getRemoteIp();
}
public function testIsXmlHttpRequest()
{
$this->assertFalse($this->getRequest()->isXmlHttpRequest());
$this->server['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->assertTrue($this->getRequesT()->isXmlHttpRequest());
}
public function testGetServer()
{
$this->server['HTTP_HOST'] = 'example.com';
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com:8080');
$this->server['SERVER_PORT'] = '80';
$this->assertEquals($this->getRequest()->getServer(), 'http://example.com');
$this->server['HTTPS'] = 'On';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com');
$this->server['SERVER_PORT'] = '8080';
$this->assertEquals($this->getRequest()->getServer(), 'https://example.com:8080');
}
+ public function testGetUri()
+ {
+ $this->server['REQUEST_URI'] = '/src/Starlight/Framework/bootloader.php';
+ $this->assertEquals($this->getRequest()->getUri(), '/src/Starlight/Framework/bootloader.php');
+
+ $this->server['REQUEST_URI'] = '';
+ $this->assertEquals($this->getRequest()->getUri(), '/');
+ }
+
+ public function testGetRoute()
+ {
+ $this->server['REQUEST_URI'] = '/photos/1/users';
+ $this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
+
+ $this->server['REQUEST_URI'] = '/photos/1/users?querystring=1';
+ $this->assertEquals($this->getRequest()->getRoute(), '/photos/1/users');
+
+ $this->server['REQUEST_URI'] = '';
+ $this->assertEquals($this->getRequest()->getRoute(), '/');
+ }
+
+ public function testIsLocalStandard()
+ {
+ $this->server['REMOTE_ADDR'] = '127.0.0.1';
+ $this->assertTrue($this->getRequest()->isLocal());
+
+ $this->server['REMOTE_ADDR'] = '127.0.0.2';
+ $this->assertFalse($this->getRequest()->isLocal());
+ }
+
+ public function testIsLocalCustom()
+ {
+ Request::$local_ips[] = '192.168.0.1';
+
+ $this->server['REMOTE_ADDR'] = '127.0.0.1';
+ $this->assertTrue($this->getRequest()->isLocal());
+
+ $this->server['REMOTE_ADDR'] = '192.168.0.1';
+ $this->assertTrue($this->getRequest()->isLocal());
+
+ $this->server['REMOTE_ADDR'] = '127.0.0.2';
+ $this->assertFalse($this->getRequest()->isLocal());
+ }
+
protected function getRequest()
{
return new Request($this->post, $this->get, $this->cookies, $this->files, $this->server);
}
};
|
synewaves/starlight | dc9de035cf403ff72484a26dfc38968e2eddaa9e | Added tests for existing library code | diff --git a/phpunit.xml.dist b/phpunit.xml.dist
old mode 100644
new mode 100755
index 676a62a..a5c04bf
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="true"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="true"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
- <testsuites>
- <testsuite name="Starlight Test Suite">
- <directory>./tests/Starlight/</directory>
- </testsuite>
- </testsuites>
-
- <filter>
- <whitelist>
- <directory>./src/Starlight/</directory>
- </whitelist>
- </filter>
+ <testsuites>
+ <testsuite name="Starlight Test Suite">
+ <directory>./tests/Starlight/</directory>
+ </testsuite>
+ </testsuites>
+
+ <filter>
+ <whitelist>
+ <directory>./src/Starlight/</directory>
+ </whitelist>
+ </filter>
</phpunit>
diff --git a/src/Starlight/Component/Http/HeaderBucket.php b/src/Starlight/Component/Http/HeaderBucket.php
index bf383c0..4b23734 100755
--- a/src/Starlight/Component/Http/HeaderBucket.php
+++ b/src/Starlight/Component/Http/HeaderBucket.php
@@ -1,297 +1,299 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class for request/response headers
*/
class HeaderBucket
{
/**
* Headers
* @var array
*/
protected $headers;
// /**
// * Wrapper class for request/response headers
// */
// protected $cache_control;
/**
* Type (request, response)
* @var string
*/
protected $type;
/**
* Constructor
* @param array $headers An array of HTTP headers
* @param string $type The type (null, request, or response)
*/
public function __construct(array $headers = array(), $type = null)
{
$this->replace($headers);
if ($type !== null && !in_array($type, array('request', 'response'))) {
throw new \InvalidArgumentException(sprintf('The "%s" type is not supported by the HeaderBucket.', $type));
}
$this->type = $type;
}
/**
* Returns the headers
* @return array An array of headers
*/
public function all()
{
return $this->headers;
}
/**
* Returns the parameter keys
* @return array An array of parameter keys
*/
public function keys()
{
return array_keys($this->headers);
}
/**
* Replaces the current HTTP headers by a new set
* @param array $headers An array of HTTP headers
* @return HeaderBucket this instance
*/
public function replace(array $headers = array())
{
$this->cache_control = null;
$this->headers = array();
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
return $this;
}
/**
* Returns a header value by name
* @param string $key The header name
* @param Boolean $first Whether to return the first value or all header values
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function get($key, $first = true)
{
$key = static::normalizeHeaderName($key);
if (!array_key_exists($key, $this->headers)) {
return $first ? null : array();
}
if ($first) {
return count($this->headers[$key]) ? $this->headers[$key][0] : '';
} else {
return $this->headers[$key];
}
}
/**
* Sets a header by name
* @param string $key The key
* @param string|array $values The value or an array of values
* @param boolean $replace Whether to replace the actual value of not (true by default)
* @return HeaderBucket this instance
*/
public function set($key, $values, $replace = true)
{
$key = static::normalizeHeaderName($key);
if (!is_array($values)) {
$values = array($values);
}
if ($replace === true || !isset($this->headers[$key])) {
$this->headers[$key] = $values;
} else {
$this->headers[$key] = array_merge($this->headers[$key], $values);
}
return $this;
}
/**
* Returns true if the HTTP header is defined
* @param string $key The HTTP header
* @return Boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists(static::normalizeHeaderName($key), $this->headers);
}
/**
* Returns true if the given HTTP header contains the given value
* @param string $key The HTTP header name
* @param string $value The HTTP value
* @return Boolean true if the value is contained in the header, false otherwise
*/
public function contains($key, $value)
{
return in_array($value, $this->get($key, false));
}
/**
* Deletes a header
* @param string $key The HTTP header name
* @return HeaderBucket this instance
*/
public function delete($key)
{
- unset($this->headers[static::normalizeHeaderName($key)]);
+ if ($this->has($key)) {
+ unset($this->headers[static::normalizeHeaderName($key)]);
+ }
return $this;
}
// /**
// * Returns an instance able to manage the Cache-Control header.
// *
// * @return CacheControl A CacheControl instance
// */
// public function getCacheControl()
// {
// if (null === $this->cacheControl) {
// $this->cacheControl = new CacheControl($this, $this->get('Cache-Control'), $this->type);
// }
//
// return $this->cacheControl;
// }
/**
* Set cookie variable
*
* Available options:
*
* <ul>
* <li><b>expires</b> <i>(integer)</i>: cookie expiration time (default: 0 [end of session])</li>
* <li><b>path</b> <i>(string)</i>: path cookie is valid for (default: '')</li>
* <li><b>domain</b> <i>(string)</i>: domain cookie is valid for (default: '')</li>
* <li><b>secure/b> <i>(boolean)</i>: should cookie only be used on a secure connection (default: false)</li>
* <li><b>http_only</b> <i>(string)</i>: cookie only valid over http? [not supported by all browsers] (default: true)</li>
* <li><b>encode</b> <i>(boolean)</i>: urlencode cookie value (default: true)</li>
* </ul>
* @param string $key cookie key
* @param mixed $value value
* @param array $options options hash (see above)
* @return HeaderBucket this instance
*/
- public function setCookie($name, $value, $options = array())
+ public function setCookie($key, $value, $options = array())
{
$default_options = array(
'expires' => null,
- 'path' => '',
- 'domain' => '',
+ 'path' => null,
+ 'domain' => null,
'secure' => false,
'http_only' => true,
);
$options += $default_options;
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
- throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
+ throw new \InvalidArgumentException(sprintf('The cookie key "%s" contains invalid characters.', $key));
}
if (preg_match("/[,; \t\r\n\013\014]/", $value)) {
throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value));
}
- if (!$name) {
- throw new \InvalidArgumentException('The cookie name cannot be empty');
+ if (trim($key) == '') {
+ throw new \InvalidArgumentException('The cookie key cannot be empty');
}
- $cookie = sprintf('%s=%s', $name, urlencode($value));
+ $cookie = sprintf('%s=%s', $key, urlencode($value));
if ($this->type == 'request') {
$this->set('Cookie', $cookie);
return;
}
if ($options['expires'] !== null) {
if (is_numeric($options['expires'])) {
$options['expires'] = (int) $options['expires'];
} elseif ($options['expires'] instanceof \DateTime) {
$options['expires'] = $options['expires']->getTimestamp();
} else {
- $expires = strtotime($options['expires']);
- if ($expires === false || $expires == -1) {
- throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $expires));
+ $options['expires'] = strtotime($options['expires']);
+ if ($options['expires'] === false || $options['expires'] == -1) {
+ throw new \InvalidArgumentException(sprintf('The "expires" cookie parameter is not valid.', $options['expires']));
}
}
- $cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $expires, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
+ $cookie .= '; expires=' . substr(\DateTime::createFromFormat('U', $options['expires'], new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5);
}
if ($options['domain']) {
$cookie .= '; domain=' . $options['domain'];
}
- if ($options['path'] !== '/') {
- $cookie .= '; path=' . $path;
+ if ($options['path'] && $options['path'] !== '/') {
+ $cookie .= '; path=' . $options['path'];
}
if ($options['secure']) {
$cookie .= '; secure';
}
- if ($options['httponly']) {
+ if ($options['http_only']) {
$cookie .= '; httponly';
}
$this->set('Set-Cookie', $cookie, false);
return $this;
}
/**
* Expire a cookie variable
* @param string $key cookie key
* @return HeaderBucket this instance
*/
public function expireCookie($key)
{
- if ($this->type == 'request') {
- return;
- }
-
if (preg_match("/[=,; \t\r\n\013\014]/", $key)) {
throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $key));
}
- if (!$name) {
+ if (!$key) {
throw new \InvalidArgumentException('The cookie name cannot be empty');
}
+
+ if ($this->type == 'request') {
+ return;
+ }
- $cookie = sprintf('%s=; expires=', $name, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
+ $cookie = sprintf('%s=; expires=', $key, substr(\DateTime::createFromFormat('U', time() - 3600, new \DateTimeZone('UTC'))->format('D, d-M-Y H:i:s T'), 0, -5));
$this->set('Set-Cookie', $cookie, false);
return $this;
}
/**
* Normalizes an HTTP header name
* @param string $key The HTTP header name
* @return string The normalized HTTP header name
*/
static public function normalizeHeaderName($key)
{
return strtr(strtolower($key), '_', '-');
}
};
diff --git a/src/Starlight/Component/Http/ParameterBucket.php b/src/Starlight/Component/Http/ParameterBucket.php
index 1be30fa..1818bdc 100755
--- a/src/Starlight/Component/Http/ParameterBucket.php
+++ b/src/Starlight/Component/Http/ParameterBucket.php
@@ -1,123 +1,125 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* Wrapper class request parameters
* @see Request
*/
class ParameterBucket
{
/**
* Parameters
* @var array
*/
protected $parameters;
/**
* Constructor
* @param array $parameters Parameters
*/
public function __construct(array $parameters = array())
{
$this->replace($parameters);
}
/**
* Returns the parameters
* @return array Parameters
*/
public function all()
{
return $this->parameters;
}
/**
* Returns the parameter keys
* @return array Parameter keys
*/
public function keys()
{
return array_keys($this->parameters);
}
/**
* Replaces the current parameters by a new set
* @param array $parameters parameters
* @return HeaderBucket this instance
*/
public function replace(array $parameters = array())
{
$this->parameters = $parameters;
return $this;
}
/**
* Adds parameters
* @param array $parameters parameters
* @return HeaderBucket this instance
*/
public function add(array $parameters = array())
{
$this->parameters = array_replace($this->parameters, $parameters);
return $this;
}
/**
* Returns a parameter by name
* @param string $key The key
* @param mixed $default default value
* @return mixed value
*/
public function get($key, $default = null)
{
return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}
/**
* Sets a parameter by name
* @param string $key The key
* @param mixed $value value
* @return HeaderBucket this instance
*/
public function set($key, $value)
{
$this->parameters[$key] = $value;
return $this;
}
/**
* Returns true if the parameter is defined
* @param string $key The key
* @return boolean true if the parameter exists, false otherwise
*/
public function has($key)
{
return array_key_exists($key, $this->parameters);
}
/**
* Deletes a parameter
* @param string $key key
* @return HeaderBucket this instance
*/
public function delete($key)
{
- unset($this->parameters[$key]);
+ if ($this->has($key)) {
+ unset($this->parameters[$key]);
+ }
return $this;
}
};
diff --git a/src/Starlight/Component/Http/Request.php b/src/Starlight/Component/Http/Request.php
index 6392155..65f7dcf 100755
--- a/src/Starlight/Component/Http/Request.php
+++ b/src/Starlight/Component/Http/Request.php
@@ -1,276 +1,277 @@
<?php
/*
* This file is part of the Starlight framework.
*
* (c) Matthew Vince <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Starlight\Component\Http;
/**
* HTTP Request
*/
class Request
{
public $post;
public $get;
public $cookies;
public $files;
public $server;
public $headers;
protected $host;
protected $port;
protected $remote_ip;
/**
* Constructor
* @param array $post POST values
* @param array $get GET values
* @param array $cookies COOKIE values
* @param array $files FILES values
* @param array $server SERVER values
*/
public function __construct(array $post = null, array $get = null, array $cookies = null, array $files = null, array $server = null)
{
$this->post = new ParameterBucket($post ?: $_POST);
$this->get = new ParameterBucket($get ?: $_GET);
$this->cookies = new ParameterBucket($cookies ?: $_COOKIE);
$this->files = new ParameterBucket($files ?: $_FILES);
$this->server = new ParameterBucket($server ?: $_SERVER);
$this->headers = new HeaderBucket($this->initializeHeaders(), 'request');
}
/**
* Clone
*/
public function __clone()
{
$this->post = clone $this->post;
$this->get = clone $this->get;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Get a value from the request
*
* Order or precedence: GET, POST, COOKIE
*/
public function get($key, $default = null)
{
return $this->get->get($key, $this->post->get($key, $this->cookies->get($key, $default)));
}
/**
* Gets request method, lowercased
*
* Method can come from three places in this order:
* <ol>
* <li>$_POST[_method]</li>
* <li>$_SERVER[X_HTTP_METHOD_OVERRIDE]</li>
* <li>$_SERVER[REQUEST_METHOD]</li>
* </ol>
* @return string request method
*/
public function getMethod()
{
- return strtolower($this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD'))));
+ $method = $this->post->get('_method', $this->server->get('X_HTTP_METHOD_OVERRIDE', $this->server->get('REQUEST_METHOD')));
+ return !is_null($method) ? strtolower($method) : null;
}
/**
* Is this a DELETE request
* @return boolean is DELETE request
*/
public function isDelete()
{
return $this->getMethod() == 'delete';
}
/**
* Is this a GET request
* @see head()
* @return boolean is GET request
*/
public function isGet()
{
return $this->isHead();
}
/**
* Is this a POST request
* @return boolean is POST request
*/
public function isPost()
{
return $this->getMethod() == 'post';
}
/**
* Is this a HEAD request
*
* Functionally equivalent to get()
* @return boolean is HEAD request
*/
public function isHead()
{
return $this->getMethod() == 'head' || $this->getMethod() == 'get';
}
/**
* Is this a PUT request
* @return boolean is PUT request
*/
public function isPut()
{
return $this->getMethod() == 'put';
}
/**
* Is this an SSL request
* @return boolean is SSL request
*/
public function isSsl()
{
return strtolower($this->server->get('HTTPS')) == 'on';
}
/**
* Gets server protocol
* @return string protocol
*/
public function getProtocol()
{
return $this->isSsl() ? 'https://' : 'http://';
}
/**
* Gets the server host
* @return string host
*/
public function getHost()
{
- if ($this->host === null) {
+ if (is_null($this->host)) {
$host = $this->server->get('HTTP_X_FORWARDED_HOST', $this->server->get('HTTP_HOST'));
$pos = strpos($host, ':');
if ($pos !== false) {
$this->host = substr($host, 0, $pos);
- $this->port = $this->port === null ? substr($host, $pos + 1) : null;
+ $this->port = is_null($this->port) ? (int) substr($host, $pos + 1) : null;
} else {
$this->host = $host;
}
}
return $this->host;
}
/**
* Gets the server port
* @return integer port
*/
public function getPort()
{
- if ($this->port === null) {
- $this->port = $this->server->get('SERVER_PORT', $this->getStandardPort());
+ if (is_null($this->port)) {
+ $this->port = (int) $this->server->get('SERVER_PORT', $this->getStandardPort());
}
return $this->port;
}
/**
* Gets the standard port number for the current protocol
* @return integer port (443, 80)
*/
public function getStandardPort()
{
return $this->isSsl() ? 443 : 80;
}
/**
* Gets the port string with colon delimiter if not standard port
* @return string port
*/
public function getPortString()
{
return (in_array($this->getPort(), array(443, 80))) ? '' : ':' . $this->getPort();
}
/**
* Gets the host with the port
* @return string host with port
*/
public function getHostWithPort()
{
return $this->getHost() . $this->getPortString();
}
/**
* Gets the client's remote ip
* @return string IP
*/
public function getRemoteIp()
{
- if ($this->remote_ip === null) {
+ if (is_null($this->remote_ip)) {
$remote_ips = null;
if ($x_forward = $this->server->get('HTTP_X_FORWARDED_FOR')) {
$remote_ips = array_map('trim', explode(',', $x_forward));
}
$client_ip = $this->server->get('HTTP_CLIENT_IP');
if ($client_ip) {
if (is_array($remote_ips) && !in_array($client_ip, $remote_ips)) {
// don't know which came from the proxy, and which from the user
throw new Exception\IpSpoofingException(sprintf("IP spoofing attack?!\nHTTP_CLIENT_IP=%s\nHTTP_X_FORWARDED_FOR=%s", $this->server->get('HTTP_CLIENT_IP'), $this->server->get('HTTP_X_FORWARDED_FOR')));
}
$this->remote_ip = $client_ip;
} elseif (is_array($remote_ips)) {
$this->remote_ip = $remote_ips[0];
} else {
$this->remote_ip = $this->server->get('REMOTE_ADDR');
}
}
return $this->remote_ip;
}
/**
* Check if the request is an XMLHttpRequest (AJAX)
* @return boolean is XHR (AJAX) request
*/
public function isXmlHttpRequest()
{
return (bool) preg_match('/XMLHttpRequest/i', $this->server->get('HTTP_X_REQUESTED_WITH'));
}
/**
* Gets the full server url with protocol and port
* @return string server path
*/
public function getServer()
{
return $this->getProtocol() . $this->getHostWithPort();
}
/**
* Initialize request headers for HeaderBucket
* @return array headers
*/
protected function initializeHeaders()
{
$headers = array();
foreach ($this->server->all() as $key => $value) {
if (strtolower(substr($key, 0, 5)) === 'http_') {
$headers[substr($key, 5)] = $value;
}
}
return $headers;
}
};
diff --git a/tests/Starlight/Component/Http/HeaderBucketTest.php b/tests/Starlight/Component/Http/HeaderBucketTest.php
new file mode 100755
index 0000000..f220ebd
--- /dev/null
+++ b/tests/Starlight/Component/Http/HeaderBucketTest.php
@@ -0,0 +1,294 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\Http\HeaderBucket;
+use Starlight\Component\Http\HeaderBucket;
+
+
+/**
+ */
+class HeaderBucketTest extends \PHPUnit_Framework_TestCase
+{
+ public function setup()
+ {
+ $this->headers = array(
+ 'HTTP_HOST' => 'localhost:80',
+ 'HTTP_CONNECTION' => 'keep-alive',
+ 'HTTP_REFERER' => 'http://localhost:80/',
+ 'HTTP_ACCEPT' => 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
+ 'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.59 Safari/534.3',
+ 'HTTP_ACCEPT_ENCODING' => 'gzip,deflate,sdch',
+ 'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
+ 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
+ );
+
+ $this->type = 'request';
+
+ $this->normalized_headers = array();
+ foreach ($this->headers as $header => $value) {
+ $this->normalized_headers[HeaderBucket::normalizeHeaderName($header)] = array($value);
+ }
+ }
+
+ public function testArguments()
+ {
+ $this->type = 'madeup';
+ $this->setExpectedException('InvalidArgumentException');
+
+ $this->getBucket();
+ }
+
+ public function testAll()
+ {
+ $this->assertEquals($this->getBucket()->all(), $this->normalized_headers);
+ }
+
+ public function testKeys()
+ {
+ $this->assertEquals($this->getBucket()->keys(), array_keys($this->normalized_headers));
+ }
+
+ public function testReplace()
+ {
+ $bucket = $this->getBucket();
+ $this->assertEquals($bucket->all(), $this->normalized_headers);
+
+ $new_headers = array(
+ 'HTTP_HOST' => 'localhost:80',
+ );
+ $normalized = array(
+ 'http-host' => array('localhost:80'),
+ );
+ $bucket->replace($new_headers);
+ $this->assertNotEquals($bucket->all(), $this->normalized_headers);
+ $this->assertEquals($bucket->all(), $normalized);
+ }
+
+ public function testGet()
+ {
+ $this->assertEquals($this->getBucket()->get('HTTP_HOST'), 'localhost:80');
+ $this->assertEquals($this->getBucket()->get('HTTP_HOST', false), array('localhost:80'));
+ $this->assertNull($this->getBucket()->get('MADE_UP'));
+ $this->assertEquals($this->getBucket()->get('MADE_UP', false), array());
+ }
+
+ public function testSet()
+ {
+ $bucket = $this->getBucket();
+
+ $bucket->set('MADE_UP', 'Value');
+ $this->assertEquals($bucket->get('MADE_UP'), 'Value');
+
+ $bucket->set('MADE_uP', 'Value 2');
+ $this->assertEquals($bucket->get('MADE_UP'), 'Value 2');
+
+ $bucket->set('MADE_UP', 'Value 1', false);
+ $this->assertEquals($bucket->get('MADE_UP', false), array('Value 2', 'Value 1'));
+ }
+
+ public function testHas()
+ {
+ $this->assertTrue($this->getBucket()->has('HTTP_HOST'));
+ $this->assertFalse($this->getBucket()->has('MADE_UP'));
+ }
+
+ public function testContains()
+ {
+ $this->assertTrue($this->getBucket()->contains('HTTP_HOST', 'localhost:80'));
+ $this->assertFalse($this->getBucket()->contains('HTTP_HOST', 'localhost'));
+ $this->assertFalse($this->getBucket()->contains('MADE_UP', 'made up value'));
+ }
+
+ public function testDelete()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertTrue($bucket->has('HTTP_HOST'));
+ $bucket->delete('HTTP_HOST');
+ $this->assertFalse($bucket->has('HTTP_HOST'));
+
+ $this->assertFalse($bucket->has('MADE_UP'));
+ $bucket->delete('MADE_UP');
+ $this->assertFalse($bucket->has('MADE_UP'));
+ }
+
+ public function testSetCookieInvalidKey()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ $this->getBucket()->setCookie('Invalid_cookie=', 'value');
+ }
+
+ public function testSetCookieInvalidValue()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ $this->getBucket()->setCookie('Invalid_cookie', 'value;');
+ }
+
+ public function testSetCookieEmptyKey()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ $this->getBucket()->setCookie('', 'value');
+ }
+
+ public function testSetCookieRequest()
+ {
+ $this->type = 'request';
+ $bucket = $this->getBucket();
+
+ $bucket->setCookie('cookie_key', 'cookie_value');
+ $this->assertEquals($bucket->get('Cookie'), 'cookie_key=cookie_value');
+ }
+
+ public function testSetCookieWithExpirationDateInteger()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+ $expires = new \DateTime('+7 days');
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'expires' => $expires->getTimestamp(),
+ 'http_only' => false,
+ ));
+
+ $this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
+ }
+
+ public function testSetCookieWithExpirationDateString()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+ $expires = 'January 1, 2000 12:00:00';
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'expires' => $expires,
+ 'http_only' => false,
+ ));
+
+ $this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
+ }
+
+ public function testSetCookieWithExpirationDateInvalidString()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+ $expires = 'This is not a date';
+
+ $this->setExpectedException('InvalidArgumentException');
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'expires' => $expires,
+ 'http_only' => false,
+ ));
+ }
+
+ public function testSetCookieWithExpirationDateDateTime()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+ $expires = new \DateTime('+7 days');
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'expires' => $expires,
+ 'http_only' => false,
+ ));
+
+ $this->assertRegExp('/^cookie\_key\=cookie\_value\; expires\=/i', $bucket->get('Set-Cookie'));
+ }
+
+ public function testSetCookieWithPath()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+ $path = '/some/awesome/path';
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'path' => $path,
+ 'http_only' => false,
+ ));
+ $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; path=' . $path);
+ }
+
+ public function testSetCookieWithDomain()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+ $domain = 'example.com';
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'domain' => $domain,
+ 'http_only' => false,
+ ));
+ $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; domain=' . $domain);
+ }
+
+ public function testSetCookieWithSecure()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'secure' => true,
+ 'http_only' => false,
+ ));
+ $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; secure');
+ }
+
+ public function testSetCookieWithHttpOnly()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+
+ $bucket->setCookie('cookie_key', 'cookie_value', array(
+ 'http_only' => true,
+ ));
+ $this->assertEquals($bucket->get('Set-Cookie'), 'cookie_key=cookie_value; httponly');
+ }
+
+ public function testExpireCookieInvalidKey()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ $this->getBucket()->expireCookie('Invalid_cookie=', 'value');
+ }
+
+ public function testExpireCookieEmptyKey()
+ {
+ $this->setExpectedException('InvalidArgumentException');
+ $this->getBucket()->expireCookie('', 'value;');
+ }
+
+ public function testExpireCookie()
+ {
+ $this->type = 'response';
+ $bucket = $this->getBucket();
+
+ $bucket->expireCookie('cookie_key');
+ $this->assertRegExp('/^cookie\_key\=\; expires\=/i', $bucket->get('Set-Cookie'));
+ }
+
+ public function testExpireCookieRequest()
+ {
+ $bucket = $this->getBucket();
+
+ $bucket->expireCookie('cookie_key');
+ $this->assertNull($bucket->get('Set-Cookie'));
+ }
+
+ public function testNormalizeHeaderName()
+ {
+ $this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_HOST'), 'http-host');
+ $this->assertEquals(HeaderBucket::normalizeHeaderName('HTTP_hoST'), 'http-host');
+ $this->assertEquals(HeaderBucket::normalizeHeaderName('http-host'), 'http-host');
+ }
+
+
+ protected function getBucket()
+ {
+ return new HeaderBucket($this->headers, $this->type);
+ }
+};
diff --git a/tests/Starlight/Component/Http/ParameterBucketTest.php b/tests/Starlight/Component/Http/ParameterBucketTest.php
new file mode 100755
index 0000000..1ba7117
--- /dev/null
+++ b/tests/Starlight/Component/Http/ParameterBucketTest.php
@@ -0,0 +1,101 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\Http\ParameterBucket;
+use Starlight\Component\Http\ParameterBucket;
+
+
+/**
+ */
+class ParameterBucketTest extends \PHPUnit_Framework_TestCase
+{
+ public function setup()
+ {
+ $this->params = array(
+ 'test_1' => 'value_1',
+ 'test_2' => 'value_2',
+ 'test_3' => 'value_3',
+ );
+ }
+
+ public function testAll()
+ {
+ $this->assertEquals($this->getBucket()->all(), $this->params);
+ }
+
+ public function testKeys()
+ {
+ $this->assertEquals($this->getBucket()->keys(), array_keys($this->params));
+ }
+
+ public function testReplace()
+ {
+ $bucket = $this->getBucket();
+ $new_parameters = array('test_4' => 'value_4');
+ $bucket->replace($new_parameters);
+
+ $this->assertEquals($bucket->all(), $new_parameters);
+ $this->assertNotEquals($bucket->all(), $this->params);
+ }
+
+ public function testAdd()
+ {
+ $bucket = $this->getBucket();
+ $new_parameters = array('test_4' => 'value_4');
+ $bucket->add($new_parameters);
+
+ $this->assertEquals($bucket->all(), array_replace($this->params, $new_parameters));
+ $this->assertNotEquals($bucket->all(), $this->params);
+ }
+
+ public function testGet()
+ {
+ $this->assertEquals($this->getBucket()->get('test_1'), 'value_1');
+ $this->assertNull($this->getBucket()->get('test_4'));
+ $this->assertEquals($this->getBucket()->get('test_4', 'value_4'), 'value_4');
+ }
+
+ public function testSet()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertNull($bucket->get('test_4'));
+ $bucket->set('test_4', 'value_4');
+ $this->assertEquals($bucket->get('test_4'), 'value_4');
+
+ $this->assertEquals($bucket->get('test_2'), 'value_2');
+ $bucket->set('test_2', 'value_22');
+ $this->assertEquals($bucket->get('test_2'), 'value_22');
+ }
+
+ public function testHas()
+ {
+ $this->assertTrue($this->getBucket()->has('test_1'));
+ $this->assertFalse($this->getBucket()->has('test_4'));
+ }
+
+ public function testDelete()
+ {
+ $bucket = $this->getBucket();
+
+ $this->assertTrue($bucket->has('test_1'));
+ $bucket->delete('test_1');
+ $this->assertFalse($bucket->has('test_1'));
+
+ $this->assertFalse($bucket->has('test_4'));
+ $bucket->delete('test_4');
+ $this->assertFalse($bucket->has('test_4'));
+ }
+
+ protected function getBucket()
+ {
+ return new ParameterBucket($this->params);
+ }
+};
diff --git a/tests/Starlight/Component/Http/RequestTest.php b/tests/Starlight/Component/Http/RequestTest.php
new file mode 100755
index 0000000..a5920e3
--- /dev/null
+++ b/tests/Starlight/Component/Http/RequestTest.php
@@ -0,0 +1,254 @@
+<?php
+/*
+ * This file is part of the Starlight framework.
+ *
+ * (c) Matthew Vince <[email protected]>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Starlight\Tests\Http\Request;
+use Starlight\Component\Http\Request;
+
+
+/**
+ */
+class RequestTest extends \PHPUnit_Framework_TestCase
+{
+ public function setup()
+ {
+ $this->post = array();
+ $this->get = array();
+ $this->cookies = array();
+ $this->files = array();
+ $this->server = array();
+ }
+
+ public function testClone()
+ {
+ $this->post['test'] = 'example';
+ $this->cookies['my_cookie'] = 'the value';
+
+ $request1 = $this->getRequest();
+ $request2 = clone $request1;
+
+ $this->assertEquals($request1->post->get('test'), $request2->post->get('test'));
+ $this->assertEquals($request1->cookies->get('my_cookie'), $request2->cookies->get('my_cookie'));
+
+ $request1->post->set('test', 'something new');
+ $this->assertNotEquals($request1->post->get('test'), $request2->post->get('test'));
+ }
+
+ public function testGet()
+ {
+ $this->cookies['check'] = 'cookies';
+ $this->post['check'] = 'post';
+ $this->get['check'] = 'get';
+ $this->assertEquals($this->getRequest()->get('check'), 'get');
+
+ unset($this->get['check']);
+ $this->assertEquals($this->getRequest()->get('check'), 'post');
+
+ unset($this->post['check']);
+ $this->assertEquals($this->getRequest()->get('check'), 'cookies');
+
+ unset($this->cookies['check']);
+ $this->assertNull($this->getRequest()->get('check'));
+ $this->assertEquals($this->getRequest()->get('check', 'default'), 'default');
+ }
+
+ public function testGetMethod()
+ {
+ $this->server['REQUEST_METHOD'] = 'post';
+ $this->server['X_HTTP_METHOD_OVERRIDE'] = 'put';
+ $this->post['_method'] = 'get';
+ $this->assertEquals($this->getRequest()->getMethod(), 'get');
+
+ unset($this->post['_method']);
+ $this->assertEquals($this->getRequest()->getMethod(), 'put');
+
+ unset($this->server['X_HTTP_METHOD_OVERRIDE']);
+ $this->assertEquals($this->getRequest()->getMethod(), 'post');
+
+ unset($this->server['REQUEST_METHOD']);
+ $this->assertNull($this->getRequest()->getMethod());
+ }
+
+ public function testIsDelete()
+ {
+ $this->server['REQUEST_METHOD'] = 'delete';
+ $this->assertTrue($this->getRequest()->isDelete());
+
+ $this->server['REQUEST_METHOD'] = 'post';
+ $this->assertFalse($this->getRequest()->isDelete());
+ }
+
+ public function testIsGet()
+ {
+ $this->server['REQUEST_METHOD'] = 'get';
+ $this->assertTrue($this->getRequest()->isGet());
+
+ $this->server['REQUEST_METHOD'] = 'post';
+ $this->assertFalse($this->getRequest()->isGet());
+ }
+
+ public function testIsPost()
+ {
+ $this->server['REQUEST_METHOD'] = 'post';
+ $this->assertTrue($this->getRequest()->isPost());
+
+ $this->server['REQUEST_METHOD'] = 'get';
+ $this->assertFalse($this->getRequest()->isPost());
+ }
+
+ public function testIsPut()
+ {
+ $this->server['REQUEST_METHOD'] = 'put';
+ $this->assertTrue($this->getRequest()->isPut());
+
+ $this->server['REQUEST_METHOD'] = 'post';
+ $this->assertFalse($this->getRequest()->isPut());
+ }
+
+ public function testIsHead()
+ {
+ $this->server['REQUEST_METHOD'] = 'head';
+ $this->assertTrue($this->getRequest()->isHead());
+
+ $this->server['REQUEST_METHOD'] = 'get';
+ $this->assertTrue($this->getRequest()->isHead());
+
+ $this->server['REQUEST_METHOD'] = 'post';
+ $this->assertFalse($this->getRequest()->isHead());
+ }
+
+ public function testIsSsl()
+ {
+ $this->server['HTTPS'] = 'On';
+ $this->assertTrue($this->getRequest()->isSsl());
+
+ $this->server['HTTPS'] = '';
+ $this->assertFalse($this->getRequest()->isSsl());
+ }
+
+ public function testGetProtocol()
+ {
+ $this->server['HTTPS'] = 'On';
+ $this->assertEquals($this->getRequest()->getProtocol(), 'https://');
+
+ $this->server['HTTPS'] = '';
+ $this->assertEquals($this->getRequest()->getProtocol(), 'http://');
+ }
+
+ public function testGetHost()
+ {
+ $this->server['HTTP_HOST'] = 'example.com';
+ $this->server['HTTP_X_FORWARDED_HOST'] = 'forwarded.example.com';
+ $this->assertEquals($this->getRequest()->getHost(), 'forwarded.example.com');
+
+ unset($this->server['HTTP_X_FORWARDED_HOST']);
+ $this->assertEquals($this->getRequest()->getHost(), 'example.com');
+ }
+
+ public function testSetPortFromHost()
+ {
+ $this->server['HTTP_HOST'] = 'example.com:8080';
+
+ $request = $this->getRequest();
+ $request->getHost();
+ $this->assertEquals($request->getPort(), 8080);
+ }
+
+ public function testGetPort()
+ {
+ $this->server['SERVER_PORT'] = '8080';
+ $this->assertEquals($this->getRequest()->getPort(), 8080);
+ }
+
+ public function testGetStandardPort()
+ {
+ $this->server['HTTPS'] = 'On';
+ $this->assertEquals($this->getRequest()->getStandardPort(), 443);
+
+ $this->server['HTTPS'] = '';
+ $this->assertEquals($this->getRequest()->getStandardPort(), 80);
+ }
+
+ public function testGetPortString()
+ {
+ $this->server['SERVER_PORT'] = '8080';
+ $this->assertEquals($this->getRequest()->getPortString(), ':8080');
+
+ $this->server['SERVER_PORT'] = '80';
+ $this->assertEquals($this->getRequest()->getPortString(), '');
+
+ $this->server['SERVER_PORT'] = '443';
+ $this->assertEquals($this->getRequest()->getPortString(), '');
+ }
+
+ public function testGetHostWithPort()
+ {
+ $this->server['HTTP_HOST'] = 'example.com';
+ $this->server['SERVER_PORT'] = '8080';
+ $this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com:8080');
+
+ $this->server['SERVER_PORT'] = '80';
+ $this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
+
+ $this->server['SERVER_PORT'] = '443';
+ $this->assertEquals($this->getRequest()->getHostWithPort(), 'example.com');
+ }
+
+ public function testGetRemoteIp()
+ {
+ $this->server['REMOTE_ADDR'] = '127.0.0.3';
+ $this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.3');
+
+ $this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
+ $this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.2');
+
+ unset($this->server['HTTP_CLIENT_IP']);
+ $this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
+ $this->assertEquals($this->getRequest()->getRemoteIp(), '127.0.0.1');
+ }
+
+ public function testGetRemoteIpException()
+ {
+ $this->server['HTTP_CLIENT_IP'] = '127.0.0.2';
+ $this->server['HTTP_X_FORWARDED_FOR'] = '127.0.0.1, 192.168.0.1, 192.168.0.2';
+
+ $this->setExpectedException('Starlight\\Component\\Http\\Exception\\IpSpoofingException');
+ $this->getRequest()->getRemoteIp();
+ }
+
+ public function testIsXmlHttpRequest()
+ {
+ $this->assertFalse($this->getRequest()->isXmlHttpRequest());
+
+ $this->server['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
+ $this->assertTrue($this->getRequesT()->isXmlHttpRequest());
+ }
+
+ public function testGetServer()
+ {
+ $this->server['HTTP_HOST'] = 'example.com';
+ $this->server['SERVER_PORT'] = '8080';
+ $this->assertEquals($this->getRequest()->getServer(), 'http://example.com:8080');
+
+ $this->server['SERVER_PORT'] = '80';
+ $this->assertEquals($this->getRequest()->getServer(), 'http://example.com');
+
+ $this->server['HTTPS'] = 'On';
+ $this->assertEquals($this->getRequest()->getServer(), 'https://example.com');
+
+ $this->server['SERVER_PORT'] = '8080';
+ $this->assertEquals($this->getRequest()->getServer(), 'https://example.com:8080');
+ }
+
+
+ protected function getRequest()
+ {
+ return new Request($this->post, $this->get, $this->cookies, $this->files, $this->server);
+ }
+};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.