4.0 alpha; initial commit

Esse commit está contido em:
Joshua Gross
2010-02-12 12:20:19 -06:00
commit e38aacff51
43 arquivos alterados com 5334 adições e 0 exclusões
+81
Ver Arquivo
@@ -0,0 +1,81 @@
<?php
// = ajaxim.php =
//
// **Copyright &copy; 2005 &ndash; 2010 Joshua Gross**\\
// //MIT Licensed//
//
// 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.
require_once('config.php');
require_once('libraries/db/base.php');
require_once('libraries/server/base.php');
# import the database library
require_once('libraries/db/' . DB_ENGINE . '.php');
$db_class = DB_ENGINE . '_Database';
if (!function_exists('class_alias')) {
// Allows us to alias Database library classes to standardized names
function class_alias($original, $alias) {
eval('class ' . $alias . ' extends ' . $original . ' {}');
}
}
class_alias(DB_ENGINE . '_Database', 'Database');
class_alias(DB_ENGINE . '_User', 'User');
class_alias(DB_ENGINE . '_Status', 'Status');
class_alias(DB_ENGINE . '_Message', 'Message');
class_alias(DB_ENGINE . '_Friend', 'Friend');
// Fix problems with magic_quotes_gpc/sybase
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
$syb = strtolower(ini_get('magic_quotes_sybase'));
if(empty($syb) || $syb == 'off') {
foreach($_POST as $key => $val) $_POST[$key] = stripslashes($val);
foreach($_GET as $key => $val) $_GET[$key] = stripslashes($val);
foreach($_COOKIE as $key => $val) $_COOKIE[$key] = stripslashes($val);
} else {
foreach($_POST as $key => $val) $_POST[$key] = str_replace("''", "'", $val);
foreach($_GET as $key => $val) $_GET[$key] = str_replace("''", "'", $val);
foreach($_COOKIE as $key => $val) $_COOKIE[$key] = str_replace("''", "'", $val);
}
}
// import the server library
require_once('libraries/server/' . IM_LIBRARY . '.php');
$im_class = IM_LIBRARY . '_IM';
$im = new $im_class();
$action = preg_replace('/^' . preg_quote($_SERVER['SCRIPT_NAME'], '/') . '\/(.+?)(\?.+)?$/', '\1', $_SERVER['REQUEST_URI']);
if(substr($action, 0, 1) != '_' && method_exists($im, $action))
if($action == 'poll') {
if($_GET['method'] == 'comet') {
$im->poll('comet');
} else {
print $_GET['callback'] . '(' . json_encode($im->poll($_GET['method'])) . ')';
}
} else {
$execute = call_user_func_array(array($im, $action), $_POST);
if($execute)
print json_encode($execute !== false ? $execute : array('e'=>'wrong args'));
}
else
print json_encode(array('e'=>'no method'));
/* End of index.php */
+93
Ver Arquivo
@@ -0,0 +1,93 @@
Node Server Memcached Protocol
for logging users in and out of the server.
-------------------------------------------
add <username> <!ignore flags> <!ignore exptime> <bytes> [!ignore noreply]\r\n
- <username> is the username of the new user
- <flags> and <exptime> are ignored.
- <bytes> is the number of bytes in the data block to follow, *not*
including the delimiting \r\n. <bytes> may *not* be zero.
After this line, the client sends the JSON-encoded data block:
<data block>\r\n
- <data block> is JSON-encoded information about the user, having a length
of <bytes> bytes.
After sending the command line and the data block, the client awaits
the reply, which may be:
- "STORED\r\n", to indicate that the user is or has been logged in.
- "NOT_STORED\r\n", to indicate that there was a problem storing the
new user data.
Retrieval command:
------------------
The retrieval commands "get" and "gets" operates like this:
get <type/identifier>\r\n
gets <type/identifier> <type/identifier> <...>\r\n
- <type/identifier> is one of:
- session/<session_id> where <session_id> is the session of an
existing user.
> returns information about the user
- username/<username> where <username> is the (properly formatted)
username of a logged in user.
> returns information about the user
- list/
> returns a list of all online users
- online/
> returns an integer value of the online user count
After this command, the client expects zero or more items, each of
which is received as a text line followed by a data block. After all
the items have been transmitted, the server sends the string
"END\r\n"
to indicate the end of response.
Each item sent by the server looks like this:
VALUE <key> <flags> <bytes>\r\n
<data block>\r\n
- <key> is the key for the item being sent
- <flags> is set to 0
- <bytes> is the length of the data block to follow, *not* including
its delimiting \r\n
- <data block> is the data for this response, usually in JSON format (exception: online/).
If some of the keys appearing in a retrieval request are not sent back
by the server in the item list this means that the server does not
hold items with such keys (because they were never stored, or stored
but deleted to make space for more items, or expired, or explicitly
deleted by a client).
Logging out
--------
The command "delete" allows for explicit logging out of users:
delete <username>\r\n
- <username> is the username of the user the client wishes the server
to log out.
The response line to this command can be one of:
- "DELETED\r\n" to indicate success
- "NOT_FOUND\r\n" to indicate that the user with this username was not
found.
+29
Ver Arquivo
@@ -0,0 +1,29 @@
<?php
// The backend engine library.
define('DB_ENGINE', 'MySQL');
// The IM server library.
define('IM_LIBRARY', 'NodeJS');
// If you're using the default MySQL server, change the below to
// match your settings.
define('MYSQL_USERNAME', 'root');
define('MYSQL_PASSWORD', 'root');
define('MYSQL_HOSTNAME', 'localhost');
define('MYSQL_DATABASE', 'ajaxim');
define('MYSQL_PREFIX', 'ajaxim_');
// Session cookie used by Ajax IM
define('COOKIE_NAME', 'ajaxim_session');
// Cookie period, in days
define('COOKIE_PERIOD', 365);
// Cookie domain (e.g.: .domain.com, if you want it to work for
// all domains and subdomains), if any.
define('COOKIE_DOMAIN', false);
// If you're using the NodeJS server, change the below to match
// your settings.
$nodejs_memcache_server = array('127.0.0.1', 11998);
?>
BIN
Ver Arquivo
Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 1.1 KiB

+596
Ver Arquivo
@@ -0,0 +1,596 @@
<!DOCTYPE html>
<html>
<head>
<title>Ajax IM &mdash; Instant Messaging Framework</title>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
}
body {
background: #fff;
font: 62.5% Helvetica Neue, Helvetica, Arial, Tahoma, sans-serif;
}
input, button, select {
font: 1.25em/1.25em Helvetica Neue, Helvetica, Arial, Tahoma, sans-serif;
}
input:focus {
outline: none;
}
code {
font-size: 1.1em;
font-family: Consolas, Inconsolata, Courier New, Courier, monospace;
}
/* [begin] Upper */
div.upper {
display: block;
width: 100%;
padding: 1em 0;
margin: 0 0 2em;
background: #444;
color: #fff;
}
/* [end] Upper */
/* [begin] Header */
div#header {
display: block;
margin: 0 0 0 6.67em;
font-size: 1.5em;
line-height: 1em;
overflow: hidden;
}
div#header a {
font-weight: 700;
color: #444;
}
h1 {
text-indent: -10000px;
/*background: url(http://ajaxim.com/images/logo.png?install);*/
background: url(site/demo/images/logo.png);
width: 146px;
height: 44px;
margin: 0 0.5em 0 0;
padding: 0;
float: left;
}
h2 {
margin: 0;
font-size: 1.2em;
line-height: 41px;
}
/* [end] Header */
/* [begin] Install form */
form {
font-size: 1.5em;
margin-left: 6.67em;
}
form fieldset {
position: relative;
border: 0;
font-size: 1em;
padding: 0 0 0.5em;
margin: 0 0 2em;
background: #eee;
width: 600px;
}
form fieldset legend {
background: #eee;
padding: 0.6em 1em 1em;
font-weight: 700;
}
form fieldset p {
margin: 0;
padding: 0 1em 1.25em 1em;
}
form fieldset p label {
display: block;
font-weight: 700;
}
form fieldset p span:first-child {
font-weight: 700;
}
form fieldset p span.desc {
display: block;
font-weight: 200;
font-size: 0.8em;
margin-bottom: 0.25em;
}
input#install_db + label {
display: inline;
}
form fieldset ul li {
margin: 1em 0 0;
}
form fieldset ul li p {
padding: 0;
}
form fieldset ul li pre {
border-left: 2px solid #dedede;
padding-left: 1em;
margin-left: -1em;
width: 540px;
}
fieldset#mysql-config, fieldset#nodejs-config, p#please-install-db {
display: none;
}
form h3 {
font-size: 2em;
margin: 0 0 0.5em;
}
p#install {
text-align: right;
width: 600px;
margin: 0 0 3em;
}
p#install input {
font-size: 2em;
}
/* [end] Install form */
/* [begin] Footer */
p#footer {
font-size: 1.2em;
color: #666;
margin-left: 8.307em;
}
p#footer a {
color: #777;
}
p#footer a:visited {
color: #666;
}
/* [end] Footer */
</style>
<script type="text/javascript">
$(function() {
$('#server, #db').click();
$('#cookie_length, #session_length').change(function() {
if(parseFloat($('#session_length').val()) < parseFloat($('#cookie_length').val())) {
$('#session_length').val($('#cookie_length').val());
}
}).keypress();
});
</script>
</head>
<body>
<div class="upper">
<div id="header">
<h1>Ajax IM</h1>
<h2>instant messaging framework</h2>
</div>
</div>
<?php
function is_configphp_writable() {
return is_writable('config.php');
}
function is_configjs_writable() {
return is_writable('node/config.js');
}
// file_array() by Jamon Holmgren. Exclude files by putting them in the $exclude
// string separated by pipes. Returns an array with filenames as strings.
function file_array($path, $exclude = ".|..", $recursive = false) {
$path = rtrim($path, "/") . "/";
$folder_handle = opendir($path);
$exclude_array = explode("|", $exclude);
$result = array();
while(false !== ($filename = readdir($folder_handle))) {
if(!in_array(strtolower($filename), $exclude_array)) {
if(is_dir($path . $filename . "/")) {
if($recursive) $result[] = file_array($path, $exclude, true);
} else {
$result[] = $filename;
}
}
}
return $result;
}
function library_array($path, $exclude, $recursive = false) {
$files = file_array($path, $exclude, $recursive);
$libs = array();
foreach($files as $f) {
$library_src = preg_replace('/[\n\r]+/', "\n", file_get_contents(rtrim($path, "/") . "/" . $f));
preg_match('/^<' . '\?php[^\/]*\/\*(.+?)\*\//sm', $library_src, $library_header);
$header_data = array(
'Library' => $f,
'Author' => 'Unknown',
'Version' => '1.0',
'Date' => '',
'Description' => '',
'Requirements' => array()
);
if(strlen($library_header[1])) {
$header_keys = array('Library', 'Author', 'Version', 'Date', 'Description', 'Requirements');
$header_lines = explode("\n", $library_header[1]);
$last_key = false;
foreach($header_lines as $ln) {
$ln_kv = explode(':', substr($ln, 3), 2);
$key = ucwords(strtolower($ln_kv[0]));
if(in_array($key, $header_keys)) {
$header_data[$ln_kv[0]] = trim($ln_kv[1]);
$last_key = $key;
} else if($last_key && strlen(trim($ln)) > 0) {
$header_data[$last_key] .= substr($ln, 3) . ' ';
}
}
if(strlen($header_data['Requirements'])) {
$reqs = explode(',', $header_data['Requirements']);
foreach($reqs as &$req) $req = trim($req);
$header_data['Requirements'] = $reqs;
}
}
$libs[$f] = $header_data;
}
return $libs;
}
function get_available_servers() {
return library_array('./server', '.|..|base.php');
}
function get_available_db_engines() {
return library_array('./db', '.|..|base.php');
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$configphp = file_get_contents('config.php');
// Replace the server type
$configphp = preg_replace("/define\('(IM_LIBRARY)', '[^']+?'\);/", "define('$1', '" . str_replace('.php', '', $_POST['server']) . "');", $configphp);
// Replace the database type
$configphp = preg_replace("/define\('(DB_ENGINE)', '[^']+?'\);/", "define('$1', '" . str_replace('.php', '', $_POST['db']) . "');", $configphp);
// Replace the cookie name
$configphp = preg_replace("/define\('(COOKIE_NAME)', '[^']+?'\);/", "define('$1', '" . $_POST['cookie'] . "');", $configphp);
// Replace the cookie storage length
$configphp = preg_replace("/define\('(COOKIE_PERIOD)', [^)]+?\);/", "define('$1', '" . $_POST['cookie_length'] . "');", $configphp);
// Replace the MySQL information
$configphp = preg_replace("/define\('(MYSQL_DATABASE)', '[^']+?'\);/", "define('$1', '" . $_POST['mysqldb'] . "');", $configphp);
$configphp = preg_replace("/define\('(MYSQL_HOSTNAME)', '[^']+?'\);/", "define('$1', '" . $_POST['mysqlhost'] . "');", $configphp);
$configphp = preg_replace("/define\('(MYSQL_USERNAME)', '[^']+?'\);/", "define('$1', '" . $_POST['mysqluser'] . "');", $configphp);
$configphp = preg_replace("/define\('(MYSQL_PASSWORD)', '[^']+?'\);/", "define('$1', '" . $_POST['mysqlpass'] . "');", $configphp);
$configphp = preg_replace("/define\('(MYSQL_PREFIX)', '[^']+?'\);/", "define('$1', '" . $_POST['mysqlprefix'] . "');", $configphp);
$imjs = file_get_contents('js/im.js');
// Add an Ajax IM init call to im.js
$imjs_init = "\nAjaxIM.init({
cookieName: '" . $_POST['cookie'] . "',
pollType: 'long',
pollServer: '" . rtrim($_POST['url'], '/') . "/server.php'
}";
if(intval($_POST['needs_nodejs']) == 1) {
$configjs = preg_replace("/[\r\n]+/", "\n", file_get_contents('node/config.js'));
// Replace the cookie name
$configjs = preg_replace("/(name: )'[^']+?',/", "$1'" . $_POST['cookie'] . "',", $configjs);
// Replace the session period
$configjs = preg_replace("/(period: )\d{1,6}/", "period: " . round(floatval($_POST['session_length']) * 24), $configjs);
// Replace the host and port numbers
$public_host = strlen(trim($_POST['public_host'])) ? "'" . trim($_POST['public_host']) . "'" : "null";
$private_host = strlen(trim($_POST['private_host'])) ? "'" . trim($_POST['private_host']) . "'" : "null";
$configjs = preg_replace("/(public: )\[8000, 'localhost'\],/", "$1[" . $_POST['public_port'] . ", " . $public_host . "],", $configjs);
$configjs = preg_replace("/(private: )\[11998, 'localhost'\]/", "$1[" . $_POST['private_port'] . ", " . $private_host . "],", $configjs);
$cjs = fopen('node/config.js', 'w');
fwrite($cjs, $configjs);
fclose($cjs);
$configphp = preg_replace('/(\$nodejs_memcache_server = array)\(\'[^\']+\', [^)]+\);/', "$1('" . ($private_host == 'null' ? 'localhost' : $_POST['private_host']) . "', " . $_POST['private_port'] . ");", $configphp);
if(!strlen(trim($_POST['public_host']))) {
$url = parse_url($_POST['url']);
$_POST['public_host'] = $url['host'];
}
$node_url = "http://" . $_POST['public_host'] . ":" . $_POST['public_port'];
$imjs_init .= ", {
poll: '" . $node_url . "/poll',
send: '" . $node_url . "/send',
status: '" . $node_url . "/status',
resume: '" . $node_url . "/resume',
}";
} else {
$imjs_init .= ", {}";
}
$imjs_init .= ");";
$imjs = fopen('js/im.js', 'a');
fwrite($imjs, $imjs_init);
fclose($imjs);
$cphp = fopen('config.php', 'w');
fwrite($cphp, $configphp);
fclose($cphp);
if(isset($_POST['install_db'])) {
// Get DB src from file, run against database
$db_library_src = preg_replace("/[\r\n]+/", "\n", file_get_contents('db/MySQL.php'));
preg_match('/\/\*\s+SQL:(.+?)\*\//sm', $db_library_src, $db_sql);
$db_sql = explode(';', str_replace("\n", '', $db_sql[1]));
$sql = new PDO('mysql:dbname=' . $_POST['mysqldb'] . ';host=' . $_POST['mysqlhost'], $_POST['mysqluser'], $_POST['mysqlpass']);
foreach($db_sql as $statement) {
$sql->exec(str_replace('ajaxim_', $_POST['mysqlprefix'], $statement));
}
}
?>
<form method="post">
<h3>Installation</h3>
<fieldset>
<legend>Installation has completed successfully!</legend>
<ul>
<li>For security purposes, please delete <code>install.php</code>.</li>
<li>Some initialization code has been added to <code>js/im.js</code>; please confirm that the URLs generated for the code are correct.</li>
<?php if(!$_POST['need_nodejs'] == 1): ?>
<li>
<p>To get the standalone Node.js server running, you will need to run the following command on the command line:</p>
<pre>node node/server.js</pre>
<p>However, it is recommended that you move the <code>node</code> folder outside of the main installation directory before going live.</p>
</li>
<?php endif; ?>
<li>
<p>To get the messenger running on your website, copy and paste the following code into the <code>&lt;head&gt;&lt;/head&gt;</code> section of your website.</p>
<pre>
&lt;script type="text/javascript" src="js/jquery-1.3.2.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="js/jquery.jsonp-1.1.0.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="js/jquery.jstore-all-min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="js/jquery.md5.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="js/im.js"&gt;&lt;/script&gt;</pre>
</li>
</ul>
</fieldset>
</form>
<?php
} else {
?>
<form method="post">
<h3>Installation</h3>
<p>For assistance, please see the <a href="http://ajaxim.com/installation">installation tutorial</a>.</p>
<fieldset>
<legend>Basic Configuration</legend>
<p>
<span>Is <code>config.php</code> writable?</span>
<?php if(is_configphp_writable()): ?>
<span class="writable">Yes.</span>
<?php else: ?>
<span class="problem"><strong>No.</strong> Please change the permissions of <code>config.php</code> to "writable" or 755 (on Unix-based systems) before continuing!</span>
<?php endif; ?>
</p>
<p>
<span>Is <code>js/im.js</code> writable?</span>
<?php if(is_configphp_writable()): ?>
<span class="writable">Yes.</span>
<?php else: ?>
<span class="problem"><strong>No.</strong> Please change the permissions of <code>js/im.js</code> to "writable" or 755 (on Unix-based systems) before continuing!</span>
<?php endif; ?>
</p>
<p>
<label for="url">What is the URL of the installation?</label>
<input type="text" size="50" name="url" id="url" value="<?php print ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['SERVER_NAME'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']); ?>">
</p>
<p>
<label for="server">Please select a server type.</label>
<select name="server" id="server">
<?php $servers = get_available_servers();
foreach($servers as $file => $server):
?>
<option value="<?php print $file; ?>"><?php print $server['Library'] . ' &mdash; ' . $server['Version']; ?> (by <?php print $server['Author']; ?>)</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="needs_nodejs" id="needs_nodejs" value="0">
<script type="text/javascript">
var servers = <?php print json_encode($servers); ?>;
servers['None'] = {Description: 'None', Requirements: ['None']};
var selected_server = servers['None'];
$('#server').live('click', function(e) {
if(!(server = $('#server').val()))
server = 'None';
$('#server-select .description').text(servers[server].Description);
$('#server-select .requirements').text(servers[server].Requirements.join(', '));
selected_server = servers[server];
});
</script>
</p>
<p id="server-select">
<em>Description:</em> <span class="description">None</span><br>
<em>Requirements:</em> <span class="requirements">None</span>
</p>
<p>
<label for="db">If you will be using a database engine, please select one.</label>
<select name="db" id="db">
<option value="">No database engine selected</option>
<?php $dbs = get_available_db_engines();
foreach($dbs as $file => $db):
?>
<option value="<?php print $file; ?>"><?php print $db['Library'] . ' &mdash; ' . $db['Version']; ?> (by <?php print $db['Author']; ?>)</option>
<?php endforeach; ?>
</select>
<script type="text/javascript">
var db_engines = <?php print json_encode($dbs); ?>;
var engine = 'None';
db_engines['None'] = {Description: 'None', Requirements: ['None']};
$('#db').live('click', function(e) {
if(!(engine = $('#db').val()))
engine = 'None';
$('#db-select .description').text(db_engines[engine].Description);
$('#db-select .requirements').text(db_engines[engine].Requirements.join(', '));
});
$('#db, #server').live('click', function() {
if(engine == 'MySQL.php' && $.inArray('Database', selected_server.Requirements) != -1) {
$('#please-install-db').fadeIn();
$('#mysql-config').slideDown();
} else {
$('#please-install-db').fadeOut();
$('#mysql-config').slideUp();
}
if($.inArray('Node.js', selected_server.Requirements) != -1) {
$('#nodejs-config').slideDown();
$('#needs_nodejs').val('1');
} else {
$('#nodejs-config').slideUp();
$('#needs_nodejs').val('0');
}
});
</script>
</p>
<p id="db-select">
<em>Description:</em> <span class="description">None</span><br>
<em>Requirements:</em> <span class="requirements">None</span>
</p>
<p id="please-install-db">
<input type="checkbox" name="install_db" id="install_db" value="yes" checked="checked">
<label for="install_db">Please install the database for me.</label>
</p>
<p>
<label for="cookie">Cookie name</label>
<span class="desc">Ajax IM uses a cookie to keep track of the authenticated user's session. You can set the cookie name and session storage length.</span>
<input type="text" name="cookie" id="cookie" value="ajaxim_session">
</p>
<p>
<label for="cookie_length">Cookie storage length</label>
<span class="desc">The number of days for which to store the cookie. Setting it to 0 makes it a session cookie (deleted when the browser is closed). If Ajax IM is integrated with another authentication system, this cookie should be kept as long or longer than that cookie.</span>
<input type="text" maxlength="4" size="4" name="cookie_length" id="cookie_length" value="365"> days
</p>
</fieldset>
<fieldset id="mysql-config">
<legend>MySQL Configuration</legend>
<p>
<label for="mysqldb">Database</label>
<input type="text" name="mysqldb" id="mysqldb">
</p>
<p>
<label for="mysqlhost">Hostname</label>
<span class="desc">Note: Usually, you will not need to change this value.</span>
<input type="text" name="mysqlhost" id="mysqlhost" value="localhost">
</p>
<p>
<label for="mysqluser">Username</label>
<input type="text" name="mysqluser" id="mysqluser">
</p>
<p>
<label for="mysqlpass">Password</label>
<input type="text" name="mysqlpass" id="mysqlpass">
</p>
<p>
<label for="mysqluser">Table Prefix</label>
<input type="text" name="mysqlprefix" id="mysqlprefix" value="ajaxim_">
</p>
</fieldset>
<fieldset id="nodejs-config">
<legend>Standalone (Node.js) Server Configuration</legend>
<p>After configuration is complete, please see the <a href="http://ajaxim.com/installation">installation tutorial</a> to complete the standalone server setup.</p>
<p>
<span>Is <code>node/config.js</code> writable?</span>
<?php if(is_configjs_writable()): ?>
<span class="writable">Yes.</span>
<?php else: ?>
<span class="problem"><strong>No.</strong> Please change the permissions of <code>node/config.js</code> to "writable" or 755 (on Unix-based systems) before continuing!</span>
<?php endif; ?>
</p>
<p>
<label for="public_port">Public host and port</label>
<span class="desc">Host is optional; set to blank for none. This is the port number that the client will use to communicate with the server.</span>
<input type="text" size="15" name="public_host" id="public_host" value="localhost"> :
<input type="text" maxlength="5" size="5" name="public_port" id="public_port" value="31411">
</p>
<p>
<label for="public_port">Private (API) host and port</label>
<span class="desc">Host is optional; set to blank for none. This is the port number that the <code>server.php</code> script will use, as well as the port you will use for the <a href="http://ajaxim.com/documentation/api">Memcache-based API</a>.</span>
<input type="text" size="15" name="private_host" id="private_host" value="localhost"> :
<input type="text" maxlength="5" size="5" name="private_port" id="private_port" value="11211">
</p>
<p>
<label for="session_length">Session storage length</label>
<span class="desc">The number of days for which to store the session &mdash; which is different than the cookie. The cookie holds on to the session identifier, but if the session doesn't exist any longer, the cookie is useless. Therefore, the session needs to be kept as long, or longer, than the cookie. Minimum 0.042 days (approx. one hour).</span>
<input type="text" maxlength="4" size="4" name="session_length" id="session_length" value="365"> days
</p>
</fieldset>
<p id="install"><input type="submit" value="Install" name="install"></p>
</form>
<? } ?>
<p id="footer"><a href="http://ajaxim.com">Ajax IM</a> is copyright &copy; 2005&thinsp;&ndash;&thinsp;2010, <a href="http://unwieldy.net">Joshua Gross</a></p></p>
</body>
</html>
+1
Ver Arquivo
Diff do arquivo suprimido porque uma ou mais linhas são muito longas
+69
Ver Arquivo
@@ -0,0 +1,69 @@
// Automatically load dependencies, in order, if they aren't already loaded.
// Each array is: [filename, deptest] where deptest is the function to
// test for the dependency.
(function() {
var tagsrc =
(thistag = document.getElementsByTagName('script'))[thistag.length-1].src;
var jsfolder = tagsrc.replace(/im.load.js([?].+)?/, '');
var imfolder = jsfolder.replace(/js\/$/, '');
var dependencies = [
['jquery-1.3.2.js', function() { return (typeof window['jQuery'] != 'undefined'); }],
['jquery.jsonp-1.1.0.js', function() { return (typeof jQuery['jsonp'] != 'undefined'); }],
['jquery.jstore-all-min.js', function() { return (typeof jQuery['jstore'] != 'undefined'); }],
['jquery.md5.js', function() { return (typeof jQuery['md5'] != 'undefined'); }],
['im.js', function() { return (typeof window['AjaxIM'] != 'undefined'); }]
];
var head = document.getElementsByTagName('head')[0];
(loadDep = function(depPos) {
if(depPos >= dependencies.length) { init(); return; }
var dep = dependencies[depPos];
if(!dep[1]()) {
var newdep = document.createElement('script');
newdep.type = 'text/javascript';
newdep.src = jsfolder + dep[0];
var nextdep = function() { loadDep(depPos + 1); };
newdep.onload = nextdep;
newdep.onreadystatechange = nextdep;
head.appendChild(newdep);
} else loadDep(depPos + 1);
})(0);
var init = function() {
if(tagsrc.match(/[?]php$/)) {
AjaxIM.init({
pollServer: imfolder + 'ajaxim.php',
theme: imfolder + 'themes/default',
flashStorage: jsfolder + 'jStore.Flash.html'
});
} else if(tagsrc.match(/[?]node$/)) {
AjaxIM.init({
pollServer: imfolder + 'ajaxim.php',
theme: imfolder + 'themes/default',
flashStorage: jsfolder + 'jStore.Flash.html'
}, {
poll: 'http://localhost:8000/poll',
send: 'http://localhost:8000/send',
status: 'http://localhost:8000/status',
resume: 'http://localhost:8000/resume'
});
} else if(tagsrc.match(/[?]guest$/)) {
AjaxIM.init({
pollServer: imfolder + 'ajaxim.php',
theme: imfolder + 'themes/default',
flashStorage: jsfolder + 'jStore.Flash.html'
}, {
poll: 'http://localhost:8000/poll',
send: 'http://localhost:8000/send',
status: 'http://localhost:8000/status',
resume: 'http://localhost:8000/resume'
});
AjaxIM.client.login();
}
};
})();
+19
Ver Arquivo
@@ -0,0 +1,19 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Flash External Object</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/**
* This function captures the flash_ready event. We need to relay this
* back to the parent so it knows flash is ready.
*/
function flash_ready(){
parent.flash_ready();
}
</script>
</head>
<body>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="1" height="1" id="jStoreFlash"><param name="allowScriptAccess" value="always" /><param name="movie" value="jStore.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffcc00" /><embed src="jStore.swf" quality="high" bgcolor="#ffcc00" width="1" height="1" name="jStoreFlash" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>
</body>
</html>
BIN
Ver Arquivo
Arquivo binário não exibido.
+19
Ver Arquivo
Diff do arquivo suprimido porque uma ou mais linhas são muito longas
+269
Ver Arquivo
@@ -0,0 +1,269 @@
/*
* jQuery JSONP Core Plugin 1.1.0 (2009-10-06)
*
* http://code.google.com/p/jquery-jsonp/
*
* Copyright (c) 2009 Julian Aubourg
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($){
// ###################### UTILITIES ##
// Test a value is neither undefined nor null
var defined = function(v) {
return v!==undefined && v!==null;
},
// Call if defined
callIfDefined = function(method,object,parameters) {
defined(method) && method.apply(object,parameters);
},
// Let the current thread running
later = function(functor) {
setTimeout(functor,0);
},
// String constants (for better minification)
empty="",
amp="&",
qMark="?",
success = "success",
error = "error",
// Head element (for faster use)
head = $("head"),
// Page cache
pageCache = {},
// ###################### DEFAULT OPTIONS ##
xOptionsDefaults = {
//beforeSend: undefined,
//cache: false,
callback: "C",
//callbackParameter: undefined,
//complete: undefined,
//data: ""
//dataFilter: undefined,
//error: undefined,
//pageCache: false,
//success: undefined,
//timeout: 0,
url: location.href
},
// ###################### MAIN FUNCTION ##
jsonp = function(xOptions) {
// Build data with default
xOptions = $.extend({},xOptionsDefaults,xOptions);
// References to beforeSend (for better minification)
var beforeSendCallback = xOptions.beforeSend,
// Abort/done flag
done = 0;
// Put a temporary abort
xOptions.abort = function() { done = 1; };
// Call beforeSend if provided (early abort if false returned)
if (defined(beforeSendCallback) && (beforeSendCallback(xOptions,xOptions)===false || done))
return xOptions;
// References to xOptions members (for better minification)
var successCallback = xOptions.success,
completeCallback = xOptions.complete,
errorCallback = xOptions.error,
dataFilter = xOptions.dataFilter,
callbackParameter = xOptions.callbackParameter,
successCallbackName = xOptions.callback,
cacheFlag = xOptions.cache,
pageCacheFlag = xOptions.pageCache,
url = xOptions.url,
data = xOptions.data,
timeout = xOptions.timeout,
// Misc variables
splitUrl,splitData,i,j;
// Control entries
url = defined(url)?url:empty;
data = defined(data)?((typeof data)=="string"?data:$.param(data)):empty;
// Add callback parameter if provided as option
defined(callbackParameter)
&& (data += (data==empty?empty:amp)+escape(callbackParameter)+"=?");
// Add anticache parameter if needed
!cacheFlag && !pageCacheFlag
&& (data += (data==empty?empty:amp)+"_"+(new Date()).getTime()+"=");
// Search for ? in url
splitUrl = url.split(qMark);
// Also in parameters if provided
// (and merge arrays)
if (data!=empty) {
splitData = data.split(qMark);
j = splitUrl.length-1;
j && (splitUrl[j] += amp + splitData.shift());
splitUrl = splitUrl.concat(splitData);
}
// If more than 2 ? replace the last one by the callback
i = splitUrl.length-2;
i && (splitUrl[i] += successCallbackName + splitUrl.pop());
// Build the final url
var finalUrl = splitUrl.join(qMark),
// Utility function
notifySuccess = function(json) {
// Apply the data filter if provided
defined(dataFilter) && (json = dataFilter.apply(xOptions,[json]));
// Call success then complete
callIfDefined(successCallback,xOptions,[json,success]);
callIfDefined(completeCallback,xOptions,[xOptions,success]);
},
notifyError = function(type) {
// Call error then complete
callIfDefined(errorCallback,xOptions,[xOptions,type]);
callIfDefined(completeCallback,xOptions,[xOptions,type]);
},
// Get from pageCache
pageCached = pageCache[finalUrl];
// Check page cache
if (pageCacheFlag && defined(pageCached)) {
later(function() {
// If an error was cached
defined(pageCached.s)
? notifySuccess(pageCached.s)
: notifyError(error);
});
return xOptions;
}
// Create & write to the iframe (sends the request)
// We let the hand to current code to avoid
// pre-emptive callbacks
// We also install the timeout here to avoid
// timeout before the code has been dumped to the frame
// (in case of insanely short timeout values)
later(function() {
// If it has been aborted, do nothing
if (done) return;
// Create an iframe & add it to the document
var frame = $("<iframe />").appendTo(head),
// Get the iframe's window and document objects
tmp = frame[0],
window = tmp.contentWindow || tmp.contentDocument,
document = window.document,
// Declaration of cleanup function
cleanUp,
// Declaration of timer for timeout (so we can clear it eventually)
timeoutTimer,
// Error function
errorFunction = function (_,type) {
// If pure error (not timeout), cache if needed
pageCacheFlag && !defined(type) && (pageCache[finalUrl] = empty);
// Cleanup
cleanUp();
// Call error then complete
notifyError(defined(type)?type:error);
},
// Iframe variable cleaning function
removeVariable = function(varName) {
window[varName] = undefined;
try { delete window[varName]; } catch(_) {}
},
// Error callback name
errorCallbackName = successCallbackName=="E"?"X":"E";
// Control if we actually retrieved the document
if(!defined(document)) {
document = window;
window = document.getParentNode();
}
// We have to open the document before
// declaring variables in the iframe's window
// Don't ask me why, I have no clue
document.open();
// Install callbacks
window[successCallbackName] = function(json) {
// Set as treated
done = 1;
// Pagecache is needed
pageCacheFlag && (pageCache[finalUrl] = {s: json});
// Give hand back to frame
// To finish gracefully
later(function(){
// Cleanup
cleanUp();
// Call success then complete
notifySuccess(json);
});
};
window[errorCallbackName] = function(state) {
// If not treated, mark
// then give hand back to iframe
// for it to finish gracefully
(!state || state=="complete") && !done++ && later(errorFunction);
};
// Clean up function (declaration)
xOptions.abort = cleanUp = function() {
// Clear the timeout (is it exists)
clearTimeout(timeoutTimer);
// Open the iframes document & clean
document.open();
removeVariable(errorCallbackName);
removeVariable(successCallbackName);
document.write(empty);
document.close();
frame.remove();
};
// Write to the document
document.write([
'<html><head><script src="',
finalUrl,'" onload="',
errorCallbackName,'()" onreadystatechange="',
errorCallbackName,'(this.readyState)"></script></head><body onload="',
errorCallbackName,'()"></body></html>'
].join(empty)
);
// Close (makes some browsers happier)
document.close();
// If a timeout is needed, install it
timeout>0 && (timeoutTimer = setTimeout(function(){
!done && errorFunction(empty,"timeout");
},timeout));
});
return xOptions;
}
// ###################### SETUP FUNCTION ##
jsonp.setup = function(xOptions) {
$.extend(xOptionsDefaults,xOptions);
};
// ###################### INSTALL in jQuery ##
$.jsonp = jsonp;
})(jQuery);
+56
Ver Arquivo
@@ -0,0 +1,56 @@
/*
* jStore - Persistent Client-Side Storage
*
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*
* Dual licensed under:
* MIT: http://www.opensource.org/licenses/mit-license.php
* GPLv3: http://www.opensource.org/licenses/gpl-3.0.html
*/
/*
* jQuery JSON Plugin
* version: 1.0 (2008-04-17)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Brantley Harris technically wrote this plugin, but it is based somewhat
* on the JSON.org website's http://www.json.org/json2.js, which proclaims:
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
* I uphold. I really just cleaned it up.
*
* It is also based heavily on MochiKit's serializeJSON, which is
* copywrited 2005 by Bob Ippolito.
*/
(function($){function toIntegersAtLease(n){return n<10?"0"+n:n}Date.prototype.toJSON=function(date){return this.getUTCFullYear()+"-"+toIntegersAtLease(this.getUTCMonth())+"-"+toIntegersAtLease(this.getUTCDate())};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};$.quoteString=function(string){if(escapeable.test(string)){return'"'+string.replace(escapeable,function(a){var c=meta[a];if(typeof c==="string"){return c}c=a.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"'}return'"'+string+'"'};$.toJSON=function(o,compact){var type=typeof(o);if(type=="undefined"){return"undefined"}else{if(type=="number"||type=="boolean"){return o+""}else{if(o===null){return"null"}}}if(type=="string"){return $.quoteString(o)}if(type=="object"&&typeof o.toJSON=="function"){return o.toJSON(compact)}if(type!="function"&&typeof(o.length)=="number"){var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact))}if(compact){return"["+ret.join(",")+"]"}else{return"["+ret.join(", ")+"]"}}if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.")}var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number"){name='"'+k+'"'}else{if(type=="string"){name=$.quoteString(k)}else{continue}}var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue}if(compact){ret.push(name+":"+val)}else{ret.push(name+": "+val)}}return"{"+ret.join(", ")+"}"};$.compactJSON=function(o){return $.toJSON(o,true)};$.evalJSON=function(src){return eval("("+src+")")};$.secureEvalJSON=function(src){var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,"@");filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]");filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,"");if(/^[\],:{}\s]*$/.test(filtered)){return eval("("+src+")")}else{throw new SyntaxError("Error parsing JSON, source is not valid.")}}})(jQuery);(function(){var a=false,b=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(g){var f=this.prototype;a=true;var e=new this();a=false;for(var d in g){e[d]=typeof g[d]=="function"&&typeof f[d]=="function"&&b.test(g[d])?(function(h,i){return function(){var k=this._super;this._super=f[h];var j=i.apply(this,arguments);this._super=k;return j}})(d,g[d]):g[d]}function c(){if(!a&&this.init){this.init.apply(this,arguments)}}c.prototype=e;c.constructor=c;c.extend=arguments.callee;return c}})();
/*
* jStore Delegate Framework
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function(a){this.jStoreDelegate=Class.extend({init:function(b){this.parent=b;this.callbacks={}},bind:function(b,c){if(!a.isFunction(c)){return this}if(!this.callbacks[b]){this.callbacks[b]=[]}this.callbacks[b].push(c);return this},trigger:function(){var d=this.parent,c=[].slice.call(arguments),e=c.shift(),b=this.callbacks[e];if(!b){return false}a.each(b,function(){this.apply(d,c)});return this}})})(jQuery);(function(b){var a;try{a=new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$')}catch(c){a=/^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/}b.jStore={};b.extend(b.jStore,{EngineOrder:[],Availability:{},Engines:{},Instances:{},CurrentEngine:null,defaults:{project:null,engine:null,autoload:true,flash:"jStore.Flash.html"},isReady:false,isFlashReady:false,delegate:new jStoreDelegate(b.jStore).bind("jStore-ready",function(d){b.jStore.isReady=true;if(b.jStore.defaults.autoload){d.connect()}}).bind("flash-ready",function(){b.jStore.isFlashReady=true}),ready:function(d){if(b.jStore.isReady){d.apply(b.jStore,[b.jStore.CurrentEngine])}else{b.jStore.delegate.bind("jStore-ready",d)}},fail:function(d){b.jStore.delegate.bind("jStore-failure",d)},flashReady:function(d){if(b.jStore.isFlashReady){d.apply(b.jStore,[b.jStore.CurrentEngine])}else{b.jStore.delegate.bind("flash-ready",d)}},use:function(g,i,f){i=i||b.jStore.defaults.project||location.hostname.replace(/\./g,"-")||"unknown";var h=b.jStore.Engines[g.toLowerCase()]||null,d=(f?f+".":"")+i+"."+g;if(!h){throw"JSTORE_ENGINE_UNDEFINED"}h=new h(i,d);if(b.jStore.Instances[d]){throw"JSTORE_JRI_CONFLICT"}if(h.isAvailable()){b.jStore.Instances[d]=h;if(!b.jStore.CurrentEngine){b.jStore.CurrentEngine=h}b.jStore.delegate.trigger("jStore-ready",h)}else{if(!h.autoload){throw"JSTORE_ENGINE_UNAVILABLE"}else{h.included(function(){if(this.isAvailable()){b.jStore.Instances[d]=this;if(!b.jStore.CurrentEngine){b.jStore.CurrentEngine=this}b.jStore.delegate.trigger("jStore-ready",this)}else{b.jStore.delegate.trigger("jStore-failure",this)}}).include()}}},setCurrentEngine:function(d){if(!b.jStore.Instances.length){return b.jStore.FindEngine()}if(!d&&b.jStore.Instances.length>=1){b.jStore.delegate.trigger("jStore-ready",b.jStore.Instances[0]);return b.jStore.CurrentEngine=b.jStore.Instances[0]}if(d&&b.jStore.Instances[d]){b.jStore.delegate.trigger("jStore-ready",b.jStore.Instances[d]);return b.jStore.CurrentEngine=b.jStore.Instances[d]}throw"JSTORE_JRI_NO_MATCH"},FindEngine:function(){b.each(b.jStore.EngineOrder,function(d){if(b.jStore.Availability[this]()){b.jStore.use(this,b.jStore.defaults.project,"default");return false}})},load:function(){if(b.jStore.defaults.engine){return b.jStore.use(b.jStore.defaults.engine,b.jStore.defaults.project,"default")}try{b.jStore.FindEngine()}catch(d){}},safeStore:function(d){switch(typeof d){case"object":case"function":return b.compactJSON(d);case"number":case"boolean":case"string":case"xml":return d;case"undefined":default:return""}},safeResurrect:function(d){return a.test(d)?b.evalJSON(d):d},store:function(d,e){if(!b.jStore.CurrentEngine){return false}if(!e){return b.jStore.CurrentEngine.get(d)}return b.jStore.CurrentEngine.set(d,e)},remove:function(d){if(!b.jStore.CurrentEngine){return false}return b.jStore.CurrentEngine.rem(d)},get:function(d){return b.jStore.store(d)},set:function(d,e){return b.jStore.store(d,e)}});b.extend(b.fn,{store:function(e,f){if(!b.jStore.CurrentEngine){return this}var d=b.jStore.store(e,f);return !f?d:this},removeStore:function(d){b.jStore.remove(d);return this},getStore:function(d){return b.jStore.store(d)},setStore:function(d,e){b.jStore.store(d,e);return this}})})(jQuery);(function(a){this.StorageEngine=Class.extend({init:function(c,b){this.project=c;this.jri=b;this.data={};this.limit=-1;this.includes=[];this.delegate=new jStoreDelegate(this).bind("engine-ready",function(){this.isReady=true}).bind("engine-included",function(){this.hasIncluded=true});this.autoload=false;this.isReady=false;this.hasIncluded=false},include:function(){var b=this,d=this.includes.length,c=0;a.each(this.includes,function(){a.ajax({type:"get",url:this,dataType:"script",cache:true,success:function(){c++;if(c==d){b.delegate.trigger("engine-included")}}})})},isAvailable:function(){return false},interruptAccess:function(){if(!this.isReady){throw"JSTORE_ENGINE_NOT_READY"}},ready:function(b){if(this.isReady){b.apply(this)}else{this.delegate.bind("engine-ready",b)}return this},included:function(b){if(this.hasIncluded){b.apply(this)}else{this.delegate.bind("engine-included",b)}return this},get:function(b){this.interruptAccess();return this.data[b]||null},set:function(b,c){this.interruptAccess();this.data[b]=c;return c},rem:function(b){this.interruptAccess();var c=this.data[b];this.data[b]=null;return c}})})(jQuery);
/*
* jStore DOM Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function(c){var b=c.jStore.Availability.session=function(){return !!window.sessionStorage},a=c.jStore.Availability.local=function(){return !!(window.localStorage||window.globalStorage)};this.jStoreDom=StorageEngine.extend({init:function(e,d){this._super(e,d);this.type="DOM";this.limit=5*1024*1024},connect:function(){this.delegate.trigger("engine-ready")},get:function(e){this.interruptAccess();var d=this.db.getItem(e);return c.jStore.safeResurrect((d&&d.value?d.value:d))},set:function(d,e){this.interruptAccess();this.db.setItem(d,c.jStore.safeStore(e));return e},rem:function(e){this.interruptAccess();var d=this.get(e);this.db.removeItem(e);return d}});this.jStoreLocal=jStoreDom.extend({connect:function(){this.db=!window.globalStorage?window.localStorage:window.globalStorage[location.hostname];this._super()},isAvailable:a});this.jStoreSession=jStoreDom.extend({connect:function(){this.db=sessionStorage;this._super()},isAvailable:b});c.jStore.Engines.local=jStoreLocal;c.jStore.Engines.session=jStoreSession;c.jStore.EngineOrder[1]="local"})(jQuery);
/*
* jStore Flash Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
* jStore.swf Copyright (c) 2008 Daniel Bulli (http://www.nuff-respec.com)
*/
(function(b){var a=b.jStore.Availability.flash=function(){return !!(b.jStore.hasFlash("8.0.0"))};this.jStoreFlash=StorageEngine.extend({init:function(e,d){this._super(e,d);this.type="Flash";var c=this;b.jStore.flashReady(function(){c.flashReady()})},connect:function(){var c="jstore-flash-embed-"+this.project;b(document.body).append('<iframe style="height:1px;width:1px;position:absolute;left:0;top:0;margin-left:-100px;" id="jStoreFlashFrame" src="'+b.jStore.defaults.flash+'"></iframe>')},flashReady:function(f){var c=b("#jStoreFlashFrame")[0];if(c.Document&&b.isFunction(c.Document.jStoreFlash.f_get_cookie)){this.db=c.Document.jStoreFlash}else{if(c.contentWindow&&c.contentWindow.document){var d=c.contentWindow.document;if(b.isFunction(b("object",b(d))[0].f_get_cookie)){this.db=b("object",b(d))[0]}else{if(b.isFunction(b("embed",b(d))[0].f_get_cookie)){this.db=b("embed",b(d))[0]}}}}if(this.db){this.delegate.trigger("engine-ready")}},isAvailable:a,get:function(d){this.interruptAccess();var c=this.db.f_get_cookie(d);return c=="null"?null:b.jStore.safeResurrect(c)},set:function(c,d){this.interruptAccess();this.db.f_set_cookie(c,b.jStore.safeStore(d));return d},rem:function(c){this.interruptAccess();var d=this.get(c);this.db.f_delete_cookie(c);return d}});b.jStore.Engines.flash=jStoreFlash;b.jStore.EngineOrder[2]="flash";b.jStore.hasFlash=function(c){var e=b.jStore.flashVersion().match(/\d+/g),f=c.match(/\d+/g);for(var d=0;d<3;d++){e[d]=parseInt(e[d]||0);f[d]=parseInt(f[d]||0);if(e[d]<f[d]){return false}if(e[d]>f[d]){return true}}return true};b.jStore.flashVersion=function(){try{try{var c=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");try{c.AllowScriptAccess="always"}catch(d){return"6,0,0"}}catch(d){}return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version").replace(/\D+/g,",").match(/^,?(.+),?$/)[1]}catch(d){try{if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){return(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g,",").match(/^,?(.+),?$/)[1]}}catch(d){}}return"0,0,0"}})(jQuery);function flash_ready(){$.jStore.delegate.trigger("flash-ready")}
/*
* jStore Google Gears Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function(b){var a=b.jStore.Availability.gears=function(){return !!(window.google&&window.google.gears)};this.jStoreGears=StorageEngine.extend({init:function(d,c){this._super(d,c);this.type="Google Gears";this.includes.push("http://code.google.com/apis/gears/gears_init.js");this.autoload=true},connect:function(){var c=this.db=google.gears.factory.create("beta.database");c.open("jstore-"+this.project);c.execute("CREATE TABLE IF NOT EXISTS jstore (k TEXT UNIQUE NOT NULL PRIMARY KEY, v TEXT NOT NULL)");this.updateCache()},updateCache:function(){var c=this.db.execute("SELECT k,v FROM jstore");while(c.isValidRow()){this.data[c.field(0)]=b.jStore.safeResurrect(c.field(1));c.next()}c.close();this.delegate.trigger("engine-ready")},isAvailable:a,set:function(d,e){this.interruptAccess();var c=this.db;c.execute("BEGIN");c.execute("INSERT OR REPLACE INTO jstore(k, v) VALUES (?, ?)",[d,b.jStore.safeStore(e)]);c.execute("COMMIT");return this._super(d,e)},rem:function(d){this.interruptAccess();var c=this.db;c.execute("BEGIN");c.execute("DELETE FROM jstore WHERE k = ?",[d]);c.execute("COMMIT");return this._super(d)}});b.jStore.Engines.gears=jStoreGears;b.jStore.EngineOrder[3]="gears"})(jQuery);
/*
* jStore HTML5 Specification Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function(b){var a=b.jStore.Availability.html5=function(){return !!window.openDatabase};this.jStoreHtml5=StorageEngine.extend({init:function(d,c){this._super(d,c);this.type="HTML5";this.limit=1024*200},connect:function(){var c=this.db=openDatabase("jstore-"+this.project,"1.0",this.project,this.limit);if(!c){throw"JSTORE_ENGINE_HTML5_NODB"}c.transaction(function(d){d.executeSql("CREATE TABLE IF NOT EXISTS jstore (k TEXT UNIQUE NOT NULL PRIMARY KEY, v TEXT NOT NULL)")});this.updateCache()},updateCache:function(){var c=this;this.db.transaction(function(d){d.executeSql("SELECT k,v FROM jstore",[],function(f,e){var h=e.rows,g=0,j;for(;g<h.length;++g){j=h.item(g);c.data[j.k]=b.jStore.safeResurrect(j.v)}c.delegate.trigger("engine-ready")})})},isAvailable:a,set:function(c,d){this.interruptAccess();this.db.transaction(function(e){e.executeSql("INSERT OR REPLACE INTO jstore(k, v) VALUES (?, ?)",[c,b.jStore.safeStore(d)])});return this._super(c,d)},rem:function(c){this.interruptAccess();this.db.transaction(function(d){d.executeSql("DELETE FROM jstore WHERE k = ?",[c])});return this._super(c)}});b.jStore.Engines.html5=jStoreHtml5;b.jStore.EngineOrder[0]="html5"})(jQuery);
/**
* jStore IE Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function(b){var a=b.jStore.Availability.ie=function(){return !!window.ActiveXObject};this.jStoreIE=StorageEngine.extend({init:function(d,c){this._super(d,c);this.type="IE";this.limit=64*1024},connect:function(){this.db=b('<div style="display:none;behavior:url(\'#default#userData\')" id="jstore-'+this.project+'"></div>').appendTo(document.body).get(0);this.delegate.trigger("engine-ready")},isAvailable:a,get:function(c){this.interruptAccess();this.db.load(this.project);return b.jStore.safeResurrect(this.db.getAttribute(c))},set:function(c,d){this.interruptAccess();this.db.setAttribute(c,b.jStore.safeStore(d));this.db.save(this.project);return d},rem:function(c){this.interruptAccess();var d=this.get(c);this.db.removeAttribute(c);this.db.save(this.project);return d}});b.jStore.Engines.ie=jStoreIE;b.jStore.EngineOrder[4]="ie"})(jQuery);
+963
Ver Arquivo
@@ -0,0 +1,963 @@
/*!
* jStore - Persistent Client-Side Storage
*
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*
* Dual licensed under:
* MIT: http://www.opensource.org/licenses/mit-license.php
* GPLv3: http://www.opensource.org/licenses/gpl-3.0.html
*/
/*!
* jQuery JSON Plugin
* version: 1.0 (2008-04-17)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Brantley Harris technically wrote this plugin, but it is based somewhat
* on the JSON.org website's http://www.json.org/json2.js, which proclaims:
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
* I uphold. I really just cleaned it up.
*
* It is also based heavily on MochiKit's serializeJSON, which is
* copywrited 2005 by Bob Ippolito.
*/
(function($) {
function toIntegersAtLease(n)
// Format integers to have at least two digits.
{
return n < 10 ? '0' + n : n;
}
Date.prototype.toJSON = function(date)
// Yes, it polutes the Date namespace, but we'll allow it here, as
// it's damned usefull.
{
return this.getUTCFullYear() + '-' +
toIntegersAtLease(this.getUTCMonth()) + '-' +
toIntegersAtLease(this.getUTCDate());
};
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
$.quoteString = function(string)
// Places quotes around a string, inteligently.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
{
if (escapeable.test(string))
{
return '"' + string.replace(escapeable, function (a)
{
var c = meta[a];
if (typeof c === 'string') {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
$.toJSON = function(o, compact)
{
var type = typeof(o);
if (type == "undefined")
return "undefined";
else if (type == "number" || type == "boolean")
return o + "";
else if (o === null)
return "null";
// Is it a string?
if (type == "string")
{
return $.quoteString(o);
}
// Does it have a .toJSON function?
if (type == "object" && typeof o.toJSON == "function")
return o.toJSON(compact);
// Is it an array?
if (type != "function" && typeof(o.length) == "number")
{
var ret = [];
for (var i = 0; i < o.length; i++) {
ret.push( $.toJSON(o[i], compact) );
}
if (compact)
return "[" + ret.join(",") + "]";
else
return "[" + ret.join(", ") + "]";
}
// If it's a function, we have to warn somebody!
if (type == "function") {
throw new TypeError("Unable to convert object of type 'function' to json.");
}
// It's probably an object, then.
var ret = [];
for (var k in o) {
var name;
type = typeof(k);
if (type == "number")
name = '"' + k + '"';
else if (type == "string")
name = $.quoteString(k);
else
continue; //skip non-string or number keys
var val = $.toJSON(o[k], compact);
if (typeof(val) != "string") {
// skip non-serializable values
continue;
}
if (compact)
ret.push(name + ":" + val);
else
ret.push(name + ": " + val);
}
return "{" + ret.join(", ") + "}";
};
$.compactJSON = function(o)
{
return $.toJSON(o, true);
};
$.evalJSON = function(src)
// Evals JSON that we know to be safe.
{
try {
return eval("(" + src + ")");
} catch(e) {
return src;
}
};
$.secureEvalJSON = function(src)
// Evals JSON in a way that is *more* secure.
{
var filtered = src;
filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
if (/^[\],:{}\s]*$/.test(filtered))
return eval("(" + src + ")");
else
throw new SyntaxError("Error parsing JSON, source is not valid.");
};
})(jQuery);
/**
* Javascript Class Framework
*
* Copyright (c) 2008 John Resig (http://ejohn.org/blog/simple-javascript-inheritance/)
* Inspired by base2 and Prototype
*/
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
/*!
* jStore Delegate Framework
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
this.jStoreDelegate = Class.extend({
init: function(parent){
// The Object this delgate operates for
this.parent = parent;
// Container for callbacks to dispatch.
// eventType => [ callback, callback, ... ]
this.callbacks = {};
},
bind: function(event, callback){
if ( !$.isFunction(callback) ) return this;
if ( !this.callbacks[ event ] ) this.callbacks[ event ] = [];
this.callbacks[ event ].push(callback);
return this;
},
trigger: function(){
var parent = this.parent,
args = [].slice.call(arguments),
event = args.shift(),
handlers = this.callbacks[ event ];
if ( !handlers ) return false;
$.each(handlers, function(){ this.apply(parent, args) });
return this;
}
});
})(jQuery);
/**
* jStore-jQuery Interface
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
var rxJson;
try {
rxJson = new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$')
} catch (e) {
rxJson = /^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/
}
// Setup the jStore namespace in jQuery for options storage
$.jStore = {};
// Seed the object
$.extend($.jStore, {
EngineOrder: [],
// Engines should put their availability tests within jStore.Availability
Availability: {},
// Defined engines should enter themselves into the jStore.Engines
Engines: {},
// Instanciated engines should exist within jStore.Instances
Instances: {},
// The current engine to use for storage
CurrentEngine: null,
// Provide global settings for overwriting
defaults: {
project: null,
engine: null,
autoload: true,
flash: 'jStore.Flash.html'
},
// Boolean for ready state handling
isReady: false,
// Boolean for flash ready state handling
isFlashReady: false,
// An event delegate
delegate: new jStoreDelegate($.jStore)
.bind('jStore-ready', function(engine){
$.jStore.isReady = true;
if ($.jStore.defaults.autoload) engine.connect();
})
.bind('flash-ready', function(){
$.jStore.isFlashReady = true;
}),
// Enable ready callback for jStore
ready: function(callback){
if ($.jStore.isReady) callback.apply($.jStore, [$.jStore.CurrentEngine]);
else $.jStore.delegate.bind('jStore-ready', callback);
},
// Enable failure callback registration for jStore
fail: function(callback){
$.jStore.delegate.bind('jStore-failure', callback);
},
// Enable ready callback for Flash
flashReady: function(callback){
if ($.jStore.isFlashReady) callback.apply($.jStore, [$.jStore.CurrentEngine]);
else $.jStore.delegate.bind('flash-ready', callback);
},
// Enable and test an engine
use: function(engine, project, identifier){
project = project || $.jStore.defaults.project || location.hostname.replace(/\./g, '-') || 'unknown';
var e = $.jStore.Engines[engine.toLowerCase()] || null,
name = (identifier ? identifier + '.' : '') + project + '.' + engine;
if ( !e ) throw 'JSTORE_ENGINE_UNDEFINED';
// Instanciate the engine
e = new e(project, name);
// Prevent against naming conflicts
if ($.jStore.Instances[name]) throw 'JSTORE_JRI_CONFLICT';
// Test the engine
if (e.isAvailable()){
$.jStore.Instances[name] = e; // The Easy Way
if (!$.jStore.CurrentEngine){
$.jStore.CurrentEngine = e;
}
$.jStore.delegate.trigger('jStore-ready', e);
} else {
if (!e.autoload) // Not available
throw 'JSTORE_ENGINE_UNAVILABLE';
else { // The hard way
e.included(function(){
if (this.isAvailable()) { // Worked out
$.jStore.Instances[name] = this;
// If there is no current engine, use this one
if (!$.jStore.CurrentEngine){
$.jStore.CurrentEngine = this;
}
$.jStore.delegate.trigger('jStore-ready', this);
}
else $.jStore.delegate.trigger('jStore-failure', this);
}).include();
}
}
},
// Set the current storage engine
setCurrentEngine: function(name){
if (!$.jStore.Instances.length ) // If no instances exist, attempt to load one
return $.jStore.FindEngine();
if (!name && $.jStore.Instances.length >= 1) { // If no name is specified, use the first engine
$.jStore.delegate.trigger('jStore-ready', $.jStore.Instances[0]);
return $.jStore.CurrentEngine = $.jStore.Instances[0];
}
if (name && $.jStore.Instances[name]) { // If a name is specified and exists, use it
$.jStore.delegate.trigger('jStore-ready', $.jStore.Instances[name]);
return $.jStore.CurrentEngine = $.jStore.Instances[name];
}
throw 'JSTORE_JRI_NO_MATCH';
},
// Test all possible engines for straightforward useability
FindEngine: function(){
$.each($.jStore.EngineOrder, function(k){
if ($.jStore.Availability[this]()){ // Find the first, easiest option and use it.
$.jStore.use(this, $.jStore.defaults.project, 'default');
return false;
}
})
},
// Provide a way for users to call for auto-loading
load: function(){
if ($.jStore.defaults.engine)
return $.jStore.use($.jStore.defaults.engine, $.jStore.defaults.project, 'default');
// Attempt to find a valid engine, and catch any exceptions if we can't
try {
$.jStore.FindEngine();
} catch (e) {}
},
// Parse a value as JSON before its stored.
safeStore: function(value){
switch (typeof value){
case 'object': case 'function': return $.compactJSON(value);
case 'number': case 'boolean': case 'string': case 'xml': return value;
case 'undefined': default: return '';
}
},
// Restores JSON'd values before returning
safeResurrect: function(value){
return rxJson.test(value) ? $.evalJSON(value) : value;
},
// Provide a simple interface for storing/getting values
store: function(key, value){
if (!$.jStore.CurrentEngine) return false;
if ( !value ) // Executing a get command
return $.jStore.CurrentEngine.get(key);
// Executing a set command
return $.jStore.CurrentEngine.set(key, value);
},
// Provide a simple interface for removing values
remove: function(key){
if (!$.jStore.CurrentEngine) return false;
return $.jStore.CurrentEngine.rem(key);
},
// Alias access for reading
get: function(key){
return $.jStore.store(key);
},
// Alias access for setting
set: function(key, value){
return $.jStore.store(key, value);
}
})
// Extend the jQuery funcitonal object
$.extend($.fn, {
// Provide a chainable interface for storing values/getting a value at the end of a chain
store: function(key, value){
if (!$.jStore.CurrentEngine) return this;
var result = $.jStore.store(key, value);
return !value ? result : this;
},
// Provide a chainable interface for removing values
removeStore: function(key){
$.jStore.remove(key);
return this;
},
// Alias access for reading at the end of a chain.
getStore: function(key){
return $.jStore.store(key);
},
// Alias access for setting on a chanin.
setStore: function(key, value){
$.jStore.store(key, value);
return this;
}
})
})(jQuery);
/**
* jStore Engine Core
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
this.StorageEngine = Class.extend({
init: function(project, name){
// Configure the project name
this.project = project;
// The JRI name given by the manager
this.jri = name;
// Cache the data so we can work synchronously
this.data = {};
// The maximum limit of the storage engine
this.limit = -1;
// Third party script includes
this.includes = [];
// Create an event delegate for users to subscribe to event triggers
this.delegate = new jStoreDelegate(this)
.bind('engine-ready', function(){
this.isReady = true;
})
.bind('engine-included', function(){
this.hasIncluded = true;
});
// If enabled, the manager will check availability, then run include(), then check again
this.autoload = false; // This should be changed by the engines, if they have required includes
// When set, we're ready to transact data
this.isReady = false;
// When the includer is finished, it will set this to true
this.hasIncluded = false;
},
// Performs all necessary script includes
include: function(){
var self = this,
total = this.includes.length,
count = 0;
$.each(this.includes, function(){
$.ajax({type: 'get', url: this, dataType: 'script', cache: true,
success: function(){
count++;
if (count == total) self.delegate.trigger('engine-included');
}
})
});
},
// This should be overloaded with an actual functionality presence check
isAvailable: function(){
return false;
},
// All get/set/rem functions across the engines should add this to the
// first line of those functions to prevent accessing the engine while unstable.
interruptAccess: function(){
if (!this.isReady) throw 'JSTORE_ENGINE_NOT_READY';
},
/** Event Subscription Shortcuts **/
ready: function(callback){
if (this.isReady) callback.apply(this);
else this.delegate.bind('engine-ready', callback);
return this;
},
included: function(callback){
if (this.hasIncluded) callback.apply(this);
else this.delegate.bind('engine-included', callback);
return this;
},
/** Cache Data Access **/
get: function(key){
this.interruptAccess();
return this.data[key] || null;
},
set: function(key, value){
this.interruptAccess();
this.data[key] = value;
return value;
},
rem: function(key){
this.interruptAccess();
var beforeDelete = this.data[key];
this.data[key] = null;
return beforeDelete;
}
});
})(jQuery);
/*!
* jStore DOM Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
// Set up a static test function for this instance
var sessionAvailability = $.jStore.Availability.session = function(){
return !!window.sessionStorage;
},
localAvailability = $.jStore.Availability.local = function(){
return !!(window.localStorage || window.globalStorage);
};
this.jStoreDom = StorageEngine.extend({
init: function(project, name){
// Call the parental init object
this._super(project, name);
// The type of storage engine
this.type = 'DOM';
// Set the Database limit
this.limit = 5 * 1024 * 1024;
},
connect: function(){
// Fire our delegate to indicate we're ready for data transactions
this.delegate.trigger('engine-ready');
},
get: function(key){
this.interruptAccess();
var out = this.db.getItem(key);
// Gecko's getItem returns {value: 'the value'}, WebKit returns 'the value'
return $.jStore.safeResurrect( (out && out.value ? out.value : out) );
},
set: function(key, value){
this.interruptAccess();
this.db.setItem(key,$.jStore.safeStore(value));
return value;
},
rem: function(key){
this.interruptAccess();
var out = this.get(key);
this.db.removeItem(key);
return out
}
})
this.jStoreLocal = jStoreDom.extend({
connect: function(){
// Gecko uses a non-standard globalStorage[ www.example.com ] DOM access object for persistant storage.
this.db = !window.globalStorage ? window.localStorage : window.globalStorage[location.hostname];
this._super();
},
isAvailable: localAvailability
})
this.jStoreSession = jStoreDom.extend({
connect: function(){
this.db = sessionStorage;
this._super();
},
isAvailable: sessionAvailability
})
$.jStore.Engines.local = jStoreLocal;
$.jStore.Engines.session = jStoreSession;
// Store the ordering preference
$.jStore.EngineOrder[ 1 ] = 'local';
})(jQuery);
/*!
* jStore Flash Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
* jStore.swf Copyright (c) 2008 Daniel Bulli (http://www.nuff-respec.com)
*/
(function($){
// Set up a static test function for this instance
var avilability = $.jStore.Availability.flash = function(){
return !!($.jStore.hasFlash('8.0.0'));
}
this.jStoreFlash = StorageEngine.extend({
init: function(project, name){
// Call the parental init object
this._super(project, name);
// The type of storage engine
this.type = 'Flash';
// Bind our flashReady function to the jStore Delegate
var self = this;
$.jStore.flashReady(function(){ self.flashReady() });
},
connect: function(){
var name = 'jstore-flash-embed-' + this.project;
// To make Flash Storage work on IE, we have to load up an iFrame
// which contains an HTML page that embeds the object using an
// object tag wrapping an embed tag. Of course, this is unnecessary for
// all browsers except for IE, which, to my knowledge, is the only browser
// in existance where you need to complicate your code to fix bugs. Goddamnit. :(
$(document.body)
.append('<iframe style="height:1px;width:1px;position:absolute;left:0;top:0;margin-left:-100px;" ' +
'id="jStoreFlashFrame" src="' +$.jStore.defaults.flash + '"></iframe>');
},
flashReady: function(e){
var iFrame = $('#jStoreFlashFrame')[0];
// IE
if (iFrame.Document && $.isFunction(iFrame.Document['jStoreFlash'].f_get_cookie)) this.db = iFrame.Document['jStoreFlash'];
// Safari && Firefox
else if (iFrame.contentWindow && iFrame.contentWindow.document){
var doc = iFrame.contentWindow.document;
// Safari
if ($.isFunction($('object', $(doc))[0].f_get_cookie)) this.db = $('object', $(doc))[0];
// Firefox
else if ($.isFunction($('embed', $(doc))[0].f_get_cookie)) this.db = $('embed', $(doc))[0];
}
// We're ready to process data
if (this.db) this.delegate.trigger('engine-ready');
},
isAvailable: avilability,
get: function(key){
this.interruptAccess();
var out = this.db.f_get_cookie(key);
return out == 'null' ? null : $.jStore.safeResurrect(out);
},
set: function(key, value){
this.interruptAccess();
this.db.f_set_cookie(key, $.jStore.safeStore(value));
return value;
},
rem: function(key){
this.interruptAccess();
var beforeDelete = this.get(key);
this.db.f_delete_cookie(key);
return beforeDelete;
}
})
$.jStore.Engines.flash = jStoreFlash;
// Store the ordering preference
$.jStore.EngineOrder[ 2 ] = 'flash';
/**
* Flash Detection functions copied from the jQuery Flash Plugin
* Copyright (c) 2006 Luke Lutman (http://jquery.lukelutman.com/plugins/flash)
* Dual licensed under the MIT and GPL licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/gpl-license.php
*/
$.jStore.hasFlash = function(version){
var pv = $.jStore.flashVersion().match(/\d+/g),
rv = version.match(/\d+/g);
for(var i = 0; i < 3; i++) {
pv[i] = parseInt(pv[i] || 0);
rv[i] = parseInt(rv[i] || 0);
// player is less than required
if(pv[i] < rv[i]) return false;
// player is greater than required
if(pv[i] > rv[i]) return true;
}
// major version, minor version and revision match exactly
return true;
}
$.jStore.flashVersion = function(){
// ie
try {
try {
// avoid fp6 minor version lookup issues
// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
try { axo.AllowScriptAccess = 'always'; }
catch(e) { return '6,0,0'; }
} catch(e) {
return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
}
// other browsers
} catch(e) {
try {
if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
}
} catch(e) {}
}
return '0,0,0';
}
})(jQuery);
// Callback fired when ExternalInterface is established
function flash_ready(){
$.jStore.delegate.trigger('flash-ready');
}
/*!
* jStore Google Gears Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
// Set up a static test function for this instance
var avilability = $.jStore.Availability.gears = function(){
return !!(window.google && window.google.gears)
}
this.jStoreGears = StorageEngine.extend({
init: function(project, name){
// Call the parental init object
this._super(project, name);
// The type of storage engine
this.type = 'Google Gears';
// Add required third-party scripts
this.includes.push('http://code.google.com/apis/gears/gears_init.js');
// Allow Autoloading on fail
this.autoload = true;
},
connect: function(){
// Create our database connection
var db = this.db = google.gears.factory.create('beta.database');
db.open( 'jstore-' + this.project );
db.execute( 'CREATE TABLE IF NOT EXISTS jstore (k TEXT UNIQUE NOT NULL PRIMARY KEY, v TEXT NOT NULL)' );
// Cache the data from the table
this.updateCache();
},
updateCache: function(){
// Read the database into our cache object
var result = this.db.execute( 'SELECT k,v FROM jstore' );
while (result.isValidRow()){
this.data[result.field(0)] = $.jStore.safeResurrect( result.field(1) );
result.next();
} result.close();
// Fire our delegate to indicate we're ready for data transactions
this.delegate.trigger('engine-ready');
},
isAvailable: avilability,
set: function(key, value){
this.interruptAccess();
// Update the database
var db = this.db;
db.execute( 'BEGIN' );
db.execute( 'INSERT OR REPLACE INTO jstore(k, v) VALUES (?, ?)', [key,$.jStore.safeStore(value)] );
db.execute( 'COMMIT' );
return this._super(key, value);
},
rem: function(key){
this.interruptAccess();
// Update the database
var db = this.db;
db.execute( 'BEGIN' );
db.execute( 'DELETE FROM jstore WHERE k = ?', [key] );
db.execute( 'COMMIT' );
return this._super(key);
}
})
$.jStore.Engines.gears = jStoreGears;
// Store the ordering preference
$.jStore.EngineOrder[ 3 ] = 'gears';
})(jQuery);
/*!
* jStore HTML5 Specification Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
// Set up a static test function for this instance
var avilability = $.jStore.Availability.html5 = function(){
return !!window.openDatabase
}
this.jStoreHtml5 = StorageEngine.extend({
init: function(project, name){
// Call the parental init object
this._super(project, name);
// The type of storage engine
this.type = 'HTML5';
// Set the Database limit
this.limit = 1024 * 200;
},
connect: function(){
// Create our database connection
var db = this.db = openDatabase('jstore-' + this.project, '1.0', this.project, this.limit);
if (!db) throw 'JSTORE_ENGINE_HTML5_NODB';
db.transaction(function(db){
db.executeSql( 'CREATE TABLE IF NOT EXISTS jstore (k TEXT UNIQUE NOT NULL PRIMARY KEY, v TEXT NOT NULL)' );
});
// Cache the data from the table
this.updateCache();
},
updateCache: function(){
var self = this;
// Read the database into our cache object
this.db.transaction(function(db){
db.executeSql( 'SELECT k,v FROM jstore', [], function(db, result){
var rows = result.rows, i = 0, row;
for (; i < rows.length; ++i){
row = rows.item(i);
self.data[row.k] = $.jStore.safeResurrect( row.v );
}
// Fire our delegate to indicate we're ready for data transactions
self.delegate.trigger('engine-ready');
});
});
},
isAvailable: avilability,
set: function(key, value){
this.interruptAccess();
// Update the database
this.db.transaction(function(db){
db.executeSql( 'INSERT OR REPLACE INTO jstore(k, v) VALUES (?, ?)', [key,$.jStore.safeStore(value)]);
});
return this._super(key, value);
},
rem: function(key){
this.interruptAccess();
// Update the database
this.db.transaction(function(db){
db.executeSql( 'DELETE FROM jstore WHERE k = ?', [key] )
})
return this._super(key);
}
})
$.jStore.Engines.html5 = jStoreHtml5;
// Store the ordering preference
$.jStore.EngineOrder[ 0 ] = 'html5';
})(jQuery);
/*!*
* jStore IE Storage Engine
* Copyright (c) 2009 Eric Garside (http://eric.garside.name)
*/
(function($){
// Set up a static test function for this instance
var avilability = $.jStore.Availability.ie = function(){
return !!window.ActiveXObject;
}
this.jStoreIE = StorageEngine.extend({
init: function(project, name){
// Call the parental init object
this._super(project, name);
// The type of storage engine
this.type = 'IE';
// Allow Autoloading on fail
this.limit = 64 * 1024;
},
connect: function(){
// Create a hidden div to store attributes in
this.db = $('<div style="display:none;behavior:url(\'#default#userData\')" id="jstore-' + this.project + '"></div>')
.appendTo(document.body).get(0);
// Fire our delegate to indicate we're ready for data transactions
this.delegate.trigger('engine-ready');
},
isAvailable: avilability,
get: function(key){
this.interruptAccess();
this.db.load(this.project);
return $.jStore.safeResurrect( this.db.getAttribute(key) );
},
set: function(key, value){
this.interruptAccess();
this.db.setAttribute(key, $.jStore.safeStore(value));
this.db.save(this.project);
return value;
},
rem: function(key){
this.interruptAccess();
var beforeDelete = this.get(key);
this.db.removeAttribute(key);
this.db.save(this.project);
return beforeDelete;
}
})
$.jStore.Engines.ie = jStoreIE;
// Store the ordering preference
$.jStore.EngineOrder[ 4 ] = 'ie';
})(jQuery);
+230
Ver Arquivo
@@ -0,0 +1,230 @@
/**
* jQuery MD5 hash algorithm function
*
* <code>
* Calculate the md5 hash of a String
* String $.md5 ( String str )
* </code>
*
* Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.
* MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of data. The generated hash is also non-reversable. Data cannot be retrieved from the message digest, the digest uniquely identifies the data.
* MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1.
* This script is used to process a variable length message into a fixed-length output of 128 bits using the MD5 algorithm. It is fully compatible with UTF-8 encoding. It is very useful when u want to transfer encrypted passwords over the internet. If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag).
* This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
*
* Example
* Code
* <code>
* $.md5("I'm Persian.");
* </code>
* Result
* <code>
* "b8c901d0f02223f9761016cfff9d68df"
* </code>
*
* @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
* @link http://www.semnanweb.com/jquery-plugin/md5.html
* @see http://www.webtoolkit.info/
* @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
* @param {jQuery} {md5:function(string))
* @return string
*/
(function($){
var rotateLeft = function(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
var addUnsigned = function(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4) {
if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ lX8 ^ lY8);
}
}
var F = function(x, y, z) {
return (x & y) | ((~ x) & z);
}
var G = function(x, y, z) {
return (x & z) | (y & (~ z));
}
var H = function(x, y, z) {
return (x ^ y ^ z);
}
var I = function(x, y, z) {
return (y ^ (x | (~ z)));
}
var FF = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var GG = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var HH = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var II = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var convertToWordArray = function(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWordsTempOne = lMessageLength + 8;
var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var wordToHex = function(lValue) {
var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValueTemp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
}
return WordToHexValue;
};
var uTF8Encode = function(string) {
string = string.replace(/\x0d\x0a/g, "\x0a");
var output = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
} else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}
return output;
};
$.extend({
md5: function(string) {
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = uTF8Encode(string);
x = convertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a; BB = b; CC = c; DD = d;
a = FF(a, b, c, d, x[k+0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k+1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k+2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k+3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k+4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k+5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k+6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k+7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k+8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k+9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k+10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k+11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k+12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k+13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k+14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k+15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k+1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k+6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k+11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k+0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k+5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k+10], S22, 0x2441453);
c = GG(c, d, a, b, x[k+15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k+4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k+9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k+14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k+3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k+8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k+13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k+2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k+7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k+12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k+5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k+8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k+11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k+14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k+1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k+4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k+7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k+10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k+13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k+0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k+3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k+6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k+9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k+12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k+15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k+2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k+0], S41, 0xF4292244);
d = II(d, a, b, c, x[k+7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k+14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k+5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k+12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k+3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k+10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k+1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k+8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k+15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k+6], S43, 0xA3014314);
b = II(b, c, d, a, x[k+13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k+4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k+11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k+2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k+9], S44, 0xEB86D391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
return tempValue.toLowerCase();
}
});
})(jQuery);
+792
Ver Arquivo
@@ -0,0 +1,792 @@
<?php
/*
* Library: MySQL
* Author: Joshua Gross
* Version: 0.1 alpha
* Date: January 16, 2010
*
* Description:
* The default MySQL server backend.
*
* Requirements: MySQL 5.0+
*/
class MySQL_Database extends BaseDatabase {
private static $_instance = false;
public static function instance() {
if(self::$_instance === false) {
// create instance
self::$_instance = new PDO('mysql:dbname=' . MYSQL_DATABASE . ';host=' . MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD);
}
return self::$_instance;
}
}
class MySQL_User extends BaseUser {
function __construct($username, $password, $user_id, $ip='', $last_login=0) {
parent::__construct($username, $password, $user_id, $ip, $last_login);
self::$db = MySQL_Database::instance();
$this->username = $username;
$this->password = $password;
$this->user_id = $user_id;
$this->ip = $ip;
$this->last_login = $last_login;
}
public static function authenticate($username, $password) {
if(!self::$db)
self::$db = MySQL_Database::instance();
$username = preg_replace('/([%_])/', '\\\\\1', $username);
$auth_sql = "SELECT * FROM " . MYSQL_PREFIX . "users
WHERE username LIKE :username LIMIT 1";
$auth = self::$db->prepare($auth_sql);
$auth->execute(array(':username' => $username));
if($auth->rowCount()) {
$user = $auth->fetch(PDO::FETCH_OBJ);
// hash given password using actual password hash, then test against real password
$pw_hash = substr($user->password, 0, 8);
if($user->password == $pw_hash . md5($pw_hash . $password)) {
$user_obj = new MySQL_User($user->username, $user->password, $user->user_id,
$user->last_known_ip, $user->last_login);
return $user_obj;
} else {
return false;
}
} else {
return false;
}
}
public static function get($user) {
if(!self::$db)
self::$db = MySQL_Database::instance();
}
public static function find($username) {
if(!self::$db)
self::$db = MySQL_Database::instance();
$username = preg_replace('/([%_])/', '\\\\\1', $username);
$find_sql = "SELECT * FROM " . MYSQL_PREFIX . "users
WHERE username LIKE :username LIMIT 1";
$find = self::$db->prepare($find_sql);
$find->execute(array(':username' => $username));
$user = $find->fetch(PDO::FETCH_OBJ);
return new User($user->username, $user->password, $user->user_id, $user->last_known_ip, $user->last_login);
}
public function status($s=null, $message=null) {
if(!$this->status) {
$this->status = MySQL_Status::of($this->user_id);
}
if($s) {
return $this->status->is($s, $message);
} else {
return $this->status;
}
}
public function ip($ip=null) {
if($ip) {
$this->ip = $ip;
if($this->user_id && $this->autosave) {
$updateip_sql = "UPDATE " . MYSQL_PREFIX . "users SET last_known_ip=:ip WHERE user_id=:id";
$updateip = self::$db->prepare($updateip_sql);
$updateip->execute(array(
':ip' => $ip,
':id' => $this->user_id
));
}
return $this;
} else {
if($this->ip) {
return $this->ip;
} else if($this->user_id) {
$getip_sql = "SELECT last_known_ip FROM " . MYSQL_PREFIX . "users WHERE user_id=:id";
$getip = self::$db->prepare($getip_sql);
$getip->execute(array(':id' => $this->user_id));
$user_obj = $getip->fetch(PDO::FETCH_OBJ);
$this->ip = $user_obj->last_known_ip;
return $this->ip;
}
return false;
}
}
public function lastLogin($ll=null) {
if($ll) {
$this->last_login = $ll;
if($this->user_id && $this->autosave) {
$updatell_sql = "UPDATE " . MYSQL_PREFIX . "users SET last_login=FROM_UNIXTIME(:ll) WHERE user_id=:id";
$updatell = self::$db->prepare($updatell_sql);
$updatell->execute(array(
':ll' => $ll,
':id' => $this->user_id
));
}
return $this;
} else {
if($this->last_login) {
return $this->last_login;
} else if($this->user_id) {
$getll_sql = "SELECT last_login FROM " . MYSQL_PREFIX . "users WHERE user_id=:id";
$getll = self::$db->prepare($getll_sql);
$getll->execute(array(':id' => $this->user_id));
$user_obj = $getll->fetch(PDO::FETCH_OBJ);
$this->last_login = strtotime($user_obj->last_login);
return $this->last_login;
}
return false;
}
}
public function save($id=null) {
}
}
class MySQL_Status extends BaseStatus {
const Offline = 0;
const Available = 1;
const Away = 2;
const Invisible = 3;
public $s = null;
public $message = '';
public $user_id = 0;
function __construct($user_id, $s=null, $message='') {
self::$db = MySQL_Database::instance();
$this->s = $s;
$this->message = $message;
$this->user_id = $user_id;
}
public static function of($user) {
$status_sql = "SELECT s, message, s.user_id FROM " . MYSQL_PREFIX . "status as s ";
if(is_int($user)) {
$status_sql .= "WHERE user_id = :user";
} else {
$status_sql .= "LEFT JOIN " . MYSQL_PREFIX . "users as u ON u.user_id=s.user_id WHERE u.username = :user";
}
$status_sql .= " LIMIT 1";
$prep = self::$db->prepare($sql);
$prep->execute(array(':user' => $user));
$status = $prep->fetch(PDO::FETCH_OBJ);
return new Status($status->s, $status->message, $status->user_id);
}
public function is($s, $message='') {
$status_sql = "INSERT INTO " . MYSQL_PREFIX . "status (user_id, message, status) VALUES(:user_id, :message, :s)
ON DUPLICATE KEY UPDATE
status = :s, message = :message";
$prep = self::$db->prepare($status_sql);
$this->s = $s;
$this->message = $message;
$changed_status = $prep->execute(array(
':s' => $s,
':message' => $message,
':user_id' => $this->user_id
));
if($changed_status) {
// broadcast status update to friends
$update_friends_sql = "INSERT INTO " . MYSQL_PREFIX . "messages (from_id, to_id, message, type)
SELECT :user_id AS from_id, friend_id as to_id, :status as message, 's' as type FROM " . MYSQL_PREFIX . "friends as friends
LEFT JOIN " . MYSQL_PREFIX . "status as status ON friends.friend_id = status.user_id WHERE friends.user_id = :user_id AND status.status > 0";
$update_friends = self::$db->prepare($update_friends_sql);
$update_friends->execute(array(
':user_id' => $this->user_id,
':status' => $s . ':' . $message
));
}
return $changed_status;
}
}
class MySQL_Message extends BaseMessage {
function __construct($from=0, $to=0, $message='', $type='m') {
self::$db = MySQL_Database::instance();
$this->id = 0;
$this->from = $from;
$this->to = $to;
$this->message = $message;
$this->type = $type;
$this->sent = 0;
// Automatically flush changes if id is set?
$this->autosave = true;
}
public static function send($from=0, $to=0, $message='') {
if(!self::$db)
self::$db = MySQL_Database::instance();
if(isset($this) && $this->from && !$from) {
$from = $this->from;
$to = $this->to;
$message = $this->message;
}
$send_sql = "INSERT INTO " . MYSQL_PREFIX . "messages (from_id, to_id, type, message)
VALUES(:from, :to, 'm', :message)";
$prep_send = self::$db->prepare($send_sql);
return $prep_send->execute(array(
':from' => $from,
':to' => $to,
':message' => $message
));
}
public static function get($id) {
if(!self::$db)
self::$db = MySQL_Database::instance();
$get_sql = "SELECT * FROM " . MYSQL_PREFIX . "messages WHERE message_id=:id LIMIT 1";
$get_message = self::$db->prepare($get_sql);
$get_message->execute(array(':id' => intval($id)));
if($get_message->rowCount()) {
$msg_obj = $get_message->fetch(PDO::FETCH_OBJ);
$message = new Message($msg_obj->from, $msg_obj->to, $msg_obj->message, $msg_obj->type);
$message->id = $msg_obj->message_id;
return $message;
} else {
return false;
}
}
public static function getMany($from_or_to, $user) {
if(!self::$db)
self::$db = MySQL_Database::instance();
$get_sql = "SELECT message_id, u1.username as `from`, u2.username as `to`, message, `type`, sent FROM " . MYSQL_PREFIX . "messages as m
LEFT JOIN ajaxim_users as u1 ON m.to_id = u1.user_id
LEFT JOIN ajaxim_users as u2 ON m.from_id = u2.user_id WHERE ";
if(is_numeric($user)) {
$get_sql .= ($from_or_to == 'from' ? 'from' : 'to') . "_id = :user";
} else {
$get_sql .= "u" . ($from_or_to == 'from' ? '2' : '1') . ".username = :user";
}
$get_sql .= " AND `read` = 0 ORDER BY sent ASC";
$get_messages = self::$db->prepare($get_sql);
$get_messages->execute(array(':user' => $user));
if($get_messages->rowCount()) {
$messages = array(); $message_ids = array();
while($msg_obj = $get_messages->fetch(PDO::FETCH_OBJ)) {
$messages[] = new Message($msg_obj->from, $msg_obj->to, $msg_obj->message, $msg_obj->type);
$idx = count($messages) - 1;
$messages[$idx]->sent = strtotime($msg_obj->sent);
$messages[$idx]->id = $msg_obj->message_id;
$message_ids[] = $msg_obj->message_id;
}
$mark_read_sql = "UPDATE " . MYSQL_PREFIX . "messages SET `read` = 1 WHERE message_id IN(" . join(',', $message_ids) . ")";
$mark_read = self::$db->prepare($mark_read_sql);
$mark_read->execute();
return $messages;
} else {
return false;
}
}
public function sent($ts=null) {
if($ts) {
$this->sent = $ts;
if($this->id && $this->autosave) {
$updatets_sql = "UPDATE " . MYSQL_PREFIX . "messages SET sent=FROM_UNIXTIME(:ts) WHERE message_id=:id";
$updatets = self::$db->prepare($updatets_sql);
$updatets->execute(array(
':ts' => $ts,
':id' => $this->id
));
}
return $this;
} else {
if($this->sent) {
return $this->sent;
} else if($this->id) {
$getts_sql = "SELECT sent FROM " . MYSQL_PREFIX . "messages WHERE message_id=:id LIMIT 1";
$getts = self::$db->prepare($getts_sql);
$getts->execute(array(':id' => $this->id));
if($getts->rowCount()) {
$msg_obj = $getts->fetch(PDO::FETCH_OBJ);
$this->sent = strtotime($msg_obj->sent);
return $this->sent;
} else {
return false;
}
}
return false;
}
}
public function from($from=null) {
// check if from is int, string, or User object
if($from) {
$this->from = $from;
if($this->id && $this->autosave) {
$updatefrom_sql = "UPDATE " . MYSQL_PREFIX . "messages SET from=:from WHERE message_id=:id";
$updatefrom = self::$db->prepare($updatefrom_sql);
$updatefrom->execute(array(
':from' => $from,
':id' => $this->id
));
}
return $this;
} else {
if($this->from) {
return $this->from;
} else if($this->id) {
$getfrom_sql = "SELECT from FROM " . MYSQL_PREFIX . "messages WHERE message_id=:id LIMIT 1";
$getfrom = self::$db->prepare($getfrom_sql);
$getfrom->execute(array(':id' => $this->id));
if($getfrom->rowCount()) {
$msg_obj = $getfrom->fetch(PDO::FETCH_OBJ);
$this->from = $msg_obj->from;
return $this->from;
} else {
return false;
}
}
return false;
}
}
public function to($to=null) {
// check if to is int, string, or User object
if($to) {
$this->to = $to;
if($this->id && $this->autosave) {
$updateto_sql = "UPDATE " . MYSQL_PREFIX . "messages SET to=:to WHERE message_id=:id";
$updateto = self::$db->prepare($updateto_sql);
$updateto->execute(array(
':to' => $to,
':id' => $this->id
));
}
return $this;
} else {
if($this->to) {
return $this->to;
} else if($this->id) {
$getto_sql = "SELECT to FROM " . MYSQL_PREFIX . "messages WHERE message_id=:id LIMIT 1";
$getto = self::$db->prepare($getto_sql);
$getto->execute(array(':id' => $this->id));
if($getto->rowCount()) {
$msg_obj = $getto->fetch(PDO::FETCH_OBJ);
$this->to = $msg_obj->to;
return $this->to;
} else {
return false;
}
}
return false;
}
}
public function message($message=null) {
if($message) {
$this->message = $message;
if($this->id && $this->autosave) {
$updatemsg_sql = "UPDATE " . MYSQL_PREFIX . "messages SET message=:message WHERE message_id=:id";
$updatemsg = self::$db->prepare($updatemsg_sql);
$updatemsg->execute(array(
':message' => $message,
':id' => $this->id
));
}
return $this;
} else {
if($this->message) {
return $this->message;
} else if($this->id) {
$getmsg_sql = "SELECT message FROM " . MYSQL_PREFIX . "messages WHERE message_id=:id LIMIT 1";
$getmsg = self::$db->prepare($getmsg_sql);
$getmsg->execute(array(':id' => $this->id));
if($getmsg->rowCount()) {
$msg_obj = $getmsg->fetch(PDO::FETCH_OBJ);
$this->message = $msg_obj->message;
return $this->message;
} else {
return false;
}
}
return false;
}
}
public function save($id=null) {
if(!$this->id && !$id)
return false;
else if($this->id)
$id = $this->id;
if($id) {
$savemsg_sql = "UPDATE " . MYSQL_PREFIX . "messages SET from_id=:from, to_id=:to, type=:type, message=:message, sent=:sent WHERE message_id=:id";
$savemsg = self::$db->prepare($savemsg_sql);
$state = $savemsg->execute(array(
':from' => $this->from,
':to' => $this->to,
':type' => $this->type,
':message' => $this->message,
':sent' => $this->sent,
':id' => $this->id
));
if($state) {
return $id;
} else {
return false;
}
} else {
$savemsg_sql = "INSERT INTO " . MYSQL_PREFIX . "messages (from_id, to_id, type, message, sent) VALUES (:from, :to, :type, :message, :sent)
ON DUPLICATE KEY UPDATE message_id=LAST_INSERT_ID(message_id), from_id=:from, to_id=:to, type=:type, message=:message, sent=:sent";
$savemsg = self::$db->prepare($savemsg_sql);
$state = $savemsg->execute(array(
':from' => $this->from,
':to' => $this->to,
':type' => $this->type,
':message' => $this->message,
':sent' => $this->sent
));
if($state) {
$this->id = self::$db->lastInsertId();
return $this->id;
} else {
return false;
}
}
}
}
class MySQL_Friend extends BaseFriend {
static $db = null;
function __construct($user=null, $friend=null, $group=null) {
self::$db = MySQL_Database::instance();
$this->id = 0;
$this->user = $user;
$this->friend = $friend;
$this->group = $group;
// Automatically flush changes if id is set?
$this->autosave = true;
}
public static function of($user=0, $offline=false) {
if(!$user && (isset($this) && !$this->user))
return array();
if(isset($this) && $this->user && !$user)
$user = $this->user;
if(!self::$db)
self::$db = MySQL_Database::instance();
$friends_of_sql = "SELECT users.username as u, status.status as s, groups.name as g FROM " . MYSQL_PREFIX . "friends as friends
LEFT JOIN " . MYSQL_PREFIX . "users as users ON friends.friend_id = users.user_id
LEFT JOIN " . MYSQL_PREFIX . "status as status ON users.user_id = status.user_id
LEFT JOIN " . MYSQL_PREFIX . "groups as groups ON friends.group_id = groups.group_id
WHERE friends.user_id = :user" . ($offline ? "" : " AND status.status != 0");
$friends_of = self::$db->prepare($friends_of_sql);
$friends_of->execute(array('user' => $user));
if($friends_of->rowCount()) {
return $friends_of->fetchAll(PDO::FETCH_ASSOC);
} else {
return array();
}
}
public static function get($id) {
if(!self::$db)
self::$db = MySQL_Database::instance();
$friend_get_sql = "SELECT users.username as u, status.status as s, groups.name as g FROM " . MYSQL_PREFIX . "friends as friends
LEFT JOIN " . MYSQL_PREFIX . "users as users ON friends.friend_id = users.user_id
LEFT JOIN " . MYSQL_PREFIX . "status as status ON users.user_id = status.user_id
LEFT JOIN " . MYSQL_PREFIX . "groups as groups ON friends.group_id = groups.group_id
WHERE friends.id = :id LIMIT 1";
$friend_get = self::$db->prepare($friend_get_sql);
$friend_get->execute(array('id' => $id));
if($friend_get->rowCount()) {
return $friend_get->fetch(PDO::FETCH_ASSOC);
} else {
return array('u' => false, 's' => 0, 'g' => false);
}
}
public static function find($friend, $user=0) {
if(!$user && (isset($this) && !$this->user))
return false;
if(!self::$db)
self::$db = MySQL_Database::instance();
if($this->user && !$user)
$user = $this->user;
$friend_find_sql = "SELECT users.username as u, status.status as s, groups.name as g FROM " . MYSQL_PREFIX . "friends as friends
LEFT JOIN " . MYSQL_PREFIX . "users as users ON friends.friend_id = users.user_id
LEFT JOIN " . MYSQL_PREFIX . "status as status ON users.user_id = status.user_id
LEFT JOIN " . MYSQL_PREFIX . "groups as groups ON friends.group_id = groups.group_id ";
if(is_int($friend))
$friend_find_sql .= "WHERE friends.friend_id = :friend";
else
$friend_find_sql .= "WHERE users.username = :friend";
$friend_find_sql .= " AND friends.user_id = :user LIMIT 1";
$friend_find = self::$db->prepare($friend_find_sql);
$friend_find->execute(array(
'friend' => $friend,
'user' => $user
));
if($friend_find->rowCount()) {
return $friend_find->fetch(PDO::FETCH_ASSOC);
} else {
return false;
}
}
public function group($group=null) {
if($group) {
$this->group = $group;
if($this->id && $this->autosave) {
if(!is_int($this->group)) {
$group_id_sql = "INSERT INTO " . MYSQL_PREFIX . "groups (name) VALUES (:group)
ON DUPLICATE KEY UPDATE group_id=LAST_INSERT_ID(group_id)";
$group_id = self::$db->prepare($group_id_sql);
$group_id->execute(array(':group' => $group));
if(!$group_id) {
return false;
} else {
$group_id = self::$db->lastInsertId();
$this->group = $group_id;
}
}
$updategroup_sql = "UPDATE " . MYSQL_PREFIX . "friends SET group_id=:group_id WHERE id=:id";
$updategroup = self::$db->prepare($updatemsg_sql);
$updategroup->execute(array(
':group_id' => $this->group,
':id' => $this->id
));
}
return $this;
} else {
if($this->group) {
return $this->group;
} else if($this->id) {
$getgroup_sql = "SELECT group FROM " . MYSQL_PREFIX . "friends WHERE id=:id LIMIT 1";
$getgroup = self::$db->prepare($getmsg_sql);
$getgroup->execute(array(':id' => $this->id));
if($getgroup->rowCount()) {
$group_obj = $getmsg->fetch(PDO::FETCH_OBJ);
$this->group = $group_obj->group;
return $this->group;
} else {
return false;
}
}
return false;
}
}
public function save($id=null) {
$as = $this->autosave;
$this->autosave = false;
if($this->id)
$id = $this->id;
if(!is_int($this->group)) {
$group_id_sql = "INSERT INTO " . MYSQL_PREFIX . "groups (name) VALUES (:group)
ON DUPLICATE KEY UPDATE group_id=LAST_INSERT_ID(group_id)";
$group_id = self::$db->prepare($group_id_sql);
$group_id->execute(array(':group' => $this->group));
if(!$group_id) {
return false;
} else {
$group_id = self::$db->lastInsertId();
$this->group = $group_id;
}
}
if(!is_int($this->user)) {
$user = MySQL_User::find($this->user);
if($user) {
$this->user = $user->user_id;
} else {
return false;
}
}
if(!is_int($this->friend)) {
$friend = MySQL_User::find($this->friend);
if($friend) {
$this->friend = $user->user_id;
} else {
return false;
}
}
if($id) {
$savefriend_sql = "UPDATE " . MYSQL_PREFIX . "friends SET user_id=:user, friend_id=:friend, group_id=:group WHERE id=:id";
$savefriend = self::$db->prepare($savefriend_sql);
$state = $savefriend->execute(array(
':user' => $this->user,
':friend' => $this->friend,
':group' => $this->group
));
if($state) {
return $id;
} else {
return false;
}
} else {
$savefriend_sql = "INSERT INTO " . MYSQL_PREFIX . "friends (user_id, friend_id, group_id) VALUES (:user, :friend, :group)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), user_id=:user, friend_id=:friend, group_id=:group";
$savefriend = self::$db->prepare($savefriend_sql);
$state = $savefriend->execute(array(
':user' => $this->user,
':friend' => $this->friend,
':group' => $this->group
));
if($state) {
$this->id = self::$db->lastInsertId();
return $this->id;
} else {
return false;
}
}
}
public function remove() {
}
}
/* SQL:
CREATE TABLE `ajaxim_friends` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`friend_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE `ajaxim_groups` (
`group_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`group_id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE `ajaxim_messages` (
`message_id` int(11) NOT NULL AUTO_INCREMENT,
`from_id` int(11) NOT NULL,
`to_id` int(11) NOT NULL,
`message` text NOT NULL,
`type` varchar(2) NOT NULL,
`sent` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`read` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE `ajaxim_status` (
`status_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`status` int(11) NOT NULL,
`message` text NOT NULL,
PRIMARY KEY (`status_id`),
UNIQUE KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE `ajaxim_users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(40) NOT NULL,
`last_known_ip` int(11) NOT NULL,
`last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
*/
/* End of libraries/db/MySQL.php */
+139
Ver Arquivo
@@ -0,0 +1,139 @@
<?php
class BaseDatabase {
private static $_instance = false;
public static function instance() {
if(self::$_instance === false) {
// create instance
self::$_instance = true;
}
return self::$_instance;
}
}
class BaseUser {
static $db = null;
function __construct($username, $password, $user_id, $ip, $last_login) {
}
public static function authenticate($username, $password) {
}
public static function get($user) {
}
public static function find($username) {
}
public function status($s=null, $message=null) {
}
public function ip($ip=null) {
}
public function lastLogin($ll=null) {
}
public function save($id=null) {
}
}
class BaseStatus {
const Offline = 0;
const Available = 1;
const Away = 2;
const Invisible = 3;
static $db = null;
function __construct($user_id, $s=null, $message='') {
}
public static function of($user) {
}
public function is($s, $message='') {
}
}
class BaseMessage {
static $db = null;
function __construct($from='', $to='', $message='', $type='') {
}
public static function send($from, $to, $message) {
}
public static function get($id) {
}
public static function getMany($from_or_to, $user) {
}
public function sent($ts=null) {
}
public function from($from=null) {
}
public function to($to=null) {
}
public function message($message=null) {
}
public function save($id=null) {
}
}
class BaseFriend {
static $db = null;
function __construct($user=null, $friend=null, $group=null) {
}
public static function get($id) {
}
public static function find($friend, $user=0) {
}
public function group($group=null) {
}
public function save() {
}
public function remove() {
}
}
class BaseFriendGroup {
static $db = null;
function __construct($user, $group) {
}
public static function get($id) {
}
public static function find($group) {
}
public function addFriend($friend) {
}
public function friends() {
}
public function save() {
}
public function remove() {
}
}
/* End of libraries/db/base.php */
+232
Ver Arquivo
@@ -0,0 +1,232 @@
<?php
/*
* Library: Default
* Author: Joshua Gross
* Version: 0.1 alpha
* Date: December 21, 2009
*
* Description:
* The default PHP-only server library. This library allows
* you to use Ajax IM on a shared server, without installing
* any extra software.
*
* Requirements: Database
*/
class Default_IM extends IM {
const FIXBUFFER = 1024; // Works around an output buffering issue in IE & Safari
const FIXEOL = '<br/>'; // Works around an end-of-line issue in Safari
function __construct() {
parent::__construct();
session_start();
if($_SESSION['username']) {
$this->username = $_SESSION['username'];
$this->user_id = $_SESSION['user_id'];
}
}
public function login($username, $password) {
if($user = User::authenticate($username, $password)) {
// user just logged in, update login time.
$user->lastLogin(time());
$_SESSION['username'] = $user->username;
$_SESSION['user_id'] = intval($user->user_id);
$online = Friend::of($user->user_id);
return array('r' => 'logged in', 's' => session_id(), 'f' => $online);
} else {
return array('r' => 'error', 'e' => 'invalid user');
}
}
public function logout() {
session_destroy();
$_SESSION = array();
return array('r' => 'logged out');
}
public function send($to, $message) {
if(!$this->username)
return array('r' => 'error', 'e' => 'no session found');
$message = $this->_sanitize($message);
$to = User::find($to);
if(!$to)
return array('r' => 'error', 'e' => 'no_recipient');
if(Message::send($this->user_id, $to->user_id, $message)) {
return array('r' => 'sent');
} else {
return array('r' => 'error', 'e' => 'send error');
}
}
public function status($status, $message) {
if(!$this->username)
return array('r' => 'error', 'e' => 'no session found');
$status = intval($status);
$message = $this->_sanitize($message);
$statuses = array(Status::Offline, Status::Available, Status::Away, Status::Invisible);
if(!in_array($status, $statuses))
$status = Status::Available;
$user_status = new Status($this->user_id);
if($user_status->is($s, $message)) {
return array('r' => 'status set');
// now, notify all friends
} else {
return array('r' => 'error', 'e' => 'status error');
}
}
public function register($username, $password) {
if(preg_match('/^[A-Za-z0-9_.]{3,16}$/', $username)) {
if(strlen($password) > 3) {
// hash the password
$password = md5($password);
$pw_str = substr($password, 0, 8);
$password = $pw_str . md5($pw_str . $password);
$register_sql = "INSERT INTO " . MYSQL_PREFIX . "users
(username, password, last_known_ip)
VALUES(:username, :password, :ip)";
$db = MySQL_Database::instance();
$register = $db->prepare($register_sql);
$is_registered = $register->execute(array(
':username' => $username,
':password' => $password,
':ip' => ip2long($_SERVER['REMOTE_ADDR'])
));
if($is_registered) {
print json_encode(array('r' => 'registered'));
} else {
print json_encode(array('r' => 'error', 'e' => 'unknown'));
}
} else {
print json_encode(array('r' => 'error', 'e' => 'invalid password'));
}
} else {
print json_encode(array('r' => 'error', 'e' => 'invalid username'));
}
}
public function poll($method) {
if(!$this->username)
return array('r' => 'error', 'e' => 'no session found');
session_write_close(); // prevents locking
// If output buffering hasn't been setup yet...
if(count(ob_list_handlers()) < 2) {
// Buffer output, but flush always after any output
ob_start();
ob_implicit_flush(true);
// Set the headers such that our response doesn't get cached
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
}
switch($method) {
case 'long':
return $this->_longPoll();
break;
case 'comet':
return $this->_comet();
break;
default:
case 'short':
return $this->_shortPoll();
break;
}
}
private function _longPoll() {
set_time_limit(30);
// We're going to keep a running tally of the number of times
// we've checked for, but haven't received, messages. As that
// number increases, the sleep duration will increase.
$no_msg_count = 0;
$start = time();
do {
$messages = Message::getMany('to', $this->user_id);
if(!$messages) {
$no_msg_count++;
sleep(2.5 + min($no_msg_count * 1.5, 7.5));
}
} while(!$messages && time() - $start < 30);
if($messages)
return $this->_pollParseMessages($messages);
else
return array();
}
private function _shortPoll() {
$messages = Message::getMany('to', $this->user_id);
if($messages) {
return $this->_pollParseMessages($messages);
} else {
return array('r' => 'no messages');
}
}
private function _comet() {
set_time_limit(0);
// First, fix buffers
echo str_repeat(chr(32), self::FIXBUFFER) . self::FIXEOL , ob_get_clean();
$no_msg_count = 0;
while(true) {
$messages = Message::getMany('to', $this->user_id);
if(!$messages) {
$no_msg_count++;
sleep(2.5 + min($no_msg_count * 1.5, 7.5));
echo chr(32) , ob_get_clean();
if(connection_aborted()) return;
} else {
$no_msg_count = 0;
echo '<script type="text/javascript">parent.AjaxIM.incoming(' .
json_encode($this->_pollParseMessages($messages)) .
');</script>' . self::FIXEOL , ob_get_clean();
sleep(1);
}
}
}
private function _pollParseMessages($messages) {
$msg_arr = array();
foreach($messages as $msg) {
$msg_arr[] = array('t' => $msg->type, 's' => $msg->from, 'r' => $msg->to, 'm' => $msg->message);
}
return $msg_arr;
}
private function _sanitize($str) {
return str_replace('>', '&gt;', str_replace('<', '&lt;', str_replace('&', '&amp;', $str)));
}
}
/* End of libraries/server/Default.php */
+132
Ver Arquivo
@@ -0,0 +1,132 @@
<?php
/*
* Library: NodeJS
* Author: Joshua Gross
* Version: 0.1 alpha
* Date: December 21, 2009
*
* Description:
* A library for the Node.js server. It will authenticate a
* user against the default database, and then add the user to
* the server.
*
* Requirements: Database, Node.js
*/
class NodeJS_IM extends IM {
function __construct() {
parent::__construct();
global $nodejs_memcache_server;
if(!is_array($nodejs_memcache_server))
die(json_encode(array('r' => 'error', 'e' => 'server misconfigured')));
$this->memcache = memcache_connect($nodejs_memcache_server[0], $nodejs_memcache_server[1]);
$cookie = json_decode($_COOKIE[COOKIE_NAME]);
if($cookie) {
$session = json_decode($this->memcache->get('session/' . $cookie->sid));
if($session) {
$this->username = $session->username;
$this->user_id = $session->user_id;
$this->server_key = $session->server_key;
}
}
}
function __destruct() {
$this->memcache->close();
}
public function login($username, $password) {
if($user = User::authenticate($username, $password)) {
// user just logged in, update login time.
$user->lastLogin(time());
$session_id = md5(microtime(true) . $user->username);
$session = array(
'username' => $user->username,
'user_id' => intval($user->user_id),
'session_id' => $session_id,
'friends' => Friend::of($user->user_id, true)
);
$cookie = json_encode(array(
'user' => $user->username,
'sid' => $session_id
));
setcookie(COOKIE_NAME, $cookie, time()+(60*60*24*COOKIE_PERIOD), '/', COOKIE_DOMAIN);
$this->memcache->add($user->username, json_encode($session));
return array('r' => 'logged in', 's' => $session_id, 'f' => $session['friends']);
} else {
return array('r' => 'error', 'e' => 'invalid user');
}
}
public function logout() {
$this->memcache->delete($this->username);
return array('r' => 'logged out');
}
public function register($username, $password) {
if(preg_match('/^[A-Za-z0-9_.]{3,16}$/', $username)) {
if(strlen($password) > 3) {
$db = MySQL_Database::instance();
$test_username_sql = "SELECT COUNT(user_id) FROM " . MYSQL_PREFIX . "users
WHERE username LIKE :username";
$test_username = $db->prepare($test_username_sql);
$test_username->execute(array(':username' => $username));
if(!$test_username->fetchColumn()) {
// hash the password
$password = md5($password);
$pw_str = substr($password, 0, 8);
$password = $pw_str . md5($pw_str . $password);
$register_sql = "INSERT INTO " . MYSQL_PREFIX . "users
(username, password, last_known_ip)
VALUES(:username, :password, :ip)";
$register = $db->prepare($register_sql);
$is_registered = $register->execute(array(
':username' => $username,
':password' => $password,
':ip' => ip2long($_SERVER['REMOTE_ADDR'])
));
if($is_registered) {
return array('r' => 'registered');
} else {
return array('r' => 'error', 'e' => 'unknown');
}
} else {
return array('r' => 'error', 'e' => 'username taken');
}
} else {
return array('r' => 'error', 'e' => 'invalid password');
}
} else {
return array('r' => 'error', 'e' => 'invalid username');
}
}
public function add_friend($friend, $group) {
if(!$this->username)
return array('r' => 'error', 'e' => 'no session found');
$friend = new Friend($this->username, $friend, $group);
$friend_obj_id = $friend->save();
if($friend_obj_id) {
$friend_arr = Friend::get($friend_obj_id);
$this->memcache->set('user/' . $this->username . '/friends/add', json_encode($friend_arr));
return array('r' => 'added');
} else {
return array('r' => 'error', 'e' => 'invalid user');
}
}
}
/* End of libaries/server/NodeJS.php */
+93
Ver Arquivo
@@ -0,0 +1,93 @@
<?php
/*
* Library: NodeJS (Guests)
* Author: Joshua Gross
* Version: 0.1 alpha
* Date: December 21, 2009
*
* Description:
* A library for the Node.js server. It does not require any
* sort of database installation, and will automatically create
* "Guest" users, making it possible to automatically sign on
* individuals without any sort of registration.
*
* Requirements: Node.js
*/
class NodeJS_Guests_IM extends IM {
function __construct() {
parent::__construct();
global $nodejs_memcache_server;
if(!is_array($nodejs_memcache_server))
die(json_encode(array('r' => 'error', 'e' => 'server misconfigured')));
$this->memcache = memcache_connect($nodejs_memcache_server[0], $nodejs_memcache_server[1]);
$cookie = json_decode($_COOKIE[COOKIE_NAME]);
if($cookie) {
$session = json_decode($this->memcache->get('session/' . $cookie->sid));
if($session) {
$this->username = $session->username;
$this->user_id = $session->user_id;
}
}
}
function __destruct() {
$this->memcache->close();
}
public function login($username='', $password='') {
$username = 'Guest' . (microtime(true) * 100);
$session_id = md5(microtime(true) . $username);
$friends_raw = json_decode($this->memcache->get('list/'));
$friends = array();
foreach($friends_raw as $friend) {
$friends[] = array(
'u' => $friend->username,
's' => $friend->status,
'g' => 'Users'
);
}
$session = array(
'username' => $username,
'user_id' => $username,
'session_id' => $session_id,
'friends' => $friends,
'guest' => true
);
$cookie = json_encode(array(
'user' => $username,
'sid' => $session_id
));
setcookie(COOKIE_NAME, $cookie, time()+(60*60*24*COOKIE_PERIOD), '/', COOKIE_DOMAIN);
$this->memcache->add($username, json_encode($session));
$this->memcache->set('from/' . $username . '/broadcast/raw', json_encode(array(
't' => 's',
's' => $username,
'r' => 'all',
'm' => '1:',
'g' => 'Users'
)));
return array(
'r' => 'logged in',
'u' => $username,
's' => $session_id,
'f' => $session['friends']
);
}
public function logout() {
$this->memcache->delete($this->username);
return array('r' => 'logged out');
}
}
/* End of libraries/server/NodeJS.php */
+26
Ver Arquivo
@@ -0,0 +1,26 @@
<?php
class IM {
function __construct() {
}
public function login($username, $password) {
return array('e'=>'not implemented');
}
public function logout() {
return array('e'=>'not implemented');
}
public function send($to, $message) {
return array('e'=>'not implemented');
}
public function status($status, $message) {
return array('e'=>'not implemented');
}
public function poll($method) {
}
}
/* End of libraries/server/base.php */
+33
Ver Arquivo
@@ -0,0 +1,33 @@
// == Node.js Server Configuration ==
//
// This is the configuration file for the Node.js Ajax IM server. Here, you
// can set which ports will be used for the public and internal servers,
// as well as other settings such as the session cookie name and expiration.
// === {{{ ports }}} ===
//
// Define the ports and hosts that Ajax IM will run on. {{{public}}} is the
// public-facing API, while {{{private}}} is the memcache-compatible API
// intended for server-side use.
//
// The first item of each array is the port, the second is the host name. If
// you do not want to specify a host, set it to {{{null}}}.
exports.ports = {
public: [8000, 'localhost'],
private: [11998, 'localhost']
};
// === {{{ cookie }}} ===
//
// Define the cookie name and how long a session will be stored on the server.
// If you change the cookie name here, you will also need to change it in the
// PHP login script/configuration; if you fail to do this, the Node.js server
// will be looking for a cookie that does not exist.
//
// **Note:** The period for the session should be as long or longer than the
// cookie itself is set to be stored. If it is less, the user won't be logged
// back in automatically, as their cookie will have been deleted.
exports.cookie = {
name: 'ajaxim_session',
period: 8760
};
+794
Ver Arquivo
@@ -0,0 +1,794 @@
// = Ajax IM =
//
// **Copyright &copy; 2005 &ndash; 2010 Joshua Gross**\\
// //MIT Licensed//
//
// 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.
//
// == Node.js Server ==
//
// This is the [[http://nodejs.org|node.js]] server for Ajax IM. It handles
// user state and passing communications amongst users, though it still
// relies on outside assistance for initial authentication. It is recommended
// that this server be used, rather than the PHP-only server script.
var sys = require('sys'),
http = require('http'),
tcp = require('tcp'),
config = require('./config');
var AjaxIM = function(config) {
var self = this;
// === {{{ public variables }}} ===
//
// There are a few public class variables that can be accessed
// if need be.
//
// * {{{users}}} is a hash table of all active users, by username. Each active
// user has their own hash table containing state and connection information:
// ** {{{username}}} is the identifying name of the user. It is the same as the hash key.
// ** {{{user_id}}} is the database-stored "id" of the user.
// ** {{{session_id}}} is the session identifier that the user uses to communicate with the server. It is stored in a cookie on the client-side.
// ** {{{last_active}}} is a Unix timestamp signifying when the user last executed a server-side action. It is used to determine when a user has become inactive.
// ** {{{friends}}} is the list of the user's friends, as provided on login. Follows the same format as is outlined in {{{im.js}}}
// ** {{{status}}} is the user's status, in the format {{{ {s: 0, m: 'message'}, }}} where {{{s}}} is the status code, and {{{m}}} is the status message.
// ** {{{callback}}} is the function that will send data back to this user through any open connections. Should this user not be connected at that moment, messages are queued.
// * {{{sessions}}} is a hash table of session ids with usernames as values.
// * {{{debug}}} enables or disables debug messages from being output to the console. Set manually.
// * {{{onlineCount}}} contains the number of users online at any one moment.
this.users = {};
this.sessions = {};
this.config = config;
this.debug = true;
this.onlineCount = 0;
// === {{{ AjaxIM.init() }}} ===
//
// Initializes the frontend webserver and the backend Memcache server, which provides
// and easy-to-use API for controlling the server from other scripts.
this.init = function() {
if(typeof this.config.ports.public[0] != 'number' ||
typeof this.config.ports.private[0] != 'number')
throw new TypeError();
this.server = new WebServer(this.config.ports.public[1],
this.config.ports.public[0]);
this.server.get('^/poll$', this.poll);
this.server.get('^/send$', this.send);
this.server.get('^/status$', this.status);
this.server.get('^/resume$', this.resume);
this.server.get('^/online$', this.online);
this.server.start();
this.internalServer =
new MemcacheServer(this.config.ports.private[1], this.config.ports.private[0]);
this.internalServer.login(function(username, data) {
self.apiLogin.apply(self, [username, data]);
});
this.internalServer.getUser(function(cmd) {
var actions = {
'session': self.apiGetSession,
'username': self.apiGetUser,
'list': self.apiGetUserList,
'online': self.apiOnlineCount
};
var parts = cmd.split('/');
if(parts[0] in actions) {
if(parts.length > 1 && parts[1].length > 0)
return actions[parts[0]].apply(self, parts.slice(1));
else
return actions[parts[0]].apply(self);
}
});
this.internalServer.logout(function(username) {
return (self._killUser.call(self, username) !== false);
});
this.internalServer.setCustom('friends/add', function(type, id, value) {
self.apiAddFriend.apply(self, [type, id, value]);
});
this.internalServer.setCustom('friends/remove', function(type, id, value) {
self.apiRemoveFriend.apply(self, [type, id, value]);
});
this.internalServer.setCustom('broadcast/message', function(type, id, value) {
self.apiBroadcastMessage.apply(self, [type, id, value]);
});
this.internalServer.setCustom('broadcast/raw', function(type, id, value) {
self.apiBroadcastRaw.apply(self, [type, id, value]);
});
this.internalServer.start();
this._start_gc();
}
// === //private//\\ {{{ AjaxIM._start_gc() }}} ===
//
// The "garbage collector," which is run every 5 seconds. It signs out
// users which are no longer active and have no active connections. Those
// users that have not been active for 50 or more seconds but have an active
// connection have their connections reset (to prevent them from automatically
// timing out).
this._start_gc = function() {
// Remove inactive users (> 30 seconds of inactivity & no callbacks)
setInterval(function() {
for(username in self.users) {
var user = self.users[username];
if((self._now() - user.last_active) > 50000 &&
user._callbacks.length == 0) {
self._killUser(username);
} else if((self._now() - user.last_active) >= 50000) {
user.callback();
}
}
}, 5000); // 5 seconds
// Remove old sessions after session expiry period
setInterval(function() {
for(s in self.sessions) {
var session = self.sessions[s];
var age = (self._now() - session.last_active) / 3600000; // in hours
if(age >= self.config.cookie.period) {
self._d('Session [' + s + '] for user [' +
session.username + '] has expired and has been discarded.');
delete self.sessions[s];
}
}
}, 3600000); // 1 hour
};
// === //private//\\ {{{ AjaxIM._now() }}} ===
//
// Returns the current time in milliseconds.
this._now = function() {
return (new Date()).getTime();
};
// === //private//\\ {{{ AjaxIM._session(request, provide) }}} ===
//
// Returns the requested session information, {{{provide}}}, based on
// the given request object, {{{request}}}. If the session does not
// exist, {{{false}}} is returned. If {{{'object'}}} is requested and
// there is no active session for that user, {{{false}}} is also returned.
//
// {{{request}}} is a request object, as is provided by the {{{http}}} module
// {{{provide}}} is one of:
// * {{{username}}} which merely checks for the existence of session data and
// returns the username for that session.
// * {{{object}}} checks for the existence of the session //and// the existence
// of an active session (the user is currently logged in), and returns the user
// object, if found.
this._session = function(request, provide) {
if(this.config.cookie.name in request.cookies) {
try {
var session_id = request.cookies[this.config.cookie.name].sid;
if(session_id in this.sessions) {
var session = this.sessions[session_id];
} else {
return false;
}
} catch(e) {
this._d('Invalid cookie for an unknown user.');
return false;
}
}
switch(provide) {
case 'username':
return session.username;
break;
case 'session':
return session;
break;
case 'object':
if(session.username in this.users) {
return this.users[session.username];
} else {
return false;
}
break;
}
};
// === //private//\\ {{{ AjaxIM._d(str) }}} ===
//
// If debugging is enabled, this function prints debug data, with the
// current formatted time, to the console.
// {{{str}}} is the debug string.
this._d = function(str) {
if(this.debug) {
var addZero = function(str) { return str < 10 ? '0' + str : str; };
var d = new Date();
var d_str = addZero(d.getMonth() + 1) + '/' + addZero(d.getDate()) + '/' + d.getFullYear() + ' ' +
addZero(d.getHours()) + ':' + addZero(d.getMinutes()) + ':' + addZero(d.getSeconds());
sys.puts('[' + d_str + '] ' + str);
}
};
// === //private//\\ {{{ AjaxIM._initUser(username, data) }}} ===
this._initUser = function(username, data) {
if(data['user_id']) {
self._d('User [' + username + '] has connected. Adding to user hash and notifying friends.');
if(!(username in self.users)) {
self.users[username] = {
username: username,
user_id: data.user_id,
session_id: data.session_id,
last_active: self._now(),
friends: data.friends,
status: {s: 1, m: ''},
guest: data['guest'] ? true : false,
callback: function(msg) {
var cbs = self.users[username]._callbacks;
if(msg)
self.users[username]._queue.push(msg);
if(cbs.length) {
for(var i = 0; i < cbs.length; i++)
cbs[i](self.users[username]._queue);
self.users[username]._callbacks = [];
self.users[username]._queue = [];
} else {
if(self.users[username]._callbackAttempts < 3) {
setTimeout(function() {
try {
self.users[username].callback();
self.users[username]._callbackAttempts++;
} catch(e) {}
}, 150);
} else {
self.users[username]._callbackAttempts = 0;
}
}
},
_callbacks: [],
_queue: [],
_callbackAttempts: 0
};
self.onlineCount++;
}
self.sessions[data.session_id] = {
username: username,
user_id: data.user_id,
friends: data.friends,
last_active: self._now()
};
return true;
} else {
return false;
}
};
// === //private//\\ {{{ AjaxIM._killUser() }}} ===
this._killUser = function(username) {
if(!username || !(username in self.users))
return false;
var user = self.users[username];
if(user['guest']) {
// User was a guest, so notify everyone that they logged off and remove their session.
self.apiBroadcastRaw('from', username, {t: 's', s: username, r: '', m: '0:'});
delete self.sessions[self.users[username].session_id];
} else {
user.friends.forEach(function(f) {
if(f.u in self.users) {
for(var i=0; i < self.users[f.u]['friends'].length; i++) {
if(self.users[f.u]['friends'][i].u == username && self.users[f.u]['friends'][i].u != user.username) {
self.users[f.u]['friends'][username].s = 0;
break;
}
}
self.users[f.u].callback({t: 's', s: username, r: f.u, m: '0:'});
}
});
}
user.callback();
self._d('User [' + username + '] has disconnected. Notifying friends and removing from user hash.');
delete self.users[username];
self.onlineCount--;
};
// === {{{ AjaxIM.poll() }}} ===
this.poll = function() {
if(this.debug && ('sid' in this.request.uri.params && this.request.uri.params['sid'].length))
this.request.cookies[self.config.cookie.name] = {sid: this.request.uri.params.sid};
if(!(user = self._session(this.request, 'object'))) {
var r = this;
self._d('User with session id [' + ('ajaxim_session' in this.request.cookies ?
this.request.cookies.ajaxim_session['sid'] :
'unknown'
) + '] tried to connect. No/invalid session found.');
r.response.reply(200, {'r': 'error', 'e': 'no session found'});
} else {
var response = this.response;
user._callbacks.push(function(msg) { response.reply(200, msg); });
self.users[user.username].last_active = self._now();
self.sessions[user.session_id].last_active = self._now();
}
};
// === {{{ AjaxIM.resume() }}} ===
this.resume = function() {
if(!(user = self._session(this.request, 'username'))) {
this.response.reply(200, {'r': 'error', 'e': 'no session found'});
} else {
if(!(user in self.users)) {
session = self._session(this.request, 'session');
session['session_id'] = this.request.cookies[self.config.cookie.name].sid;
self._initUser(user, session);
}
this.response.reply(200, {'r': 'connected'});
}
};
// === {{{ AjaxIM.send() }}} ===
this.send = function() {
var sent = false;
var user = self._session(this.request, 'object');
var to = this.request.uri.params['to'];
if(!user) {
self._d('An unknown user tried to send a message to [' + to + '] without being authenticated.');
return this.response.reply(200, {'r': 'error', 'e': 'no session found'});
}
if(user.username && to &&
to in self.users &&
self.users[to].callback
) {
var time = Math.round((new Date()).getTime() / 1000);
self.users[to].callback({
t: 'm',
s: user.username,
r: to,
m: this.request.uri.params.message
});
sent = true;
}
self._d('User [' + user.username + '] sent a message to [' + to + '] ' + (sent ? 'successfully.' : 'UNSUCCESSFULLY.'));
self.users[user.username].last_active = self._now();
self.sessions[user.session_id].last_active = self._now();
this.response.reply(200, {'sent': sent});
};
// === {{{ AjaxIM.status() }}} ===
this.status = function() {
var status_updated = false;
var user = self._session(this.request, 'object');
if(!user) {
self._d('An unknown user tried to change their status without being authenticated.');
return this.response.reply(200, {'r': 'error', 'e': 'no session found'});
}
var status = this.request.uri.params.status;
var statusMsg = status + ':' + this.request.uri.params.message;
user.friends.forEach(function(f) {
if(f.u in self.users) {
var group = null;
for(var i=0; i < self.users[f.u]['friends'].length; i++) {
if(self.users[f.u]['friends'][i].u == user.username) {
self.users[f.u]['friends'][i].s = status;
group = self.users[f.u]['friends'][i].g;
break;
}
}
self.users[f.u].callback({t: 's', s: user.username, r: f.u, m: statusMsg, g: group});
}
});
self._d('User [' + user.username + '] set his/her status to [' + statusMsg + ']. Friends notified.');
self.users[user.username].status = {s: status, m: this.request.uri.params.message};
self.users[user.username].last_active = self._now();
self.sessions[user.session_id].last_active = self._now();
this.response.reply(200, {status_updated: status_updated});
};
// === {{{ AjaxIM.online() }}} ===
this.online = function() {
this.response.reply(200, {count: self.onlineCount});
};
// === {{{ AjaxIM.apiLogin(username, data) }}} ===
this.apiLogin = function(username, data) {
this._initUser.call(self, username, data);
};
// === {{{ AjaxIM.apiGetUser(username) }}} ===
this.apiGetUser = function(username) {
var user = this.users[username];
return {
username: user.username,
user_id: user.user_id,
status: user.status,
session_id: user.session_id
};
};
// === {{{ AjaxIM.apiGetSession(session_id) }}} ===
this.apiGetSession = function(session_id) {
if(session_id in this.sessions)
return this.apiGetUser(this.sessions[session_id].username);
else
return false;
};
// === {{{ AjaxIM.apiGetUserList() }}} ===
this.apiGetUserList = function() {
var users = [];
for(var username in this.users) {
var user = this.users[username];
if(user.status.s > 0) {
users.push({
username: user.username,
user_id: user.user_id,
status: user.status,
session_id: user.session_id
});
}
}
return users;
};
// === {{{ AjaxIM.apiOnlineCount() }}} ===
this.apiOnlineCount = function() {
return {count: this.onlineCount};
};
// === {{{ AjaxIM.apiAddFriend(type, id, value) }}} ===
this.apiAddFriend = function(type, id, value) {
if(type == 'session') {
if(id in this.sessions)
id = this.sessions[id].username;
else
return false;
}
if(id in this.users && typeof value == 'object' && 'u' in value) {
if(value.u in this.users) {
value['s'] = this.users[value.u].status.s;
var status = this.users[value.u].status.s + ':' +
this.users[value.u].status.m;
this.users[id].callback({t: 's', s: value.u, r: id, m: status, g: value.g});
}
this.users[id].friends.push(value);
return true;
} else {
return false;
}
};
// === {{{ AjaxIM.apiRemoveFriend(type, id, value) }}} ===
this.apiRemoveFriend = function(type, id, value) {
if(type == 'session') {
if(id in this.sessions)
id = this.sessions[id].username;
else
return false;
}
if(id in this.users && typeof value == 'string' && value.length > 0) {
for(var i = 0; i < this.users[id].friends.length; i++) {
if(this.users[id].friends[i].u == value) {
var group = this.users[id].friends[i].g;
// should be a 'remove' type, not a 'status' type...we'll fix this later.
this.users[id].callback({t: 's', s: value, r: id, m: '0:', g: group});
return true;
}
}
}
return false;
};
// === {{{ AjaxIM.apiBroadcastMessage(type, id, value) }}} ===
this.apiBroadcastMessage = function(type, id, value) {
if(type != 'from' || !id.length)
return false;
for(user in this.users) {
this.users[user].callback({t: 'm', s: id, r: user, m: value});
}
return true;
};
// === {{{ AjaxIM.apiBroadcastRaw(type, id, value) }}} ===
this.apiBroadcastRaw = function(type, id, value) {
if(type != 'from' || !id.length || typeof value != 'object')
return false;
for(user in this.users) {
this.users[user].callback(value);
}
return true;
};
};
// == WebServer Class ==
function WebServer(host, port) {
var self = this;
this.host = host;
this.port = port;
this.urlMap = [];
this.get = function(path, handler) {
this._map(path, 'GET', handler);
};
this.post = function(path, handler) {
this._map(path, 'POST', handler);
};
this._map = function(path, type, handler) {
var path_regex = new RegExp(path);
this.urlMap.push([path_regex, type, handler]);
};
this._notFound = function() {
var nf = 'Not Found\n';
this.response.sendHeader(404, {
'Content-Type': 'text/plain',
'Content-Length': nf.length
});
this.response.sendBody(nf);
this.response.finish();
};
this._parseCookies = function(str) {
var c = {};
if(!str) return c;
str = str.replace(/;/g, ', ');
str.split(', ').forEach(function(cookie) {
var parts = cookie.split('='),
name = parts[0].trim(),
value = parts[1].trim();
try {
c[name] = JSON.parse(decodeURIComponent(value));
} catch(e) {
c[name] = value;
}
});
return c;
}
this.start = function() {
http.createServer(function(request, response) {
var handler = self._notFound, args = [];
for(var i = 0; i < self.urlMap.length; i++) {
var map = self.urlMap[i];
if(map[1] == request.method && map[0].test(request.uri.path)) {
args = map[0].exec(request.uri.path);
handler = map[2];
break;
}
}
request.setBodyEncoding('utf8');
request.cookies = self._parseCookies(request.headers['cookie']);
response.reply = function(code, obj) {
var content = JSON.stringify(obj);
response.sendHeader(code, {
'Content-Type': 'text/html',
'Content-Length': content.length,
'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
'Pragma': 'no-cache'
});
response.sendBody(request.uri.params.callback + '(' + content + ');');
response.finish();
}
handler.apply({request: request, response: response}, args.slice(1));
}).listen(this.port, this.host);
};
}
// == MemcacheServer Class ==
function MemcacheServer(host, port) {
var self = this;
this.host = host;
this.port = port;
this._cb_login = null;
this._cb_logout = null;
this._cb_getuser = null;
this._cb_custom = {};
this.login = function(callback) {
this._cb_login = callback;
};
this.logout = function(callback) {
this._cb_logout = callback;
};
this.getUser = function(callback) {
this._cb_getuser = callback;
};
this.setCustom = function(action, callback) {
this._cb_custom[action] = callback;
};
this._add = function(username, data) {
if(typeof self._cb_login != 'function' ||
!('user_id' in data) || !('session_id' in data)) {
this.send('NOT_STORED\r\n');
} else if(self._cb_login(username, data)) {
this.send('STORED\r\n');
} else {
this.send('NOT_STORED\r\n');
}
};
this._set = function(username, action, value) {
if(!action.length || !value) {
this.send('NOT_STORED\r\n');
} else {
var result = false;
for(var axn in self._cb_custom) {
var rx = new RegExp(axn);
if(rx.test(action)) {
result = self._cb_custom[axn](username[0], username[1], value);
break;
}
}
if(result) {
this.send('STORED\r\n');
} else {
this.send('NOT_STORED\r\n');
}
}
};
this._delete = function(username) {
if(typeof self._cb_logout == 'function' && self._cb_logout(username)) {
this.send('DELETED\r\n');
} else {
this.send('NOT_FOUND\r\n');
}
};
this._get = function(username) {
if(typeof self._cb_getuser == 'function') {
var user = self._cb_getuser(username);
if(user) {
var json_user = JSON.stringify(user);
this.send('VALUE ' + username + ' 0 ' + json_user.length + '\r\n')
this.send(json_user + '\r\n');
}
}
this.send('END\r\n');
};
this._gets = function(list) {
if(typeof self._cb_getuser == 'function') {
var results = [];
for(var i = 0; i < list.length; i++) {
var user = self._cb_getuser(list[i]);
if(user) {
var json_user = JSON.stringify(user);
results.push('VALUE ' + list[i] + ' 0 ' + json_user.length + '\r\n');
results.push(json_user + '\r\n');
}
}
if(results.length) {
this.send(results.join(''));
}
}
this.send('END\r\n');
};
this.start = function() {
tcp.createServer(function(socket) {
socket.setEncoding('utf8');
var cmd = {};
var incoming = '';
socket.addListener('receive', function(data) {
incoming += data;
// We're in the middle of receiving some data, so we can't
// parse it yet.
if(data.substring(data.length - 2) != '\r\n')
return;
data = incoming;
incoming = '';
var parts = data.split(/ /);
if(parts[0].match(/^(add|set|delete|get|gets)$/i)) {
switch(parts[0]) {
case 'add':
var message = JSON.parse(data.split('\r\n')[1]);
self._add.call(socket, parts[1].replace('\r\n', ''), message);
break;
case 'set':
var message = data.split('\r\n')[1];
try {
message = JSON.parse(message);
} catch(e) {}
var subparts = parts[1].replace('\r\n', '').split('/');
self._set.call(socket, subparts.slice(0, 2), subparts.slice(2).join('/'), message);
break;
case 'delete':
self._delete.call(socket, parts[1].replace('\r\n', ''));
break;
case 'get':
self._get.call(socket, parts[1].replace('\r\n', ''));
break;
case 'gets':
var getsparts = parts.slice(1);
getsparts[getsparts.length - 1] =
getsparts[getsparts.length - 1].replace('\r\n', '');
self._gets.call(socket, getsparts);
break;
}
}
});
}).listen(this.port, this.host);
};
}
var im = new AjaxIM(config);
im.init();
+8
Ver Arquivo
@@ -0,0 +1,8 @@
Emoticons and "error" icon from "LED Icon Set" by led24.de
----------------------------------------------------------
You can do whatever you want with these icons (use on web or in desktop applications) as long as you dont pass them off as your own and remove this readme file. A credit statement and a link back to
http://led24.de/iconset/ or http://led24.de/ would be appreciated.
Follow us on twitter http://twitter.com/gasyoun or email leds24@gmail.com
512 icons 20/05/2009
----------------------------------------------------------
Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 868 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 814 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 853 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 853 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 850 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 843 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 860 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 846 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 854 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 121 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 176 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 552 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 212 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 706 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 142 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 141 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 234 B

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 109 B

+528
Ver Arquivo
@@ -0,0 +1,528 @@
.imjs-default { display: none; }
/* [begin] Chatbox */
.imjs-chatbox {
position: absolute;
bottom: 25px;
right: -1px;
width: 225px;
border: 1px solid #cecece;
font: 12px/14px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
color: #000;
cursor: default;
text-shadow: none;
}
.imjs-chatbox > div {
display: block;
}
/* [begin] Chatbox header */
div.imjs-header {
display: block;
position: relative;
width: 215px;
height: 12px;
padding: 5px;
background: #f0efed;
border-bottom: 1px solid #999;
font-weight: 700;
box-shadow: 0 1px 2px #ccc;
-moz-box-shadow: 0 1px 2px #ccc;
text-shadow: 0 1px 0 #fff;
color: #333;
}
div.imjs-header a {
position: absolute;
text-shadow: none;
color: #333;
text-decoration: none;
line-height: 2em;
}
div.imjs-header a.imjs-close {
top: 6px;
right: 5px;
height: 0;
padding-top: 10px;
width: 10px;
overflow: hidden;
background: url(images/closemin.png) 0 0 no-repeat;
}
div.imjs-header a.imjs-minimize {
position: absolute;
top: 0;
left: 0;
padding-top: 23px;
height: 0;
width: 207px;
overflow: hidden;
background: url(images/closemin.png) 100% -10px no-repeat;
}
div.imjs-header a.imjs-minimize:active {
outline: none;
}
/* [end] Chatbox header */
/* [begin] Message log */
ul.imjs-msglog {
display: block;
overflow-y: auto;
height: 235px;
list-style-type: none;
margin: 0;
padding: 0;
border-bottom: 1px solid #ddd;
background: #fff;
}
li.imjs-date {
display: block;
padding: 5px 5px 3px 8px;
border-top: 1px dotted #afafaf;
background-color: #e9e9e9;
}
li.imjs-error {
display: block;
padding: 0 5px 3px 8px;
border-top: 1px dotted #afafaf;
background-color: #ffeded;
color: #ff0000;
}
li.imjs-error span.imjs-msg-time {
color: #ff0000;
}
li.imjs-msg-a, li.imjs-msg-b {
display: block;
padding: 3px 5px 3px 8px;
border-top: 1px dotted #bfbfbf;
}
li.imjs-msg-b > span {
color: #ff0000;
font-weight: 700;
}
li.imjs-msg-a > span {
color: #0099ff;
font-weight: 700;
}
li.imjs-msg-old {
opacity: 0.4;
}
/* [end] Message log */
/* [begin] Message Log Messages */
ul.imjs-msglog li ul {
list-style-type: none;
margin: 0;
padding: 0;
font-size: 11px;
line-height: 14px;
}
ul.imjs-msglog li ul span {
float: left;
margin-right: 5px;
color: #bcbcbc;
}
li.imjs-msg-a ul p, li.imjs-msg-b ul p, li.imjs-date ul p {
margin: 0;
}
/* [end] Message Log Messages */
/* [begin] Input */
textarea.imjs-input {
font: 12px/14px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
height: 16px;
padding: 3px;
margin: 0;
width: 219px;
border: solid #aaa;
border-width: 1px 0 0 0;
overflow: hidden;
}
/* [end] Input */
/* [end] Chatbox */
/* [begin] Messenger bar */
ul#imjs-bar {
display: block;
position: fixed;
bottom: 0;
left: 50%;
width: 95%;
background: #f0efed url(images/w.png) top left repeat-x;
height: 25px;
border: solid #cfceca;
border-width: 1px 1px 0 1px;
list-style-type: none;
padding: 0;
margin: 0 0 0 -47.5%;
font: 12px/25px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
color: #222;
}
/* [begin] Generic bar item */
ul#imjs-bar > li {
position: relative;
float: right;
width: 161px;
border-left: 1px solid #cecece;
padding: 0 10px;
cursor: pointer;
text-shadow: 0 1px 0 #fff;
}
ul#imjs-bar > li:hover {
background: #fff;
}
ul#imjs-bar > li .imjs-tab-text strong {
position: relative;
color: #00cc00;
font-size: 28px;
line-height: 19px;
top: 6px;
margin-right: 5px;
}
ul#imjs-bar > li.imjs-offline .imjs-tab-text strong {
color: #777;
}
ul#imjs-bar > li.imjs-away .imjs-tab-text strong {
color: #df9b00;
}
ul#imjs-bar > li.imjs-selected {
text-shadow: 0 1px 0 #eaeaea;
background: #fff;
color: #000;
margin: -1px 0 0;
border: solid #444;
border-width: 0 1px 1px 1px;
width: 160px;
line-height: 23px;
height: 25px;
}
ul#imjs-bar > li.imjs-selected .imjs-tab-text {
font-weight: 700;
}
ul#imjs-bar > li.imjs-selected .imjs-tab-text strong {
line-height: 17px;
}
ul#imjs-bar > li.imjs-selected .imjs-tab-text a {
display: block;
}
ul#imjs-bar > li.imjs-selected > .imjs-chatbox {
border-color: #444;
border-bottom: 0;
padding-bottom: 1px;
background-image: url(images/bottom.png);
background-position: left bottom;
background-repeat: no-repeat;
}
ul#imjs-bar > li.imjs-selected > #imjs-friends-panel.imjs-chatbox {
background-repeat: repeat-x;
background-position: -45px bottom;
}
/* [begin] Generic bar close */
ul#imjs-bar > li .imjs-tab-text a {
float: right;
text-decoration: none;
display: none;
width: 10px;
height: 0;
padding-top: 10px;
overflow: hidden;
margin-top: 7.5px;
background: url(images/closemin.png) 0 0 no-repeat;
}
ul#imjs-bar > li:hover .imjs-tab-text a {
display: inline;
}
/* [end] Generic bar close */
/* [end] Generic bar item */
/* [begin] Bar scrolling buttons */
ul#imjs-bar > li.imjs-scroll {
width: 20px;
text-align: center;
font-size: 9px;
font-weight: 700;
background-repeat: no-repeat;
}
ul#imjs-bar li#imjs-scroll-left {
padding: 1px 6px 0 4px;
background-image: url(images/sl.png);
background-position: 5px center;
}
ul#imjs-bar li#imjs-scroll-right {
padding: 1px 5px 0;
background-image: url(images/sr.png);
background-position: 20px center;
}
/* [end] Bar scrolling buttons */
/* [begin] Notification icon */
span.imjs-notification {
display: block;
position: absolute;
width: 15px;
height: 15px;
right: -9px;
top: -12px;
padding: 2px;
line-height: 16px;
background: #eb2121;
color: #fff;
text-shadow: none;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
overflow: hidden;
text-align: center;
}
/* [end] Notification icon */
/* [begin] Tooltip */
span.imjs-tooltip {
display: none;
position: absolute;
padding-bottom: 5px;
margin: 0 0 3px 6px;
left: -10000px;
background: url(images/tooltip.png) right bottom no-repeat;
color: #fff;
text-shadow: none;
opacity: 0.9;
}
span.imjs-tooltip p {
font: 11px/18px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
margin: 0;
padding: 2px 6px;
background: #000;
max-width: 200px;
}
/* [end] Tooltip */
/* [begin] Friends list button */
ul#imjs-bar > li#imjs-friends.imjs-not-connected,
ul#imjs-bar > li#imjs-friends.not-connected:hover {
width: 10px;
background-image: url(images/error.png);
background-position: center;
background-repeat: no-repeat;
}
ul#imjs-bar > li#imjs-friends.imjs-not-connected span.imjs-tab-text {
margin-left: -10000px;
}
li#imjs-friends .imjs-tab-text span {
color: #888;
}
li#imjs-friends .imjs-tab-text span > span {
color: #222;
font-weight: 700;
}
/* [end] Friends list button */
/* [end] Messenger bar */
/* [begin] Friends list */
div#imjs-friends-panel {
background: #fff;
width: 200px;
right: auto;
left: -1px;
z-index: 100;
}
div#imjs-friends-panel div.imjs-header {
width: 190px;
}
div#imjs-friends-panel a.imjs-minimize {
width: 194px;
}
div#imjs-friends-panel a.imjs-minimize:active {
outline: 0;
}
ul#imjs-friends-list {
list-style-type: none;
padding: 0;
margin: 0;
font: 12px/25px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
max-height: 300px;
overflow-x: hidden;
overflow-y: auto;
}
ul#imjs-friends-list li, ul.imjs-friend-group li {
width: 200px;
padding: 0;
margin: 0;
cursor: pointer;
list-style-type: none;
}
span.imjs-friend-group-header {
display: block;
padding: 0 0 0 5px;
width: 195px;
font-weight: 700;
border-top: 1px solid #aaa;
cursor: default;
}
li.imjs-friend-group ul {
margin: 0 0 5px;
padding: 0;
}
li.imjs-friend-group ul li {
width: 200px;
}
li.imjs-friend-group ul li:hover {
background: #0055aa;
color: #fff;
}
li.imjs-friend-group ul li > strong {
position: relative;
color: #00cc00;
font-size: 28px;
line-height: 19px;
top: 6px;
margin: 0 5px;
}
li.imjs-friend-group ul li.imjs-offline > strong {
color: #777;
}
li.imjs-friend-group ul li.imjs-away > strong {
color: #df9b00;
}
li.imjs-friend-group ul li.imjs-selected {
background: #686868;
color: #eee;
font-weight: 700;
text-shadow: 0 1px 0 #333;
}
div#imjs-friends-panel form, div#imjs-friends-panel form p {
margin: 0;
padding: 0;
}
input#imjs-search-friends {
font: 12px/14px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
height: 16px;
width: 194px;
padding: 6px 3px 3px;
margin: 0;
border: solid #aaa;
border-width: 1px 0 0 0;
color: #aaa;
}
/* [end] Friends list */
/* [begin] Login/Registration Forms */
div#imjs-lr form {
background: #F0EFED url(images/w.png) repeat-x;
border: 1px solid #cfceca;
max-width: 220px;
padding: 5px 5px 10px 10px;
overflow: auto;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
}
div#imjs-lr .error {
font: 700 12px/18px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
color: #ff0000;
}
div#imjs-lr form fieldset {
border: 0;
padding: 0;
margin: 0;
overflow: auto;
}
div#imjs-lr form h2 {
font: 700 20px/24px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
margin: 0;
padding: 7px 0 0;
color: #555;
text-shadow: 0 1px 0px #fff;
}
div#imjs-lr form label {
display: block;
font: 700 12px/14px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
color: #7B7A79;
}
div#imjs-lr form input {
width: 200px;
}
div#imjs-lr form input.imjs-lr-error, div#imjs-lr form input.imjs-lr-error:focus {
margin: -1px;
border: 2px solid #ff1111;
}
div#imjs-lr form input, div#imjs-lr form button {
border: 1px solid #ddd;
color: #000;
padding: 4px 3px;
font: 16px/20px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
}
div#imjs-lr form input:focus, div#imjs-lr form button:focus {
margin: -1px;
border: 2px solid #999;
}
div#imjs-lr form button {
float: right;
background: #f4f3f1;
}
p.imjs-submit {
width: 207px;
overflow: visible;
}
form#imjs-login {
margin-bottom: 10px;
}
/* [end] Login/Registration Forms */
+132
Ver Arquivo
@@ -0,0 +1,132 @@
<!-- Ajax IM Instant Messenger, Footer Bar -->
<ul id="imjs-bar">
<li id="imjs-friends" class="imjs-not-connected">
<span class="imjs-tab-text"><strong>&bull;</strong> Friends <span>(<span>0</span>)</span></span>
<div id="imjs-friends-panel" class="imjs-chatbox">
<div class="imjs-header">
<span>{username}</span>
<a href="#" class="imjs-minimize">_</a>
</div>
<ul id="imjs-friends-list">
<li class="imjs-friend-group imjs-default">
<span class="imjs-friend-group-header">{group}</span>
<ul>
<li class="imjs-friend imjs-default"><strong>&bull;</strong> {username}</li>
</ul>
</li>
</ul>
<form>
<p><input type="text" id="imjs-search-friends" value="Search" /></p>
</form>
</div>
</li>
<li id="imjs-scroll-right" class="imjs-scroll">{count}</li>
<li class="imjs-tab imjs-default">
<span class="imjs-tab-text"><strong>&bull;</strong> {label} <a href="#" class="imjs-close">x</a></span>
<span class="imjs-notification">{count}</span>
<form class="imjs-chatbox">
<div>
<div class="imjs-header">
<span>{username}</span>
<a href="#" class="imjs-close">x</a>
<a href="#" class="imjs-minimize">_</a>
</div>
<ul class="imjs-msglog">
<li class="imjs-date">
<ul>
<li>
<span class="imjs-msg-time">hh:MM TT &bull;</span>
<p class="imjs-date-date">ddd, mmmm d, yyyy</p>
</li>
</ul>
</li>
<li class="imjs-error">
<ul>
<li>
<span class="imjs-msg-time">hh:MM TT &bull;</span>
<p class="imjs-error-error">ddd, mmmm d, yyyy</p>
</li>
</ul>
</li>
<li class="imjs-msg-a">
<span>{username}</span>
<ul class="imjs-msg-a-container">
<li class="imjs-msg-a-msg">
<span class="imjs-msg-time">hh:MM TT &bull;</span>
<p>{message}</p>
</li>
</ul>
</li>
<li class="imjs-msg-b">
<span>{username}</span>
<ul class="imjs-msg-b-container">
<li class="imjs-msg-b-msg">
<span class="imjs-msg-time">hh:MM TT &bull;</span>
<p>{message}</p>
</li>
</ul>
</li>
</ul>
<textarea class="imjs-input"></textarea>
</div>
</form>
</li>
<li id="imjs-scroll-left" class="imjs-scroll">{count}</li>
</ul>
<span class="imjs-tooltip"><p>{tip}</p></span>
<!-- Ajax IM Instant Messenger, Login/Registration Form -->
<div id="imjs-lr">
<form id="imjs-login">
<fieldset>
<h2>Login</h2>
<p class="error"></p>
<p>
<label for="imjs-login-username">Username</label>
<input type="text" name="username" id="imjs-login-username" />
</p>
<p>
<label for="imjs-login-password">Password</label>
<input type="password" name="password" id="imjs-login-password" />
</p>
<p class="imjs-submit">
<button id="imjs-login-submit">Sign In</button>
</p>
</fieldset>
<p id="imjs-logged-in">Signed in as <strong>{username}</strong>. <a href="#logout">Sign Out</a>.</p>
</form>
<form id="imjs-register">
<fieldset>
<h2>Register</h2>
<p class="error"></p>
<p>
<label for="imjs-register-username">Username</label>
<input type="text" name="username" id="imjs-register-username" />
</p>
<p>
<label for="imjs-register-password">Password</label>
<input type="password" name="password" id="imjs-register-password" />
</p>
<p>
<label for="imjs-register-cpassword">Confirm Password</label>
<input type="password" name="cpassword" id="imjs-register-cpassword" />
</p>
<p class="imjs-submit">
<button id="imjs-register-submit">Register</button>
</p>
</fieldset>
</form>
</div>