Comparar commits
98 Commits
| Autor | SHA1 | Data | |
|---|---|---|---|
| ac361419b8 | |||
| 7985251207 | |||
| 5805778a17 | |||
| f522e0874e | |||
| 58bdceef45 | |||
| b20f678a38 | |||
| ba32c3b727 | |||
| a6ef421f79 | |||
| 9f7c470b05 | |||
| 0a5b025c3e | |||
| c75b3d2f31 | |||
| bb3fc41c32 | |||
| 6f05609dab | |||
| 0893da7df5 | |||
| 7658637231 | |||
| 01df091f45 | |||
| 9e7ab46683 | |||
| 1c3c68c7db | |||
| 48f51255a1 | |||
| 1678ebb345 | |||
| acf9bffb7e | |||
| dff403f604 | |||
| 80d5d177f5 | |||
| 786aec2505 | |||
| 438ea86155 | |||
| ed404bffcb | |||
| 1b1a7a5159 | |||
| fd191229a0 | |||
| c8747974ee | |||
| d6caf96690 | |||
| 8b94d6c411 | |||
| 5226091385 | |||
| a89a9f0ac4 | |||
| 519ae5c751 | |||
| 014375eea3 | |||
| e1097a73d5 | |||
| 26282c4929 | |||
| b52aab4136 | |||
| ad03007044 | |||
| b38ba6a3c5 | |||
| 8c26db802f | |||
| 7a7015078a | |||
| 2742cdd014 | |||
| c1d9011d70 | |||
| 884e776d3e | |||
| 677587ca05 | |||
| d0afe8590d | |||
| 5be7d482e7 | |||
| ea69a15a62 | |||
| 6899d8e63d | |||
| c819c7ec43 | |||
| 8d2675e328 | |||
| c44ec4751d | |||
| 9a9bbfef50 | |||
| 3be668abaf | |||
| b98e531bca | |||
| 02896ecc4a | |||
| 43289d0d17 | |||
| eeac0be514 | |||
| f00a7fe1c3 | |||
| eb5a174e3b | |||
| 053795c875 | |||
| 4cd2d4f406 | |||
| e43ecf2c82 | |||
| dc8a4ab000 | |||
| 00de205459 | |||
| 263b00b5cd | |||
| 409199ea97 | |||
| 3d667cf94b | |||
| df28002475 | |||
| e90343e072 | |||
| 3a2b35f2db | |||
| 46fdfb74c3 | |||
| a16b250bd1 | |||
| 115480d535 | |||
| bf45db98a5 | |||
| 1d66d44a5d | |||
| 8338810e21 | |||
| 5f8c4d02c6 | |||
| 1806a93762 | |||
| 728711939f | |||
| 78ac74f202 | |||
| b7b5a874c4 | |||
| 27255ac23d | |||
| 67927622fb | |||
| a73d883a76 | |||
| 0b921b5afa | |||
| 065d5f84a7 | |||
| 833883928a | |||
| 7fd52d5454 | |||
| 1308dca732 | |||
| 3da4903542 | |||
| 2fe92d49be | |||
| 1d34639a7c | |||
| 7b44b2aede | |||
| 7a33c1a039 | |||
| 02d51c63ae | |||
| 18b44b6312 |
@@ -0,0 +1,7 @@
|
||||
local/*
|
||||
*.local.*
|
||||
*.local/
|
||||
server/libs/daemon/daemon.node
|
||||
server/libs/daemon/.lock-wscript
|
||||
client/js/im.compiled.js
|
||||
client/js/im.min.js
|
||||
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2005 - 2010 Joshua Gross, http://ajaxim.com
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,44 @@
|
||||
SRC_DIR = client/js
|
||||
BUILD_DIR = build
|
||||
|
||||
PREFIX = .
|
||||
DIST_DIR = client/js
|
||||
|
||||
BASE_FILES = ${SRC_DIR}/md5.js\
|
||||
${SRC_DIR}/store.js\
|
||||
${SRC_DIR}/cookies.js\
|
||||
${SRC_DIR}/dateformat.js\
|
||||
${SRC_DIR}/json.js\
|
||||
${SRC_DIR}/im.js
|
||||
|
||||
MODULES = ${SRC_DIR}/intro.js\
|
||||
${BASE_FILES}\
|
||||
${SRC_DIR}/outro.js
|
||||
|
||||
IMJS = ${DIST_DIR}/im.compiled.js
|
||||
IMJS_MIN = ${DIST_DIR}/im.min.js
|
||||
|
||||
COMPILER = java -jar ${BUILD_DIR}/google-compiler-20100616.jar
|
||||
|
||||
all: imjs min
|
||||
@@echo "Ajax IM build complete."
|
||||
|
||||
imjs: ${IMJS}
|
||||
|
||||
${IMJS}: ${MODULES}
|
||||
@@echo "Building" ${IMJS}
|
||||
@@cat ${MODULES} | sed 's/debug = true/debug = false/' > ${IMJS}
|
||||
|
||||
min: ${IMJS_MIN}
|
||||
|
||||
${IMJS_MIN}: ${IMJS}
|
||||
@@echo "Building" ${IMJS_MIN}
|
||||
|
||||
@@head -21 ${IMJS} > ${IMJS_MIN}
|
||||
@@${COMPILER} --js ${IMJS} --warning_level QUIET >> ${IMJS_MIN}
|
||||
@@rm -f ${IMJS}
|
||||
|
||||
clean:
|
||||
@@echo "Removing built files"
|
||||
@@rm -f ${IMJS}
|
||||
@@rm -f ${IMJS_MIN}
|
||||
@@ -1,2 +1,233 @@
|
||||
# What is Ajax IM?
|
||||
**Ajax IM ("Ajax Instant Messenger") is a browser-centric instant messaging framework.** It uses AJAX to create a real-time (or near real-time) IM environment that can be used in conjunction with existing community and commercial software, or simply as a stand-alone product.
|
||||
# Ajax IM
|
||||
|
||||
## What is Ajax IM?
|
||||
|
||||
Ajax IM ("Ajax Instant Messenger") is an instant messenger for the web. It is
|
||||
intended to be integrated with existing websites to provide a more interactive
|
||||
community experience.
|
||||
|
||||
## Features
|
||||
|
||||
* Instant communication between connected users
|
||||
* Robust backend server built on [Node.js](http://nodejs.org)
|
||||
* Support for [Socket.IO](http://socket.io), JSON and JSONP
|
||||
* Can be integrated with virtually any existing website
|
||||
* Seamless authentication
|
||||
* Works across an entire website, unobtrusively
|
||||
* Automatic state management between page reloads
|
||||
* User state and statuses
|
||||
* and _much_ more!
|
||||
|
||||
## Installation
|
||||
|
||||
Install `Node.js`:
|
||||
|
||||
wget http://nodejs.org/dist/v0.10.32/node-v0.10.32-linux-x86.tar.gz
|
||||
tar xzf node-v0.10.32-linux-x86.tar.gz
|
||||
cd node-v0.10.32-linux-x86
|
||||
./configure
|
||||
make
|
||||
make install
|
||||
|
||||
Install Ajax IM:
|
||||
|
||||
unzip AjaxIM_v4.0a4.zip
|
||||
cd AjaxIM_v4.0a4
|
||||
npm install
|
||||
|
||||
## Starting up the server
|
||||
|
||||
Starting the server in _development_ mode is as simple as:
|
||||
|
||||
node server/app.js
|
||||
|
||||
To start the server in _production_ mode:
|
||||
|
||||
NODE_ENV=production node server/app.js
|
||||
|
||||
To start the server using forever with a log file:
|
||||
|
||||
npm install forever
|
||||
forever -l ~/ajaxim.log start ~/AjaxIM_v4.0a4/server/app.js
|
||||
|
||||
## Testing it out
|
||||
|
||||
Once the server is up and running in _development_ mode, you can test it out
|
||||
through the included development testing app. The below instructions are
|
||||
assuming that you have left all default configuration options. If not, please
|
||||
replace the host/port values with the correct ones.
|
||||
|
||||
To get started, head over to the development page:
|
||||
|
||||
http://localhost:8000/dev/
|
||||
|
||||
That's it!
|
||||
|
||||
## More Information
|
||||
|
||||
* Follow [ajaximrpg](http://twitter.com/ajaximrpg) on twitter for updates
|
||||
* [Google Group](http://groups.google.com/group/ajaxim) for discussion
|
||||
* [GitHub Wiki](https://github.com/endtwist/AjaxIM/wiki) for guidance
|
||||
|
||||
## Node Compatibility
|
||||
|
||||
The `master` branch of Ajax IM is compatible with node --version:
|
||||
|
||||
v0.10.32
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull requests are being accepted! If you would like to contribute, simply fork
|
||||
the project and make your changes.
|
||||
|
||||
### Style Guide
|
||||
|
||||
If you intend on contributing, please follow this style guide when submitting
|
||||
patches or commits. Submissions that do not follow these guidelines will not
|
||||
be accepted.
|
||||
|
||||
* Use 4 space indents (not tabs!)
|
||||
* No trailing whitespace
|
||||
* Blank line at the end of files
|
||||
* Semi-colons at the ends of lines, where appropriate
|
||||
* Keep lines to 80 characters or less
|
||||
* Never bump the version
|
||||
|
||||
No whitespace between keys and values:
|
||||
{foo: 'bar'}
|
||||
// good
|
||||
|
||||
{foo : 'bar'}
|
||||
// bad
|
||||
|
||||
Hash formatting:
|
||||
{foo: 'bar', baz: 'taz'}
|
||||
// good
|
||||
|
||||
{
|
||||
foo: 'bar',
|
||||
baz: 'taz',
|
||||
moo: 'cow'
|
||||
}
|
||||
// good
|
||||
|
||||
{ foo: 'bar', baz: 'taz' }
|
||||
// bad
|
||||
|
||||
{foo: 'bar',
|
||||
baz: 'taz',
|
||||
moo: 'cow'}
|
||||
// bad
|
||||
|
||||
Chained methods:
|
||||
str
|
||||
.strip
|
||||
.replace(...)
|
||||
.replace(...)
|
||||
// good
|
||||
|
||||
str
|
||||
.strip
|
||||
.replace(...)
|
||||
.replace(...)
|
||||
// bad
|
||||
|
||||
str.
|
||||
strip.
|
||||
replace(...).
|
||||
replace(...)
|
||||
// bad
|
||||
|
||||
Single quotes over double quotes, unless double quotes make sense:
|
||||
'hello'
|
||||
// good
|
||||
|
||||
"what's up?"
|
||||
// good
|
||||
|
||||
"hello"
|
||||
// bad
|
||||
|
||||
Ternary expressions are fine, but cannot be nested and must be formatted as:
|
||||
foo = (a ? b : c);
|
||||
// good
|
||||
|
||||
foo = (something.hasAPropertyLikeThis == 'some other value'
|
||||
? 'result one'
|
||||
: 'result two'
|
||||
);
|
||||
// good
|
||||
|
||||
foo = something.hasAPropertyLikeThis === 'some other value' ?
|
||||
'result one' :
|
||||
'result two'
|
||||
// bad
|
||||
|
||||
Use braces for conditionals, unless conditionals are single statements:
|
||||
if(foo) {
|
||||
bar();
|
||||
baz();
|
||||
}
|
||||
// good
|
||||
|
||||
if(foo) bar();
|
||||
else baz();
|
||||
// good
|
||||
|
||||
if(foo)
|
||||
bar(),
|
||||
baz()
|
||||
// bad
|
||||
|
||||
Closures:
|
||||
function() {
|
||||
}
|
||||
// good
|
||||
|
||||
function () {
|
||||
}
|
||||
// bad
|
||||
|
||||
function()
|
||||
{
|
||||
}
|
||||
// bad
|
||||
|
||||
Methods:
|
||||
foo.bar = function() {
|
||||
}
|
||||
// good
|
||||
|
||||
foo.bar = function (){
|
||||
}
|
||||
// bad
|
||||
|
||||
foo.bar = function()
|
||||
{
|
||||
}
|
||||
// bad
|
||||
|
||||
## License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2012-2014 [Daniel Howard] (http://www.svexpertise.com)
|
||||
Copyright (c) 2010 [Joshua Gross](http://www.unwieldy.net)
|
||||
|
||||
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.
|
||||
@@ -1,81 +0,0 @@
|
||||
<?php
|
||||
// = ajaxim.php =
|
||||
//
|
||||
// **Copyright © 2005 – 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 ajaxim.php */
|
||||
@@ -1,93 +0,0 @@
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Ajax IM</title>
|
||||
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
|
||||
<script src="js/md5.js" type="text/javascript"></script>
|
||||
<script src="js/store.js" type="text/javascript"></script>
|
||||
<script src="js/dateformat.js" type="text/javascript"></script>
|
||||
<script src="js/im.js" type="text/javascript"></script>
|
||||
<script type="text/javascript">
|
||||
$(function(){
|
||||
var u = window.location.href.split("/");
|
||||
var p = 8000; // Node.js port
|
||||
u = u[0]+"//"+u[2]+":"+p;
|
||||
var im = AjaxIM.init({pollServer: u, theme: "themes/default"});
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
Hello.
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,120 @@
|
||||
// Date Format 1.2.3\\
|
||||
// © 2007-2009 Steven Levithan ([[http://blog.stevenlevithan.com/archives/date-time-format|stevenlevithan.com]])\\
|
||||
// MIT license
|
||||
//
|
||||
// Includes enhancements by Scott Trenda
|
||||
// and Kris Kowal ([[http://cixar.com/~kris.kowal/|cixar.com/~kris.kowal/]])
|
||||
//
|
||||
// Accepts a date, a mask, or a date and a mask and returns a formatted version
|
||||
// of the given date.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{date}}} is a {{{Date()}}} object. If not specified, the date defaults to the
|
||||
// current date/time.
|
||||
// * {{{mask}}} is a string that defines the formatting of the date. Formatting
|
||||
// options can be found in the
|
||||
// [[http://blog.stevenlevithan.com/archives/date-time-format|Date Format]]
|
||||
// documentation. If not specified, the mask defaults to {{{dateFormat.masks.default}}}.
|
||||
|
||||
var dateFormat = function() {
|
||||
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
|
||||
timezone = new RegExp('\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) ' +
|
||||
'(?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b',
|
||||
'g'),
|
||||
timezoneClip = /[^-+\dA-Z]/g,
|
||||
pad = function (val, len) {
|
||||
val = String(val);
|
||||
len = len || 2;
|
||||
while (val.length < len) val = "0" + val;
|
||||
return val;
|
||||
};
|
||||
|
||||
// Regexes and supporting functions are cached through closure
|
||||
return function (date, mask, utc) {
|
||||
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
|
||||
if (arguments.length == 1 && Object.prototype.toString.call(date) ==
|
||||
"[object String]" && !/\d/.test(date)) {
|
||||
mask = date;
|
||||
date = undefined;
|
||||
}
|
||||
|
||||
// Passing date through Date applies Date.parse, if necessary
|
||||
date = date ? new Date(date) : new Date;
|
||||
if (isNaN(date)) throw SyntaxError("invalid date");
|
||||
|
||||
mask = String(dateFormat.masks[mask] ||
|
||||
mask ||
|
||||
dateFormat.masks["default"]);
|
||||
|
||||
// Allow setting the utc argument via the mask
|
||||
if (mask.slice(0, 4) == "UTC:") {
|
||||
mask = mask.slice(4);
|
||||
utc = true;
|
||||
}
|
||||
|
||||
var _ = utc ? "getUTC" : "get",
|
||||
d = date[_ + "Date"](),
|
||||
D = date[_ + "Day"](),
|
||||
m = date[_ + "Month"](),
|
||||
y = date[_ + "FullYear"](),
|
||||
H = date[_ + "Hours"](),
|
||||
M = date[_ + "Minutes"](),
|
||||
s = date[_ + "Seconds"](),
|
||||
L = date[_ + "Milliseconds"](),
|
||||
o = utc ? 0 : date.getTimezoneOffset(),
|
||||
flags = {
|
||||
d: d,
|
||||
dd: pad(d),
|
||||
ddd: AjaxIM.l10n.dayNames[D],
|
||||
dddd: AjaxIM.l10n.dayNames[D + 7],
|
||||
m: m + 1,
|
||||
mm: pad(m + 1),
|
||||
mmm: AjaxIM.l10n.monthNames[m],
|
||||
mmmm: AjaxIM.l10n.monthNames[m + 12],
|
||||
yy: String(y).slice(2),
|
||||
yyyy: y,
|
||||
h: H % 12 || 12,
|
||||
hh: pad(H % 12 || 12),
|
||||
H: H,
|
||||
HH: pad(H),
|
||||
M: M,
|
||||
MM: pad(M),
|
||||
s: s,
|
||||
ss: pad(s),
|
||||
l: pad(L, 3),
|
||||
L: pad(L > 99 ? Math.round(L / 10) : L),
|
||||
t: H < 12 ? "a" : "p",
|
||||
tt: H < 12 ? "am" : "pm",
|
||||
T: H < 12 ? "A" : "P",
|
||||
TT: H < 12 ? "AM" : "PM",
|
||||
Z: utc ? "UTC" :
|
||||
(String(date).match(timezone) || [""])
|
||||
.pop().replace(timezoneClip, ""),
|
||||
o: (o > 0 ? "-" : "+") +
|
||||
pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
|
||||
S: ["th", "st", "nd", "rd"][d % 10 > 3 ?
|
||||
0 :
|
||||
(d % 100 - d % 10 != 10) * d % 10]
|
||||
};
|
||||
|
||||
return mask.replace(token, function ($0) {
|
||||
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
|
||||
});
|
||||
};
|
||||
}();
|
||||
|
||||
// Some common format strings
|
||||
dateFormat.masks = {
|
||||
"default": "ddd mmm dd yyyy HH:MM:ss",
|
||||
shortDate: "m/d/yy",
|
||||
mediumDate: "mmm d, yyyy",
|
||||
longDate: "mmmm d, yyyy",
|
||||
fullDate: "dddd, mmmm d, yyyy",
|
||||
shortTime: "h:MM TT",
|
||||
mediumTime: "h:MM:ss TT",
|
||||
longTime: "h:MM:ss TT Z",
|
||||
isoDate: "yyyy-mm-dd",
|
||||
isoTime: "HH:MM:ss",
|
||||
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
|
||||
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
|
||||
};
|
||||
@@ -0,0 +1,227 @@
|
||||
/*
|
||||
http://www.JSON.org/json2.js
|
||||
2010-03-20
|
||||
Public Domain.
|
||||
*/
|
||||
if (!this.JSON) {
|
||||
this.JSON = {};
|
||||
}
|
||||
|
||||
(function () {
|
||||
|
||||
function f(n) {
|
||||
// Format integers to have at least two digits.
|
||||
return n < 10 ? '0' + n : n;
|
||||
}
|
||||
|
||||
if (typeof Date.prototype.toJSON !== 'function') {
|
||||
|
||||
Date.prototype.toJSON = function (key) {
|
||||
|
||||
return isFinite(this.valueOf()) ?
|
||||
this.getUTCFullYear() + '-' +
|
||||
f(this.getUTCMonth() + 1) + '-' +
|
||||
f(this.getUTCDate()) + 'T' +
|
||||
f(this.getUTCHours()) + ':' +
|
||||
f(this.getUTCMinutes()) + ':' +
|
||||
f(this.getUTCSeconds()) + 'Z' : null;
|
||||
};
|
||||
|
||||
String.prototype.toJSON =
|
||||
Number.prototype.toJSON =
|
||||
Boolean.prototype.toJSON = function (key) {
|
||||
return this.valueOf();
|
||||
};
|
||||
}
|
||||
|
||||
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
||||
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
|
||||
gap,
|
||||
indent,
|
||||
meta = { // table of character substitutions
|
||||
'\b': '\\b',
|
||||
'\t': '\\t',
|
||||
'\n': '\\n',
|
||||
'\f': '\\f',
|
||||
'\r': '\\r',
|
||||
'"' : '\\"',
|
||||
'\\': '\\\\'
|
||||
},
|
||||
rep;
|
||||
|
||||
|
||||
function quote(string) {
|
||||
escapable.lastIndex = 0;
|
||||
return escapable.test(string) ?
|
||||
'"' + string.replace(escapable, function (a) {
|
||||
var c = meta[a];
|
||||
return typeof c === 'string' ? c :
|
||||
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
||||
}) + '"' :
|
||||
'"' + string + '"';
|
||||
}
|
||||
|
||||
|
||||
function str(key, holder) {
|
||||
var i,
|
||||
k,
|
||||
v,
|
||||
length,
|
||||
mind = gap,
|
||||
partial,
|
||||
value = holder[key];
|
||||
|
||||
if (value && typeof value === 'object' &&
|
||||
typeof value.toJSON === 'function') {
|
||||
value = value.toJSON(key);
|
||||
}
|
||||
|
||||
if (typeof rep === 'function') {
|
||||
value = rep.call(holder, key, value);
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return quote(value);
|
||||
|
||||
case 'number':
|
||||
return isFinite(value) ? String(value) : 'null';
|
||||
|
||||
case 'boolean':
|
||||
case 'null':
|
||||
return String(value);
|
||||
|
||||
case 'object':
|
||||
if (!value) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
gap += indent;
|
||||
partial = [];
|
||||
|
||||
if (Object.prototype.toString.apply(value) === '[object Array]') {
|
||||
length = value.length;
|
||||
for (i = 0; i < length; i += 1) {
|
||||
partial[i] = str(i, value) || 'null';
|
||||
}
|
||||
|
||||
v = partial.length === 0 ? '[]' :
|
||||
gap ? '[\n' + gap +
|
||||
partial.join(',\n' + gap) + '\n' +
|
||||
mind + ']' :
|
||||
'[' + partial.join(',') + ']';
|
||||
gap = mind;
|
||||
return v;
|
||||
}
|
||||
|
||||
if (rep && typeof rep === 'object') {
|
||||
length = rep.length;
|
||||
for (i = 0; i < length; i += 1) {
|
||||
k = rep[i];
|
||||
if (typeof k === 'string') {
|
||||
v = str(k, value);
|
||||
if (v) {
|
||||
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (k in value) {
|
||||
if (Object.hasOwnProperty.call(value, k)) {
|
||||
v = str(k, value);
|
||||
if (v) {
|
||||
partial.push(quote(k) + (gap ? ': ' : ':') + v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join all of the member texts together, separated with commas,
|
||||
// and wrap them in braces.
|
||||
|
||||
v = partial.length === 0 ? '{}' :
|
||||
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
|
||||
mind + '}' : '{' + partial.join(',') + '}';
|
||||
gap = mind;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
// If the JSON object does not yet have a stringify method, give it one.
|
||||
|
||||
if (typeof JSON.stringify !== 'function') {
|
||||
JSON.stringify = function (value, replacer, space) {
|
||||
|
||||
// The stringify method takes a value and an optional replacer, and an optional
|
||||
// space parameter, and returns a JSON text. The replacer can be a function
|
||||
// that can replace values, or an array of strings that will select the keys.
|
||||
// A default replacer method can be provided. Use of the space parameter can
|
||||
// produce text that is more easily readable.
|
||||
|
||||
var i;
|
||||
gap = '';
|
||||
indent = '';
|
||||
|
||||
if (typeof space === 'number') {
|
||||
for (i = 0; i < space; i += 1) {
|
||||
indent += ' ';
|
||||
}
|
||||
|
||||
} else if (typeof space === 'string') {
|
||||
indent = space;
|
||||
}
|
||||
|
||||
rep = replacer;
|
||||
if (replacer && typeof replacer !== 'function' &&
|
||||
(typeof replacer !== 'object' ||
|
||||
typeof replacer.length !== 'number')) {
|
||||
throw new Error('JSON.stringify');
|
||||
}
|
||||
|
||||
return str('', {'': value});
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof JSON.parse !== 'function') {
|
||||
JSON.parse = function (text, reviver) {
|
||||
var j;
|
||||
|
||||
function walk(holder, key) {
|
||||
var k, v, value = holder[key];
|
||||
if (value && typeof value === 'object') {
|
||||
for (k in value) {
|
||||
if (Object.hasOwnProperty.call(value, k)) {
|
||||
v = walk(value, k);
|
||||
if (v !== undefined) {
|
||||
value[k] = v;
|
||||
} else {
|
||||
delete value[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return reviver.call(holder, key, value);
|
||||
}
|
||||
|
||||
text = String(text);
|
||||
cx.lastIndex = 0;
|
||||
if (cx.test(text)) {
|
||||
text = text.replace(cx, function (a) {
|
||||
return '\\u' +
|
||||
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
|
||||
});
|
||||
}
|
||||
|
||||
if (/^[\],:{}\s]*$/.
|
||||
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
|
||||
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
|
||||
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
|
||||
j = eval('(' + text + ')');
|
||||
return typeof reviver === 'function' ?
|
||||
walk({'': j}, '') : j;
|
||||
}
|
||||
|
||||
throw new SyntaxError('JSON.parse');
|
||||
};
|
||||
}
|
||||
}());
|
||||
@@ -0,0 +1,256 @@
|
||||
/*
|
||||
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
|
||||
* Digest Algorithm, as defined in RFC 1321.
|
||||
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
|
||||
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
|
||||
* Distributed under the BSD License
|
||||
* See http://pajhome.org.uk/crypt/md5 for more info.
|
||||
*/
|
||||
|
||||
var md5 = (function() {
|
||||
/*
|
||||
* Calculate the MD5 of an array of little-endian words, and a bit length
|
||||
*/
|
||||
function core_md5(x, len) {
|
||||
/* append padding */
|
||||
x[len >> 5] |= 0x80 << ((len) % 32);
|
||||
x[(((len + 64) >>> 9) << 4) + 14] = len;
|
||||
|
||||
var a = 1732584193;
|
||||
var b = -271733879;
|
||||
var c = -1732584194;
|
||||
var d = 271733878;
|
||||
|
||||
for(var i = 0; i < x.length; i += 16) {
|
||||
var olda = a;
|
||||
var oldb = b;
|
||||
var oldc = c;
|
||||
var oldd = d;
|
||||
|
||||
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
|
||||
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
|
||||
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
|
||||
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
|
||||
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
|
||||
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
|
||||
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
|
||||
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
|
||||
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
|
||||
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
|
||||
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
|
||||
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
|
||||
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
|
||||
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
|
||||
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
|
||||
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
|
||||
|
||||
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
|
||||
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
|
||||
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
|
||||
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
|
||||
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
|
||||
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
|
||||
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
|
||||
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
|
||||
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
|
||||
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
|
||||
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
|
||||
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
|
||||
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
|
||||
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
|
||||
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
|
||||
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
|
||||
|
||||
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
|
||||
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
|
||||
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
|
||||
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
|
||||
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
|
||||
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
|
||||
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
|
||||
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
|
||||
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
|
||||
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
|
||||
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
|
||||
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
|
||||
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
|
||||
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
|
||||
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
|
||||
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
|
||||
|
||||
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
|
||||
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
|
||||
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
|
||||
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
|
||||
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
|
||||
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
|
||||
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
|
||||
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
|
||||
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
|
||||
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
|
||||
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
|
||||
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
|
||||
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
|
||||
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
|
||||
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
|
||||
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
|
||||
|
||||
a = safe_add(a, olda);
|
||||
b = safe_add(b, oldb);
|
||||
c = safe_add(c, oldc);
|
||||
d = safe_add(d, oldd);
|
||||
}
|
||||
return [a, b, c, d];
|
||||
}
|
||||
|
||||
/*
|
||||
* These functions implement the four basic operations the algorithm uses.
|
||||
*/
|
||||
function md5_cmn(q, a, b, x, s, t) {
|
||||
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
|
||||
}
|
||||
function md5_ff(a, b, c, d, x, s, t) {
|
||||
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
|
||||
}
|
||||
function md5_gg(a, b, c, d, x, s, t) {
|
||||
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
|
||||
}
|
||||
function md5_hh(a, b, c, d, x, s, t) {
|
||||
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
|
||||
}
|
||||
function md5_ii(a, b, c, d, x, s, t) {
|
||||
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculate the HMAC-MD5, of a key and some data
|
||||
*/
|
||||
function core_hmac_md5(key, data) {
|
||||
var bkey = str2binl(key);
|
||||
if(bkey.length > 16) bkey = core_md5(bkey, key.length * md5.chrsz);
|
||||
|
||||
var ipad = [], opad = [];
|
||||
for(var i = 0; i < 16; i++) {
|
||||
ipad[i] = bkey[i] ^ 0x36363636;
|
||||
opad[i] = bkey[i] ^ 0x5C5C5C5C;
|
||||
}
|
||||
|
||||
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * md5.chrsz);
|
||||
return core_md5(opad.concat(hash), 512 + 128);
|
||||
}
|
||||
|
||||
/*
|
||||
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
|
||||
* to work around bugs in some JS interpreters.
|
||||
*/
|
||||
function safe_add(x, y) {
|
||||
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
|
||||
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
|
||||
return (msw << 16) | (lsw & 0xFFFF);
|
||||
}
|
||||
|
||||
/*
|
||||
* Bitwise rotate a 32-bit number to the left.
|
||||
*/
|
||||
function bit_rol(num, cnt) {
|
||||
return (num << cnt) | (num >>> (32 - cnt));
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert a string to an array of little-endian words
|
||||
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
|
||||
*/
|
||||
function str2binl(str) {
|
||||
var bin = [], chrsz = md5.chrsz;
|
||||
var mask = (1 << chrsz) - 1;
|
||||
for(var i = 0; i < str.length * chrsz; i += chrsz)
|
||||
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
|
||||
return bin;
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an array of little-endian words to a string
|
||||
*/
|
||||
function binl2str(bin) {
|
||||
var str = "", chrsz = md5.chrsz;
|
||||
var mask = (1 << chrsz) - 1;
|
||||
for(var i = 0; i < bin.length * 32; i += chrsz)
|
||||
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
|
||||
return str;
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an array of little-endian words to a hex string.
|
||||
*/
|
||||
function binl2hex(binarray) {
|
||||
var hex_tab = md5.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
|
||||
var str = "";
|
||||
for(var i = 0; i < binarray.length * 4; i++) {
|
||||
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
|
||||
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an array of little-endian words to a base-64 string
|
||||
*/
|
||||
function binl2b64(binarray) {
|
||||
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var str = "";
|
||||
for(var i = 0; i < binarray.length * 4; i += 3) {
|
||||
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
|
||||
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
|
||||
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
|
||||
for(var j = 0; j < 4; j++) {
|
||||
if(i * 8 + j * 6 > binarray.length * 32) str += md5.b64pad;
|
||||
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
return {
|
||||
/*
|
||||
* Configurable variables. You may need to tweak these to be compatible with
|
||||
* the server-side, but the defaults work in most cases.
|
||||
*/
|
||||
hexcase: 0, // hex output format. 0 - lowercase; 1 - uppercase
|
||||
b64pad: "", // base-64 pad character. "=" for strict RFC compliance
|
||||
chrsz: 8, // bits per input character. 8 - ASCII; 16 - Unicode
|
||||
|
||||
/*
|
||||
* These are the functions you'll usually want to call
|
||||
* They take string arguments and return either hex or base-64 encoded strings
|
||||
*/
|
||||
hex:function( s ) {
|
||||
return binl2hex( core_md5( str2binl( s ), s.length * md5.chrsz ) );
|
||||
},
|
||||
|
||||
base64:function( s ) {
|
||||
return binl2b64( core_md5( str2binl( s ), s.length * md5.chrsz ) );
|
||||
},
|
||||
|
||||
string:function( s ) {
|
||||
return binl2str( core_md5( str2binl( s ), s.length * md5.chrsz ) );
|
||||
},
|
||||
|
||||
hmac:{
|
||||
hex:function( key, data ) {
|
||||
return binl2hex( core_hmac_md5( key, data ) );
|
||||
},
|
||||
|
||||
base64:function( key, data ) {
|
||||
return binl2b64( core_hmac_md5( key, data ) );
|
||||
},
|
||||
|
||||
string:function( key, data ) {
|
||||
return binl2str( core_hmac_md5( key, data ) );
|
||||
}
|
||||
},
|
||||
|
||||
test:function() { // Perform a simple self-test to see if the VM is working
|
||||
return this.hex("abc") == "900150983cd24fb0d6963f7d28e17f72";
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,82 @@
|
||||
// Storage API
|
||||
var store = (function(){
|
||||
var api = {},
|
||||
win = window,
|
||||
doc = win.document,
|
||||
sessionStorageName = 'sessionStorage',
|
||||
localStorageName = 'localStorage',
|
||||
globalStorageName = 'globalStorage',
|
||||
storage
|
||||
|
||||
api.set = function(key, value) {}
|
||||
api.get = function(key) {}
|
||||
api.remove = function(key) {}
|
||||
api.clear = function() {}
|
||||
|
||||
function serialize(value) {
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
function deserialize(value) {
|
||||
if (typeof value != 'string') { return undefined }
|
||||
return JSON.parse(value)
|
||||
}
|
||||
|
||||
if (sessionStorageName in win && win[sessionStorageName]) {
|
||||
storage = win[sessionStorageName]
|
||||
api.set = function(key, val) { storage[key] = serialize(val) }
|
||||
api.get = function(key) { return deserialize(storage[key]) }
|
||||
api.remove = function(key) { delete storage[key] }
|
||||
api.clear = function() { storage.clear() }
|
||||
|
||||
} else if (localStorageName in win && win[localStorageName]) {
|
||||
storage = win[localStorageName]
|
||||
api.set = function(key, val) { storage[key] = serialize(val) }
|
||||
api.get = function(key) { return deserialize(storage[key]) }
|
||||
api.remove = function(key) { delete storage[key] }
|
||||
api.clear = function() { storage.clear() }
|
||||
|
||||
} else if (globalStorageName in win && win[globalStorageName]) {
|
||||
storage = win[globalStorageName][win.location.hostname]
|
||||
api.set = function(key, val) { storage[key] = serialize(val) }
|
||||
api.get = function(key) { return deserialize(storage[key] && storage[key].value) }
|
||||
api.remove = function(key) { delete storage[key] }
|
||||
api.clear = function() { for (var key in storage ) { delete storage[key] } }
|
||||
|
||||
} else if (doc.documentElement.addBehavior) {
|
||||
function getStorage() {
|
||||
if (storage) { return storage; }
|
||||
storage = doc.body.appendChild(doc.createElement('div'))
|
||||
storage.style.display = 'none'
|
||||
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
|
||||
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
|
||||
storage.addBehavior('#default#userData')
|
||||
storage.load(localStorageName)
|
||||
return storage;
|
||||
}
|
||||
api.set = function(key, val) {
|
||||
var storage = getStorage()
|
||||
storage.setAttribute(key, serialize(val))
|
||||
storage.save(localStorageName)
|
||||
}
|
||||
api.get = function(key) {
|
||||
var storage = getStorage()
|
||||
return deserialize(storage.getAttribute(key))
|
||||
}
|
||||
api.remove = function(key) {
|
||||
var storage = getStorage()
|
||||
storage.removeAttribute(key)
|
||||
storage.save(localStorageName)
|
||||
}
|
||||
api.clear = function() {
|
||||
var storage = getStorage()
|
||||
var attributes = storage.XMLDocument.documentElement.attributes;
|
||||
storage.load(localStorageName)
|
||||
for (var i=0, attr; attr = attributes[i]; i++) {
|
||||
storage.removeAttribute(attr.name)
|
||||
}
|
||||
storage.save(localStorageName)
|
||||
}
|
||||
}
|
||||
|
||||
return api
|
||||
})();
|
||||
|
Antes Largura: | Altura: | Tamanho: 868 B Depois Largura: | Altura: | Tamanho: 868 B |
|
Antes Largura: | Altura: | Tamanho: 814 B Depois Largura: | Altura: | Tamanho: 814 B |
|
Antes Largura: | Altura: | Tamanho: 853 B Depois Largura: | Altura: | Tamanho: 853 B |
|
Antes Largura: | Altura: | Tamanho: 853 B Depois Largura: | Altura: | Tamanho: 853 B |
|
Antes Largura: | Altura: | Tamanho: 850 B Depois Largura: | Altura: | Tamanho: 850 B |
|
Antes Largura: | Altura: | Tamanho: 843 B Depois Largura: | Altura: | Tamanho: 843 B |
|
Antes Largura: | Altura: | Tamanho: 860 B Depois Largura: | Altura: | Tamanho: 860 B |
|
Antes Largura: | Altura: | Tamanho: 846 B Depois Largura: | Altura: | Tamanho: 846 B |
|
Antes Largura: | Altura: | Tamanho: 854 B Depois Largura: | Altura: | Tamanho: 854 B |
|
Depois Largura: | Altura: | Tamanho: 124 B |
|
Antes Largura: | Altura: | Tamanho: 176 B Depois Largura: | Altura: | Tamanho: 176 B |
|
Antes Largura: | Altura: | Tamanho: 552 B Depois Largura: | Altura: | Tamanho: 552 B |
|
Depois Largura: | Altura: | Tamanho: 847 B |
|
Antes Largura: | Altura: | Tamanho: 212 B Depois Largura: | Altura: | Tamanho: 212 B |
|
Antes Largura: | Altura: | Tamanho: 706 B Depois Largura: | Altura: | Tamanho: 706 B |
|
Antes Largura: | Altura: | Tamanho: 142 B Depois Largura: | Altura: | Tamanho: 142 B |
|
Antes Largura: | Altura: | Tamanho: 141 B Depois Largura: | Altura: | Tamanho: 141 B |
|
Antes Largura: | Altura: | Tamanho: 234 B Depois Largura: | Altura: | Tamanho: 234 B |
|
Antes Largura: | Altura: | Tamanho: 109 B Depois Largura: | Altura: | Tamanho: 109 B |
@@ -149,6 +149,8 @@
|
||||
border: solid #aaa;
|
||||
border-width: 1px 0 0 0;
|
||||
overflow: hidden;
|
||||
resize: none;
|
||||
outline: none;
|
||||
}
|
||||
/* [end] Input */
|
||||
/* [end] Chatbox */
|
||||
@@ -158,15 +160,14 @@ ul#imjs-bar {
|
||||
display: block;
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
width: 95%;
|
||||
right: 5%;
|
||||
background: #f0efed url(images/w.png) top left repeat-x;
|
||||
height: 25px;
|
||||
border: solid #cfceca;
|
||||
border-width: 1px 1px 0 1px;
|
||||
border-width: 1px 1px 0 0;
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
margin: 0 0 0 -47.5%;
|
||||
margin: 0;
|
||||
font: 12px/25px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
|
||||
color: #222;
|
||||
}
|
||||
@@ -174,7 +175,7 @@ ul#imjs-bar {
|
||||
/* [begin] Generic bar item */
|
||||
ul#imjs-bar > li {
|
||||
position: relative;
|
||||
float: right;
|
||||
float: left;
|
||||
width: 161px;
|
||||
border-left: 1px solid #cecece;
|
||||
padding: 0 10px;
|
||||
@@ -190,7 +191,8 @@ ul#imjs-bar {
|
||||
position: relative;
|
||||
color: #00cc00;
|
||||
font-size: 28px;
|
||||
line-height: 19px;
|
||||
line-height: 13px;
|
||||
left: -1px;
|
||||
top: 6px;
|
||||
margin-right: 5px;
|
||||
}
|
||||
@@ -232,13 +234,13 @@ ul#imjs-bar {
|
||||
border-bottom: 0;
|
||||
padding-bottom: 1px;
|
||||
background-image: url(images/bottom.png);
|
||||
background-position: left bottom;
|
||||
background-position: -142px bottom;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
ul#imjs-bar > li.imjs-selected > #imjs-friends-panel.imjs-chatbox {
|
||||
background-repeat: repeat-x;
|
||||
background-position: -45px bottom;
|
||||
background-position: -132px bottom;
|
||||
}
|
||||
|
||||
/* [begin] Generic bar close */
|
||||
@@ -267,18 +269,21 @@ ul#imjs-bar {
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
background-repeat: no-repeat;
|
||||
display: none;
|
||||
}
|
||||
|
||||
ul#imjs-bar li#imjs-scroll-left {
|
||||
padding: 1px 6px 0 4px;
|
||||
background-image: url(images/sl.png);
|
||||
background-position: 5px center;
|
||||
float: left;
|
||||
}
|
||||
|
||||
ul#imjs-bar li#imjs-scroll-right {
|
||||
padding: 1px 5px 0;
|
||||
background-image: url(images/sr.png);
|
||||
background-position: 20px center;
|
||||
float: right;
|
||||
}
|
||||
/* [end] Bar scrolling buttons */
|
||||
|
||||
@@ -326,8 +331,13 @@ ul#imjs-bar {
|
||||
/* [end] Tooltip */
|
||||
|
||||
/* [begin] Friends list button */
|
||||
ul#imjs-bar > li#imjs-friends {
|
||||
float: right;
|
||||
width: 125px;
|
||||
}
|
||||
|
||||
ul#imjs-bar > li#imjs-friends.imjs-not-connected,
|
||||
ul#imjs-bar > li#imjs-friends.not-connected:hover {
|
||||
ul#imjs-bar > li#imjs-friends.imjs-not-connected:hover {
|
||||
width: 10px;
|
||||
background-image: url(images/error.png);
|
||||
background-position: center;
|
||||
@@ -347,14 +357,111 @@ ul#imjs-bar {
|
||||
font-weight: 700;
|
||||
}
|
||||
/* [end] Friends list button */
|
||||
|
||||
/* [begin] Reconnect button */
|
||||
ul#imjs-bar > li#imjs-reconnect {
|
||||
display: none;
|
||||
float: right;
|
||||
width: 10px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
ul#imjs-bar > li#imjs-reconnect span {
|
||||
margin-left: -3px;
|
||||
}
|
||||
/* [end] Reconnect button */
|
||||
/* [end] Messenger bar */
|
||||
|
||||
/* [begin] Status panel */
|
||||
div#imjs-status-panel {
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
textarea#imjs-away-message-text {
|
||||
display: none;
|
||||
resize: none;
|
||||
width: 169px;
|
||||
height: 30px;
|
||||
margin: 5px 9px 0;
|
||||
padding: 5px;
|
||||
border: 1px solid #cfceca;
|
||||
font: 11px/17px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
|
||||
}
|
||||
|
||||
textarea#imjs-away-message-text.imjs-loading {
|
||||
background: url(images/loading.gif) 161px 2px no-repeat;
|
||||
}
|
||||
|
||||
div#imjs-away-message-text-arrow {
|
||||
display: none;
|
||||
width: 0;
|
||||
height: 0;
|
||||
margin: -3px 0 0 87px;
|
||||
border-style: solid;
|
||||
border-width: 4px 4px 0;
|
||||
border-color: #cfceca transparent transparent transparent;
|
||||
}
|
||||
|
||||
textarea#imjs-away-message-text:focus {
|
||||
outline: 2px solid #cfceca;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a.imjs-button {
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
padding: 0 7px;
|
||||
font-size: 10px;
|
||||
margin: 5px 0;
|
||||
-moz-border-radius: 10px;
|
||||
-webkit-border-radius: 10px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a.imjs-button span {
|
||||
float: left;
|
||||
font-size: 14px;
|
||||
margin: 1px 3px 0 0;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a.imjs-button.imjs-toggled {
|
||||
background-color: #e0e0e0;
|
||||
border-left-color: #c0c0c0;
|
||||
border-top-color: #c0c0c0;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a.imjs-button.imjs-toggled:hover {
|
||||
background-color: #d7d7d7;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a.imjs-button:hover {
|
||||
background: #e0e0e0;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a#imjs-button-away span {
|
||||
color: #df9b00;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a#imjs-button-available {
|
||||
margin-left: 12px;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a#imjs-button-available span {
|
||||
color: #00cc00;
|
||||
}
|
||||
|
||||
div#imjs-status-panel > a#imjs-button-offline span {
|
||||
color: #777;
|
||||
}
|
||||
/* [end] Status panel */
|
||||
|
||||
/* [begin] Friends list */
|
||||
div#imjs-friends-panel {
|
||||
background: #fff;
|
||||
width: 200px;
|
||||
right: auto;
|
||||
left: -1px;
|
||||
right: -1px;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
@@ -411,6 +518,10 @@ ul#imjs-friends-list {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
li.imjs-friend-group ul li:hover span.imjs-friend-status {
|
||||
color: #5184e0;
|
||||
}
|
||||
|
||||
li.imjs-friend-group ul li > strong {
|
||||
position: relative;
|
||||
color: #00cc00;
|
||||
@@ -435,12 +546,19 @@ ul#imjs-friends-list {
|
||||
text-shadow: 0 1px 0 #333;
|
||||
}
|
||||
|
||||
span.imjs-friend-status {
|
||||
color: #888;
|
||||
white-space: nowrap;
|
||||
padding: 0 0 0 5px;
|
||||
}
|
||||
|
||||
div#imjs-friends-panel form, div#imjs-friends-panel form p {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
input#imjs-search-friends {
|
||||
display: none; /* Search does not work yet. */
|
||||
font: 12px/14px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
|
||||
height: 16px;
|
||||
width: 194px;
|
||||
@@ -451,85 +569,3 @@ div#imjs-friends-panel form, div#imjs-friends-panel form p {
|
||||
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 8px;
|
||||
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;
|
||||
}
|
||||
|
||||
div#imjs-lr form h2 {
|
||||
font: 700 20px/24px Helvetica Neue, Helvetica, Arial, Calibri, Tahoma, Verdana, sans-serif;
|
||||
margin: 0;
|
||||
padding: 7px 0 0 2px;
|
||||
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 button {
|
||||
float: right;
|
||||
background: #f4f3f1;
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
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;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
div#imjs-lr form p {
|
||||
padding-left: 2px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
div#imjs-lr form input:focus, div#imjs-lr form button:focus {
|
||||
position: relative;
|
||||
border: 2px solid #999;
|
||||
margin: -1px;
|
||||
}
|
||||
|
||||
p.imjs-submit {
|
||||
width: 207px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
form#imjs-login {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
/* [end] Login/Registration Forms */
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- Ajax IM Instant Messenger, Footer Bar -->
|
||||
<!-- Ajax IM, Footer Bar -->
|
||||
<ul id="imjs-bar">
|
||||
<li id="imjs-friends" class="imjs-not-connected">
|
||||
<span class="imjs-tab-text"><strong>•</strong> Friends <span>(<span>0</span>)</span></span>
|
||||
@@ -7,11 +7,18 @@
|
||||
<span>{username}</span>
|
||||
<a href="#" class="imjs-minimize">_</a>
|
||||
</div>
|
||||
<div id="imjs-status-panel">
|
||||
<textarea id="imjs-away-message-text"></textarea>
|
||||
<div id="imjs-away-message-text-arrow"></div>
|
||||
<a href="#" id="imjs-button-available" class="imjs-button"><span>•</span> Available</a>
|
||||
<a href="#" id="imjs-button-away" class="imjs-button"><span>•</span> Away</a>
|
||||
<a href="#" id="imjs-button-offline" class="imjs-button"><span>•</span> Offline</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>•</strong> {username}</li>
|
||||
<li class="imjs-friend imjs-default"><strong>•</strong><span>{username}</span><span class="imjs-friend-status">{status}</span></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -20,7 +27,8 @@
|
||||
</form>
|
||||
</div>
|
||||
</li>
|
||||
<li id="imjs-scroll-right" class="imjs-scroll">{count}</li>
|
||||
<li id="imjs-reconnect"><span class="imjs-tab-text">↻</span></li>
|
||||
<li id="imjs-scroll-left" class="imjs-scroll">{count}</li>
|
||||
<li class="imjs-tab imjs-default">
|
||||
<span class="imjs-tab-text"><strong>•</strong> {label} <a href="#" class="imjs-close">x</a></span>
|
||||
<span class="imjs-notification">{count}</span>
|
||||
@@ -73,60 +81,6 @@
|
||||
</div>
|
||||
</form>
|
||||
</li>
|
||||
<li id="imjs-scroll-left" class="imjs-scroll">{count}</li>
|
||||
<li id="imjs-scroll-right" 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>
|
||||
<span class="imjs-tooltip"><p>{tip}</p></span>
|
||||
@@ -1,29 +0,0 @@
|
||||
<?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);
|
||||
?>
|
||||
|
Antes Largura: | Altura: | Tamanho: 1.1 KiB |
@@ -1,573 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Ajax IM — 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
|
||||
// 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('./libraries/server', '.|..|base.php');
|
||||
}
|
||||
|
||||
function get_available_db_engines() {
|
||||
return library_array('./libraries/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);
|
||||
|
||||
if(intval($_POST['needs_nodejs']) == 1) {
|
||||
$configjs = preg_replace("/[\r\n]+/", "\n", file_get_contents('server/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('server/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 = $_POST['public_host'] . ":" . $_POST['public_port'];
|
||||
|
||||
$imloadjs = file_get_contents('js/im.load.js');
|
||||
$imloadjs = preg_replace("/(var nodehost = )'';/", "$1'" . $node_url . "';", $imloadjs);
|
||||
$imljs = fopen('js/im.load.js', 'w');
|
||||
fwrite($imljs, $imloadjs);
|
||||
fclose($imljs);
|
||||
}
|
||||
|
||||
$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('libraries/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>
|
||||
|
||||
<?php if(!$_POST['need_nodejs'] == 1) { ?>
|
||||
<li>The Node.js server host has been added to <code>js/im.load.js</code>; please confirm that the URL generated is correct.</li>
|
||||
<li>
|
||||
<p>To get the standalone Node.js server running, you will need to run the following command on the command line of your server:</p>
|
||||
<pre>node server/server.js</pre>
|
||||
|
||||
<p>However, it is recommended that you move the <code>server</code> folder outside of the main installation directory before going live.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Now that Ajax IM is installed, please see the <a href="http://ajaxim.com/documentation/basics/quick-start-nodejs/">Quick Start with Node.js</a> guide to complete set up.</p>
|
||||
</li>
|
||||
<?php } else { ?>
|
||||
<li>Since you did <strong>not</strong> setup Ajax IM with the Node.js server, it is recommended that you delete the <code>server</code> folder (containing the files <code>config.js</code> and <code>server.js</code>).</li>
|
||||
<li>
|
||||
<p>Now that Ajax IM is installed, please see the <a href="http://ajaxim.com/documentation/basics/quick-start/">Quick Start</a> guide to complete set up.</p>
|
||||
</li>
|
||||
<?php } ?>
|
||||
</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_writable('config.php')): ?>
|
||||
<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.load.js</code> writable?</span>
|
||||
<?php if(is_writable('js/im.load.js')): ?>
|
||||
<span class="writable">Yes.</span>
|
||||
<?php else: ?>
|
||||
<span class="problem"><strong>No.</strong> Please change the permissions of <code>js/im.load.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'] . ' — ' . $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'];
|
||||
var update_server_list = 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];
|
||||
};
|
||||
$('#server').live('click', update_server_list).live('change', update_server_list);
|
||||
</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'] . ' — ' . $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']};
|
||||
var update_db_list = 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').live('click', update_db_list).live('change', update_db_list);
|
||||
|
||||
var update_reqs = function() {
|
||||
setTimeout(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');
|
||||
}
|
||||
}, 100);
|
||||
};
|
||||
$('#db, #server').live('click', update_reqs).live('change', update_reqs);
|
||||
</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>server/config.js</code> writable?</span>
|
||||
<?php if(is_writable('server/config.js')) { ?>
|
||||
<span class="writable">Yes.</span>
|
||||
<?php } else { ?>
|
||||
<span class="problem"><strong>No.</strong> Please change the permissions of <code>server/config.js</code> to "writable" or 755 (on Unix-based systems) before continuing!</span>
|
||||
<?php } ?>
|
||||
</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 — 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>
|
||||
<?php } ?>
|
||||
|
||||
<p id="footer"><a href="http://ajaxim.com">Ajax IM</a> © 2005 – 2010, <a href="http://unwieldy.net">Joshua Gross</a></p></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,79 +0,0 @@
|
||||
// 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.
|
||||
var AjaxIM, AjaxIMLoadedFunction;
|
||||
(function() {
|
||||
AjaxIM = {};
|
||||
AjaxIM.loaded = function(f) {
|
||||
AjaxIMLoadedFunction = f;
|
||||
};
|
||||
|
||||
var tagsrc =
|
||||
(thistag = document.getElementsByTagName('script'))[thistag.length-1].src;
|
||||
var jsfolder = tagsrc.replace(/im.load.js([?].+)?/, '');
|
||||
var imfolder = jsfolder.replace(/js\/$/, '');
|
||||
|
||||
var nodehost = '';
|
||||
|
||||
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'] != 'object'); }]
|
||||
];
|
||||
|
||||
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://' + nodehost + '/poll',
|
||||
send: 'http://' + nodehost + '/send',
|
||||
status: 'http://' + nodehost + '/status',
|
||||
resume: 'http://' + nodehost + '/resume'
|
||||
});
|
||||
} else if(tagsrc.match(/[?]guest$/)) {
|
||||
AjaxIM.init({
|
||||
pollServer: imfolder + 'ajaxim.php',
|
||||
theme: imfolder + 'themes/default',
|
||||
flashStorage: jsfolder + 'jStore.Flash.html'
|
||||
}, {
|
||||
poll: 'http://' + nodehost + '/poll',
|
||||
send: 'http://' + nodehost + '/send',
|
||||
status: 'http://' + nodehost + '/status',
|
||||
resume: 'http://' + nodehost + '/resume'
|
||||
});
|
||||
AjaxIM.client.login();
|
||||
}
|
||||
|
||||
AjaxIM.loaded();
|
||||
};
|
||||
})();
|
||||
@@ -1,19 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,269 +0,0 @@
|
||||
/*
|
||||
* 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);
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* 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);
|
||||
@@ -1,963 +0,0 @@
|
||||
/*!
|
||||
* 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);
|
||||
@@ -1,230 +0,0 @@
|
||||
|
||||
/**
|
||||
* 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);
|
||||
@@ -1,792 +0,0 @@
|
||||
<?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 */
|
||||
@@ -1,139 +0,0 @@
|
||||
<?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 */
|
||||
@@ -1,305 +0,0 @@
|
||||
<?php
|
||||
/*
|
||||
* Library: Default
|
||||
* Author: Joshua Gross
|
||||
* Version: 0.1 alpha
|
||||
* Date: February 12, 2010
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
|
||||
// == Default Server Library ==
|
||||
//
|
||||
// This is the default PHP-only server library. This library allows you
|
||||
// to use Ajax IM on a shared server, without installing any extra software.
|
||||
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
|
||||
|
||||
// === {{{Default_IM::}}}**{{{__construct()}}}** ===
|
||||
//
|
||||
// Initializes the IM library and retrieves the user's session, if one
|
||||
// currently exists.
|
||||
function __construct() {
|
||||
parent::__construct();
|
||||
|
||||
session_start();
|
||||
if($_SESSION['username']) {
|
||||
$this->username = $_SESSION['username'];
|
||||
$this->user_id = $_SESSION['user_id'];
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{Default_IM::}}}**{{{login($username, $password)}}}** ===
|
||||
//
|
||||
// Authenticate a user against the database. If the user is valid,
|
||||
// log them in.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$username}}} is the user's login name.\\
|
||||
// * {{{$password}}} is an already-md5'd copy of the user's password.
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{Default_IM::}}}**{{{logout()}}}** ===
|
||||
//
|
||||
// Signs the user out.
|
||||
public function logout() {
|
||||
session_destroy();
|
||||
$_SESSION = array();
|
||||
|
||||
return array('r' => 'logged out');
|
||||
}
|
||||
|
||||
// === {{{Default_IM::}}}**{{{send($to, $message)}}}** ===
|
||||
//
|
||||
// Send a message to another user by adding the message to the
|
||||
// database.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$to}}} is the username of the recipient.\\
|
||||
// * {{{$message}}} is the content.
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{Default_IM::}}}**{{{status($status, $message)}}}** ===
|
||||
//
|
||||
// Sets the status of the current user, including any associated
|
||||
// status message.
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{Default_IM::}}}**{{{register($username, $password)}}}** ===
|
||||
//
|
||||
// Create a new user based on the provided username and password.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$username}}} is the new user's login name.\\
|
||||
// * {{{$password}}} is the user's plaintext password.
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{Default_IM::}}}**{{{poll($method)}}}** ===
|
||||
//
|
||||
// Query the database for any new messages, and respond (or wait)
|
||||
// using the specified method (short, long, or comet).
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$method}}} is the type of response method to use as a reply.
|
||||
// See {{{im.js}}} for a description of each method.
|
||||
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// {{{Default_IM::}}}**{{{_longPoll()}}}** ===
|
||||
//
|
||||
// Use the long polling technique to check for and deliver new messages.
|
||||
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// {{{Default_IM::}}}**{{{_shortPoll()}}}** ===
|
||||
//
|
||||
// Use the short polling technique to check for and deliver new messages.
|
||||
private function _shortPoll() {
|
||||
$messages = Message::getMany('to', $this->user_id);
|
||||
|
||||
if($messages) {
|
||||
return $this->_pollParseMessages($messages);
|
||||
} else {
|
||||
return array('r' => 'no messages');
|
||||
}
|
||||
}
|
||||
|
||||
// === //private// {{{Default_IM::}}}**{{{_comet()}}}** ===
|
||||
//
|
||||
// Use the comet/streaming technique to check for and deliver new 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// {{{Default_IM::}}}**{{{_pollParseMessages()}}}** ===
|
||||
//
|
||||
// Parse each message object and return it as an array deliverable to the client.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$messages}}} is the array of message objects.
|
||||
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// {{{Default_IM::}}}**{{{_sanitize()}}}** ===
|
||||
//
|
||||
// Sanitize messages by preventing any HTML tags from being created
|
||||
// (replaces < and > entities).
|
||||
private function _sanitize($str) {
|
||||
return str_replace('>', '>', str_replace('<', '<', str_replace('&', '&', $str)));
|
||||
}
|
||||
}
|
||||
|
||||
/* End of libraries/server/Default.php */
|
||||
@@ -1,170 +0,0 @@
|
||||
<?php
|
||||
/*
|
||||
* Library: NodeJS
|
||||
* Author: Joshua Gross
|
||||
* Version: 0.1 alpha
|
||||
* Date: February 12, 2010
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
|
||||
// == Node.js Server Library ==
|
||||
//
|
||||
// This is the [[http://nodejs.org|Node.js]] server library for Ajax IM. It
|
||||
// handles registration and passing login to the Node.js server.
|
||||
class NodeJS_IM extends IM {
|
||||
// === {{{NodeJS_IM::}}}**{{{__construct()}}}** ===
|
||||
//
|
||||
// Initializes the IM library and retrieves the user's session, if one
|
||||
// currently exists.
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{__destruct()}}}** ===
|
||||
//
|
||||
// Closes the connection to the Node.js server.
|
||||
function __destruct() {
|
||||
$this->memcache->close();
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{login($username, $password)}}}** ===
|
||||
//
|
||||
// Authenticate a user against the database. If the user is valid,
|
||||
// pass the user's information to the Node.js server.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$username}}} is the user's login name.\\
|
||||
// * {{{$password}}} is an already-md5'd copy of the user's password.
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{logout()}}}** ===
|
||||
//
|
||||
// Signs the user out of the Node.js server.
|
||||
public function logout() {
|
||||
$this->memcache->delete($this->username);
|
||||
|
||||
return array('r' => 'logged out');
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{register($username, $password)}}}** ===
|
||||
//
|
||||
// Create a new user based on the provided username and password.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$username}}} is the new user's login name.\\
|
||||
// * {{{$password}}} is the user's plaintext password.
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{add_friend($friend, $group)}}}** ===
|
||||
//
|
||||
// Add a new friend to the current user's friend list, in the specified
|
||||
// group name. Adds the friend to both the database and the current
|
||||
// Node.js server session.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$friend}}} is the username of the friend.\\
|
||||
// * {{{$group}}} is the name of group in which to place the friend.
|
||||
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 */
|
||||
@@ -1,117 +0,0 @@
|
||||
<?php
|
||||
/*
|
||||
* Library: NodeJS (Guests)
|
||||
* Author: Joshua Gross
|
||||
* Version: 0.1 alpha
|
||||
* Date: February 12, 2010
|
||||
*
|
||||
* 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
|
||||
*/
|
||||
|
||||
// == Node.js Guest Server Library ==
|
||||
//
|
||||
// This is the [[http://nodejs.org|Node.js]] Guest server library for Ajax IM. It
|
||||
// creates a random "Guest" username upon login and passes that information to
|
||||
// the Node.js server. Additionally, it makes every user a friend of every other
|
||||
// user.
|
||||
class NodeJS_Guests_IM extends IM {
|
||||
// === {{{NodeJS_Guests_IM::}}}**{{{__construct()}}}** ===
|
||||
//
|
||||
// Initializes the IM library and retrieves the user's session, if one
|
||||
// currently exists.
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === {{{NodeJS_Guests_IM::}}}**{{{__destruct()}}}** ===
|
||||
//
|
||||
// Closes the connection to the Node.js server.
|
||||
function __destruct() {
|
||||
$this->memcache->close();
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{login($username, $password)}}}** ===
|
||||
//
|
||||
// Create a new Guest username based in the microtime, then
|
||||
// pass the user's information to the Node.js server.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{$username}}} is unused (kept for compatability with caller).\\
|
||||
// * {{{$password}}} is unused (kept for compatability with caller).
|
||||
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']
|
||||
);
|
||||
}
|
||||
|
||||
// === {{{NodeJS_IM::}}}**{{{logout()}}}** ===
|
||||
//
|
||||
// Signs the user out of the Node.js server.
|
||||
public function logout() {
|
||||
$this->memcache->delete($this->username);
|
||||
|
||||
return array('r' => 'logged out');
|
||||
}
|
||||
}
|
||||
|
||||
/* End of libraries/server/NodeJS.php */
|
||||
@@ -1,26 +0,0 @@
|
||||
<?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 */
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "AjaxIM",
|
||||
"description": "instant messaging framework",
|
||||
"author": "ajaximrpg <ajaximrpg@svexpertise.com>",
|
||||
"version": "4.0.0",
|
||||
"dependencies": {
|
||||
"express": ">= 4.0.0",
|
||||
"connect": ">= 2.14.0",
|
||||
"method-override": ">= 1.0.0",
|
||||
"body-parser": ">= 1.0.0",
|
||||
"express-error-handler": ">= 0.5.0",
|
||||
"morgan": ">= 1.0.0",
|
||||
"cookie": ">= 0.1.0",
|
||||
"jade": ">= 1.3.0",
|
||||
"socket.io": ">= 1.0.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env node
|
||||
var sys = require('util'),
|
||||
express = require('express'),
|
||||
packages = require('./libs/packages'),
|
||||
o_ = require('./libs/utils');
|
||||
|
||||
o_.merge(global, require('./settings'));
|
||||
try { o_.merge(global, require('./settings.local')); } catch(e) {}
|
||||
|
||||
var app = express();
|
||||
//app.set('env', 'development');
|
||||
app.use( require('request-param')() )
|
||||
|
||||
app.use(require('method-override')());
|
||||
app.use(require('cookie-parser')());;
|
||||
//app.use(require('body-parser')());;
|
||||
app.use(require('body-parser').urlencoded({extended: true}));;
|
||||
app.use(require('body-parser').json());;
|
||||
app.use(require('./middleware/im')({
|
||||
maxAge: 15 * 60 * 1000,
|
||||
reapInterval: 60 * 1000,
|
||||
authentication: require('./libs/authentication/' + AUTH_LIBRARY)
|
||||
}));
|
||||
|
||||
app.set('root', __dirname);
|
||||
|
||||
if ('development' == app.get('env')) {
|
||||
app.set('views', __dirname + '/dev/views');
|
||||
app.set('view engine', 'jade');
|
||||
|
||||
app.use(require("morgan")("dev"));
|
||||
require('./dev/app')('/dev', app);
|
||||
app.use(express.static(
|
||||
require('path').join(__dirname, '../client')));
|
||||
app.use(require('express-error-handler')({dumpExceptions: true, showStack: true}));
|
||||
}
|
||||
|
||||
app.listen(APP_PORT, APP_HOST);
|
||||
|
||||
// Listener endpoint; handled in middleware
|
||||
app.get('/app/listen', function(){});
|
||||
|
||||
app.use('/app/message', function(req, res) {
|
||||
|
||||
res.find(req.param('to'), function(user) {
|
||||
if(!user)
|
||||
return res.send(new packages.Error('not online'));
|
||||
|
||||
res.message(user, new packages.Message(
|
||||
req.session.data('username'),
|
||||
req.param('body')
|
||||
));
|
||||
});
|
||||
});
|
||||
|
||||
app.use('/app/message/typing', function(req, res) {
|
||||
if(~packages.TYPING_STATES.indexOf('typing' + req.param('state'))) {
|
||||
res.find(req.param('to'), function(user) {
|
||||
if(user) {
|
||||
res.message(user, new packages.Status(
|
||||
req.session.data('username'),
|
||||
'typing' + req.param('state')
|
||||
));
|
||||
}
|
||||
|
||||
// Typing updates do not receive confirmations,
|
||||
// as they are not important enough.
|
||||
res.send('');
|
||||
});
|
||||
} else {
|
||||
res.send(new packages.Error('invalid state'));
|
||||
}
|
||||
});
|
||||
|
||||
app.use('/app/status', function(req, res) {
|
||||
if(~packages.STATUSES.indexOf(req.param('status'))) {
|
||||
res.status(req.param('status'), req.param('message'));
|
||||
res.send(new packages.Success('status updated'));
|
||||
} else {
|
||||
res.send(new packages.Error('invalid status'));
|
||||
}
|
||||
});
|
||||
|
||||
app.use('/app/signoff', function(req, res) {
|
||||
res.signOff();
|
||||
res.send(new packages.Success('goodbye'));
|
||||
});
|
||||
|
||||
console.log('Ajax IM server started...');
|
||||
@@ -1,33 +0,0 @@
|
||||
// == 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
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = function(route, app) {
|
||||
app.get(route+'/', function(req, res) {
|
||||
res.render('chat', {
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
../../../client/js/
|
||||
@@ -0,0 +1 @@
|
||||
../../../client/themes/
|
||||
@@ -0,0 +1,13 @@
|
||||
doctype html
|
||||
html(lang="en")
|
||||
head
|
||||
title Ajax IM
|
||||
script(src='/js/jquery-1.11.1.js', type='text/javascript')
|
||||
script(src='/js/md5.js', type='text/javascript')
|
||||
script(src='/js/store.js', type='text/javascript')
|
||||
script(src='/js/dateformat.js', type='text/javascript')
|
||||
script(src='/js/im.js', type='text/javascript')
|
||||
script(type='text/javascript').
|
||||
$(function(){var im = AjaxIM.init({theme: "/themes/default"});});
|
||||
body.
|
||||
Hello.
|
||||
@@ -0,0 +1 @@
|
||||
!{body}
|
||||
@@ -0,0 +1,53 @@
|
||||
var o_ = require('../../utils');
|
||||
var User = require('../../../middleware/im/user');
|
||||
|
||||
exports.authenticate = function(store, event, callback) {
|
||||
// remove authentication from event
|
||||
var sessionid = event.sessionid;
|
||||
delete event.sessionid;
|
||||
|
||||
// find the user
|
||||
var user = event.from? store.sessions[event.from]: undefined;
|
||||
|
||||
// create, validate or reject user
|
||||
if (user) {
|
||||
// found the user so check authentication
|
||||
if (sessionid && (sessionid === user.data('sessionid'))) {
|
||||
event.from = user.data('username');
|
||||
callback(event, user);
|
||||
} else {
|
||||
event._status = {sent: false, e: 'not authenticated'};
|
||||
callback(event);
|
||||
}
|
||||
} else if (event.type == 'hello') {
|
||||
store.find('sessionid', sessionid, function(user) {
|
||||
if (user) {
|
||||
// relogin as same user
|
||||
event.from = user.data('username');
|
||||
callback(event, user);
|
||||
} else {
|
||||
// if no username requested, assign user name
|
||||
if (!event.from) {
|
||||
event.from = 'username' + (++store.uid);
|
||||
}
|
||||
// everybody is your friend!
|
||||
var friends = o_.values(store.sessions).map(function(friend) {
|
||||
return friend.data('username');
|
||||
});
|
||||
// you're even friends with yourself!
|
||||
friends.push(event.from);
|
||||
// create new user
|
||||
user = new User(store, {
|
||||
username: event.from,
|
||||
sessionid: sessionid,
|
||||
displayname: 'John Smith',
|
||||
otherinfo: 'any other relevant key/values'
|
||||
}, friends);
|
||||
callback(event, user);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
event._status = {sent: false, e: 'not authenticated'};
|
||||
callback(event);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
exports.TYPING_STATES = ['typing+', 'typing~', 'typing-'];
|
||||
exports.STATUSES = ['available', 'away', 'idle'];
|
||||
@@ -0,0 +1,61 @@
|
||||
// Many functions borrowed from
|
||||
// ext.js - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
|
||||
|
||||
module.exports = o_ = {
|
||||
merge: function(a, b) {
|
||||
if(!b) return a;
|
||||
var keys = Object.keys(b);
|
||||
for(var i = 0, len = keys.length; i < len; i++)
|
||||
a[keys[i]] = b[keys[i]];
|
||||
return a;
|
||||
},
|
||||
|
||||
extend: function() {
|
||||
var o = {};
|
||||
for (var a=0; a < arguments.length; ++a) {
|
||||
this.merge(o, arguments[a]);
|
||||
}
|
||||
return o;
|
||||
},
|
||||
|
||||
deletekey: function(o, key) {
|
||||
if (o.hasOwnProperty(key)) {
|
||||
delete o[key];
|
||||
}
|
||||
return o;
|
||||
},
|
||||
|
||||
values: function(obj) {
|
||||
if(typeof obj == 'array')
|
||||
return obj;
|
||||
if(!obj || typeof obj !== 'object')
|
||||
return [];
|
||||
var keys = Object.keys(obj),
|
||||
vals = [];
|
||||
for(var i = 0, len = keys.length; i < len; ++i)
|
||||
vals.push(obj[keys[i]]);
|
||||
return vals;
|
||||
},
|
||||
|
||||
find: function(arr, fn, context) {
|
||||
if(typeof arr == 'array') {
|
||||
for(var i = 0, len = arr.length; i < len; ++i)
|
||||
if(fn.call(context, arr[i], i, arr))
|
||||
return arr[i];
|
||||
} else if(typeof arr == 'object') {
|
||||
var keys = Object.keys(obj);
|
||||
for(var i = 0, len = keys.length; i < len; ++i)
|
||||
if(fn.call(context, arr[keys[i]], keys[i], arr))
|
||||
return [arr[keys[i]], keys[i]];
|
||||
}
|
||||
},
|
||||
|
||||
bind: function(fn, context) {
|
||||
var self = fn,
|
||||
args = Array.prototype.slice.call(arguments, 2);
|
||||
return function() {
|
||||
var _args = Array.prototype.slice.call(arguments);
|
||||
return fn.apply(context, args.concat(_args));
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
var url = require('url'),
|
||||
Hub = require('./im/hub'),
|
||||
packages = require('../libs/packages'),
|
||||
o_ = require('../libs/utils');
|
||||
|
||||
module.exports = function setupHub(options) {
|
||||
options = options || {};
|
||||
|
||||
var store = new Hub(options);
|
||||
|
||||
return {store: store, session: function session(req, res, next) {
|
||||
req.sessionStore = store;
|
||||
|
||||
// create the event object
|
||||
req.event = o_.extend({}, req.query, req.body, req.params);
|
||||
o_.deletekey(req.event, 'callback');
|
||||
o_.deletekey(req.event, '_');
|
||||
|
||||
req.event.reply = function(status) {
|
||||
if (status) {
|
||||
this._status = status;
|
||||
}
|
||||
delete this.reply;
|
||||
res.jsonp(this);
|
||||
};
|
||||
|
||||
var unauthenticated = function() {
|
||||
req.event.reply({sent: false, e: 'unauthenticated'});
|
||||
};
|
||||
|
||||
// set event handlers to unauthenticated by default
|
||||
res.message = res.typing = res.status = res.signOff = unauthenticated;
|
||||
|
||||
if(url.parse(req.url).pathname.substring(0, 5) === '/app/') {
|
||||
store.get(req.event, function(event, user) {
|
||||
if(!user) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
user.touch();
|
||||
if(url.parse(req.url).pathname === '/app/listen') {
|
||||
req.connection.setTimeout(5 * 60 * 1000);
|
||||
user.listener(res);
|
||||
store.set(user.data('username'), user);
|
||||
|
||||
if(msg = user.message_queue.shift()) {
|
||||
user._send.apply(user, msg);
|
||||
}
|
||||
} else {
|
||||
req.event.from = user.data('username');
|
||||
}
|
||||
|
||||
res.message = function() {
|
||||
user.message(req.event);
|
||||
};
|
||||
res.typing = function() {
|
||||
if(~packages.TYPING_STATES.indexOf('typing' + req.event.state)) {
|
||||
store.find('username', req.event.to, function(to) {
|
||||
if(to) {
|
||||
req.event.status = 'typing' + req.event.state;
|
||||
user.message(req.event);
|
||||
} else {
|
||||
// Typing updates do not receive confirmations,
|
||||
// as they are not important enough.
|
||||
req.event.reply({sent: true});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
req.event.reply({sent: false, e: 'invalid state'});
|
||||
}
|
||||
};
|
||||
res.status = function() {
|
||||
user.status(req.event);
|
||||
};
|
||||
res.signOff = function() {
|
||||
user.signOff(req.event);
|
||||
};
|
||||
|
||||
if(url.parse(req.url).pathname !== '/app/listen') {
|
||||
next();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
}};
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
var events = require('events'),
|
||||
sys = require('sys'),
|
||||
packages = require('../../libs/packages'),
|
||||
o_ = require('../../libs/utils'),
|
||||
User = require('./user');
|
||||
|
||||
var Hub = module.exports = function Hub(options) {
|
||||
this.uid = 0;
|
||||
this.events = new events.EventEmitter();
|
||||
this.auth = options.authentication;
|
||||
this.sessions = {};
|
||||
|
||||
this.maxAge = options.maxAge || 4 * 60 * 60 * 1000;
|
||||
this.reapInterval = options.reapInterval || 60 * 1000;
|
||||
|
||||
if(this.reapInterval !== -1) {
|
||||
setInterval(function(self) {
|
||||
self.reapCheck(self.maxAge);
|
||||
}, this.reapInterval, this);
|
||||
}
|
||||
|
||||
this.events.addListener('update', o_.bind(function(event) {
|
||||
if(event.type == 'status' && event.status == 'offline') {
|
||||
var sids = Object.keys(this.sessions), sid, sess;
|
||||
for(sid in this.sessions) {
|
||||
sess = this.sessions[sid];
|
||||
if (sess.data('username') == event.from) {
|
||||
if (sess.listeners.length) {
|
||||
sess.send({type: 'goodbye'});
|
||||
}
|
||||
delete this.sessions[sid];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, this));
|
||||
};
|
||||
|
||||
Hub.prototype.reapCheck = function(ms) {
|
||||
var threshold = +new Date - ms;
|
||||
var sids = Object.keys(this.sessions);
|
||||
for(var i = 0, len = sids.length; i < len; ++i) {
|
||||
var sid = sids[i];
|
||||
if(this.sessions[sid].lastAccess < threshold) {
|
||||
this.reap(sid);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Hub.prototype.reap = function(sid) {
|
||||
var sess = this.sessions[sid];
|
||||
console.log('reaping '+sess.data('username'));
|
||||
var event = {type: 'status', from: sess.data('username'), status: 'offline', message: ''};
|
||||
this.events.emit('update', event);
|
||||
delete this.sessions[sid];
|
||||
sess.close();
|
||||
};
|
||||
|
||||
Hub.prototype.get = function(event, fn, socket) {
|
||||
this.auth.authenticate(this, event, o_.bind(function(event, user) {
|
||||
if (user) {
|
||||
if (socket) {
|
||||
user.socketio = socket;
|
||||
}
|
||||
if (this.sessions[user.data('username')]) {
|
||||
fn(event, user);
|
||||
return;
|
||||
}
|
||||
this.set(user.data('username'), user);
|
||||
var friends = user.friends;
|
||||
var friends_copy = friends.slice();
|
||||
o_.values(this.sessions).filter(function(friend) {
|
||||
return ~friends.indexOf(friend.data('username'));
|
||||
}).forEach(function(friend) {
|
||||
var username = friend.data('username');
|
||||
friends_copy[friends_copy.indexOf(username)] = [username, friend.status()];
|
||||
}, this);
|
||||
user._friends(friends_copy);
|
||||
user.events.addListener('status', o_.bind(function(value, message) {
|
||||
var event = {type: 'status', from: user.data('username'), status: value, message: message};
|
||||
this.events.emit('update', event);
|
||||
}, this));
|
||||
this.events.addListener('update', o_.bind(user.receivedUpdate, user));
|
||||
fn(event, user);
|
||||
} else {
|
||||
fn(event);
|
||||
}
|
||||
}, this));
|
||||
};
|
||||
|
||||
Hub.prototype.set = function(sid, sess, fn) {
|
||||
this.sessions[sid] = sess;
|
||||
fn && fn();
|
||||
};
|
||||
|
||||
Hub.prototype.find = function(key, value, fn) {
|
||||
for(var sid in this.sessions) {
|
||||
var session = this.sessions[sid];
|
||||
var user_value = session.data(key);
|
||||
if (user_value == value) {
|
||||
fn(session);
|
||||
return;
|
||||
}
|
||||
}
|
||||
fn(false);
|
||||
};
|
||||
|
||||
Hub.prototype.dispatch = function(event) {
|
||||
this.find('username', event.from, function(from) {
|
||||
if (from) {
|
||||
from.dispatch(event);
|
||||
} else {
|
||||
event.reply({sent: false, e: 'not authenticated'});
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
var events = require('events'),
|
||||
packages = require('../../libs/packages'),
|
||||
o_ = require('../../libs/utils');
|
||||
|
||||
var User = module.exports = function(store, data, friends) {
|
||||
this.store = store;
|
||||
this.connection = null;
|
||||
this.listeners = [];
|
||||
this.message_queue = [];
|
||||
this._data = data;
|
||||
this.friends = friends;
|
||||
|
||||
this.events = new events.EventEmitter();
|
||||
this._status = packages.STATUSES[0];
|
||||
this._status_message = '';
|
||||
|
||||
this.interval = setInterval(o_.bind(this._expireConns, this), 500);
|
||||
};
|
||||
|
||||
User.prototype.close = function() {
|
||||
clearInterval(this.interval);
|
||||
var conn,
|
||||
noop = JSON.stringify({type: 'noop'}),
|
||||
noop_headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': noop.length
|
||||
};
|
||||
for(var i = this.listeners.length-1; i >= 0; i--) {
|
||||
conn = this.listeners[i].connection;
|
||||
this.listeners[i].writeHead(200, noop_headers);
|
||||
this.listeners[i].end(noop);
|
||||
}
|
||||
};
|
||||
|
||||
User.prototype.receivedUpdate = function(event) {
|
||||
event = o_.extend({}, event);
|
||||
event.to = this.data('username');
|
||||
if(this.friends.indexOf(event.from))
|
||||
this.send(event);
|
||||
};
|
||||
|
||||
User.prototype._friends = function(friends) {
|
||||
this.friends = friends;
|
||||
this.send({
|
||||
type: 'hello',
|
||||
username: this.data('username'),
|
||||
friends: friends
|
||||
});
|
||||
};
|
||||
|
||||
User.prototype._expireConns = function() {
|
||||
var conn,
|
||||
noop = JSON.stringify({type: 'noop'}),
|
||||
noop_headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': noop.length
|
||||
};
|
||||
for(var i = 0; i < this.listeners.length; i++) {
|
||||
conn = this.listeners[i].connection;
|
||||
if((Date.now() - conn._idleStart) >= conn._idleTimeout - 2000) {
|
||||
this.listeners[i].writeHead(200, noop_headers);
|
||||
this.listeners[i].end(noop);
|
||||
this.listeners.splice(i, 1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
User.prototype.listener = function(conn) {
|
||||
this.listeners.push(conn);
|
||||
};
|
||||
|
||||
User.prototype.send = function(event) {
|
||||
this._send('listener', event);
|
||||
};
|
||||
|
||||
User.prototype._send = function(type, event, res) {
|
||||
if (this.socketio) {
|
||||
var id = event.id;
|
||||
if (event.id) {
|
||||
delete event.id;
|
||||
}
|
||||
this.socketio.emit('client', event);
|
||||
if (id) {
|
||||
event.id = id;
|
||||
}
|
||||
} else if(type == 'connection') {
|
||||
// end a regular connection with a response
|
||||
res.jsonp(event);
|
||||
} else {
|
||||
// end a long-polling connection with an event
|
||||
if(!this.listeners.length)
|
||||
return this.message_queue.push(arguments);
|
||||
|
||||
var cx = this.listeners.slice(), conn;
|
||||
this.listeners = [];
|
||||
while(conn = cx.shift()) {
|
||||
conn.jsonp(event);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
User.prototype.data = function(key, def) {
|
||||
return this._data[key] || this['_' + key] ||
|
||||
(typeof this[key] != 'function' && this[key]) ||
|
||||
def || false;
|
||||
};
|
||||
|
||||
User.prototype.touch = function() {
|
||||
this.lastAccess = +new Date;
|
||||
};
|
||||
|
||||
User.prototype.message = function(event) {
|
||||
var self = this;
|
||||
try {
|
||||
self.store.find('username', event.to, function(to) {
|
||||
if(to) {
|
||||
to.send(event);
|
||||
event.reply({sent: true});
|
||||
} else {
|
||||
event.reply({sent: false, e: 'not online'});
|
||||
}
|
||||
});
|
||||
} catch(e) {
|
||||
event.reply({sent: false, e: e.description});
|
||||
}
|
||||
};
|
||||
|
||||
User.prototype.status = function(event) {
|
||||
if (!event) {
|
||||
return this._status;
|
||||
}
|
||||
|
||||
this._status = event.status;
|
||||
this._status_message = event.message;
|
||||
this.events.emit('status', event.status, event.message);
|
||||
if (event.reply) {
|
||||
event.reply({sent: true});
|
||||
}
|
||||
};
|
||||
|
||||
User.prototype.signOff = function(event) {
|
||||
event.status = 'offline';
|
||||
this.store.events.emit('update', event);
|
||||
event.reply({sent: true});
|
||||
};
|
||||
|
||||
User.prototype.dispatch = function(event) {
|
||||
if (event.type == 'message') {
|
||||
this.message(event);
|
||||
} else if (event.type == 'status') {
|
||||
this.status(event);
|
||||
} else if (event.type == 'signoff') {
|
||||
this.signOff(event);
|
||||
} else {
|
||||
event.reply({sent: false, e: 'invalid event type'});
|
||||
}
|
||||
};
|
||||
@@ -1,902 +0,0 @@
|
||||
// = Ajax IM =
|
||||
//
|
||||
// **Copyright © 2005 – 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'),
|
||||
url = require('url'),
|
||||
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((Date.now() - user.last_active) > 50000 &&
|
||||
user._callbacks.length == 0) {
|
||||
|
||||
self._killUser(username);
|
||||
} else if((Date.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 = (Date.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._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.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{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;
|
||||
}
|
||||
} else {
|
||||
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.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{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) }}} ===
|
||||
//
|
||||
// Initializes a user session and adds the user to the users list. Additionally,
|
||||
// it stores a callback function which will push data directly to this user. A
|
||||
// "session" object is also stored, allowing a user to reconnect at a later time
|
||||
// (provided that their session hasn't yet expired).
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{username}}} is the user's account name\\
|
||||
// * {{{data}}} is an array of user data:\\
|
||||
// ** {{{user_id}}} is a unique id for this particular user.
|
||||
// ** {{{session_id}}} is the user's unique session id (used to (re)connect to the server).
|
||||
// ** {{{friends}}} is the friends list.
|
||||
// ** {{{guest}}} (optional) defines whether or not this is a "guest" (temporary) user.
|
||||
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: Date.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: Date.now()
|
||||
};
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// === //private//\\ {{{ AjaxIM._killUser() }}} ===
|
||||
//
|
||||
// Remove a user from the server. If they are a guest user, also remove
|
||||
// their session data; otherwise, retain session data so that the user's
|
||||
// session can be resumed later.
|
||||
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() }}} ===
|
||||
//
|
||||
// Store the user's connection in the callback list and update both the
|
||||
// user and session "last_active" variable (denoting when the user last
|
||||
// contacted the server).
|
||||
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 = Date.now();
|
||||
self.sessions[user.session_id].last_active = Date.now();
|
||||
}
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.resume() }}} ===
|
||||
//
|
||||
// Attempt to resume a session based on a session id stored in a
|
||||
// cookie.
|
||||
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() }}} ===
|
||||
//
|
||||
// Send a message to the user specified in the query and return a
|
||||
// result declaring whether or not the message was sent. Messages
|
||||
// are only sent if the user has an active session.
|
||||
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 = Date.now();
|
||||
self.sessions[user.session_id].last_active = Date.now();
|
||||
this.response.reply(200, {'sent': sent});
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.status() }}} ===
|
||||
//
|
||||
// Update a user's status based on the query parameters; this includes
|
||||
// both their status code and any custom status message associated with
|
||||
// that code. If the status update is successful, send an update to the
|
||||
// user's friends.
|
||||
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 = Date.now();
|
||||
self.sessions[user.session_id].last_active = Date.now();
|
||||
this.response.reply(200, {status_updated: status_updated});
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.online() }}} ===
|
||||
//
|
||||
// Return a count of the number of online users.
|
||||
this.online = function() {
|
||||
this.response.reply(200, {count: self.onlineCount});
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.apiLogin(username, data) }}} ===
|
||||
//
|
||||
// A Memcache API function. Initializes a new user based on the
|
||||
// sent username and decoded JSON user data.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{username}}} is the unique username to initialize.
|
||||
// * {{{data}}} is the user data outlined in the _initUser function.
|
||||
this.apiLogin = function(username, data) {
|
||||
this._initUser.call(self, username, data);
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.apiGetUser(username) }}} ===
|
||||
//
|
||||
// A Memcache API function. Returns user data based on a
|
||||
// specified username.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{username}}} is the name of the user to retrieve.
|
||||
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) }}} ===
|
||||
//
|
||||
// A Memcache API function. Returns user data based on a
|
||||
// specified session id. Returns the same data as apiGetUser.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{session_id}}} is the session id of the user to retrieve.
|
||||
this.apiGetSession = function(session_id) {
|
||||
if(session_id in this.sessions)
|
||||
return this.apiGetUser(this.sessions[session_id].username);
|
||||
else
|
||||
return false;
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.apiGetUserList() }}} ===
|
||||
//
|
||||
// A Memcache API function. Returns user data for all online users.
|
||||
// Same data returned as apiGetUser, but in an array of all users.
|
||||
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() }}} ===
|
||||
//
|
||||
// A Memcache API function. Returns a count of all online users.
|
||||
this.apiOnlineCount = function() {
|
||||
return {count: this.onlineCount};
|
||||
};
|
||||
|
||||
// === {{{ AjaxIM.apiAddFriend(type, id, value) }}} ===
|
||||
//
|
||||
// A Memcache API function. Adds a user to the friends list
|
||||
// of another user. Note, however, that this only adds the friend
|
||||
// to the user's active session; it does not add the friend permanently
|
||||
// to any database that might be in use.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{type}}} is the type of identifier used to identify the user. One of
|
||||
// "session" or "username".\\
|
||||
// * {{{id}}} is the actual identifier; a username or session id.\\
|
||||
// * {{{value}}} is an array of data about the new friend:
|
||||
// ** {{{u}}} is the username of the friend.
|
||||
// ** {{{g}}} is the group into which the friend will be placed.
|
||||
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) }}} ===
|
||||
//
|
||||
// A Memcache API function. Does the exact opposite of {{{apiAddFriend}}}.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{type}}} is the type of identifier used to identify the user. One of
|
||||
// "session" or "username".\\
|
||||
// * {{{id}}} is the actual identifier; a username or session id.\\
|
||||
// * {{{value}}} is the username of the friend to remove.
|
||||
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) }}} ===
|
||||
//
|
||||
// A Memcache API function. Broadcasts a message of type "message" ("m")
|
||||
// to all signed-in users.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{type}}} should be "from".\\
|
||||
// * {{{id}}} is the name of the sender; can be anything.\\
|
||||
// * {{{value}}} is message.
|
||||
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) }}} ===
|
||||
//
|
||||
// A Memcache API function. Broadcasts a message of the specified
|
||||
// type to all signed-in users.
|
||||
//
|
||||
// ==== Parameters ====
|
||||
// * {{{type}}} should be "from".\\
|
||||
// * {{{id}}} is the name of the sender; can be anything.\\
|
||||
// * {{{value}}} is message object:
|
||||
// ** {{{t}}} is the type of message.
|
||||
// ** {{{s}}} is the sender.
|
||||
// ** {{{r}}} is the recipient (usually irrelevant in broadcasted messages).
|
||||
// ** {{{m}}} is the content of the message.
|
||||
this.apiBroadcastRaw = function(type, id, value) {
|
||||
// Why "from?" This needs to be reconsidered.
|
||||
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 = [];
|
||||
|
||||
if(typeof request['uri'] == 'undefined') {
|
||||
uri = url.parse(request.url, true);
|
||||
request['uri'] = {
|
||||
'path': uri.pathname,
|
||||
'params': uri.query || {}
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
content = request.uri.params.callback + '(' + content + ');';
|
||||
|
||||
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(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();
|
||||
@@ -0,0 +1,23 @@
|
||||
// == 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.
|
||||
|
||||
// === Host and Port ===
|
||||
//
|
||||
// Define the host and port that Ajax IM will run on.
|
||||
APP_HOST = 'localhost';
|
||||
APP_PORT = 8000;
|
||||
|
||||
// === Authentication Library ===
|
||||
//
|
||||
// This is the library (from libs/authenticate/) that we will use to
|
||||
// authenticate a user signing in. The value should be the name of the file
|
||||
// without the '.js' part. 'index' is the default library.
|
||||
AUTH_LIBRARY = 'default';
|
||||
|
||||
// === Daemon ===
|
||||
//
|
||||
// Define where the PID and log files will be deposited when run as a daemon.
|
||||
PID_FILE = '/tmp/ajaxim.pid';
|
||||
LOG_FILE = '/var/run/ajaxim.log';
|
||||
|
Antes Largura: | Altura: | Tamanho: 121 B |