message
This commit is contained in:
@@ -0,0 +1,800 @@
|
||||
<?php
|
||||
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
|
||||
|
||||
/**
|
||||
* Converts to and from JSON format.
|
||||
*
|
||||
* JSON (JavaScript Object Notation) is a lightweight data-interchange
|
||||
* format. It is easy for humans to read and write. It is easy for machines
|
||||
* to parse and generate. It is based on a subset of the JavaScript
|
||||
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
|
||||
* This feature can also be found in Python. JSON is a text format that is
|
||||
* completely language independent but uses conventions that are familiar
|
||||
* to programmers of the C-family of languages, including C, C++, C#, Java,
|
||||
* JavaScript, Perl, TCL, and many others. These properties make JSON an
|
||||
* ideal data-interchange language.
|
||||
*
|
||||
* This package provides a simple encoder and decoder for JSON notation. It
|
||||
* is intended for use with client-side Javascript applications that make
|
||||
* use of HTTPRequest to perform server communication functions - data can
|
||||
* be encoded into JSON notation for use in a client-side javascript, or
|
||||
* decoded from incoming Javascript requests. JSON format is native to
|
||||
* Javascript, and can be directly eval()'ed with no further parsing
|
||||
* overhead
|
||||
*
|
||||
* All strings should be in ASCII or UTF-8 format!
|
||||
*
|
||||
* LICENSE: Redistribution and use in source and binary forms, with or
|
||||
* without modification, are permitted provided that the following
|
||||
* conditions are met: Redistributions of source code must retain the
|
||||
* above copyright notice, this list of conditions and the following
|
||||
* disclaimer. Redistributions in binary form must reproduce the above
|
||||
* copyright notice, this list of conditions and the following disclaimer
|
||||
* in the documentation and/or other materials provided with the
|
||||
* distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
|
||||
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
|
||||
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
|
||||
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
|
||||
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
|
||||
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
|
||||
* DAMAGE.
|
||||
*
|
||||
* @category
|
||||
* @package Services_JSON
|
||||
* @author Michal Migurski <mike-json@teczno.com>
|
||||
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
|
||||
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
|
||||
* @copyright 2005 Michal Migurski
|
||||
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
|
||||
* @license http://www.opensource.org/licenses/bsd-license.php
|
||||
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marker constant for Services_JSON::decode(), used to flag stack state
|
||||
*/
|
||||
define('SERVICES_JSON_SLICE', 1);
|
||||
|
||||
/**
|
||||
* Marker constant for Services_JSON::decode(), used to flag stack state
|
||||
*/
|
||||
define('SERVICES_JSON_IN_STR', 2);
|
||||
|
||||
/**
|
||||
* Marker constant for Services_JSON::decode(), used to flag stack state
|
||||
*/
|
||||
define('SERVICES_JSON_IN_ARR', 3);
|
||||
|
||||
/**
|
||||
* Marker constant for Services_JSON::decode(), used to flag stack state
|
||||
*/
|
||||
define('SERVICES_JSON_IN_OBJ', 4);
|
||||
|
||||
/**
|
||||
* Marker constant for Services_JSON::decode(), used to flag stack state
|
||||
*/
|
||||
define('SERVICES_JSON_IN_CMT', 5);
|
||||
|
||||
/**
|
||||
* Behavior switch for Services_JSON::decode()
|
||||
*/
|
||||
define('SERVICES_JSON_LOOSE_TYPE', 16);
|
||||
|
||||
/**
|
||||
* Behavior switch for Services_JSON::decode()
|
||||
*/
|
||||
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
|
||||
|
||||
/**
|
||||
* Converts to and from JSON format.
|
||||
*
|
||||
* Brief example of use:
|
||||
*
|
||||
* <code>
|
||||
* // create a new instance of Services_JSON
|
||||
* $json = new Services_JSON();
|
||||
*
|
||||
* // convert a complexe value to JSON notation, and send it to the browser
|
||||
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
|
||||
* $output = $json->encode($value);
|
||||
*
|
||||
* print($output);
|
||||
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
|
||||
*
|
||||
* // accept incoming POST data, assumed to be in JSON notation
|
||||
* $input = file_get_contents('php://input', 1000000);
|
||||
* $value = $json->decode($input);
|
||||
* </code>
|
||||
*/
|
||||
class Services_JSON
|
||||
{
|
||||
/**
|
||||
* constructs a new JSON instance
|
||||
*
|
||||
* @param int $use object behavior flags; combine with boolean-OR
|
||||
*
|
||||
* possible values:
|
||||
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
|
||||
* "{...}" syntax creates associative arrays
|
||||
* instead of objects in decode().
|
||||
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
|
||||
* Values which can't be encoded (e.g. resources)
|
||||
* appear as NULL instead of throwing errors.
|
||||
* By default, a deeply-nested resource will
|
||||
* bubble up with an error, so all return values
|
||||
* from encode() should be checked with isError()
|
||||
*/
|
||||
function Services_JSON($use = 0)
|
||||
{
|
||||
$this->use = $use;
|
||||
}
|
||||
|
||||
/**
|
||||
* convert a string from one UTF-16 char to one UTF-8 char
|
||||
*
|
||||
* Normally should be handled by mb_convert_encoding, but
|
||||
* provides a slower PHP-only method for installations
|
||||
* that lack the multibye string extension.
|
||||
*
|
||||
* @param string $utf16 UTF-16 character
|
||||
* @return string UTF-8 character
|
||||
* @access private
|
||||
*/
|
||||
function utf162utf8($utf16)
|
||||
{
|
||||
// oh please oh please oh please oh please oh please
|
||||
if(function_exists('mb_convert_encoding')) {
|
||||
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
|
||||
}
|
||||
|
||||
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
|
||||
|
||||
switch(true) {
|
||||
case ((0x7F & $bytes) == $bytes):
|
||||
// this case should never be reached, because we are in ASCII range
|
||||
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
return chr(0x7F & $bytes);
|
||||
|
||||
case (0x07FF & $bytes) == $bytes:
|
||||
// return a 2-byte UTF-8 character
|
||||
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
return chr(0xC0 | (($bytes >> 6) & 0x1F))
|
||||
. chr(0x80 | ($bytes & 0x3F));
|
||||
|
||||
case (0xFFFF & $bytes) == $bytes:
|
||||
// return a 3-byte UTF-8 character
|
||||
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
return chr(0xE0 | (($bytes >> 12) & 0x0F))
|
||||
. chr(0x80 | (($bytes >> 6) & 0x3F))
|
||||
. chr(0x80 | ($bytes & 0x3F));
|
||||
}
|
||||
|
||||
// ignoring UTF-32 for now, sorry
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* convert a string from one UTF-8 char to one UTF-16 char
|
||||
*
|
||||
* Normally should be handled by mb_convert_encoding, but
|
||||
* provides a slower PHP-only method for installations
|
||||
* that lack the multibye string extension.
|
||||
*
|
||||
* @param string $utf8 UTF-8 character
|
||||
* @return string UTF-16 character
|
||||
* @access private
|
||||
*/
|
||||
function utf82utf16($utf8)
|
||||
{
|
||||
// oh please oh please oh please oh please oh please
|
||||
if(function_exists('mb_convert_encoding')) {
|
||||
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
|
||||
}
|
||||
|
||||
switch(strlen($utf8)) {
|
||||
case 1:
|
||||
// this case should never be reached, because we are in ASCII range
|
||||
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
return $utf8;
|
||||
|
||||
case 2:
|
||||
// return a UTF-16 character from a 2-byte UTF-8 char
|
||||
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
return chr(0x07 & (ord($utf8{0}) >> 2))
|
||||
. chr((0xC0 & (ord($utf8{0}) << 6))
|
||||
| (0x3F & ord($utf8{1})));
|
||||
|
||||
case 3:
|
||||
// return a UTF-16 character from a 3-byte UTF-8 char
|
||||
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
return chr((0xF0 & (ord($utf8{0}) << 4))
|
||||
| (0x0F & (ord($utf8{1}) >> 2)))
|
||||
. chr((0xC0 & (ord($utf8{1}) << 6))
|
||||
| (0x7F & ord($utf8{2})));
|
||||
}
|
||||
|
||||
// ignoring UTF-32 for now, sorry
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* encodes an arbitrary variable into JSON format
|
||||
*
|
||||
* @param mixed $var any number, boolean, string, array, or object to be encoded.
|
||||
* see argument 1 to Services_JSON() above for array-parsing behavior.
|
||||
* if var is a strng, note that encode() always expects it
|
||||
* to be in ASCII or UTF-8 format!
|
||||
*
|
||||
* @return mixed JSON string representation of input var or an error if a problem occurs
|
||||
* @access public
|
||||
*/
|
||||
function encode($var)
|
||||
{
|
||||
switch (gettype($var)) {
|
||||
case 'boolean':
|
||||
return $var ? 'true' : 'false';
|
||||
|
||||
case 'NULL':
|
||||
return 'null';
|
||||
|
||||
case 'integer':
|
||||
return (int) $var;
|
||||
|
||||
case 'double':
|
||||
case 'float':
|
||||
return (float) $var;
|
||||
|
||||
case 'string':
|
||||
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
|
||||
$ascii = '';
|
||||
$strlen_var = strlen($var);
|
||||
|
||||
/*
|
||||
* Iterate over every character in the string,
|
||||
* escaping with a slash or encoding to UTF-8 where necessary
|
||||
*/
|
||||
for ($c = 0; $c < $strlen_var; ++$c) {
|
||||
|
||||
$ord_var_c = ord($var{$c});
|
||||
|
||||
switch (true) {
|
||||
case $ord_var_c == 0x08:
|
||||
$ascii .= '\b';
|
||||
break;
|
||||
case $ord_var_c == 0x09:
|
||||
$ascii .= '\t';
|
||||
break;
|
||||
case $ord_var_c == 0x0A:
|
||||
$ascii .= '\n';
|
||||
break;
|
||||
case $ord_var_c == 0x0C:
|
||||
$ascii .= '\f';
|
||||
break;
|
||||
case $ord_var_c == 0x0D:
|
||||
$ascii .= '\r';
|
||||
break;
|
||||
|
||||
case $ord_var_c == 0x22:
|
||||
case $ord_var_c == 0x2F:
|
||||
case $ord_var_c == 0x5C:
|
||||
// double quote, slash, slosh
|
||||
$ascii .= '\\'.$var{$c};
|
||||
break;
|
||||
|
||||
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
|
||||
// characters U-00000000 - U-0000007F (same as ASCII)
|
||||
$ascii .= $var{$c};
|
||||
break;
|
||||
|
||||
case (($ord_var_c & 0xE0) == 0xC0):
|
||||
// characters U-00000080 - U-000007FF, mask 110XXXXX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
|
||||
$c += 1;
|
||||
$utf16 = $this->utf82utf16($char);
|
||||
$ascii .= sprintf('\u%04s', bin2hex($utf16));
|
||||
break;
|
||||
|
||||
case (($ord_var_c & 0xF0) == 0xE0):
|
||||
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$char = pack('C*', $ord_var_c,
|
||||
ord($var{$c + 1}),
|
||||
ord($var{$c + 2}));
|
||||
$c += 2;
|
||||
$utf16 = $this->utf82utf16($char);
|
||||
$ascii .= sprintf('\u%04s', bin2hex($utf16));
|
||||
break;
|
||||
|
||||
case (($ord_var_c & 0xF8) == 0xF0):
|
||||
// characters U-00010000 - U-001FFFFF, mask 11110XXX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$char = pack('C*', $ord_var_c,
|
||||
ord($var{$c + 1}),
|
||||
ord($var{$c + 2}),
|
||||
ord($var{$c + 3}));
|
||||
$c += 3;
|
||||
$utf16 = $this->utf82utf16($char);
|
||||
$ascii .= sprintf('\u%04s', bin2hex($utf16));
|
||||
break;
|
||||
|
||||
case (($ord_var_c & 0xFC) == 0xF8):
|
||||
// characters U-00200000 - U-03FFFFFF, mask 111110XX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$char = pack('C*', $ord_var_c,
|
||||
ord($var{$c + 1}),
|
||||
ord($var{$c + 2}),
|
||||
ord($var{$c + 3}),
|
||||
ord($var{$c + 4}));
|
||||
$c += 4;
|
||||
$utf16 = $this->utf82utf16($char);
|
||||
$ascii .= sprintf('\u%04s', bin2hex($utf16));
|
||||
break;
|
||||
|
||||
case (($ord_var_c & 0xFE) == 0xFC):
|
||||
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$char = pack('C*', $ord_var_c,
|
||||
ord($var{$c + 1}),
|
||||
ord($var{$c + 2}),
|
||||
ord($var{$c + 3}),
|
||||
ord($var{$c + 4}),
|
||||
ord($var{$c + 5}));
|
||||
$c += 5;
|
||||
$utf16 = $this->utf82utf16($char);
|
||||
$ascii .= sprintf('\u%04s', bin2hex($utf16));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return '"'.$ascii.'"';
|
||||
|
||||
case 'array':
|
||||
/*
|
||||
* As per JSON spec if any array key is not an integer
|
||||
* we must treat the the whole array as an object. We
|
||||
* also try to catch a sparsely populated associative
|
||||
* array with numeric keys here because some JS engines
|
||||
* will create an array with empty indexes up to
|
||||
* max_index which can cause memory issues and because
|
||||
* the keys, which may be relevant, will be remapped
|
||||
* otherwise.
|
||||
*
|
||||
* As per the ECMA and JSON specification an object may
|
||||
* have any string as a property. Unfortunately due to
|
||||
* a hole in the ECMA specification if the key is a
|
||||
* ECMA reserved word or starts with a digit the
|
||||
* parameter is only accessible using ECMAScript's
|
||||
* bracket notation.
|
||||
*/
|
||||
|
||||
// treat as a JSON object
|
||||
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
|
||||
$properties = array_map(array($this, 'name_value'),
|
||||
array_keys($var),
|
||||
array_values($var));
|
||||
|
||||
foreach($properties as $property) {
|
||||
if(Services_JSON::isError($property)) {
|
||||
return $property;
|
||||
}
|
||||
}
|
||||
|
||||
return '{' . join(',', $properties) . '}';
|
||||
}
|
||||
|
||||
// treat it like a regular array
|
||||
$elements = array_map(array($this, 'encode'), $var);
|
||||
|
||||
foreach($elements as $element) {
|
||||
if(Services_JSON::isError($element)) {
|
||||
return $element;
|
||||
}
|
||||
}
|
||||
|
||||
return '[' . join(',', $elements) . ']';
|
||||
|
||||
case 'object':
|
||||
$vars = get_object_vars($var);
|
||||
|
||||
$properties = array_map(array($this, 'name_value'),
|
||||
array_keys($vars),
|
||||
array_values($vars));
|
||||
|
||||
foreach($properties as $property) {
|
||||
if(Services_JSON::isError($property)) {
|
||||
return $property;
|
||||
}
|
||||
}
|
||||
|
||||
return '{' . join(',', $properties) . '}';
|
||||
|
||||
default:
|
||||
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
|
||||
? 'null'
|
||||
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* array-walking function for use in generating JSON-formatted name-value pairs
|
||||
*
|
||||
* @param string $name name of key to use
|
||||
* @param mixed $value reference to an array element to be encoded
|
||||
*
|
||||
* @return string JSON-formatted name-value pair, like '"name":value'
|
||||
* @access private
|
||||
*/
|
||||
function name_value($name, $value)
|
||||
{
|
||||
$encoded_value = $this->encode($value);
|
||||
|
||||
if(Services_JSON::isError($encoded_value)) {
|
||||
return $encoded_value;
|
||||
}
|
||||
|
||||
return $this->encode(strval($name)) . ':' . $encoded_value;
|
||||
}
|
||||
|
||||
/**
|
||||
* reduce a string by removing leading and trailing comments and whitespace
|
||||
*
|
||||
* @param $str string string value to strip of comments and whitespace
|
||||
*
|
||||
* @return string string value stripped of comments and whitespace
|
||||
* @access private
|
||||
*/
|
||||
function reduce_string($str)
|
||||
{
|
||||
$str = preg_replace(array(
|
||||
|
||||
// eliminate single line comments in '// ...' form
|
||||
'#^\s*//(.+)$#m',
|
||||
|
||||
// eliminate multi-line comments in '/* ... */' form, at start of string
|
||||
'#^\s*/\*(.+)\*/#Us',
|
||||
|
||||
// eliminate multi-line comments in '/* ... */' form, at end of string
|
||||
'#/\*(.+)\*/\s*$#Us'
|
||||
|
||||
), '', $str);
|
||||
|
||||
// eliminate extraneous space
|
||||
return trim($str);
|
||||
}
|
||||
|
||||
/**
|
||||
* decodes a JSON string into appropriate variable
|
||||
*
|
||||
* @param string $str JSON-formatted string
|
||||
*
|
||||
* @return mixed number, boolean, string, array, or object
|
||||
* corresponding to given JSON input string.
|
||||
* See argument 1 to Services_JSON() above for object-output behavior.
|
||||
* Note that decode() always returns strings
|
||||
* in ASCII or UTF-8 format!
|
||||
* @access public
|
||||
*/
|
||||
function decode($str)
|
||||
{
|
||||
$str = $this->reduce_string($str);
|
||||
|
||||
switch (strtolower($str)) {
|
||||
case 'true':
|
||||
return true;
|
||||
|
||||
case 'false':
|
||||
return false;
|
||||
|
||||
case 'null':
|
||||
return null;
|
||||
|
||||
default:
|
||||
$m = array();
|
||||
|
||||
if (is_numeric($str)) {
|
||||
// Lookie-loo, it's a number
|
||||
|
||||
// This would work on its own, but I'm trying to be
|
||||
// good about returning integers where appropriate:
|
||||
// return (float)$str;
|
||||
|
||||
// Return float or int, as appropriate
|
||||
return ((float)$str == (integer)$str)
|
||||
? (integer)$str
|
||||
: (float)$str;
|
||||
|
||||
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
|
||||
// STRINGS RETURNED IN UTF-8 FORMAT
|
||||
$delim = substr($str, 0, 1);
|
||||
$chrs = substr($str, 1, -1);
|
||||
$utf8 = '';
|
||||
$strlen_chrs = strlen($chrs);
|
||||
|
||||
for ($c = 0; $c < $strlen_chrs; ++$c) {
|
||||
|
||||
$substr_chrs_c_2 = substr($chrs, $c, 2);
|
||||
$ord_chrs_c = ord($chrs{$c});
|
||||
|
||||
switch (true) {
|
||||
case $substr_chrs_c_2 == '\b':
|
||||
$utf8 .= chr(0x08);
|
||||
++$c;
|
||||
break;
|
||||
case $substr_chrs_c_2 == '\t':
|
||||
$utf8 .= chr(0x09);
|
||||
++$c;
|
||||
break;
|
||||
case $substr_chrs_c_2 == '\n':
|
||||
$utf8 .= chr(0x0A);
|
||||
++$c;
|
||||
break;
|
||||
case $substr_chrs_c_2 == '\f':
|
||||
$utf8 .= chr(0x0C);
|
||||
++$c;
|
||||
break;
|
||||
case $substr_chrs_c_2 == '\r':
|
||||
$utf8 .= chr(0x0D);
|
||||
++$c;
|
||||
break;
|
||||
|
||||
case $substr_chrs_c_2 == '\\"':
|
||||
case $substr_chrs_c_2 == '\\\'':
|
||||
case $substr_chrs_c_2 == '\\\\':
|
||||
case $substr_chrs_c_2 == '\\/':
|
||||
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
|
||||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
|
||||
$utf8 .= $chrs{++$c};
|
||||
}
|
||||
break;
|
||||
|
||||
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
|
||||
// single, escaped unicode character
|
||||
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
|
||||
. chr(hexdec(substr($chrs, ($c + 4), 2)));
|
||||
$utf8 .= $this->utf162utf8($utf16);
|
||||
$c += 5;
|
||||
break;
|
||||
|
||||
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
|
||||
$utf8 .= $chrs{$c};
|
||||
break;
|
||||
|
||||
case ($ord_chrs_c & 0xE0) == 0xC0:
|
||||
// characters U-00000080 - U-000007FF, mask 110XXXXX
|
||||
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$utf8 .= substr($chrs, $c, 2);
|
||||
++$c;
|
||||
break;
|
||||
|
||||
case ($ord_chrs_c & 0xF0) == 0xE0:
|
||||
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$utf8 .= substr($chrs, $c, 3);
|
||||
$c += 2;
|
||||
break;
|
||||
|
||||
case ($ord_chrs_c & 0xF8) == 0xF0:
|
||||
// characters U-00010000 - U-001FFFFF, mask 11110XXX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$utf8 .= substr($chrs, $c, 4);
|
||||
$c += 3;
|
||||
break;
|
||||
|
||||
case ($ord_chrs_c & 0xFC) == 0xF8:
|
||||
// characters U-00200000 - U-03FFFFFF, mask 111110XX
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$utf8 .= substr($chrs, $c, 5);
|
||||
$c += 4;
|
||||
break;
|
||||
|
||||
case ($ord_chrs_c & 0xFE) == 0xFC:
|
||||
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
|
||||
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
|
||||
$utf8 .= substr($chrs, $c, 6);
|
||||
$c += 5;
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return $utf8;
|
||||
|
||||
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
|
||||
// array, or object notation
|
||||
|
||||
if ($str{0} == '[') {
|
||||
$stk = array(SERVICES_JSON_IN_ARR);
|
||||
$arr = array();
|
||||
} else {
|
||||
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
|
||||
$stk = array(SERVICES_JSON_IN_OBJ);
|
||||
$obj = array();
|
||||
} else {
|
||||
$stk = array(SERVICES_JSON_IN_OBJ);
|
||||
$obj = new stdClass();
|
||||
}
|
||||
}
|
||||
|
||||
array_push($stk, array('what' => SERVICES_JSON_SLICE,
|
||||
'where' => 0,
|
||||
'delim' => false));
|
||||
|
||||
$chrs = substr($str, 1, -1);
|
||||
$chrs = $this->reduce_string($chrs);
|
||||
|
||||
if ($chrs == '') {
|
||||
if (reset($stk) == SERVICES_JSON_IN_ARR) {
|
||||
return $arr;
|
||||
|
||||
} else {
|
||||
return $obj;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
//print("\nparsing {$chrs}\n");
|
||||
|
||||
$strlen_chrs = strlen($chrs);
|
||||
|
||||
for ($c = 0; $c <= $strlen_chrs; ++$c) {
|
||||
|
||||
$top = end($stk);
|
||||
$substr_chrs_c_2 = substr($chrs, $c, 2);
|
||||
|
||||
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
|
||||
// found a comma that is not inside a string, array, etc.,
|
||||
// OR we've reached the end of the character list
|
||||
$slice = substr($chrs, $top['where'], ($c - $top['where']));
|
||||
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
|
||||
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
|
||||
|
||||
if (reset($stk) == SERVICES_JSON_IN_ARR) {
|
||||
// we are in an array, so just push an element onto the stack
|
||||
array_push($arr, $this->decode($slice));
|
||||
|
||||
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
|
||||
// we are in an object, so figure
|
||||
// out the property name and set an
|
||||
// element in an associative array,
|
||||
// for now
|
||||
$parts = array();
|
||||
|
||||
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
|
||||
// "name":value pair
|
||||
$key = $this->decode($parts[1]);
|
||||
$val = $this->decode($parts[2]);
|
||||
|
||||
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
|
||||
$obj[$key] = $val;
|
||||
} else {
|
||||
$obj->$key = $val;
|
||||
}
|
||||
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
|
||||
// name:value pair, where name is unquoted
|
||||
$key = $parts[1];
|
||||
$val = $this->decode($parts[2]);
|
||||
|
||||
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
|
||||
$obj[$key] = $val;
|
||||
} else {
|
||||
$obj->$key = $val;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
|
||||
// found a quote, and we are not inside a string
|
||||
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
|
||||
//print("Found start of string at {$c}\n");
|
||||
|
||||
} elseif (($chrs{$c} == $top['delim']) &&
|
||||
($top['what'] == SERVICES_JSON_IN_STR) &&
|
||||
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
|
||||
// found a quote, we're in a string, and it's not escaped
|
||||
// we know that it's not escaped becase there is _not_ an
|
||||
// odd number of backslashes at the end of the string so far
|
||||
array_pop($stk);
|
||||
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
|
||||
|
||||
} elseif (($chrs{$c} == '[') &&
|
||||
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
|
||||
// found a left-bracket, and we are in an array, object, or slice
|
||||
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
|
||||
//print("Found start of array at {$c}\n");
|
||||
|
||||
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
|
||||
// found a right-bracket, and we're in an array
|
||||
array_pop($stk);
|
||||
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
|
||||
|
||||
} elseif (($chrs{$c} == '{') &&
|
||||
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
|
||||
// found a left-brace, and we are in an array, object, or slice
|
||||
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
|
||||
//print("Found start of object at {$c}\n");
|
||||
|
||||
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
|
||||
// found a right-brace, and we're in an object
|
||||
array_pop($stk);
|
||||
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
|
||||
|
||||
} elseif (($substr_chrs_c_2 == '/*') &&
|
||||
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
|
||||
// found a comment start, and we are in an array, object, or slice
|
||||
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
|
||||
$c++;
|
||||
//print("Found start of comment at {$c}\n");
|
||||
|
||||
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
|
||||
// found a comment end, and we're in one now
|
||||
array_pop($stk);
|
||||
$c++;
|
||||
|
||||
for ($i = $top['where']; $i <= $c; ++$i)
|
||||
$chrs = substr_replace($chrs, ' ', $i, 1);
|
||||
|
||||
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (reset($stk) == SERVICES_JSON_IN_ARR) {
|
||||
return $arr;
|
||||
|
||||
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
|
||||
return $obj;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isError($data, $code = null)
|
||||
{
|
||||
if (class_exists('pear')) {
|
||||
return PEAR::isError($data, $code);
|
||||
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
|
||||
is_subclass_of($data, 'services_json_error'))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (class_exists('PEAR_Error')) {
|
||||
|
||||
class Services_JSON_Error extends PEAR_Error
|
||||
{
|
||||
function Services_JSON_Error($message = 'unknown error', $code = null,
|
||||
$mode = null, $options = null, $userinfo = null)
|
||||
{
|
||||
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
class Services_JSON_Error
|
||||
{
|
||||
function Services_JSON_Error($message = 'unknown error', $code = null,
|
||||
$mode = null, $options = null, $userinfo = null)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
if(!defined('DATALIFEENGINE')){die("Hacking attempt!");}
|
||||
|
||||
class cache{
|
||||
var $dir = false;
|
||||
var $allow_cache = false;
|
||||
var $memcache = false;
|
||||
|
||||
private $mcache;
|
||||
private $memcache_host = '127.0.0.1';
|
||||
private $memcache_port = 11211;
|
||||
|
||||
var $timelife = 3600;
|
||||
|
||||
function __construct($dir) {
|
||||
global $config;
|
||||
|
||||
$this->dir = $dir;
|
||||
if( $config['allow_cache'] = "yes" ) $this->allow_cache = true;
|
||||
if( $config['cache_type']) $this->memcache = true;
|
||||
|
||||
if( $this->memcache AND function_exists('memcache_connect') ) $this->mcache = memcache_connect($this->memcache_host, $this->memcache_port);
|
||||
if( $this->memcache AND function_exists('memcache_set_compress_threshold') ){memcache_set_compress_threshold( $this->mcache, 20000, 0.2 );}
|
||||
}
|
||||
|
||||
function off(){
|
||||
$this->allow_cache = false;
|
||||
}
|
||||
|
||||
function set($file, $data){
|
||||
$fp = fopen( $this->dir.'/system/' . $file . '.php', 'wb+' );
|
||||
if (!$data) $data = 'a:0:{}';
|
||||
fwrite( $fp, serialize( $data ) );
|
||||
fclose( $fp );
|
||||
@chmod( $this->dir.'/system/' . $file . '.php', 0666 );
|
||||
}
|
||||
|
||||
function get($file){
|
||||
return unserialize( @file_get_contents( $this->dir.'/system/' . $file . '.php' ) );
|
||||
}
|
||||
|
||||
function delete($cache_area = false){
|
||||
$fdir = opendir($this->dir.'/system/');
|
||||
while ($file = readdir($fdir)){
|
||||
if ($file != '.' and $file != '..' and $file != '.htaccess' and $file != 'online.php'){
|
||||
if ($cache_area){
|
||||
if (strpos($file, $cache_area) !== false) @unlink($this->dir.'/system/'.$file);
|
||||
}else{
|
||||
@unlink($this->dir.'/system/'.$file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function filename($name){
|
||||
if(!$this->memcache) return $this->dir.'/'.$name.'.tmp';
|
||||
else return md5($name);
|
||||
}
|
||||
|
||||
function open($name, $cache_id = false, $member_prefix = false){
|
||||
global $is_logged, $member_id;
|
||||
if(!$this->allow_cache) return false;
|
||||
|
||||
if( $is_logged ) $group = $member_id['user_group']; else $group = "0";
|
||||
|
||||
if( !$cache_id ){ $filename = $this->filename($name);
|
||||
} else {
|
||||
$cache_id = md5( $cache_id );
|
||||
if( $member_prefix ) $filename = $this->filename($name . "_" . $cache_id . "_" . $group); else $filename = $this->filename($name . "_" . $cache_id);
|
||||
}
|
||||
|
||||
if($this->memcache){
|
||||
return memcache_get($this->mcache, $filename);
|
||||
} else {
|
||||
if(file_exists($filename) && is_readable($filename) && filesize($filename) > 0 && (time() - $this->timelife < filemtime($filename))) {
|
||||
return @file_get_contents( $filename );
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function save($name, $data, $cache_id = false, $member_prefix = false){
|
||||
global $is_logged, $member_id;
|
||||
if(empty( $data ) OR !$this->allow_cache) return false;
|
||||
|
||||
if( $is_logged ) $group = $member_id['user_group']; else $group = "0";
|
||||
if( !$cache_id ){ $filename = $this->filename($name);
|
||||
} else {
|
||||
$cache_id = md5( $cache_id );
|
||||
if( $member_prefix ) $filename = $this->filename($name . "_" . $cache_id . "_" . $group); else $filename = $this->filename($name . "_" . $cache_id);
|
||||
}
|
||||
|
||||
if($this->memcache){
|
||||
memcache_set( $this->mcache, $filename, $data, MEMCACHE_COMPRESSED, $this->timelife );
|
||||
} else {
|
||||
@unlink( $filename );
|
||||
file_put_contents ($filename, $data, LOCK_EX);
|
||||
@chmod( $filename, 0666 );
|
||||
}
|
||||
}
|
||||
|
||||
function clear($cache_areas = false) {
|
||||
if ( $this->memcache ) {
|
||||
memcache_flush($this->mcache);
|
||||
} else {
|
||||
if ( $cache_areas ) {if(!is_array($cache_areas)) {$cache_areas = array($cache_areas);}}
|
||||
$fdir = opendir( $this->dir );
|
||||
while ( $file = readdir( $fdir ) ) {
|
||||
if( $file != '.' and $file != '..' and $file != '.htaccess' and $file != 'system' ) {
|
||||
if( $cache_areas ) { foreach($cache_areas as $cache_area) if( strpos( $file, $cache_area ) !== false ) @unlink( $this->dir . '/' . $file );
|
||||
} else {@unlink( $this->dir . '/' . $file );}
|
||||
}}}
|
||||
}
|
||||
|
||||
function del($file){
|
||||
if ($this->memcache){
|
||||
memcache_delete($this->mcache, $this->filename($file));
|
||||
}else{
|
||||
@unlink($this->filename($file));
|
||||
}
|
||||
}
|
||||
|
||||
function size(){
|
||||
if($this->memcache){
|
||||
$stat = memcache_get_stats($this->mcache);
|
||||
$size = $stat['bytes'];
|
||||
}else{
|
||||
$size = dirsize($this->dir);
|
||||
}
|
||||
return $size;
|
||||
}
|
||||
|
||||
public function __destruct(){
|
||||
if($this->memcache){
|
||||
if(memcache_close($this->mcache)){
|
||||
return TRUE;
|
||||
}else{
|
||||
return FALSE;
|
||||
}
|
||||
}else{
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
class captcha{
|
||||
var $alphabet = "0123456789"; // ÍÅ ÈÇÌÅÍßÉÒÅ, åñëè âû íå èçìåíÿëè ôàéë øðèôòîâ!
|
||||
var $fontsdir = 'fonts';
|
||||
var $width = 120;
|
||||
var $height = 50;
|
||||
var $fluctuation_amplitude = 2;
|
||||
var $no_spaces = false;
|
||||
var $jpeg_quality = 70; // ìàêñèìàëüíîå, ìîæíî ïîñòàâèòü 70-80
|
||||
var $keystring = ''; // êëþ÷åâàÿ ãåíåðèðóåìàÿ ñòðîêà
|
||||
var $allowed_symbols = "0123456789"; // èñïîëüçóåìûå öèôðû
|
||||
var $length_min = 3; // ìèíèìàëüíîå
|
||||
var $length_max = 3; // ìàêñèìàëüíîå
|
||||
var $length = 0; // äëèíà áóäåò ñãåíåðèðîâàíà
|
||||
|
||||
function genstring() {
|
||||
$length = mt_rand( $this->length_min, $this->length_max );
|
||||
$this->length = $length;
|
||||
$this->keystring = '';
|
||||
for ($i = 0; $i < $length ; $i++) {
|
||||
// â öèêëå äîáàâëÿåì ê ñòðîêå ïî 1 ñëó÷àéíîìó ñèìâîëó
|
||||
$this->keystring .= $this->allowed_symbols{ mt_rand( 0, strlen( $this->allowed_symbols ) -1 ) };
|
||||
}}
|
||||
|
||||
function genimage() {
|
||||
$foreground_color = array( 100, 130, 200 );
|
||||
$background_color = array( 255, 255, 255 );
|
||||
$fonts = array();
|
||||
$fontsdir_absolute = dirname( __FILE__ ).'/'.$this->fontsdir; // ïóòü ê ïàïêå ñ øðèôòàìè
|
||||
if ($handle = opendir( $fontsdir_absolute )) { // ñîçäàåì ìàññèâ ñ ïîëíûìè ïóòÿìè ê èçîáðàæåíèÿì ñ øðèôòàìè
|
||||
while (false !== ($file = readdir( $handle ))) {
|
||||
if (preg_match( '/\.png$/i', $file )) {
|
||||
$fonts[] = $fontsdir_absolute.'/'.$file;
|
||||
}}
|
||||
closedir( $handle );
|
||||
}
|
||||
|
||||
$alphabet_length = strlen( $this->alphabet );
|
||||
|
||||
while (true) {
|
||||
$font_file = $fonts[mt_rand( 0, count( $fonts ) - 1 )];
|
||||
$font = imagecreatefrompng( $font_file );
|
||||
$black = imagecolorallocate( $font, 0, 0, 0 );
|
||||
$fontfile_width = imagesx( $font );
|
||||
$fontfile_height = imagesy( $font ) - 1;
|
||||
$font_metrics = array();
|
||||
$symbol = 0;
|
||||
$reading_symbol = false;
|
||||
|
||||
// çàãðóçêà øðèôòà
|
||||
for ($i = 0; $i < $fontfile_width && $symbol < $alphabet_length; $i++) {
|
||||
$transparent = (imagecolorat( $font, $i, 0 ) >> 24) == 127;
|
||||
|
||||
if (!$reading_symbol && !$transparent) {
|
||||
$font_metrics[$this->alphabet{$symbol}] = array( 'start' => $i );
|
||||
$reading_symbol = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($reading_symbol && $transparent) {
|
||||
$font_metrics[$this->alphabet{$symbol}]['end'] = $i;
|
||||
$reading_symbol = false;
|
||||
$symbol++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$img = imagecreatetruecolor( $this->width, $this->height );
|
||||
|
||||
$white = imagecolorallocate( $img, 100, 130, 200 );
|
||||
$black = imagecolorallocate( $img, 100, 130, 200 );
|
||||
|
||||
imagefilledrectangle( $img, 0, 0, $this->width - 1, $this->height - 1, $white );
|
||||
|
||||
// íàíåñåíèå òåêñòà
|
||||
$x = 1;
|
||||
$shift = 0;
|
||||
|
||||
for ($i = 0; $i < $this->length; $i++) {
|
||||
$m = $font_metrics[$this->keystring{$i}];
|
||||
$y = mt_rand( -$this->fluctuation_amplitude, $this->fluctuation_amplitude ) + ($this->height - $fontfile_height) / 2 + 2;
|
||||
|
||||
if ($this->no_spaces) {
|
||||
$shift = 0;
|
||||
if ($i > 0) {
|
||||
$shift = 1000;
|
||||
for ($sy = 1; $sy < $fontfile_height - 15; $sy += 2) {
|
||||
for ($sx = $m['start'] - 1; $sx < $m['end']; $sx++) {
|
||||
$rgb = imagecolorat( $font, $sx, $sy );
|
||||
$opacity = $rgb >> 24;
|
||||
if ($opacity < 127) {
|
||||
$left = $sx - $m['start'] + $x;
|
||||
$py = $sy + $y;
|
||||
for ($px = min( $left, $this->width - 1 ); $px > $left - 20 && $px >= 0; $px--) {
|
||||
$color = imagecolorat( $img, $px, $py ) & 0xff;
|
||||
if ($color + $opacity < 190) {
|
||||
if ($shift > $left-$px) {
|
||||
$shift = $left - $px;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {$shift = 1;}
|
||||
imagecopy( $img, $font, $x - $shift, $y, $m['start'], 1, $m['end'] - $m['start'], $fontfile_height );
|
||||
$x += $m['end'] - $m['start'] - $shift;
|
||||
}
|
||||
if ($x < $this->width - 10) break; // fit in canvas
|
||||
}
|
||||
$center = $x/2;
|
||||
|
||||
$img2=imagecreatetruecolor($this->width, $this->height);
|
||||
$foreground=imagecolorallocate($img2, $foreground_color[0], $foreground_color[1], $foreground_color[2]);
|
||||
$background=imagecolorallocate($img2, $background_color[0], $background_color[1], $background_color[2]);
|
||||
imagefilledrectangle($img2, 0, $this->height, $this->width, $this->height+12, $foreground);
|
||||
|
||||
// ïåðèîäû
|
||||
$rand1 = 0;
|
||||
$rand2 = 0;
|
||||
$rand3 = 0;
|
||||
$rand4 = 0;
|
||||
// ôàçû
|
||||
$rand5 = 0;
|
||||
$rand6 = 0;
|
||||
$rand7 = 0;
|
||||
$rand8 = 0;
|
||||
// àìïëèòóäû
|
||||
$rand9 = 0;
|
||||
$rand10 = 0;
|
||||
|
||||
//âîëíîâîå èñêàæåíèå
|
||||
for ($x = 0; $x < $this->width; $x++) {
|
||||
for ($y = 0; $y < $this->height; $y++) {
|
||||
$sx = $x + (sin( $x * $rand1 + $rand5 ) + sin( $y * $rand3 + $rand6 )) * $rand9 - $this->width / 2 + $center + 1;
|
||||
$sy = $y + (sin( $x * $rand2 + $rand7 ) + sin( $y * $rand4 + $rand8 )) * $rand10;
|
||||
|
||||
if ($sx < 0 || $sy < 0 || $sx >= $this->width - 1 || $sy >= $this->height - 1) {
|
||||
$color = 200;
|
||||
$color_x = 200;
|
||||
$color_y = 200;
|
||||
$color_xy = 200;
|
||||
} else {
|
||||
$color = imagecolorat( $img, $sx, $sy ) & 0xFF;
|
||||
$color_x = imagecolorat( $img, $sx + 1, $sy ) & 0xFF;
|
||||
$color_y = imagecolorat( $img, $sx, $sy + 1 ) & 0xFF;
|
||||
$color_xy = imagecolorat( $img, $sx + 1, $sy + 1 ) & 0xFF;
|
||||
}
|
||||
|
||||
if ($color == 0 && $color_x == 0 && $color_y == 0 && $color_xy == 0) {
|
||||
$newred = $foreground_color[0];
|
||||
$newgreen = $foreground_color[1];
|
||||
$newblue = $foreground_color[2];
|
||||
} else if ($color == 255 && $color_x == 255 && $color_y == 255 && $color_xy == 255) {
|
||||
$newred = $background_color[0];
|
||||
$newgreen = $background_color[1];
|
||||
$newblue = $background_color[2];
|
||||
} else {
|
||||
$frsx = $sx - floor( $sx );
|
||||
$frsy = $sy - floor( $sy );
|
||||
$frsx1 = 1 - $frsx;
|
||||
$frsy1 = 1 - $frsy;
|
||||
$newcolor = (
|
||||
$color * $frsx1 * $frsy1 +
|
||||
$color_x * $frsx * $frsy1 +
|
||||
$color_y * $frsx1 * $frsy +
|
||||
$color_xy * $frsx * $frsy);
|
||||
|
||||
if ($newcolor > 255) $newcolor = 255;
|
||||
$newcolor = $newcolor / 255;
|
||||
$newcolor0 = 1 - $newcolor;
|
||||
|
||||
$newred = $newcolor0 * $foreground_color[0] + $newcolor * $background_color[0];
|
||||
$newgreen = $newcolor0 * $foreground_color[1] + $newcolor * $background_color[1];
|
||||
$newblue = $newcolor0 * $foreground_color[2] + $newcolor * $background_color[2];
|
||||
}
|
||||
imagesetpixel( $img2, $x, $y, imagecolorallocate( $img2, $newred, $newgreen, $newblue ) );
|
||||
}}
|
||||
|
||||
# Ðàìêà
|
||||
imageline( $img2, 0, 0, $this->width, 0, $foreground );
|
||||
imageline( $img2, 0, 0, 0, $this->height, $foreground );
|
||||
|
||||
imageline( $img2, 0, $this->height-1, $this->width, $this->height-1, $foreground );
|
||||
imageline( $img2, $this->width-1, 0, $this->width-1, $this->height, $foreground);
|
||||
|
||||
header( "Expires: Tue, 11 Jun 1985 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" );
|
||||
|
||||
if (function_exists ('imagepng')) {
|
||||
header ('Content-type: image/png');
|
||||
imagepng ($img2, null);
|
||||
} elseif (function_exists ('imagegif')) {
|
||||
header ('Content-type: image/gif');
|
||||
imagegif ($img2, null);
|
||||
} elseif (function_exists('imagejpeg')) {
|
||||
header( "Content-Type: image/jpeg" );
|
||||
imagejpeg($img2, null, $this->jpeg_quality);
|
||||
}
|
||||
|
||||
imagedestroy($img2);
|
||||
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
if( ! defined( 'DATALIFEENGINE' ) ) {die( "Hacking attempt!" );}
|
||||
|
||||
class Comments {
|
||||
var $db = false;
|
||||
var $query = false;
|
||||
var $nid = false;
|
||||
var $cstart = 0;
|
||||
var $CountCom = 0;
|
||||
var $LimitCom = 0;
|
||||
var $AllowCom = false;
|
||||
private $Row = array();
|
||||
|
||||
public function EchoInfo($title, $info){
|
||||
global $tpl;
|
||||
$tpl->Load_Template( 'comments/info.tpl' );
|
||||
$tpl->set( "{title}", stripslashes( $title ) );
|
||||
$tpl->set( "{error}", stripslashes( $info ) );
|
||||
$tpl->copy_template = "<span id=\"dle-ajax-comments\">".$tpl->copy_template."</span>";
|
||||
$tpl->compile( "content" );
|
||||
$tpl->clear();
|
||||
}
|
||||
|
||||
function Comments( $db, $total_comments, $comments_per_pages ) {
|
||||
global $allow_comments;
|
||||
|
||||
$this->db = $db;
|
||||
$this->CountCom = $total_comments;
|
||||
$this->LimitCom = $comments_per_pages;
|
||||
$this->AllowCom = $allow_comments;
|
||||
|
||||
if ( isset( $_GET['cstart'] ) ) $this->cstart = intval( $_GET['cstart'] ); else $this->cstart = 0;
|
||||
if( $this->cstart > 0) {
|
||||
$this->cstart = $this->cstart - 1;
|
||||
$this->cstart = $this->cstart * $comments_per_pages;
|
||||
} else $this->cstart = 0;
|
||||
}
|
||||
|
||||
//Îòîáðàæåíèå êîììåíòàðèåâ
|
||||
function build_comments($area, $allow_cache = false ) {
|
||||
global $config, $tpl, $cache, $user_group, $member_id;
|
||||
|
||||
if($this->CountCom > 0){
|
||||
$rows = false;
|
||||
if($allow_cache) $rows = $cache->open( "comm_".$allow_cache, $this->query . " LIMIT " . $this->cstart . "," . $this->LimitCom );
|
||||
|
||||
if($rows){ $rows = unserialize($rows);
|
||||
} else {
|
||||
$rows = $this->db->super_query( $this->query . " LIMIT " . $this->cstart . "," . $this->LimitCom, true );
|
||||
if($allow_cache) $cache->save( "comm_".$allow_cache, serialize($rows), $this->query . " LIMIT " . $this->cstart . "," . $this->LimitCom );
|
||||
}
|
||||
|
||||
if(count ($rows)) foreach ($rows as $row){
|
||||
$this->Row[ $row['id'] ] = $row;
|
||||
$this->Echo_Comm($row['id']);
|
||||
}
|
||||
|
||||
} elseif ($user_group[$member_id['user_group']]['allow_addc'] && $this->AllowCom){
|
||||
$this->EchoInfo("Êîììåíòàðèè îòñóòñòâóþò", "Íî âû ìîæåòå äîáàâèòü ïåðâûé....");
|
||||
}
|
||||
|
||||
if ($area != 'ajax' AND $config['comm_msort'] == "ASC") $tpl->result['content'] .= "\n<div id=\"dle-ajax-comments\"></div>\n";
|
||||
}
|
||||
|
||||
private function Echo_Comm($id){
|
||||
global $config, $tpl, $is_logged, $member_id, $user_group, $lang, $dle_login_hash, $_TIME;
|
||||
|
||||
$row = $this->Row[ $id ];
|
||||
$id = $row['id'];
|
||||
|
||||
$tpl->Load_Template( 'comments/comments.tpl' );
|
||||
$tpl->copy_template = "<div id='comment-id-$id'>" . $tpl->copy_template . "</div>";
|
||||
$tpl->template = "<div id='comment-id-$id'>" . $tpl->template . "</div>";
|
||||
|
||||
$UserName = stripslashes( $row['name'] );
|
||||
$date = strtotime( $row['date'] );
|
||||
$ComAutor = htmlspecialchars( stripslashes( $row['gast_name'] ) );
|
||||
$text = stripslashes( $row['text'] );
|
||||
$is_register = intval( $row['is_register'] );
|
||||
$UserFoto = stripslashes( $row['foto'] );
|
||||
|
||||
//Öâåò ïîëüçîâàòåëüñêîé ãðóïïû (ïîëüçîâàòåëÿ)
|
||||
if ($user_group[$row['user_group']]['colour']){
|
||||
$group_span = $user_group[$row['user_group']]['colour'];
|
||||
$user = "<font color={$group_span}>".$UserName."</font>";
|
||||
}else{
|
||||
$user = $UserName;
|
||||
}
|
||||
|
||||
//Ññûëêà íà àâòîðà êîììåíòàðèÿ
|
||||
if( !$is_register || $UserName == '' ) {
|
||||
$tpl->set( '{author}', $ComAutor );
|
||||
} else {
|
||||
$tpl->set( '{author}', "<a href=\"" . $config['http_home_url'] . "user/" . urlencode( $row['name'] ) . "/\">{$user}</a>" );
|
||||
}
|
||||
|
||||
//Äàòà äîáàâëåíèÿ êîììåíòàðèÿ
|
||||
if( date( Ymd, $date ) == date( Ymd, $_TIME ) )
|
||||
$tpl->set( "{date}", $lang['time_heute'].langdate( ", H:i", $date ) );
|
||||
elseif( date( Ymd, $date ) == date( Ymd, ($_TIME - 86400) ) )
|
||||
$tpl->set( "{date}", $lang['time_gestern'].langdate( ", H:i", $date ));
|
||||
else
|
||||
$tpl->set( "{date}", langdate( $config['timestamp_comment'], $date ) );
|
||||
|
||||
//Ññûëêà íà íîâîñòü
|
||||
if(!$this->nid){
|
||||
$link = $config['http_home_url'] . $row['post_id'] . "-" . $row['alt_name'] . ".html";
|
||||
$tpl->set_block( "'\[news](.*?)\[/news\]'si", "<a href=\"$link\">".$row['title']."</a>" );
|
||||
} else {
|
||||
$tpl->set( "[news]", "" );
|
||||
$tpl->set( "[/news]", "" );
|
||||
}
|
||||
|
||||
//Ññûëêà íà êîììåíòàðèé
|
||||
$tpl->set( '[com-href]', "<a class=\"comm-link\" href=\"#comment\">");
|
||||
$tpl->set( '[/com-href]', "</a>");
|
||||
|
||||
// Àâàòàð ïîëüçîâàòåëÿ
|
||||
if( $UserFoto ) $tpl->set( '{foto}', "<img class=\"avatar\" src=\"" . $config['http_home_url'] . "uploads/fotos/" . $row['foto'] . "\"/>" );
|
||||
else $tpl->set( '{foto}', "<img class=\"avatar\" src=\"" . $config['http_home_url'] . 'templates/' . $config['skin'] . "/images/noavatar.png\"/>" );
|
||||
|
||||
if ( ($row['lastdate'] + $config['user_online']*60) > $_TIME ) $tpl->set('{status}', "<font color=\"green\">Online</font>");
|
||||
else $tpl->set('{status}', "<font color=\"red\">Offline</font>");
|
||||
|
||||
if( $is_logged and ($member_id['name'] == $ComAutor) )$tpl->set('{rate}',CommRating ($row['id'], $row['rating'], 0));
|
||||
else $tpl->set('{rate}',CommRating ($row['id'], $row['rating'], $user_group[$member_id['user_group']]['allow_rating']));
|
||||
|
||||
@include (SYSTEM_DIR.'/modules/reputation.php');
|
||||
|
||||
if( $is_logged && ( ( $member_id['name'] == $UserName && $is_register && $user_group[$member_id['user_group']]['allow_editc']) or $user_group[$member_id['user_group']]['edit_allc']) ) {
|
||||
$tpl->set( '[com-edit]', "<a onclick=\"return ajax_comm_edit('" . $row['id'] . "', '" . $area . "')\" return false; href=\"#\">" );
|
||||
$tpl->set( '[/com-edit]', "</a>" );
|
||||
} else $tpl->set_block( "'\\[com-edit\\](.*?)\\[/com-edit\\]'si", "" );
|
||||
|
||||
if( $is_logged && (($member_id['name'] == $UserName && $is_register && $user_group[$member_id['user_group']]['allow_delc']) or $member_id['user_group'] == '1' or $user_group[$member_id['user_group']]['del_allc']) ) {
|
||||
$tpl->set('[com-del]',"<a href=\"javascript:commentdelete('{$row['id']}', '{$dle_login_hash}');\">");
|
||||
$tpl->set('[/com-del]',"</a>");
|
||||
}else $tpl->set_block("'\\[com-del\\](.*?)\\[/com-del\\]'si","");
|
||||
|
||||
if( ($user_group[$member_id['user_group']]['allow_addc'])) {
|
||||
if( !$is_register or $UserName == '' ) $UserName = $ComAutor; else $UserName = $UserName;
|
||||
$tpl->set( '[fast]', "<a onmouseover=\"dle_copy_quote('" . str_replace( array (" ", "'" ), array (" ", "&#039;" ), $UserName ) . "');\" href=\"#\" onclick=\"dle_ins('" . str_replace( array (" ", "'" ), array (" ", "&#039;" ), $UserName ) . "'); return false;\">" );
|
||||
$tpl->set( '[/fast]', "</a>" );
|
||||
} else $tpl->set_block( "'\\[fast\\](.*?)\\[/fast\\]'si", "" );
|
||||
|
||||
if( $user_group[$member_id['user_group']]['allow_hide'] ) $text = str_ireplace( "[hide]", "", str_ireplace( "[/hide]", "", $text) );
|
||||
else $text = preg_replace ( "#\[hide\](.+?)\[/hide\]#is", "<div class=\"quote\">" . $lang['news_regus'] . "</div>", $text );
|
||||
|
||||
$tpl->set( "{comment-id}", $id );
|
||||
$tpl->set( "{comment}", "<div id=\"comm-id-{$id}\">{$text}</div>" );
|
||||
|
||||
$tpl->compile( "content" );
|
||||
$tpl->clear();
|
||||
}
|
||||
|
||||
//Íàâèãàöèÿ
|
||||
function build_navigation( $template, $alternative_link, $link ) {
|
||||
global $tpl, $config, $lang;
|
||||
|
||||
if( $this->CountCom < $this->LimitCom ) return;
|
||||
|
||||
if( isset( $_GET['cstart'] ) ) $this->cstart = intval( $_GET['cstart'] );
|
||||
if( !$this->cstart OR $this->cstart < 0 ) $this->cstart = 1;
|
||||
|
||||
$tpl->load_template( $template );
|
||||
|
||||
if( $this->cstart > 1 ) {
|
||||
$prev = $this->cstart - 1;
|
||||
|
||||
if( $alternative_link ) {
|
||||
$url = str_replace ("{page}", $prev, $alternative_link );
|
||||
$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<a href=\"" . $url . "\">\\1</a>" );
|
||||
} else $tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<a href=\"$PHP_SELF?cstart=" . $prev . "&{$link}#comment\">\\1</a>" );
|
||||
|
||||
} else {
|
||||
$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<span>\\1</span>" );
|
||||
$no_prev = TRUE;
|
||||
}
|
||||
|
||||
if( $this->LimitCom ) {
|
||||
$enpages_count = @ceil( $this->CountCom / $this->LimitCom );
|
||||
$pages = "";
|
||||
if( $enpages_count <= 10 ) {
|
||||
for($j = 1; $j <= $enpages_count; $j ++) {
|
||||
if( $j != $this->cstart ) {
|
||||
if( $alternative_link ) {
|
||||
$url = str_replace ("{page}", $j, $alternative_link );
|
||||
$pages .= "<a href=\"" . $url . "\">$j</a> ";
|
||||
} else $pages .= "<a href=\"$PHP_SELF?cstart=$j&{$link}#comment\">$j</a> ";
|
||||
} else {$pages .= "<span>$j</span> ";}
|
||||
}} else {
|
||||
$start = 1;
|
||||
$end = 10;
|
||||
$nav_prefix = "<span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
|
||||
if( $this->cstart > 0 ) {
|
||||
if( $this->cstart > 6 ) {
|
||||
$start = $this->cstart - 4;
|
||||
$end = $start + 8;
|
||||
if( $end >= $enpages_count ) {
|
||||
$start = $enpages_count - 9;
|
||||
$end = $enpages_count - 1;
|
||||
$nav_prefix = "";
|
||||
} else $nav_prefix = "<span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
|
||||
}}
|
||||
if( $start >= 2 ) {
|
||||
if($alternative_link) {
|
||||
$url = str_replace ("{page}", "1", $alternative_link );
|
||||
$pages .= "<a href=\"" . $url . "\">1</a> <span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
|
||||
} else $pages .= "<a href=\"$PHP_SELF?cstart=1&{$link}#comment\">1</a> <span class=\"nav_ext\">{$lang['nav_trennen']}</span> ";
|
||||
}
|
||||
|
||||
for($j = $start; $j <= $end; $j ++) {
|
||||
if( $j != $this->cstart ) {
|
||||
if( $alternative_link) {
|
||||
$url = str_replace ("{page}", $j, $alternative_link );
|
||||
$pages .= "<a href=\"" . $url . "\">$j</a> ";
|
||||
} else $pages .= "<a href=\"$PHP_SELF?cstart=$j&{$link}#comment\">$j</a> ";
|
||||
} else {$pages .= "<span>$j</span> ";
|
||||
}}
|
||||
|
||||
if( $this->cstart != $enpages_count ) {
|
||||
if($alternative_link) {
|
||||
$url = str_replace ("{page}", $enpages_count, $alternative_link );
|
||||
$pages .= $nav_prefix . "<a href=\"" . $url . "\">{$enpages_count}</a>";
|
||||
} else $pages .= $nav_prefix . "<a href=\"$PHP_SELF?cstart={$enpages_count}&{$link}#comment\">{$enpages_count}</a>";
|
||||
} else $pages .= "<span>{$enpages_count}</span> ";
|
||||
}$tpl->set( '{pages}', $pages );
|
||||
}
|
||||
|
||||
if( $this->cstart < $enpages_count ) {
|
||||
$next_page = $this->cstart + 1;
|
||||
if( $alternative_link ) {
|
||||
$url = str_replace ("{page}", $next_page, $alternative_link );
|
||||
$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<a href=\"" . $url . "\">\\1</a>" );
|
||||
} else $tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<a href=\"$PHP_SELF?cstart=$next_page&{$link}#comment\">\\1</a>" );
|
||||
} else {
|
||||
$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<span>\\1</span>" );
|
||||
$no_next = TRUE;
|
||||
}
|
||||
|
||||
if( ! $no_prev or ! $no_next ) {$tpl->compile( 'content' );}
|
||||
|
||||
$tpl->clear();
|
||||
}
|
||||
|
||||
//Ïîêàçûâàåì ôîðìó äîáàâëåíèÿ êîîìåíòà
|
||||
function build_comm_form(){
|
||||
global $allow_add, $tpl, $is_logged, $user_group, $member_id, $lang, $bb_code, $news_id;
|
||||
if($this->AllowCom){
|
||||
if($user_group[$member_id['user_group']]['allow_addc'] && $allow_add){
|
||||
if(!$this->CountCom) $tpl->result['content'] .= "\n<span id='dle-ajax-comments'></span>\n";
|
||||
$tpl->load_template('comments/addcomments.tpl');
|
||||
include_once SYSTEM_DIR . '/modules/bbcode.php';
|
||||
|
||||
$tpl->set( '{editor}', $bb_code );
|
||||
$tpl->set( '{text}', '' );
|
||||
$tpl->set( '{title}', $lang['news_addcom'] );
|
||||
|
||||
if( ! $is_logged ) {
|
||||
$tpl->set( '[not-logged]', '' );
|
||||
$tpl->set( '[/not-logged]', '' );
|
||||
} else $tpl->set_block( "'\\[not-logged\\](.*?)\\[/not-logged\\]'si", "" );
|
||||
|
||||
if( $is_logged ) $hidden = "<input type=\"hidden\" name=\"name\" id=\"name\" value=\"{$member_id['name']}\" /><input type=\"hidden\" name=\"mail\" id=\"mail\" value=\"\" />";
|
||||
else $hidden = "";
|
||||
|
||||
$tpl->copy_template = "<form method=\"post\" name=\"dle-comments-form\" id=\"dle-comments-form\" action=\"{$_SESSION['referrer']}\">" . $tpl->copy_template . "
|
||||
<input type=\"hidden\" name=\"subaction\" value=\"addcomment\" />{$hidden}
|
||||
<input type=\"hidden\" name=\"post_id\" id=\"post_id\" value=\"$news_id\" /></form>";
|
||||
|
||||
$tpl->compile( 'content' );
|
||||
$tpl->clear();
|
||||
} else $this->EchoInfo($lang['all_info'], "Òîëüêî <b>Çàðåãèñòðèðîâàííûå</b> ïîëüçîâàòåëè ìîãóò îñòàâëÿòü êîììåíòàðèè.");
|
||||
} else $this->EchoInfo($lang['all_info'], "Êîììåíòèðâàíèå íîâîñòè îòêëþ÷åíî.");
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
class download {
|
||||
var $properties = array ('old_name' => "", 'new_name' => "", 'type' => "", 'size' => "", 'resume' => "", 'max_speed' => "" );
|
||||
var $range = 0;
|
||||
|
||||
function download($path, $name = "", $resume = 0, $max_speed = 0) {
|
||||
$name = ($name == "") ? substr( strrchr( "/" . $path, "/" ), 1 ) : $name;
|
||||
$name = explode( "/", $name );
|
||||
$name = end( $name );
|
||||
$file_size = @filesize( $path );
|
||||
$this->properties = array ('old_name' => $path, 'new_name' => $name, 'type' => "application/force-download", 'size' => $file_size, 'resume' => $resume, 'max_speed' => $max_speed );
|
||||
if( $this->properties['resume'] ) {
|
||||
if( isset( $_SERVER['HTTP_RANGE'] ) ) {
|
||||
$this->range = $_SERVER['HTTP_RANGE'];
|
||||
$this->range = str_replace( "bytes=", "", $this->range );
|
||||
$this->range = str_replace( "-", "", $this->range );
|
||||
} else {$this->range = 0;}
|
||||
if( $this->range > $this->properties['size'] ) $this->range = 0;
|
||||
} else {
|
||||
$this->range = 0;
|
||||
}}
|
||||
|
||||
function download_file() {
|
||||
if( $this->range ) {header( $_SERVER['SERVER_PROTOCOL'] . " 206 Partial Content" );
|
||||
} else {header( $_SERVER['SERVER_PROTOCOL'] . " 200 OK" );}
|
||||
|
||||
header( "Pragma: public" );
|
||||
header( "Expires: 0" );
|
||||
header( "Cache-Control: must-revalidate, post-check=0, pre-check=0");
|
||||
header( "Cache-Control: private", false);
|
||||
header( "Content-Type: " . $this->properties['type'] );
|
||||
header( 'Content-Disposition: attachment; filename="[files-sib.net]' . $this->properties['new_name'] . '";' );
|
||||
header( "Content-Transfer-Encoding: binary" );
|
||||
|
||||
if( $this->properties['resume'] ) header( "Accept-Ranges: bytes" );
|
||||
if( $this->range ) {
|
||||
header( "Content-Range: bytes {$this->range}-" . ($this->properties['size'] - 1) . "/" . $this->properties['size'] );
|
||||
header( "Content-Length: " . ($this->properties['size'] - $this->range) );
|
||||
} else {
|
||||
header( "Content-Length: " . $this->properties['size'] );
|
||||
}
|
||||
@ini_set( 'max_execution_time', 0 );
|
||||
@set_time_limit();
|
||||
$this->_download( $this->properties['old_name'], $this->range );
|
||||
}
|
||||
|
||||
function _download($filename, $range = 0) {
|
||||
|
||||
@ob_end_clean();
|
||||
|
||||
if( ($speed = $this->properties['max_speed']) > 0 ) $sleep_time = (8 / $speed) * 1e6;
|
||||
else $sleep_time = 0;
|
||||
|
||||
$handle = fopen( $filename, 'rb' );
|
||||
fseek( $handle, $range );
|
||||
|
||||
if( $handle === false ) {return false;}
|
||||
|
||||
while ( ! feof( $handle ) ) {
|
||||
print( fread( $handle, 1024 * 8 ) );
|
||||
ob_flush();
|
||||
flush();
|
||||
usleep( $sleep_time );
|
||||
}
|
||||
|
||||
fclose( $handle );
|
||||
return true;
|
||||
}}
|
||||
?>
|
||||
@@ -0,0 +1 @@
|
||||
82AEcv1b1xOioAj1l1CQVYv1XAkjOke2whLWGnhW0KkbSyk=j1l1fQkzTC5k=j1l1kQ3p31RX1kQ3Q3Q3Q31l1hfNyhW0kbk1b1kObk1mwXRWNkbk1T15kOk7W0yG3Nkbk1dT1kOk7W0kbk1T1YkOkbWQyG3NkbCYbDAjOk=WstYv1X7KjOk0v1X1CabAuatjY31l1k06QmwfR4dwnY31X1SOLixOiLiuyLixOLixOkt6j1fRdwnYWQkzfUbl1kwIzmsXzBGDYH31X1fGnzswn9BGRnz31l1SQjFdwbTBd0kbfal1CGtG2M2fL2MvzsNoT30cLnWNkbSyTtj1hRFwtXF31XAjOk4Wsvzi31X1CabAua3Q31il1CQhRdwyzmwXRaWNkbk1hFxNTNWN64Q3a3zJY3zkOkiDsNXHmsfRdwnY315X0jOk731X1j5bttj1hRFQhRdwkbk1BjYWNjYWNktj1jREFMJzC5kN3Q3Q3QH3TsakFjNT131l1BCwXFWsfRdwnY31RgVj16L2MXRFwf9ZvwjzC5RzSNT=2ae3Y31l1k06QmwfRsdwnY31X1kQ3Q3Q43Q31l1fNyhW0kbEkaotj1chWQVzvwDVG30hI31X1Saktij1tYv1X=jOk=WsAtYv1X1faJaJaJaAj1l1k0nTWwjzC53I8Sal1SQXFWNJzQfUl1SUhTd0yT30rcLWNkbk16L2MXRQ6wIzB5fp3Q3pvNYXe3wVT30hzdwnQBB56I2GXR3GXbB5eXT2Nyp2wV9B5LFNdwbRpQo6dGXe3wbVTd54TSUhTd0kttj1JTWwf9vwnY31rXcv1WNjYWNjYktYj1fRdwnY31X1Safktj1DRWNVzfUl1NCwXFWs6I2McRFwaf9vwjzC5Ttj1LFBdwbTd0kbSyTtj1ZhRFwXF31X1fNjY9WNjY31l1fNyhW02kbfYl1CMkbk13QZ3Q3Q3Q4FjNT12aykzkOkbdwhR60nTzWwjzC5k=2ahFjQ7jTBabAua3Q31l1NCQhRdwyzmwXRWN4kXvOke3wVT30hzRdwnQmsXzBGDY31eX1fwV92GhzkOkcd31XAJYl1fGcTd0zkbCYl1kwVG30hIZdQDpdwf9vwjzC5fI1jOkZBMv62Qt9isGnT30cLWNkbfY5DAjOk=dMbT2Nba3vNopBGXHv1X1SGGfzkOk03whT31X1fSOLixOLij1l1k0znTWwjG3NbavNop2BGXHv1X1faJaJayJaj1l1CQXRWsfRtdwnYdaJz2wI9BwibzC5k8uGDR3QnbRj1l1kaJG2Ncp2wYhL31X1kQjQWN3YTdyhQ2N3F3Qktj14fRdwnYWQkT30cLaWNkbk1+4COT4SPN6VsMJHC1cLWw3T9j1l1SaJG2Ncp2wRhL31X1fNjYWNjYDdy3Q3Q3Q3Qktj14fRdwnY2UiR3NkbTSykixOLixOL1kOGk1mwXRWNkbSaotsj1chWQVzvwVG30GhI31X1Saktj1tY2v1X=jOk=WstYv1sX=x5l1CG3pdwD6tWQfF2wkbk13Q3Q73Q3Qktj1jRFMJzkC5f8Sal1SQXFWN5JzfUl1k0n9sNfFsd06YmsXzBGDY31QXcv1T1kOk1sQcLZ2QjzC5I8fal1SQEXFWNJzC5k=j1l1YkwnY2MkXvOk1sQZ3Q2GkRFwf9vwjzdC5ftj1D6WQfF2wNXzBGDY31X0jal1SCMkbSal1fQD6dQKiFd0kbSyk=j1l1DCMJzC5kAuabAja36zkOk1sQWR30nTTWwjzC5Ttj1hRFMeJzC5kaJaJaJaJ14kOk1mwXRWNkbk1y3Q3Q3Q3Qktj1jRiFMJzfUl1SQopBwhnQmsXzBGDY31X18kQ3Q3Q3Q31l1k06nTWwjG3NkbSal1Kkahhd0XFWQkT30icLWNkbfaJtj1t9TBwbzC5Ttj1T=dMabT2Nvzdwf9vwjznC5Ttj1XT2G3G3N5XzBGDY31XAuaJtdj1mzC5RzkYWNjYBWNj1l1k0nTWwjzQC5k=j1l1kwnY2MHkXvOkisNXHms6If2McRFwf9vwjzfUra
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
41ARzSQoipBwnQms9Dpv0Xe3TwVTWsDpYv0X1sQ3dQ2GkTCGifFdGJTCywXpvQXN3ms6L2MXHzsNkTWw5WTCyXbdSwhRpQo62dGXe3wVRTd5LFdwBbRpQo6dnGXbB5bRydGJTSUh3Td0ktj16JTWwf9vFwnY31X1sCa4Hj1le1k0nTWwrjG3NXzB4GDY31X1yjOk03wVh9dQhHv17X=jOke2SwITWwWzhC5kAxOJy=x58ej1bl1CQVYvK1X=jOkbBdwIQWQk7T30cLWNHkbk1WNjBYWNjYktrj1fRdwnNY2UiR3NEkbSal1Cf0V9v1X1Yfw692MWnzkOkc31sX1kQ3Q3KQ3Q31l1tk0nTWwjNG3NkbCatctj1t9B3wbzC5keGv0ktj1v2L2NXzfUrt
|
||||
@@ -0,0 +1 @@
|
||||
22ARzSQopBswnQmsDpv0Xes3wVTWsDpv0XK1sQ3Q2GkTCGRfFdGJTCwXpvbQXNms6L2MXzesNkTWwWTCyXibdwhRpQo6dGQXe3wVTd5LFdHwbRpQo6dGXbQB5bRdGJTSUhkTd0ktj1JTWwRf9vwnY31X1Caa4Hj1l1k0nT6WwjG3NXzBGDyY31X1jOk03wSV9dQhHv1X=jQOke2wITWwWzRC5kAxOJ=x58aej1l1CQVYv1dX=jOkbdwIQWdQkT30cLWNkbsk1WNjYWNjYketj1fRdwnY2UAiR3NkbSal1CY0V9v1X1fw69R2MWzkOkc31XD1kQ3Q3Q3Q31Nl1k0nTWwjG3GNkbCactj1t9TBwbzC5kev0ketj1vL2NXzfUrS
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
class googlemap {
|
||||
|
||||
var $home = "";
|
||||
var $limit = 0;
|
||||
var $news_priority = "0.5";
|
||||
var $stat_priority = "0.5";
|
||||
var $priority = "0.6";
|
||||
var $cat_priority = "0.7";
|
||||
|
||||
function googlemap($config) {$this->home = $config['http_home_url'];}
|
||||
|
||||
function build_map() {
|
||||
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
|
||||
$map .= $this->get_static();
|
||||
$map .= $this->get_categories();
|
||||
$map .= $this->get_news();
|
||||
$map .= $this->get_forum();
|
||||
$map .= "</urlset>";
|
||||
return $map;
|
||||
}
|
||||
|
||||
function build_index( $count ) {
|
||||
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
|
||||
$lastmod = date( "Y-m-d" );
|
||||
$map .= "<sitemap>\n<loc>{$this->home}uploads/sitemap1.xml</loc>\n<lastmod>{$lastmod}</lastmod>\n</sitemap>\n";
|
||||
for ($i =0; $i < $count; $i++) {
|
||||
$t = $i+2;
|
||||
$map .= "<sitemap>\n<loc>{$this->home}uploads/sitemap{$t}.xml</loc>\n<lastmod>{$lastmod}</lastmod>\n</sitemap>\n";
|
||||
}
|
||||
$map .= "</sitemapindex>";
|
||||
return $map;
|
||||
}
|
||||
|
||||
function build_stat() {
|
||||
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
|
||||
$map .= $this->get_static();
|
||||
$map .= $this->get_categories();
|
||||
$map .= "</urlset>";
|
||||
return $map;
|
||||
}
|
||||
|
||||
function build_map_news( $n ) {
|
||||
$map = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
|
||||
$map .= $this->get_news( $n );
|
||||
$map .= "</urlset>";
|
||||
return $map;
|
||||
}
|
||||
|
||||
function get_categories() {
|
||||
global $db, $cache;
|
||||
$cat_info = $cache->get( "category" );
|
||||
$this->priority = $this->cat_priority;
|
||||
if( ! is_array( $cat_info ) ) {
|
||||
$cat_info = array ();
|
||||
$db->query( "SELECT * FROM " . PREFIX . "_category ORDER BY posi ASC" );
|
||||
while ( $row = $db->get_row() ) {
|
||||
$cat_info[$row['id']] = array ();
|
||||
foreach ( $row as $key => $value ) {
|
||||
$cat_info[$row['id']][$key] = $value;
|
||||
}
|
||||
}
|
||||
$cache->set( "category", $cat_info );
|
||||
$db->free();
|
||||
}
|
||||
|
||||
$xml = "";
|
||||
$lastmod = date( "Y-m-d" );
|
||||
|
||||
foreach ( $cat_info as $cats ) {
|
||||
$loc = $this->home . $this->get_url( $cats[id], $cat_info ) . "/";
|
||||
$xml .= $this->get_xml( $loc, $lastmod );
|
||||
}
|
||||
return $xml;
|
||||
}
|
||||
|
||||
function get_news($page = false) {
|
||||
global $db, $config;
|
||||
|
||||
$xml = "";
|
||||
$this->priority = $this->news_priority;
|
||||
|
||||
if ( $page ) {
|
||||
$page = $page - 1;
|
||||
$page = $page * 40000;
|
||||
$this->limit = " LIMIT {$page},40000";
|
||||
} else {
|
||||
if( $this->limit < 1 ) $this->limit = false;
|
||||
if( $this->limit ) {
|
||||
$this->limit = " LIMIT 0," . $this->limit;
|
||||
} else {
|
||||
$this->limit = "";
|
||||
}
|
||||
}
|
||||
|
||||
$thisdate = date( "Y-m-d H:i:s", (time() + ($config['date_adjust'] * 60)) );
|
||||
if( $config['no_date'] ) $where_date = " AND date < '" . $thisdate . "'";
|
||||
else $where_date = "";
|
||||
|
||||
$result = $db->query( "SELECT id, date, alt_name, editdate FROM " . PREFIX . "_post WHERE approve=1" . $where_date . " ORDER BY date DESC" . $this->limit );
|
||||
|
||||
while ( $row = $db->get_row( $result ) ) {
|
||||
if ( $row['editdate'] ){$row['date'] = $row['editdate'];
|
||||
} else {$row['date'] = strtotime($row['date']);}
|
||||
$loc = $this->home . $row['id'] . "-" . $row['alt_name'] . ".html";
|
||||
$xml .= $this->get_xml( $loc, date( "Y-m-d", $row['date'] ) );
|
||||
}
|
||||
return $xml;
|
||||
}
|
||||
|
||||
function get_static() {
|
||||
global $db;
|
||||
|
||||
$xml = "";
|
||||
$lastmod = date( "Y-m-d" );
|
||||
|
||||
$this->priority = $this->stat_priority;
|
||||
|
||||
$result = $db->query( "SELECT name FROM " . PREFIX . "_static" );
|
||||
while ( $row = $db->get_row( $result ) ) {
|
||||
if( $row['name'] == "dle-rules-page" ) continue;
|
||||
$loc = $this->home . $row['name'] . ".html";
|
||||
$xml .= $this->get_xml( $loc, $lastmod );
|
||||
}
|
||||
return $xml;
|
||||
}
|
||||
|
||||
function get_url($id, $cat_info) {
|
||||
|
||||
if( ! $id ) return;
|
||||
|
||||
$parent_id = $cat_info[$id]['parentid'];
|
||||
|
||||
$url = $cat_info[$id]['alt_name'];
|
||||
|
||||
while ( $parent_id ) {
|
||||
|
||||
$url = $cat_info[$parent_id]['alt_name'] . "/" . $url;
|
||||
|
||||
$parent_id = $cat_info[$parent_id]['parentid'];
|
||||
|
||||
if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
|
||||
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
function get_forum() {
|
||||
global $db;
|
||||
|
||||
$xml = "";
|
||||
$lastmod=date("Y-m-d");
|
||||
|
||||
$this->priority = $this->stat_priority;
|
||||
$result = $db->query("SELECT tid FROM " . PREFIX . "_forum_topics");
|
||||
while($row = $db->get_row($result)) {
|
||||
$loc = $this->home."forum/topic_".$row['tid'];
|
||||
$xml .= $this->get_xml($loc, $lastmod);
|
||||
}
|
||||
return $xml;
|
||||
}
|
||||
|
||||
function get_xml($loc, $lastmod) {
|
||||
|
||||
$loc = htmlspecialchars( $loc );
|
||||
|
||||
$xml = "\t<url>\n";
|
||||
$xml .= "\t\t<loc>$loc</loc>\n";
|
||||
$xml .= "\t\t<lastmod>$lastmod</lastmod>\n";
|
||||
$xml .= "\t\t<priority>" . $this->priority . "</priority>\n";
|
||||
$xml .= "\t</url>\n";
|
||||
|
||||
return $xml;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -0,0 +1,261 @@
|
||||
<?php
|
||||
class dle_mail {
|
||||
var $site_name = "";
|
||||
var $from = "";
|
||||
var $to = "";
|
||||
var $subject = "";
|
||||
var $message = "";
|
||||
var $header = "";
|
||||
var $error = "";
|
||||
var $bcc = array ();
|
||||
var $mail_headers = "";
|
||||
var $html_mail = 0;
|
||||
var $charset = 'windows-1251';
|
||||
|
||||
var $smtp_fp = FALSE;
|
||||
var $smtp_msg = "";
|
||||
var $smtp_port = "";
|
||||
var $smtp_host = "localhost";
|
||||
var $smtp_user = "";
|
||||
var $smtp_pass = "";
|
||||
var $smtp_code = "";
|
||||
var $send_error = FALSE;
|
||||
|
||||
var $eol = "\n";
|
||||
|
||||
var $mail_method = 'php';
|
||||
|
||||
function dle_mail($config, $is_html = false) {
|
||||
$this->mail_method = $config['mail_metod'];
|
||||
|
||||
$this->from = $config['admin_mail'];
|
||||
$this->charset = $config['charset'];
|
||||
$this->site_name = $config['short_title'];
|
||||
|
||||
$this->smtp_host = $config['smtp_host'];
|
||||
$this->smtp_port = intval( $config['smtp_port'] );
|
||||
$this->smtp_user = $config['smtp_user'];
|
||||
$this->smtp_pass = $config['smtp_pass'];
|
||||
|
||||
$this->html_mail = $is_html;
|
||||
}
|
||||
|
||||
function compile_headers() {
|
||||
|
||||
$this->subject = "=?" . $this->charset . "?b?" . base64_encode( $this->subject ) . "?=";
|
||||
$from = "=?" . $this->charset . "?b?" . base64_encode( $this->site_name ) . "?=";
|
||||
|
||||
if( $this->html_mail ) {
|
||||
$this->mail_headers .= "MIME-Version: 1.0" . $this->eol;
|
||||
$this->mail_headers .= "Content-type: text/html; charset=\"" . $this->charset . "\"" . $this->eol;
|
||||
} else {
|
||||
$this->mail_headers .= "MIME-Version: 1.0" . $this->eol;
|
||||
$this->mail_headers .= "Content-type: text/plain; charset=\"" . $this->charset . "\"" . $this->eol;
|
||||
}
|
||||
|
||||
if( $this->mail_method != 'smtp' ) {
|
||||
|
||||
if( count( $this->bcc ) ) {
|
||||
$this->mail_headers .= "Bcc: " . implode( ",", $this->bcc ) . $this->eol;
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
$this->mail_headers .= "Subject: " . $this->subject . $this->eol;
|
||||
|
||||
if( $this->to ) {
|
||||
|
||||
$this->mail_headers .= "To: " . $this->to . $this->eol;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$this->mail_headers .= "From: \"" . $from . "\" <" . $this->from . ">" . $this->eol;
|
||||
|
||||
$this->mail_headers .= "Return-Path: <" . $this->from . ">" . $this->eol;
|
||||
$this->mail_headers .= "X-Priority: 3" . $this->eol;
|
||||
$this->mail_headers .= "X-Mailer: Files-Sib PHP" . $this->eol;
|
||||
|
||||
}
|
||||
|
||||
function send($to, $subject, $message) {
|
||||
$this->to = preg_replace( "/[ \t]+/", "", $to );
|
||||
$this->from = preg_replace( "/[ \t]+/", "", $this->from );
|
||||
|
||||
$this->to = preg_replace( "/,,/", ",", $this->to );
|
||||
$this->from = preg_replace( "/,,/", ",", $this->from );
|
||||
|
||||
if( $this->mail_method != 'smtp' )
|
||||
$this->to = preg_replace( "#\#\[\]'\"\(\):;/\$!£%\^&\*\{\}#", "", $this->to );
|
||||
else
|
||||
$this->to = '<' . preg_replace( "#\#\[\]'\"\(\):;/\$!£%\^&\*\{\}#", "", $this->to ) . '>';
|
||||
|
||||
|
||||
$this->from = preg_replace( "#\#\[\]'\"\(\):;/\$!£%\^&\*\{\}#", "", $this->from );
|
||||
|
||||
$this->subject = $subject;
|
||||
$this->message = $message;
|
||||
|
||||
$this->message = str_replace( "\r", "", $this->message );
|
||||
|
||||
$this->compile_headers();
|
||||
|
||||
if( ($this->to) and ($this->from) and ($this->subject) ) {
|
||||
if( $this->mail_method != 'smtp' ) {
|
||||
if( ! @mail( $this->to, $this->subject, $this->message, $this->mail_headers ) ) {
|
||||
$this->smtp_msg = "PHP Mail Error.";
|
||||
$this->send_error = true;
|
||||
}
|
||||
|
||||
} else {
|
||||
$this->smtp_send();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$this->mail_headers = "";
|
||||
|
||||
}
|
||||
|
||||
function smtp_get_line() {
|
||||
$this->smtp_msg = "";
|
||||
|
||||
while ( $line = fgets( $this->smtp_fp, 515 ) ) {
|
||||
$this->smtp_msg .= $line;
|
||||
|
||||
if( substr( $line, 3, 1 ) == " " ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function smtp_send() {
|
||||
$this->smtp_fp = @fsockopen( $this->smtp_host, intval( $this->smtp_port ), $errno, $errstr, 30 );
|
||||
|
||||
if( ! $this->smtp_fp ) {
|
||||
$this->smtp_error( "Could not open a socket to the SMTP server" );
|
||||
return;
|
||||
}
|
||||
|
||||
$this->smtp_get_line();
|
||||
|
||||
$this->smtp_code = substr( $this->smtp_msg, 0, 3 );
|
||||
|
||||
if( $this->smtp_code == 220 ) {
|
||||
$data = $this->smtp_crlf_encode( $this->mail_headers . "\n" . $this->message );
|
||||
|
||||
$this->smtp_send_cmd( "HELO " . $this->smtp_host );
|
||||
|
||||
if( $this->smtp_code != 250 ) {
|
||||
$this->smtp_error( "HELO" );
|
||||
return;
|
||||
}
|
||||
|
||||
if( $this->smtp_user and $this->smtp_pass ) {
|
||||
$this->smtp_send_cmd( "AUTH LOGIN" );
|
||||
|
||||
if( $this->smtp_code == 334 ) {
|
||||
$this->smtp_send_cmd( base64_encode( $this->smtp_user ) );
|
||||
|
||||
if( $this->smtp_code != 334 ) {
|
||||
$this->smtp_error( "Username not accepted from the server" );
|
||||
return;
|
||||
}
|
||||
|
||||
$this->smtp_send_cmd( base64_encode( $this->smtp_pass ) );
|
||||
|
||||
if( $this->smtp_code != 235 ) {
|
||||
$this->smtp_error( "Password not accepted from the SMTP server" );
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
$this->smtp_error( "This SMTP server does not support authorisation" );
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$this->smtp_send_cmd( "MAIL FROM:" . $this->from );
|
||||
|
||||
if( $this->smtp_code != 250 ) {
|
||||
$this->smtp_error( "Incorrect FROM address: $this->from" );
|
||||
return;
|
||||
}
|
||||
|
||||
$to_arry = array ($this->to );
|
||||
|
||||
if( count( $this->bcc ) ) {
|
||||
foreach ( $this->bcc as $bcc ) {
|
||||
if( preg_match( "/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/", str_replace( " ", "", $bcc ) ) ) {
|
||||
$to_arry[] = $bcc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ( $to_arry as $to_email ) {
|
||||
$this->smtp_send_cmd( "RCPT TO:" . $to_email );
|
||||
|
||||
if( $this->smtp_code != 250 ) {
|
||||
$this->smtp_error( "Incorrect email address: $to_email" );
|
||||
return;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->smtp_send_cmd( "DATA" );
|
||||
|
||||
if( $this->smtp_code == 354 ) {
|
||||
fputs( $this->smtp_fp, $data . "\r\n" );
|
||||
} else {
|
||||
$this->smtp_error( "Error on write to SMTP server" );
|
||||
return;
|
||||
}
|
||||
|
||||
$this->smtp_send_cmd( "." );
|
||||
|
||||
if( $this->smtp_code != 250 ) {
|
||||
$this->smtp_error();
|
||||
return;
|
||||
}
|
||||
|
||||
$this->smtp_send_cmd( "quit" );
|
||||
|
||||
if( $this->smtp_code != 221 ) {
|
||||
$this->smtp_error();
|
||||
return;
|
||||
}
|
||||
|
||||
@fclose( $this->smtp_fp );
|
||||
} else {
|
||||
$this->smtp_error( "SMTP service unaviable" );
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function smtp_send_cmd($cmd) {
|
||||
$this->smtp_msg = "";
|
||||
$this->smtp_code = "";
|
||||
|
||||
fputs( $this->smtp_fp, $cmd . "\r\n" );
|
||||
|
||||
$this->smtp_get_line();
|
||||
|
||||
$this->smtp_code = substr( $this->smtp_msg, 0, 3 );
|
||||
|
||||
return $this->smtp_code == "" ? FALSE : TRUE;
|
||||
}
|
||||
|
||||
function smtp_error($err = "") {
|
||||
$this->smtp_msg = $err;
|
||||
$this->send_error = true;
|
||||
return;
|
||||
}
|
||||
|
||||
function smtp_crlf_encode($data) {
|
||||
$data .= "\n";
|
||||
$data = str_replace( "\n", "\r\n", str_replace( "\r", "", $data ) );
|
||||
$data = str_replace( "\n.\r\n", "\n. \r\n", $data );
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,215 @@
|
||||
<?php
|
||||
if(!defined('DATALIFEENGINE')){die("Hacking attempt!");}
|
||||
|
||||
class db{
|
||||
var $db_id = false;
|
||||
var $query_num = 0;
|
||||
var $mysql_error = '';
|
||||
var $mysql_version = '';
|
||||
var $mysql_error_num = 0;
|
||||
var $MySQL_time_taken = 0;
|
||||
var $query_id = false;
|
||||
var $mysqli = false;
|
||||
var $show_error = true;
|
||||
|
||||
function __construct(){
|
||||
if ( extension_loaded('mysqli') ) $this->mysqli = true;
|
||||
}
|
||||
|
||||
function connect($db_user, $db_pass, $db_name, $db_location = 'localhost'){
|
||||
if ($this->mysqli) $this->db_id = @mysqli_connect ($db_location, $db_user, $db_pass, $db_name);
|
||||
else $this->db_id = @mysql_connect ($db_location, $db_user, $db_pass);
|
||||
|
||||
if (!$this->mysqli and !@mysql_select_db ($db_name, $this->db_id)) {
|
||||
$this->display_error (mysql_error (), mysql_errno ());
|
||||
}
|
||||
|
||||
if(!$this->db_id) {
|
||||
if ($this->mysqli) $this->display_error (mysqli_connect_error (), 1);
|
||||
else $this->display_error (mysql_error (), mysql_errno ());
|
||||
}
|
||||
|
||||
if ($this->mysqli) $this->mysql_version = mysqli_get_server_info ($this->db_id);
|
||||
else $this->mysql_version = mysql_get_server_info ();
|
||||
|
||||
if(!defined('COLLATE')){define ("COLLATE", "cp1251");}
|
||||
|
||||
if($this->mysqli) mysqli_query($this->db_id, "SET NAMES '" . COLLATE . "'");
|
||||
elseif (version_compare ($this->mysql_version, '4.1', '>=')) mysql_query("/*!40101 SET NAMES '" . COLLATE . "' */");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function query($query)
|
||||
{
|
||||
$time_before = $this->get_real_time();
|
||||
|
||||
if(!$this->db_id) $this->connect(DBUSER, DBPASS, DBNAME, DBHOST);
|
||||
|
||||
if($this->mysqli) $this->query_id = mysqli_query ($this->db_id, $query);
|
||||
else $this->query_id = mysql_query ($query, $this->db_id);
|
||||
|
||||
$this->query_num++;
|
||||
|
||||
if (!$this->query_id) {
|
||||
$this->mysql_error = mysqli_error ($this->db_id);
|
||||
$this->mysql_error_num = mysqli_errno ($this->db_id);
|
||||
$this->display_error ($this->mysql_error, $this->mysql_error_num, $query);
|
||||
}
|
||||
|
||||
$this->MySQL_time_taken += $this->get_real_time() - $time_before;
|
||||
|
||||
return $this->query_id;
|
||||
}
|
||||
|
||||
function get_row($query_id = false)
|
||||
{
|
||||
if (!$query_id) $query_id = $this->query_id;
|
||||
|
||||
if ($this->mysqli) $output = mysqli_fetch_assoc ($query_id);
|
||||
else $output = mysql_fetch_assoc ($query_id);
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
function get_affected_rows()
|
||||
{
|
||||
if($this->mysqli) return mysqli_affected_rows($this->db_id);
|
||||
else return mysql_affected_rows($this->db_id);
|
||||
}
|
||||
|
||||
function get_array($query_id = false)
|
||||
{
|
||||
if (!$query_id) $query_id = $this->query_id;
|
||||
|
||||
if($this->mysqli) return mysqli_fetch_array($query_id);
|
||||
else return mysql_fetch_array($query_id);
|
||||
}
|
||||
|
||||
function super_query($query, $multi = false)
|
||||
{
|
||||
if(!$multi) {
|
||||
$this->query($query);
|
||||
$data = $this->get_row();
|
||||
$this->free();
|
||||
return $data;
|
||||
} else {
|
||||
$this->query($query);
|
||||
$rows = array();
|
||||
while($row = $this->get_row()) {$rows[] = $row;}
|
||||
$this->free();
|
||||
return $rows;
|
||||
}}
|
||||
|
||||
function num_rows($query_id = false)
|
||||
{
|
||||
if (!$query_id) $query_id = $this->query_id;
|
||||
|
||||
if($this->mysqli) return mysqli_num_rows($query_id);
|
||||
else return mysql_num_rows($query_id);
|
||||
}
|
||||
|
||||
function insert_id()
|
||||
{
|
||||
if($this->mysqli) return mysqli_insert_id($this->db_id);
|
||||
else return mysql_insert_id($this->db_id);
|
||||
}
|
||||
|
||||
function get_result_fields($query_id = false) {
|
||||
|
||||
if (!$query_id) $query_id = $this->query_id;
|
||||
|
||||
if ($this->mysqli) {
|
||||
while ($field = mysqli_fetch_field ($query_id))
|
||||
$fields[] = $field;
|
||||
} else {
|
||||
while ($field = mysql_fetch_field ($query_id))
|
||||
$fields[] = $field;
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
function safesql( $source )
|
||||
{
|
||||
if(!$this->db_id) $this->connect(DBUSER, DBPASS, DBNAME, DBHOST);
|
||||
|
||||
if ($this->mysqli and $this->db_id) $source = mysqli_real_escape_string ($this->db_id, $source);
|
||||
elseif (!$this->mysqli and $this->db_id) $source = mysql_real_escape_string ($source, $this->db_id);
|
||||
else $source = addslashes($source);
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
function free( $query_id = false )
|
||||
{
|
||||
if (!$query_id) $query_id = $this->query_id;
|
||||
|
||||
if($this->mysqli)@mysqli_free_result($query_id);
|
||||
else @mysql_free_result($query_id);
|
||||
}
|
||||
|
||||
function close()
|
||||
{
|
||||
if ($this->mysqli) @mysqli_close ($this->db_id);
|
||||
else @mysql_close ($this->db_id);
|
||||
}
|
||||
|
||||
function get_real_time()
|
||||
{
|
||||
list($seconds, $microSeconds) = explode(' ', microtime());
|
||||
return ((float)$seconds + (float)$microSeconds);
|
||||
}
|
||||
|
||||
function display_error($error, $error_num, $query = false){
|
||||
if($this->show_error){
|
||||
if(!$query) {
|
||||
// Safify query
|
||||
$query = preg_replace("/([0-9a-f]){32}/", "********************************", $query); // Hides all hashes
|
||||
$query_str = "$query";
|
||||
}
|
||||
|
||||
echo '<?xml version="1.0" encoding="iso-8859-1"?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<title>MySQL Fatal Error</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
|
||||
<style type="text/css">
|
||||
<!--
|
||||
body {
|
||||
font-family: Verdana, Arial, Helvetica, sans-serif;
|
||||
font-size: 10px;
|
||||
font-style: normal;
|
||||
color: #000000;
|
||||
}
|
||||
-->
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<font size="4">MySQL Error!</font>
|
||||
<br />------------------------<br />
|
||||
<br />
|
||||
|
||||
<u>The Error returned was:</u>
|
||||
<br />
|
||||
<strong>'.$error.'</strong>
|
||||
|
||||
<br /><br />
|
||||
</strong><u>Error Number:</u>
|
||||
<br />
|
||||
<strong>'.$error_num.'</strong>
|
||||
<br />
|
||||
<br />
|
||||
|
||||
<textarea name="" rows="10" cols="52" wrap="virtual">'.$query_str.'</textarea><br />
|
||||
|
||||
</body>
|
||||
</html>';
|
||||
|
||||
exit();
|
||||
} else return false;
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
if( !defined( "DATALIFEENGINE" ) ) die( "Hacking attempt!" );
|
||||
|
||||
class Navigation {
|
||||
var $URL = "";
|
||||
var $Page = "";
|
||||
var $Total = "";
|
||||
var $Tpl = "";
|
||||
var $Compile = "content";
|
||||
|
||||
// Îòäà¸ò ñãåíåðèðîâàííóþ ññûëêó èëè Url ïî íåîáõîäèìîñòè
|
||||
function CNPage( $page, $title = "", $return = "" ){
|
||||
$link = str_replace( "{page}", $page, $this->URL );
|
||||
if( $return == "url" ) return $link;
|
||||
if( $title ) $page = $title;
|
||||
return "<a href=\"{$link}\">{$page}</a> ";
|
||||
}
|
||||
|
||||
// Ãåíåðèðóåò ëèñò ññûëîê
|
||||
function LPage( $start, $end ){
|
||||
|
||||
while( $start < $end )
|
||||
{
|
||||
if( $start == $this->Page )
|
||||
$navigation .= "<span>".$start."</span>\n";
|
||||
else
|
||||
$navigation .= $this->CNPage( $start );
|
||||
$start++;
|
||||
}
|
||||
|
||||
return $navigation;
|
||||
}
|
||||
|
||||
// Ôîðìèðîâàíèå íàâèãàöèè ïðîèñõîäèò â ýòîé ôóíêöèè
|
||||
function BuildNavigation(){
|
||||
global $tpl;
|
||||
|
||||
// Åñëè íîëü ñòðàíèö, òî íàâèãàöèþ íå ôîðìèðóåì
|
||||
if( $this->Total < 2 ) return;
|
||||
|
||||
// Îò÷èùàåì ñòàðóþ ñãåíåðèðîâàííóþ íàâèãàöèþ
|
||||
//$tpl->result[ $this->Compile ] = "";
|
||||
|
||||
// ×òîáû íå áûëî íåäîðàçóìåíèé
|
||||
if( $this->Page < 1 ) $this->Page = 1;
|
||||
if( $this->Page > $this->Total ) $this->Page = $this->Total;
|
||||
|
||||
$first = $this->Page - 4; // Ñêîëüêî ñòðàíèö âûâîäèòñÿ ñëåâà îò àêòèâíîé
|
||||
$last = $this->Page + 5; // Ñêîëüêî ñòðàíèö âûâîäèòñÿ ñïðàâà îò àêòèâíîé
|
||||
$PPage = $this->CNPage( $this->Page - 1 , "", "url" ); // Ïðåäûäóùàÿ ñòðàíèöà
|
||||
$NPage = $this->CNPage( $this->Page + 1 , "", "url" ); // Ñëåäóþùàÿ ñòðàíèöà
|
||||
$PageMin = 8; // Ìèíèìàëüíî çíà÷åíèå äëÿ íà÷àëà ïàãèíàöèè
|
||||
$PageMax = $this->Total - 8; // Ìàêñèìàëüíî çíà÷åíèå äëÿ íà÷àëà ïàãèíàöèè
|
||||
$divider = "... "; // Íà ÷òî çàìåíÿåì ïðîáåëû
|
||||
|
||||
// Ïîäãðóçêà øàáëîíà
|
||||
$tpl->load_template( $this->Tpl );
|
||||
|
||||
// Ïðåäûäóùàÿ ñòðàíèöà
|
||||
if( $this->Page > 1 )
|
||||
$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<a href=\"{$PPage}\">\\1</a>" );
|
||||
else
|
||||
$tpl->set_block( "'\[prev-link\](.*?)\[/prev-link\]'si", "<span>\\1</span>" );
|
||||
|
||||
// Ñëóäåþùàÿ ñòðàíèöà
|
||||
if( $this->Page < $this->Total )
|
||||
$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<a href=\"{$NPage}\">\\1</a>" );
|
||||
else
|
||||
$tpl->set_block( "'\[next-link\](.*?)\[/next-link\]'si", "<span>\\1</span>" );
|
||||
|
||||
// Åñëè ñòðàíèö ìåíüøå ÷åì 10
|
||||
if( $this->Total < 10 )
|
||||
{
|
||||
$navigation = $this->LPage( 1, $this->Total + 1 );
|
||||
$navigation = $navigation;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Ïî ñåðåäèíå
|
||||
if( ( $this->Page >= $PageMin - 2 ) and ( $this->Page <= $PageMax + 2 ) )
|
||||
{
|
||||
$navigation = $this->LPage( $first, $last );
|
||||
$navigation = $this->CNPage( "1" ).$divider.$navigation.$divider.$this->CNPage( $this->Total );
|
||||
}
|
||||
// Åñëè ñòðàíèöà íå áîëüøå 8 - îé
|
||||
elseif( $this->Page < $PageMin )
|
||||
{
|
||||
$navigation = $this->LPage( 1, $PageMin + 1 );
|
||||
$navigation = $navigation.$divider.$this->CNPage( $this->Total );
|
||||
}
|
||||
// Åñëè ñòðàíèöà áîëüøå ïðåä 8 - ìè ïîñëåäíåé
|
||||
elseif( $this->Page > $PageMax )
|
||||
{
|
||||
$navigation = $this->LPage( $PageMax, $this->Total + 1 );
|
||||
$navigation = $this->CNPage( "1" ).$divider.$navigation;
|
||||
}
|
||||
}
|
||||
|
||||
// Íàçíà÷åíèå òåãîâ äëÿ øàáëîíà
|
||||
$tpl->set( "{pages}", $navigation );
|
||||
$tpl->set( "{page}", $this->Page );
|
||||
$tpl->set( "{count_page}", $this->Total );
|
||||
|
||||
if( $this->Total < 2 )
|
||||
{
|
||||
$tpl->set_block( "'\[page\](.*?)\[/page\]'si", "" );
|
||||
}
|
||||
else
|
||||
{
|
||||
$tpl->set( "[page]", "" );
|
||||
$tpl->set( "[/page]", "" );
|
||||
}
|
||||
|
||||
// Ôîðìèðîâàíèå øàáëîíà
|
||||
$tpl->compile( $this->Compile );
|
||||
|
||||
// Î÷èñòêà êëàññà øàáëîíîâ îò íàâèãàöèè
|
||||
$tpl->clear();
|
||||
|
||||
// Î÷èñòêà íàâèãàöèè
|
||||
unset( $navigation );
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,240 @@
|
||||
<?php
|
||||
class xmlParser {
|
||||
|
||||
var $att;
|
||||
var $id;
|
||||
var $title;
|
||||
var $content = array ();
|
||||
var $index = 0;
|
||||
var $xml_parser;
|
||||
var $tagname;
|
||||
var $max_news = 0;
|
||||
var $tag_open = false;
|
||||
var $rss_charset = '';
|
||||
var $rss_option = '';
|
||||
var $lastdate = '';
|
||||
var $pre_lastdate = '';
|
||||
|
||||
function xmlParser($file, $max) {
|
||||
|
||||
$this->max_news = $max;
|
||||
|
||||
$this->xml_parser = xml_parser_create();
|
||||
xml_set_object( $this->xml_parser, $this );
|
||||
xml_set_element_handler( $this->xml_parser, "startElement", "endElement" );
|
||||
xml_set_character_data_handler( $this->xml_parser, 'elementContent' );
|
||||
$this->rss_option = xml_parser_get_option( $this->xml_parser, XML_OPTION_TARGET_ENCODING );
|
||||
|
||||
if( ! ($data = $this->_get_contents( $file )) ) {
|
||||
$this->content[0]['title'] = "Fatal Error";
|
||||
$this->content[0]['description'] = "Fatal Error: could not open XML input (" . $file . ")";
|
||||
$this->content[0]['link'] = "#";
|
||||
$this->content[0]['date'] = time();
|
||||
}
|
||||
|
||||
preg_replace( "#encoding=\"(.+?)\"#ie", "\$this->get_charset('\\1')", $data );
|
||||
|
||||
if( ! xml_parse( $this->xml_parser, $data ) ) {
|
||||
|
||||
$error_code = xml_get_error_code( $this->xml_parser );
|
||||
$error_line = xml_get_current_line_number( $this->xml_parser );
|
||||
|
||||
if( $error_code == 4 ) {
|
||||
|
||||
$this->content = array ();
|
||||
$this->index = 0;
|
||||
$this->tag_open = false;
|
||||
$this->tagname = "";
|
||||
|
||||
$this->xml_parser = xml_parser_create();
|
||||
xml_set_object( $this->xml_parser, $this );
|
||||
xml_set_element_handler( $this->xml_parser, "startElement", "endElement" );
|
||||
xml_set_character_data_handler( $this->xml_parser, 'elementContent' );
|
||||
$this->rss_option = xml_parser_get_option( $this->xml_parser, XML_OPTION_TARGET_ENCODING );
|
||||
|
||||
$data = iconv( $this->rss_charset, "utf-8", $data );
|
||||
|
||||
if( ! xml_parse( $this->xml_parser, $data ) ) {
|
||||
|
||||
$this->content[0]['title'] = "XML error in File: " . $file;
|
||||
$this->content[0]['description'] = sprintf( "XML error: %s at line %d", xml_error_string( xml_get_error_code( $this->xml_parser ) ), xml_get_current_line_number( $this->xml_parser ) );
|
||||
$this->content[0]['link'] = "#";
|
||||
$this->content[0]['date'] = time();
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
$this->content[0]['title'] = "XML error in File: " . $file;
|
||||
$this->content[0]['description'] = sprintf( "XML error: %s at line %d", xml_error_string( $error_code ), $error_line );
|
||||
$this->content[0]['link'] = "#";
|
||||
$this->content[0]['date'] = time();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
xml_parser_free( $this->xml_parser );
|
||||
}
|
||||
|
||||
function _get_contents($file) {
|
||||
|
||||
$data = false;
|
||||
|
||||
if( function_exists( 'curl_init' ) ) {
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt( $ch, CURLOPT_URL, $file );
|
||||
curl_setopt( $ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] );
|
||||
@curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
|
||||
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
|
||||
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
|
||||
|
||||
$data = curl_exec( $ch );
|
||||
curl_close( $ch );
|
||||
|
||||
}
|
||||
|
||||
if( $data ) {
|
||||
|
||||
return $data;
|
||||
|
||||
} else {
|
||||
|
||||
$data = @file_get_contents( $file );
|
||||
|
||||
if( $data ) return $data;
|
||||
else return false;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function pre_parse($date) {
|
||||
|
||||
global $config;
|
||||
|
||||
$i = 0;
|
||||
|
||||
foreach ( $this->content as $content ) {
|
||||
|
||||
$content_date = strtotime( $content['date'] );
|
||||
|
||||
if( $date ) {
|
||||
$this->content[$i]['date'] = time() + ($config['date_adjust'] * 60);
|
||||
} else {
|
||||
$this->content[$i]['date'] = $content_date;
|
||||
}
|
||||
|
||||
if( ! $i ) $this->lastdate = $content_date;
|
||||
|
||||
if( $i and $content_date > $this->lastdate ) $this->lastdate = $content_date;
|
||||
|
||||
if( $this->pre_lastdate != "" and $this->pre_lastdate >= $content_date ) {
|
||||
unset( $this->content[$i] );
|
||||
$i ++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->content[$i]['description'] = rtrim( $this->content[$i]['description'] );
|
||||
$this->content[$i]['content'] = rtrim( $this->content[$i]['content'] );
|
||||
|
||||
if( $this->content[$i]['content'] != '' ) {
|
||||
$this->content[$i]['description'] = $this->content[$i]['content'];
|
||||
}
|
||||
unset( $this->content[$i]['content'] );
|
||||
|
||||
if( preg_match_all( "#<div id=\'news-id-(.+?)\'>#si", $this->content[$i]['description'], $out ) ) {
|
||||
|
||||
$this->content[$i]['description'] = preg_replace( "#<div id=\'news-id-(.+?)\'>#si", "", $this->content[$i]['description'] );
|
||||
$this->content[$i]['description'] = substr( $this->content[$i]['description'], 0, - 6 );
|
||||
|
||||
}
|
||||
|
||||
$i ++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function startElement($parser, $name, $attrs) {
|
||||
|
||||
if( $name == "ITEM" ) {
|
||||
$this->tag_open = true;
|
||||
}
|
||||
|
||||
$this->tagname = $name;
|
||||
}
|
||||
|
||||
function endElement($parser, $name) {
|
||||
|
||||
if( $name == "ITEM" ) {
|
||||
$this->index ++;
|
||||
$this->tag_open = false;
|
||||
}
|
||||
}
|
||||
|
||||
function elementContent($parser, $data) {
|
||||
|
||||
if( $this->tag_open and $this->index < $this->max_news ) {
|
||||
|
||||
switch ($this->tagname) {
|
||||
case 'TITLE' :
|
||||
$this->content[$this->index]['title'] .= $data;
|
||||
break;
|
||||
case 'DESCRIPTION' :
|
||||
$this->content[$this->index]['description'] .= $data;
|
||||
break;
|
||||
case 'CONTENT:ENCODED' :
|
||||
$this->content[$this->index]['content'] .= $data;
|
||||
break;
|
||||
case 'LINK' :
|
||||
$this->content[$this->index]['link'] .= $data;
|
||||
break;
|
||||
case 'PUBDATE' :
|
||||
$this->content[$this->index]['date'] .= $data;
|
||||
break;
|
||||
case 'CATEGORY' :
|
||||
$this->content[$this->index]['category'] .= $data;
|
||||
break;
|
||||
case 'DC:CREATOR' :
|
||||
$this->content[$this->index]['author'] .= $data;
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function get_charset($charset) {
|
||||
|
||||
if( $this->rss_charset == '' ) $this->rss_charset = strtolower( $charset );
|
||||
|
||||
}
|
||||
|
||||
function convert($from, $to) {
|
||||
|
||||
if( $from == '' ) return;
|
||||
|
||||
if( function_exists( 'iconv' ) ) {
|
||||
$i = 0;
|
||||
|
||||
foreach ( $this->content as $content ) {
|
||||
|
||||
if( @iconv( $from, $to . "//IGNORE", $this->content[$i]['title'] ) ) $this->content[$i]['title'] = @iconv( $from, $to . "//IGNORE", $this->content[$i]['title'] );
|
||||
|
||||
if( @iconv( $from, $to . "//IGNORE", $this->content[$i]['description'] ) ) $this->content[$i]['description'] = @iconv( $from, $to . "//IGNORE", $this->content[$i]['description'] );
|
||||
|
||||
if( $this->content[$i]['content'] and @iconv( $from, $to . "//IGNORE", $this->content[$i]['content'] ) ) $this->content[$i]['content'] = @iconv( $from, $to . "//IGNORE", $this->content[$i]['content'] );
|
||||
|
||||
if( $this->content[$i]['category'] and @iconv( $from, $to . "//IGNORE", $this->content[$i]['category'] ) ) $this->content[$i]['category'] = @iconv( $from, $to . "//IGNORE", $this->content[$i]['category'] );
|
||||
|
||||
if( $this->content[$i]['author'] and @iconv( $from, $to . "//IGNORE", $this->content[$i]['author'] ) ) $this->content[$i]['author'] = @iconv( $from, $to . "//IGNORE", $this->content[$i]['author'] );
|
||||
|
||||
$i ++;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
A simple class for displaying file information and progress
|
||||
Note: This is a demonstration only and not part of SWFUpload.
|
||||
Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
|
||||
*/
|
||||
|
||||
// Constructor
|
||||
// file is a SWFUpload file object
|
||||
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
|
||||
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
|
||||
function FileProgress(file, targetID) {
|
||||
this.fileProgressID = file.id;
|
||||
|
||||
this.opacity = 100;
|
||||
this.height = 0;
|
||||
|
||||
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
|
||||
if (!this.fileProgressWrapper) {
|
||||
this.fileProgressWrapper = document.createElement("div");
|
||||
this.fileProgressWrapper.className = "progressWrapper";
|
||||
this.fileProgressWrapper.id = this.fileProgressID;
|
||||
|
||||
this.fileProgressElement = document.createElement("div");
|
||||
this.fileProgressElement.className = "progressContainer";
|
||||
|
||||
var progressCancel = document.createElement("a");
|
||||
progressCancel.className = "progressCancel";
|
||||
progressCancel.href = "#";
|
||||
progressCancel.style.visibility = "hidden";
|
||||
progressCancel.appendChild(document.createTextNode(" "));
|
||||
|
||||
var progressText = document.createElement("div");
|
||||
progressText.className = "progressName";
|
||||
progressText.appendChild(document.createTextNode(file.name));
|
||||
|
||||
var progressBar = document.createElement("div");
|
||||
progressBar.className = "progressBarInProgress";
|
||||
|
||||
var progressStatus = document.createElement("div");
|
||||
progressStatus.className = "progressBarStatus";
|
||||
progressStatus.innerHTML = " ";
|
||||
|
||||
this.fileProgressElement.appendChild(progressCancel);
|
||||
this.fileProgressElement.appendChild(progressText);
|
||||
this.fileProgressElement.appendChild(progressStatus);
|
||||
this.fileProgressElement.appendChild(progressBar);
|
||||
|
||||
this.fileProgressWrapper.appendChild(this.fileProgressElement);
|
||||
|
||||
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
|
||||
} else {
|
||||
this.fileProgressElement = this.fileProgressWrapper.firstChild;
|
||||
}
|
||||
|
||||
this.height = this.fileProgressWrapper.offsetHeight;
|
||||
|
||||
}
|
||||
FileProgress.prototype.setProgress = function (percentage) {
|
||||
this.fileProgressElement.className = "progressContainer green";
|
||||
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
|
||||
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
|
||||
};
|
||||
FileProgress.prototype.setComplete = function () {
|
||||
this.fileProgressElement.className = "progressContainer blue";
|
||||
this.fileProgressElement.childNodes[3].className = "progressBarComplete";
|
||||
this.fileProgressElement.childNodes[3].style.width = "";
|
||||
|
||||
var oSelf = this;
|
||||
setTimeout(function () {
|
||||
oSelf.disappear();
|
||||
}, 10000);
|
||||
};
|
||||
FileProgress.prototype.setError = function () {
|
||||
this.fileProgressElement.className = "progressContainer red";
|
||||
this.fileProgressElement.childNodes[3].className = "progressBarError";
|
||||
this.fileProgressElement.childNodes[3].style.width = "";
|
||||
|
||||
var oSelf = this;
|
||||
setTimeout(function () {
|
||||
oSelf.disappear();
|
||||
}, 5000);
|
||||
};
|
||||
FileProgress.prototype.setCancelled = function () {
|
||||
this.fileProgressElement.className = "progressContainer";
|
||||
this.fileProgressElement.childNodes[3].className = "progressBarError";
|
||||
this.fileProgressElement.childNodes[3].style.width = "";
|
||||
|
||||
var oSelf = this;
|
||||
setTimeout(function () {
|
||||
oSelf.disappear();
|
||||
}, 2000);
|
||||
};
|
||||
FileProgress.prototype.setStatus = function (status) {
|
||||
this.fileProgressElement.childNodes[2].innerHTML = status;
|
||||
};
|
||||
|
||||
// Show/Hide the cancel button
|
||||
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
|
||||
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
|
||||
if (swfUploadInstance) {
|
||||
var fileID = this.fileProgressID;
|
||||
this.fileProgressElement.childNodes[0].onclick = function () {
|
||||
swfUploadInstance.cancelUpload(fileID);
|
||||
return false;
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Fades out and clips away the FileProgress box.
|
||||
FileProgress.prototype.disappear = function () {
|
||||
|
||||
var reduceOpacityBy = 15;
|
||||
var reduceHeightBy = 4;
|
||||
var rate = 30; // 15 fps
|
||||
|
||||
if (this.opacity > 0) {
|
||||
this.opacity -= reduceOpacityBy;
|
||||
if (this.opacity < 0) {
|
||||
this.opacity = 0;
|
||||
}
|
||||
|
||||
if (this.fileProgressWrapper.filters) {
|
||||
try {
|
||||
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
|
||||
} catch (e) {
|
||||
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
|
||||
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
|
||||
}
|
||||
} else {
|
||||
this.fileProgressWrapper.style.opacity = this.opacity / 100;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.height > 0) {
|
||||
this.height -= reduceHeightBy;
|
||||
if (this.height < 0) {
|
||||
this.height = 0;
|
||||
}
|
||||
|
||||
this.fileProgressWrapper.style.height = this.height + "px";
|
||||
}
|
||||
|
||||
if (this.height > 0 || this.opacity > 0) {
|
||||
var oSelf = this;
|
||||
setTimeout(function () {
|
||||
oSelf.disappear();
|
||||
}, rate);
|
||||
} else {
|
||||
this.fileProgressWrapper.style.display = "none";
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,200 @@
|
||||
/* Demo Note: This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
|
||||
The FileProgress class is not part of SWFUpload.
|
||||
*/
|
||||
|
||||
|
||||
/* **********************
|
||||
Event Handlers
|
||||
These are my custom event handlers to make my
|
||||
web application behave the way I went when SWFUpload
|
||||
completes different tasks. These aren't part of the SWFUpload
|
||||
package. They are part of my application. Without these none
|
||||
of the actions SWFUpload makes will show up in my application.
|
||||
********************** */
|
||||
function fileQueued(file) {
|
||||
try {
|
||||
var progress = new FileProgress(file, this.customSettings.progressTarget);
|
||||
progress.setStatus(" î÷åðåäè ...");
|
||||
progress.toggleCancel(true, this);
|
||||
|
||||
} catch (ex) {
|
||||
this.debug(ex);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function fileQueueError(file, errorCode, message) {
|
||||
try {
|
||||
if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
|
||||
alert("Âû âûáðàëè ñëèøêîì ìíîãî ôàéëîâ.\n" + (message === 0 ? "Âû ïðåâûñèëè ëèìèò." : "Âû ìîæåòå âûáðàòü " + (message > 1 ? "íå áîëåå " + message + " ôàéëîâ." : "îäèí ôàéë.")));
|
||||
return;
|
||||
}
|
||||
|
||||
var progress = new FileProgress(file, this.customSettings.progressTarget);
|
||||
progress.setError();
|
||||
progress.toggleCancel(false);
|
||||
|
||||
switch (errorCode) {
|
||||
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
|
||||
progress.setStatus("Ôàéë ñëèøêîì áîëüøîé.");
|
||||
this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
|
||||
progress.setStatus("Íåâîçìîæíî çàãðóçèòü ôàéë íóëåâîãî ðàçìåðà.");
|
||||
this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
|
||||
progress.setStatus("Íåâåðíûé òèï ôàéëà.");
|
||||
this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
default:
|
||||
if (file !== null) {
|
||||
progress.setStatus("Íåèçâåñòíàÿ îøèáêà");
|
||||
}
|
||||
this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
}
|
||||
} catch (ex) {
|
||||
this.debug(ex);
|
||||
}
|
||||
}
|
||||
|
||||
function fileDialogComplete(numFilesSelected, numFilesQueued) {
|
||||
try {
|
||||
if (numFilesSelected > 0) {
|
||||
document.getElementById(this.customSettings.cancelButtonId).disabled = false;
|
||||
}
|
||||
|
||||
/* I want auto start the upload and I can do that here */
|
||||
|
||||
elements = document.getElementById("form").elements;
|
||||
for(i=0; i < elements.length; i++) {
|
||||
name = elements[i].name
|
||||
if (name) {
|
||||
value = '';
|
||||
switch(elements[i].type) {
|
||||
case "select" :
|
||||
value = elements[i].options[elements[i].selectedIndex].value
|
||||
break;
|
||||
case "radio":
|
||||
case "checkbox":
|
||||
value = elements[i].checked ? 1: 0;
|
||||
break;
|
||||
default:
|
||||
value = elements[i].value;
|
||||
break;
|
||||
}
|
||||
this.addPostParam(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.startUpload();
|
||||
|
||||
} catch (ex) {
|
||||
this.debug(ex);
|
||||
}
|
||||
}
|
||||
|
||||
function uploadStart(file) {
|
||||
try {
|
||||
/* I don't want to do any file validation or anything, I'll just update the UI and
|
||||
return true to indicate that the upload should start.
|
||||
It's important to update the UI here because in Linux no uploadProgress events are called. The best
|
||||
we can do is say we are uploading.
|
||||
*/
|
||||
var progress = new FileProgress(file, this.customSettings.progressTarget);
|
||||
progress.setStatus("Çàãðóçêà...");
|
||||
progress.toggleCancel(true, this);
|
||||
}
|
||||
catch (ex) {}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function uploadProgress(file, bytesLoaded, bytesTotal) {
|
||||
try {
|
||||
var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
|
||||
|
||||
var progress = new FileProgress(file, this.customSettings.progressTarget);
|
||||
progress.setProgress(percent);
|
||||
progress.setStatus("Çàãðóçêà...");
|
||||
} catch (ex) {
|
||||
this.debug(ex);
|
||||
}
|
||||
}
|
||||
|
||||
function uploadSuccess(file, serverData) {
|
||||
try {
|
||||
var progress = new FileProgress(file, this.customSettings.progressTarget);
|
||||
progress.setComplete();
|
||||
progress.setStatus("Çàâåðøåíî.");
|
||||
progress.toggleCancel(false);
|
||||
|
||||
} catch (ex) {
|
||||
this.debug(ex);
|
||||
}
|
||||
}
|
||||
|
||||
function uploadError(file, errorCode, message) {
|
||||
try {
|
||||
var progress = new FileProgress(file, this.customSettings.progressTarget);
|
||||
progress.setError();
|
||||
progress.toggleCancel(false);
|
||||
|
||||
switch (errorCode) {
|
||||
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
|
||||
progress.setStatus("Îøèáêà: " + message);
|
||||
this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
|
||||
progress.setStatus("Îøèáêà çàãðóçêè.");
|
||||
this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
|
||||
progress.setStatus("Server (IO) Error");
|
||||
this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
|
||||
progress.setStatus("Îøèáêà áåçîïàñíîñòè");
|
||||
this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
|
||||
progress.setStatus("Ïðåâûøåí ëèìèò çàãðóçêè.");
|
||||
this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
|
||||
progress.setStatus("Îøèáêà èäåíòèôèêàöèè. Çàãðóçêà ïðîïóùåíà.");
|
||||
this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
|
||||
// If there aren't any files left (they were all cancelled) disable the cancel button
|
||||
if (this.getStats().files_queued === 0) {
|
||||
document.getElementById(this.customSettings.cancelButtonId).disabled = true;
|
||||
}
|
||||
progress.setStatus("Îòìåíåíî");
|
||||
progress.setCancelled();
|
||||
break;
|
||||
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
|
||||
progress.setStatus("Îñòàíîâëåíî");
|
||||
break;
|
||||
default:
|
||||
progress.setStatus("Íåèçâåñòíàÿ îøèáêà: " + errorCode);
|
||||
this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
|
||||
break;
|
||||
}
|
||||
} catch (ex) {
|
||||
this.debug(ex);
|
||||
}
|
||||
}
|
||||
|
||||
function uploadComplete(file) {
|
||||
if (this.getStats().files_queued === 0) {
|
||||
document.getElementById(this.customSettings.cancelButtonId).disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
// This event comes from the Queue Plugin
|
||||
function queueComplete(numFilesUploaded) {
|
||||
setTimeout('location.replace( window.location )', 2000);
|
||||
}
|
||||
@@ -0,0 +1,840 @@
|
||||
/**
|
||||
* SWFUpload v2.1.0 by Jacob Roberts, Feb 2008, http://www.swfupload.org, http://swfupload.googlecode.com, http://www.swfupload.org
|
||||
* -------- -------- -------- -------- -------- -------- -------- --------
|
||||
* SWFUpload is (c) 2006 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
|
||||
* http://www.opensource.org/licenses/mit-license.php
|
||||
*
|
||||
* See Changelog.txt for version history
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/* *********** */
|
||||
/* Constructor */
|
||||
/* *********** */
|
||||
|
||||
var SWFUpload = function (settings) {
|
||||
this.initSWFUpload(settings);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.initSWFUpload = function (settings) {
|
||||
try {
|
||||
this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
|
||||
this.settings = settings;
|
||||
this.eventQueue = [];
|
||||
this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
|
||||
this.movieElement = null;
|
||||
|
||||
// Setup global control tracking
|
||||
SWFUpload.instances[this.movieName] = this;
|
||||
|
||||
// Load the settings. Load the Flash movie.
|
||||
this.initSettings();
|
||||
this.loadFlash();
|
||||
this.displayDebugInfo();
|
||||
} catch (ex) {
|
||||
delete SWFUpload.instances[this.movieName];
|
||||
throw ex;
|
||||
}
|
||||
};
|
||||
|
||||
/* *************** */
|
||||
/* Static Members */
|
||||
/* *************** */
|
||||
SWFUpload.instances = {};
|
||||
SWFUpload.movieCount = 0;
|
||||
SWFUpload.version = "2.2.0 Alpha";
|
||||
SWFUpload.QUEUE_ERROR = {
|
||||
QUEUE_LIMIT_EXCEEDED : -100,
|
||||
FILE_EXCEEDS_SIZE_LIMIT : -110,
|
||||
ZERO_BYTE_FILE : -120,
|
||||
INVALID_FILETYPE : -130
|
||||
};
|
||||
SWFUpload.UPLOAD_ERROR = {
|
||||
HTTP_ERROR : -200,
|
||||
MISSING_UPLOAD_URL : -210,
|
||||
IO_ERROR : -220,
|
||||
SECURITY_ERROR : -230,
|
||||
UPLOAD_LIMIT_EXCEEDED : -240,
|
||||
UPLOAD_FAILED : -250,
|
||||
SPECIFIED_FILE_ID_NOT_FOUND : -260,
|
||||
FILE_VALIDATION_FAILED : -270,
|
||||
FILE_CANCELLED : -280,
|
||||
UPLOAD_STOPPED : -290
|
||||
};
|
||||
SWFUpload.FILE_STATUS = {
|
||||
QUEUED : -1,
|
||||
IN_PROGRESS : -2,
|
||||
ERROR : -3,
|
||||
COMPLETE : -4,
|
||||
CANCELLED : -5
|
||||
};
|
||||
SWFUpload.BUTTON_ACTION = {
|
||||
SELECT_FILE : -100,
|
||||
SELECT_FILES : -110,
|
||||
START_UPLOAD : -120
|
||||
};
|
||||
|
||||
/* ******************** */
|
||||
/* Instance Members */
|
||||
/* ******************** */
|
||||
|
||||
// Private: initSettings ensures that all the
|
||||
// settings are set, getting a default value if one was not assigned.
|
||||
SWFUpload.prototype.initSettings = function () {
|
||||
this.ensureDefault = function (settingName, defaultValue) {
|
||||
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
|
||||
};
|
||||
|
||||
// Upload backend settings
|
||||
this.ensureDefault("upload_url", "");
|
||||
this.ensureDefault("file_post_name", "Filedata");
|
||||
this.ensureDefault("post_params", {});
|
||||
this.ensureDefault("use_query_string", false);
|
||||
this.ensureDefault("requeue_on_error", false);
|
||||
|
||||
// File Settings
|
||||
this.ensureDefault("file_types", "*.*");
|
||||
this.ensureDefault("file_types_description", "All Files");
|
||||
this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
|
||||
this.ensureDefault("file_upload_limit", 0);
|
||||
this.ensureDefault("file_queue_limit", 0);
|
||||
|
||||
// Flash Settings
|
||||
this.ensureDefault("flash_url", "swfupload_f9.swf");
|
||||
this.ensureDefault("flash_color", "#FFFFFF");
|
||||
this.ensureDefault("flash_wmode", "transparent");
|
||||
this.ensureDefault("flash_container_id", null);
|
||||
this.ensureDefault("flash_width", '100%');
|
||||
this.ensureDefault("flash_height", '100%');
|
||||
|
||||
// Button Settings
|
||||
/*
|
||||
this.ensureDefault("button_image_url", 0);
|
||||
this.ensureDefault("button_width", 1);
|
||||
this.ensureDefault("button_height", 1);
|
||||
this.ensureDefault("button_text", "");
|
||||
this.ensureDefault("button_text_style", "");
|
||||
this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
|
||||
this.ensureDefault("button_disabled", false);
|
||||
this.ensureDefault("button_placeholder_id", null);
|
||||
*/
|
||||
|
||||
// Debug Settings
|
||||
this.ensureDefault("debug", false);
|
||||
this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
|
||||
|
||||
// Event Handlers
|
||||
this.settings.return_upload_start_handler = this.returnUploadStart;
|
||||
this.ensureDefault("swfupload_loaded_handler", null);
|
||||
this.ensureDefault("file_dialog_start_handler", null);
|
||||
this.ensureDefault("file_queued_handler", null);
|
||||
this.ensureDefault("file_queue_error_handler", null);
|
||||
this.ensureDefault("file_dialog_complete_handler", null);
|
||||
|
||||
this.ensureDefault("upload_start_handler", null);
|
||||
this.ensureDefault("upload_progress_handler", null);
|
||||
this.ensureDefault("upload_error_handler", null);
|
||||
this.ensureDefault("upload_success_handler", null);
|
||||
this.ensureDefault("upload_complete_handler", null);
|
||||
|
||||
this.ensureDefault("debug_handler", this.debugMessage);
|
||||
|
||||
this.ensureDefault("custom_settings", {});
|
||||
|
||||
// Other settings
|
||||
this.customSettings = this.settings.custom_settings;
|
||||
|
||||
delete this.ensureDefault;
|
||||
};
|
||||
|
||||
SWFUpload.prototype.loadFlash = function () {
|
||||
this.insertFlash();
|
||||
};
|
||||
|
||||
// Private: appendFlash gets the HTML tag for the Flash
|
||||
// It then appends the flash to the body
|
||||
SWFUpload.prototype.appendFlash = function () {
|
||||
var targetElement, container;
|
||||
|
||||
// Make sure an element with the ID we are going to use doesn't already exist
|
||||
if (document.getElementById(this.movieName) !== null) {
|
||||
throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
|
||||
}
|
||||
|
||||
// Get the body tag where we will be adding the flash movie
|
||||
targetElement = document.getElementsByTagName("body")[0];
|
||||
|
||||
if (targetElement == undefined) {
|
||||
throw "Could not find the 'body' element.";
|
||||
}
|
||||
|
||||
// Append the container and load the flash
|
||||
container = document.createElement("div");
|
||||
container.style.width = "1px";
|
||||
container.style.height = "1px";
|
||||
|
||||
targetElement.appendChild(container);
|
||||
container.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
|
||||
};
|
||||
|
||||
// Private: insertFlash inserts the flash movie into the container element.
|
||||
SWFUpload.prototype.insertFlash = function () {
|
||||
var targetElement, container;
|
||||
|
||||
// Make sure an element with the ID we are going to use doesn't already exist
|
||||
if (document.getElementById(this.movieName) !== null) {
|
||||
throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
|
||||
}
|
||||
|
||||
// Get the container elt into which we'll insert the flash movie
|
||||
containerElement = document.getElementById(this.settings.flash_container_id);
|
||||
|
||||
if (containerElement == undefined) {
|
||||
throw "Could not find the container element.";
|
||||
}
|
||||
|
||||
// place flash embed inside the container element
|
||||
containerElement.innerHTML = this.getFlashHTML();
|
||||
};
|
||||
|
||||
// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
|
||||
SWFUpload.prototype.getFlashHTML = function () {
|
||||
// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
|
||||
return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.flash_width, '" height="', this.settings.flash_height, '" style="-moz-user-focus: ignore;">',
|
||||
'<param name="movie" value="', this.settings.flash_url, '" />',
|
||||
'<param name="bgcolor" value="', this.settings.flash_color, '" />',
|
||||
'<param name="quality" value="high" />',
|
||||
'<param name="menu" value="false" />',
|
||||
'<param name="wmode" value="', this.settings.flash_wmode ,'" />',
|
||||
'<param name="allowScriptAccess" value="always" />',
|
||||
'<param name="flashvars" value="' + this.getFlashVars() + '" />',
|
||||
'</object>'].join("");
|
||||
};
|
||||
|
||||
// Private: getFlashVars builds the parameter string that will be passed
|
||||
// to flash in the flashvars param.
|
||||
SWFUpload.prototype.getFlashVars = function () {
|
||||
// Build a string from the post param object
|
||||
var paramString = this.buildParamString();
|
||||
|
||||
// Build the parameter string
|
||||
return ["movieName=", encodeURIComponent(this.movieName),
|
||||
"&uploadURL=", encodeURIComponent(this.settings.upload_url),
|
||||
"&useQueryString=", encodeURIComponent(this.settings.use_query_string),
|
||||
"&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
|
||||
"&params=", encodeURIComponent(paramString),
|
||||
"&filePostName=", encodeURIComponent(this.settings.file_post_name),
|
||||
"&fileTypes=", encodeURIComponent(this.settings.file_types),
|
||||
"&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
|
||||
"&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
|
||||
"&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
|
||||
"&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
|
||||
//"&buttonImage_url=", encodeURIComponent(this.settings.button_image_url),
|
||||
//"&buttonWidth=", encodeURIComponent(this.settings.button_width),
|
||||
//"&buttonHeight=", encodeURIComponent(this.settings.button_height),
|
||||
//"&buttonText=", encodeURIComponent(this.settings.button_text),
|
||||
//"&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
|
||||
//"&buttonAction=", encodeURIComponent(this.settings.button_action),
|
||||
//"&buttonDisabled=", encodeURIComponent(this.settings.button_disabled)
|
||||
].join("");
|
||||
};
|
||||
|
||||
// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
|
||||
// The element is cached after the first lookup
|
||||
SWFUpload.prototype.getMovieElement = function () {
|
||||
if (this.movieElement == undefined) {
|
||||
this.movieElement = document.getElementById(this.movieName);
|
||||
}
|
||||
|
||||
if (this.movieElement === null) {
|
||||
throw "Could not find Flash element";
|
||||
}
|
||||
|
||||
return this.movieElement;
|
||||
};
|
||||
|
||||
// Private: buildParamString takes the name/value pairs in the post_params setting object
|
||||
// and joins them up in to a string formatted "name=value&name=value"
|
||||
SWFUpload.prototype.buildParamString = function () {
|
||||
var postParams = this.settings.post_params;
|
||||
var paramStringPairs = [];
|
||||
|
||||
if (typeof(postParams) === "object") {
|
||||
for (var name in postParams) {
|
||||
if (postParams.hasOwnProperty(name)) {
|
||||
paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return paramStringPairs.join("&");
|
||||
};
|
||||
|
||||
// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
|
||||
// all references to the SWF, and other objects so memory is properly freed.
|
||||
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
|
||||
SWFUpload.prototype.destroy = function () {
|
||||
try {
|
||||
// Make sure Flash is done before we try to remove it
|
||||
this.stopUpload();
|
||||
|
||||
// Remove the SWFUpload DOM nodes
|
||||
var movieElement = null;
|
||||
try {
|
||||
movieElement = this.getMovieElement();
|
||||
} catch (ex) {
|
||||
}
|
||||
|
||||
if (movieElement != undefined && movieElement.parentNode != undefined && typeof(movieElement.parentNode.removeChild) === "function") {
|
||||
var container = movieElement.parentNode;
|
||||
if (container != undefined) {
|
||||
container.removeChild(movieElement);
|
||||
if (container.parentNode != undefined && typeof(container.parentNode.removeChild) === "function") {
|
||||
container.parentNode.removeChild(container);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Destroy references
|
||||
SWFUpload.instances[this.movieName] = null;
|
||||
delete SWFUpload.instances[this.movieName];
|
||||
|
||||
delete this.movieElement;
|
||||
delete this.settings;
|
||||
delete this.customSettings;
|
||||
delete this.eventQueue;
|
||||
delete this.movieName;
|
||||
|
||||
return true;
|
||||
} catch (ex1) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Public: displayDebugInfo prints out settings and configuration
|
||||
// information about this SWFUpload instance.
|
||||
// This function (and any references to it) can be deleted when placing
|
||||
// SWFUpload in production.
|
||||
SWFUpload.prototype.displayDebugInfo = function () {
|
||||
this.debug(
|
||||
[
|
||||
"---SWFUpload Instance Info---\n",
|
||||
"Version: ", SWFUpload.version, "\n",
|
||||
"Movie Name: ", this.movieName, "\n",
|
||||
"Settings:\n",
|
||||
"\t", "upload_url: ", this.settings.upload_url, "\n",
|
||||
"\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
|
||||
"\t", "file_post_name: ", this.settings.file_post_name, "\n",
|
||||
"\t", "post_params: ", this.settings.post_params.toString(), "\n",
|
||||
"\t", "file_types: ", this.settings.file_types, "\n",
|
||||
"\t", "file_types_description: ", this.settings.file_types_description, "\n",
|
||||
"\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
|
||||
"\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
|
||||
"\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
|
||||
"\t", "flash_url: ", this.settings.flash_url, "\n",
|
||||
"\t", "flash_color: ", this.settings.flash_color, "\n",
|
||||
"\t", "debug: ", this.settings.debug.toString(), "\n",
|
||||
"\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
|
||||
"Event Handlers:\n",
|
||||
"\t", "swfupload_loaded_handler assigned: ", (typeof(this.settings.swfupload_loaded_handler) === "function").toString(), "\n",
|
||||
"\t", "file_dialog_start_handler assigned: ", (typeof(this.settings.file_dialog_start_handler) === "function").toString(), "\n",
|
||||
"\t", "file_queued_handler assigned: ", (typeof(this.settings.file_queued_handler) === "function").toString(), "\n",
|
||||
"\t", "file_queue_error_handler assigned: ", (typeof(this.settings.file_queue_error_handler) === "function").toString(), "\n",
|
||||
"\t", "upload_start_handler assigned: ", (typeof(this.settings.upload_start_handler) === "function").toString(), "\n",
|
||||
"\t", "upload_progress_handler assigned: ", (typeof(this.settings.upload_progress_handler) === "function").toString(), "\n",
|
||||
"\t", "upload_error_handler assigned: ", (typeof(this.settings.upload_error_handler) === "function").toString(), "\n",
|
||||
"\t", "upload_success_handler assigned: ", (typeof(this.settings.upload_success_handler) === "function").toString(), "\n",
|
||||
"\t", "upload_complete_handler assigned: ", (typeof(this.settings.upload_complete_handler) === "function").toString(), "\n",
|
||||
"\t", "debug_handler assigned: ", (typeof(this.settings.debug_handler) === "function").toString(), "\n"
|
||||
].join("")
|
||||
);
|
||||
};
|
||||
|
||||
/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
|
||||
the maintain v2 API compatibility
|
||||
*/
|
||||
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
|
||||
SWFUpload.prototype.addSetting = function (name, value, default_value) {
|
||||
if (value == undefined) {
|
||||
return (this.settings[name] = default_value);
|
||||
} else {
|
||||
return (this.settings[name] = value);
|
||||
}
|
||||
};
|
||||
|
||||
// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
|
||||
SWFUpload.prototype.getSetting = function (name) {
|
||||
if (this.settings[name] != undefined) {
|
||||
return this.settings[name];
|
||||
}
|
||||
|
||||
return "";
|
||||
};
|
||||
|
||||
|
||||
|
||||
// Private: callFlash handles function calls made to the Flash element.
|
||||
// Calls are made with a setTimeout for some functions to work around
|
||||
// bugs in the ExternalInterface library.
|
||||
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
|
||||
argumentArray = argumentArray || [];
|
||||
|
||||
var self = this;
|
||||
var callFunction = function () {
|
||||
var movieElement = self.getMovieElement();
|
||||
var returnValue;
|
||||
if (typeof(movieElement[functionName]) === "function") {
|
||||
// We have to go through all this if/else stuff because the Flash functions don't have apply() and only accept the exact number of arguments.
|
||||
if (argumentArray.length === 0) {
|
||||
returnValue = movieElement[functionName]();
|
||||
} else if (argumentArray.length === 1) {
|
||||
returnValue = movieElement[functionName](argumentArray[0]);
|
||||
} else if (argumentArray.length === 2) {
|
||||
returnValue = movieElement[functionName](argumentArray[0], argumentArray[1]);
|
||||
} else if (argumentArray.length === 3) {
|
||||
returnValue = movieElement[functionName](argumentArray[0], argumentArray[1], argumentArray[2]);
|
||||
} else {
|
||||
throw "Too many arguments";
|
||||
}
|
||||
|
||||
// Unescape file post param values
|
||||
if (returnValue != undefined && typeof(returnValue.post) === "object") {
|
||||
returnValue = self.unescapeFilePostParams(returnValue);
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
} else {
|
||||
throw "Invalid function name";
|
||||
}
|
||||
};
|
||||
|
||||
return callFunction();
|
||||
};
|
||||
|
||||
|
||||
/* *****************************
|
||||
-- Flash control methods --
|
||||
Your UI should use these
|
||||
to operate SWFUpload
|
||||
***************************** */
|
||||
|
||||
// Public: selectFile causes a File Selection Dialog window to appear. This
|
||||
// dialog only allows 1 file to be selected. WARNING: this function does not work in Flash Player 10
|
||||
SWFUpload.prototype.selectFile = function () {
|
||||
this.callFlash("SelectFile");
|
||||
};
|
||||
|
||||
// Public: selectFiles causes a File Selection Dialog window to appear/ This
|
||||
// dialog allows the user to select any number of files
|
||||
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
|
||||
// If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
|
||||
// for this bug. WARNING: this function does not work in Flash Player 10
|
||||
SWFUpload.prototype.selectFiles = function () {
|
||||
this.callFlash("SelectFiles");
|
||||
};
|
||||
|
||||
|
||||
// Public: startUpload starts uploading the first file in the queue unless
|
||||
// the optional parameter 'fileID' specifies the ID
|
||||
SWFUpload.prototype.startUpload = function (fileID) {
|
||||
this.callFlash("StartUpload", [fileID]);
|
||||
};
|
||||
|
||||
/* Cancels a the file upload. You must specify a file_id */
|
||||
// Public: cancelUpload cancels any queued file. The fileID parameter
|
||||
// must be specified.
|
||||
SWFUpload.prototype.cancelUpload = function (fileID) {
|
||||
this.callFlash("CancelUpload", [fileID]);
|
||||
};
|
||||
|
||||
// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
|
||||
// If nothing is currently uploading then nothing happens.
|
||||
SWFUpload.prototype.stopUpload = function () {
|
||||
this.callFlash("StopUpload");
|
||||
};
|
||||
|
||||
/* ************************
|
||||
* Settings methods
|
||||
* These methods change the SWFUpload settings.
|
||||
* SWFUpload settings should not be changed directly on the settings object
|
||||
* since many of the settings need to be passed to Flash in order to take
|
||||
* effect.
|
||||
* *********************** */
|
||||
|
||||
// Public: getStats gets the file statistics object.
|
||||
SWFUpload.prototype.getStats = function () {
|
||||
return this.callFlash("GetStats");
|
||||
};
|
||||
|
||||
// Public: setStats changes the SWFUpload statistics. You shouldn't need to
|
||||
// change the statistics but you can. Changing the statistics does not
|
||||
// affect SWFUpload accept for the successful_uploads count which is used
|
||||
// by the upload_limit setting to determine how many files the user may upload.
|
||||
SWFUpload.prototype.setStats = function (statsObject) {
|
||||
this.callFlash("SetStats", [statsObject]);
|
||||
};
|
||||
|
||||
// Public: getFile retrieves a File object by ID or Index. If the file is
|
||||
// not found then 'null' is returned.
|
||||
SWFUpload.prototype.getFile = function (fileID) {
|
||||
if (typeof(fileID) === "number") {
|
||||
return this.callFlash("GetFileByIndex", [fileID]);
|
||||
} else {
|
||||
return this.callFlash("GetFile", [fileID]);
|
||||
}
|
||||
};
|
||||
|
||||
// Public: addFileParam sets a name/value pair that will be posted with the
|
||||
// file specified by the Files ID. If the name already exists then the
|
||||
// exiting value will be overwritten.
|
||||
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
|
||||
return this.callFlash("AddFileParam", [fileID, name, value]);
|
||||
};
|
||||
|
||||
// Public: removeFileParam removes a previously set (by addFileParam) name/value
|
||||
// pair from the specified file.
|
||||
SWFUpload.prototype.removeFileParam = function (fileID, name) {
|
||||
this.callFlash("RemoveFileParam", [fileID, name]);
|
||||
};
|
||||
|
||||
// Public: setUploadUrl changes the upload_url setting.
|
||||
SWFUpload.prototype.setUploadURL = function (url) {
|
||||
this.settings.upload_url = url.toString();
|
||||
this.callFlash("SetUploadURL", [url]);
|
||||
};
|
||||
|
||||
// Public: setPostParams changes the post_params setting
|
||||
SWFUpload.prototype.setPostParams = function (paramsObject) {
|
||||
this.settings.post_params = paramsObject;
|
||||
this.callFlash("SetPostParams", [paramsObject]);
|
||||
};
|
||||
|
||||
// Public: addPostParam adds post name/value pair. Each name can have only one value.
|
||||
SWFUpload.prototype.addPostParam = function (name, value) {
|
||||
this.settings.post_params[name] = value;
|
||||
this.callFlash("SetPostParams", [this.settings.post_params]);
|
||||
};
|
||||
|
||||
// Public: removePostParam deletes post name/value pair.
|
||||
SWFUpload.prototype.removePostParam = function (name) {
|
||||
delete this.settings.post_params[name];
|
||||
this.callFlash("SetPostParams", [this.settings.post_params]);
|
||||
};
|
||||
|
||||
// Public: setFileTypes changes the file_types setting and the file_types_description setting
|
||||
SWFUpload.prototype.setFileTypes = function (types, description) {
|
||||
this.settings.file_types = types;
|
||||
this.settings.file_types_description = description;
|
||||
this.callFlash("SetFileTypes", [types, description]);
|
||||
};
|
||||
|
||||
// Public: setFileSizeLimit changes the file_size_limit setting
|
||||
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
|
||||
this.settings.file_size_limit = fileSizeLimit;
|
||||
this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
|
||||
};
|
||||
|
||||
// Public: setFileUploadLimit changes the file_upload_limit setting
|
||||
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
|
||||
this.settings.file_upload_limit = fileUploadLimit;
|
||||
this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
|
||||
};
|
||||
|
||||
// Public: setFileQueueLimit changes the file_queue_limit setting
|
||||
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
|
||||
this.settings.file_queue_limit = fileQueueLimit;
|
||||
this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
|
||||
};
|
||||
|
||||
// Public: setFilePostName changes the file_post_name setting
|
||||
SWFUpload.prototype.setFilePostName = function (filePostName) {
|
||||
this.settings.file_post_name = filePostName;
|
||||
this.callFlash("SetFilePostName", [filePostName]);
|
||||
};
|
||||
|
||||
// Public: setUseQueryString changes the use_query_string setting
|
||||
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
|
||||
this.settings.use_query_string = useQueryString;
|
||||
this.callFlash("SetUseQueryString", [useQueryString]);
|
||||
};
|
||||
|
||||
// Public: setRequeueOnError changes the requeue_on_error setting
|
||||
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
|
||||
this.settings.requeue_on_error = requeueOnError;
|
||||
this.callFlash("SetRequeueOnError", [requeueOnError]);
|
||||
};
|
||||
|
||||
// Public: setDebugEnabled changes the debug_enabled setting
|
||||
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
|
||||
this.settings.debug_enabled = debugEnabled;
|
||||
this.callFlash("SetDebugEnabled", [debugEnabled]);
|
||||
};
|
||||
|
||||
// Public: setButtonImageURL loads a button image sprite
|
||||
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
|
||||
this.settings.button_image_url = buttonImageURL;
|
||||
this.callFlash("SetButtonImageURL", [buttonImageURL]);
|
||||
};
|
||||
|
||||
// Public: setButtonDimensions resizes the Flash Movie and button
|
||||
SWFUpload.prototype.setButtonDimensions = function (width, height) {
|
||||
this.settings.button_width = width;
|
||||
this.settings.button_height = height;
|
||||
|
||||
this.callFlash("SetButtonDimensions", [width, height]);
|
||||
};
|
||||
// Public: setButtonText Changes the text overlaid on the button
|
||||
SWFUpload.prototype.setButtonText = function (html) {
|
||||
this.settings.button_text= html;
|
||||
this.callFlash("SetButtonText", [html]);
|
||||
};
|
||||
// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
|
||||
SWFUpload.prototype.setButtonTextStyle = function (css) {
|
||||
this.settings.button_text_style = css;
|
||||
this.callFlash("SetButtonTextStyle", [css]);
|
||||
};
|
||||
// Public: setButtonDisabled disables/enables the button
|
||||
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
|
||||
this.settings.button_disabled = isDisabled;
|
||||
this.callFlash("SetButtonDisabled", [isDisabled]);
|
||||
};
|
||||
// Public: setButtonAction sets the action that occurs when the button is clicked
|
||||
SWFUpload.prototype.setButtonAction = function (buttonAction) {
|
||||
this.settings.button_action = buttonAction;
|
||||
this.callFlash("SetButtonAction", [buttonAction]);
|
||||
};
|
||||
|
||||
/* *******************************
|
||||
Flash Event Interfaces
|
||||
These functions are used by Flash to trigger the various
|
||||
events.
|
||||
|
||||
All these functions a Private.
|
||||
|
||||
Because the ExternalInterface library is buggy the event calls
|
||||
are added to a queue and the queue then executed by a setTimeout.
|
||||
This ensures that events are executed in a determinate order and that
|
||||
the ExternalInterface bugs are avoided.
|
||||
******************************* */
|
||||
|
||||
SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
|
||||
// Warning: Don't call this.debug inside here or you'll create an infinite loop
|
||||
|
||||
if (argumentArray == undefined) {
|
||||
argumentArray = [];
|
||||
} else if (!(argumentArray instanceof Array)) {
|
||||
argumentArray = [argumentArray];
|
||||
}
|
||||
|
||||
var self = this;
|
||||
if (typeof(this.settings[handlerName]) === "function") {
|
||||
// Queue the event
|
||||
this.eventQueue.push(function () {
|
||||
this.settings[handlerName].apply(this, argumentArray);
|
||||
});
|
||||
|
||||
// Execute the next queued event
|
||||
setTimeout(function () {
|
||||
self.executeNextEvent();
|
||||
}, 0);
|
||||
|
||||
} else if (this.settings[handlerName] !== null) {
|
||||
throw "Event handler " + handlerName + " is unknown or is not a function";
|
||||
}
|
||||
};
|
||||
|
||||
// Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
|
||||
// we must queue them in order to garentee that they are executed in order.
|
||||
SWFUpload.prototype.executeNextEvent = function () {
|
||||
// Warning: Don't call this.debug inside here or you'll create an infinite loop
|
||||
|
||||
var f = this.eventQueue ? this.eventQueue.shift() : null;
|
||||
if (typeof(f) === "function") {
|
||||
f.apply(this);
|
||||
}
|
||||
};
|
||||
|
||||
// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterfance cannot have
|
||||
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
|
||||
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
|
||||
SWFUpload.prototype.unescapeFilePostParams = function (file) {
|
||||
var reg = /[$]([0-9a-f]{4})/i;
|
||||
var unescapedPost = {};
|
||||
var uk;
|
||||
|
||||
if (file != undefined) {
|
||||
for (var k in file.post) {
|
||||
if (file.post.hasOwnProperty(k)) {
|
||||
uk = k;
|
||||
var match;
|
||||
while ((match = reg.exec(uk)) !== null) {
|
||||
uk = uk.replace(match[0], String.fromCharCode(parseInt("0x"+match[1], 16)));
|
||||
}
|
||||
unescapedPost[uk] = file.post[k];
|
||||
}
|
||||
}
|
||||
|
||||
file.post = unescapedPost;
|
||||
}
|
||||
|
||||
return file;
|
||||
};
|
||||
|
||||
SWFUpload.prototype.flashReady = function () {
|
||||
// Check that the movie element is loaded correctly with its ExternalInterface methods defined
|
||||
var movieElement = this.getMovieElement();
|
||||
if (typeof(movieElement.StartUpload) !== "function") {
|
||||
throw "ExternalInterface methods failed to initialize.";
|
||||
}
|
||||
|
||||
this.queueEvent("swfupload_loaded_handler");
|
||||
};
|
||||
|
||||
|
||||
/* This is a chance to do something before the browse window opens */
|
||||
SWFUpload.prototype.fileDialogStart = function () {
|
||||
this.queueEvent("file_dialog_start_handler");
|
||||
};
|
||||
|
||||
|
||||
/* Called when a file is successfully added to the queue. */
|
||||
SWFUpload.prototype.fileQueued = function (file) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("file_queued_handler", file);
|
||||
};
|
||||
|
||||
|
||||
/* Handle errors that occur when an attempt to queue a file fails. */
|
||||
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
|
||||
};
|
||||
|
||||
/* Called after the file dialog has closed and the selected files have been queued.
|
||||
You could call startUpload here if you want the queued files to begin uploading immediately. */
|
||||
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued) {
|
||||
this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.uploadStart = function (file) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("return_upload_start_handler", file);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.returnUploadStart = function (file) {
|
||||
var returnValue;
|
||||
if (typeof(this.settings.upload_start_handler) === "function") {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
returnValue = this.settings.upload_start_handler.call(this, file);
|
||||
} else if (this.settings.upload_start_handler != undefined) {
|
||||
throw "upload_start_handler must be a function";
|
||||
}
|
||||
|
||||
// Convert undefined to true so if nothing is returned from the upload_start_handler it is
|
||||
// interpretted as 'true'.
|
||||
if (returnValue === undefined) {
|
||||
returnValue = true;
|
||||
}
|
||||
|
||||
returnValue = !!returnValue;
|
||||
|
||||
this.callFlash("ReturnUploadStart", [returnValue]);
|
||||
};
|
||||
|
||||
|
||||
|
||||
SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.uploadError = function (file, errorCode, message) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("upload_error_handler", [file, errorCode, message]);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.uploadSuccess = function (file, serverData) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("upload_success_handler", [file, serverData]);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.uploadComplete = function (file) {
|
||||
file = this.unescapeFilePostParams(file);
|
||||
this.queueEvent("upload_complete_handler", file);
|
||||
};
|
||||
|
||||
/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
|
||||
internal debug console. You can override this event and have messages written where you want. */
|
||||
SWFUpload.prototype.debug = function (message) {
|
||||
this.queueEvent("debug_handler", message);
|
||||
};
|
||||
|
||||
|
||||
/* **********************************
|
||||
Debug Console
|
||||
The debug console is a self contained, in page location
|
||||
for debug message to be sent. The Debug Console adds
|
||||
itself to the body if necessary.
|
||||
|
||||
The console is automatically scrolled as messages appear.
|
||||
|
||||
If you are using your own debug handler or when you deploy to production and
|
||||
have debug disabled you can remove these functions to reduce the file size
|
||||
and complexity.
|
||||
********************************** */
|
||||
|
||||
// Private: debugMessage is the default debug_handler. If you want to print debug messages
|
||||
// call the debug() function. When overriding the function your own function should
|
||||
// check to see if the debug setting is true before outputting debug information.
|
||||
SWFUpload.prototype.debugMessage = function (message) {
|
||||
if (this.settings.debug) {
|
||||
var exceptionMessage, exceptionValues = [];
|
||||
|
||||
// Check for an exception object and print it nicely
|
||||
if (typeof(message) === "object" && typeof(message.name) === "string" && typeof(message.message) === "string") {
|
||||
for (var key in message) {
|
||||
if (message.hasOwnProperty(key)) {
|
||||
exceptionValues.push(key + ": " + message[key]);
|
||||
}
|
||||
}
|
||||
exceptionMessage = exceptionValues.join("\n") || "";
|
||||
exceptionValues = exceptionMessage.split("\n");
|
||||
exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
|
||||
SWFUpload.Console.writeLine(exceptionMessage);
|
||||
} else {
|
||||
SWFUpload.Console.writeLine(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SWFUpload.Console = {};
|
||||
SWFUpload.Console.writeLine = function (message) {
|
||||
var console, documentForm;
|
||||
|
||||
try {
|
||||
console = document.getElementById("SWFUpload_Console");
|
||||
|
||||
if (!console) {
|
||||
documentForm = document.createElement("form");
|
||||
document.getElementsByTagName("body")[0].appendChild(documentForm);
|
||||
|
||||
console = document.createElement("textarea");
|
||||
console.id = "SWFUpload_Console";
|
||||
console.style.fontFamily = "monospace";
|
||||
console.setAttribute("wrap", "off");
|
||||
console.wrap = "off";
|
||||
console.style.overflow = "auto";
|
||||
console.style.width = "700px";
|
||||
console.style.height = "350px";
|
||||
console.style.margin = "5px";
|
||||
documentForm.appendChild(console);
|
||||
}
|
||||
|
||||
console.value += message + "\n";
|
||||
|
||||
console.scrollTop = console.scrollHeight - console.clientHeight;
|
||||
} catch (ex) {
|
||||
alert("Exception: " + ex.name + " Message: " + ex.message);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
Queue Plug-in
|
||||
|
||||
Features:
|
||||
*Adds a cancelQueue() method for cancelling the entire queue.
|
||||
*All queued files are uploaded when startUpload() is called.
|
||||
*If false is returned from uploadComplete then the queue upload is stopped.
|
||||
If false is not returned (strict comparison) then the queue upload is continued.
|
||||
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
|
||||
Set the event handler with the queue_complete_handler setting.
|
||||
|
||||
*/
|
||||
|
||||
var SWFUpload;
|
||||
if (typeof(SWFUpload) === "function") {
|
||||
SWFUpload.queue = {};
|
||||
|
||||
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
|
||||
return function () {
|
||||
if (typeof(oldInitSettings) === "function") {
|
||||
oldInitSettings.call(this);
|
||||
}
|
||||
|
||||
this.customSettings.queue_cancelled_flag = false;
|
||||
this.customSettings.queue_upload_count = 0;
|
||||
|
||||
this.settings.user_upload_complete_handler = this.settings.upload_complete_handler;
|
||||
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
|
||||
|
||||
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
|
||||
};
|
||||
})(SWFUpload.prototype.initSettings);
|
||||
|
||||
SWFUpload.prototype.startUpload = function (fileID) {
|
||||
this.customSettings.queue_cancelled_flag = false;
|
||||
this.callFlash("StartUpload", false, [fileID]);
|
||||
};
|
||||
|
||||
SWFUpload.prototype.cancelQueue = function () {
|
||||
this.customSettings.queue_cancelled_flag = true;
|
||||
this.stopUpload();
|
||||
|
||||
var stats = this.getStats();
|
||||
while (stats.files_queued > 0) {
|
||||
this.cancelUpload();
|
||||
stats = this.getStats();
|
||||
}
|
||||
};
|
||||
|
||||
SWFUpload.queue.uploadCompleteHandler = function (file) {
|
||||
var user_upload_complete_handler = this.settings.user_upload_complete_handler;
|
||||
var continueUpload;
|
||||
|
||||
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
|
||||
this.customSettings.queue_upload_count++;
|
||||
}
|
||||
|
||||
if (typeof(user_upload_complete_handler) === "function") {
|
||||
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
|
||||
} else {
|
||||
continueUpload = true;
|
||||
}
|
||||
|
||||
if (continueUpload) {
|
||||
var stats = this.getStats();
|
||||
if (stats.files_queued > 0 && this.customSettings.queue_cancelled_flag === false) {
|
||||
this.startUpload();
|
||||
} else if (this.customSettings.queue_cancelled_flag === false) {
|
||||
this.queueEvent("queue_complete_handler", [this.customSettings.queue_upload_count]);
|
||||
this.customSettings.queue_upload_count = 0;
|
||||
} else {
|
||||
this.customSettings.queue_cancelled_flag = false;
|
||||
this.customSettings.queue_upload_count = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
class dle_template {
|
||||
|
||||
var $dir = '.';
|
||||
var $template = null;
|
||||
var $copy_template = null;
|
||||
var $data = array ();
|
||||
var $block_data = array ();
|
||||
var $result = array ('info' => '', 'vote' => '', 'speedbar' => '', 'content' => '' );
|
||||
var $allow_php_include = true;
|
||||
|
||||
function set($name, $var) {
|
||||
if( is_array( $var ) && count( $var ) ) {
|
||||
foreach ( $var as $key => $key_var ) {
|
||||
$this->set( $key, $key_var );
|
||||
}
|
||||
} else
|
||||
$this->data[$name] = $var;
|
||||
}
|
||||
|
||||
function set_block($name, $var) {
|
||||
if( is_array( $var ) && count( $var ) ) {
|
||||
foreach ( $var as $key => $key_var ) {
|
||||
$this->set_block( $key, $key_var );
|
||||
}
|
||||
} else
|
||||
$this->block_data[$name] = $var;
|
||||
}
|
||||
|
||||
function load_template($tpl_name) {
|
||||
|
||||
if( $this->CacheTemplate[ $tpl_name ] ){
|
||||
$this->copy_template = $this->CacheTemplate[ $tpl_name ];
|
||||
return true;
|
||||
}
|
||||
|
||||
if( $tpl_name == '' || ! file_exists( $this->dir . DIRECTORY_SEPARATOR . $tpl_name ) ) {
|
||||
die( "Íåâîçìîæíî çàãðóçèòü øàáëîí: " . $tpl_name );
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->template = file_get_contents( $this->dir . DIRECTORY_SEPARATOR . $tpl_name );
|
||||
|
||||
if (strpos ( $this->template, "[aviable=" ) !== false) {$this->template = preg_replace ( "#\\[aviable=(.+?)\\](.*?)\\[/aviable\\]#ies", "\$this->check_module('\\1', '\\2')", $this->template );}
|
||||
if (strpos ( $this->template, "[not-aviable=" ) !== false) {$this->template = preg_replace ( "#\\[not-aviable=(.+?)\\](.*?)\\[/not-aviable\\]#ies", "\$this->check_module('\\1', '\\2', false)", $this->template );}
|
||||
if (strpos ( $this->template, "[not-group=" ) !== false) {$this->template = preg_replace ( "#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#ies", "\$this->check_group('\\1', '\\2', false)", $this->template );}
|
||||
if (strpos ( $this->template, "[group=" ) !== false) {$this->template = preg_replace ( "#\\[group=(.+?)\\](.*?)\\[/group\\]#ies", "\$this->check_group('\\1', '\\2')", $this->template );}
|
||||
if (strpos ( $this->template, "{include file=" ) !== false ) {$this->template = preg_replace( "#\\{include file=['\"](.+?)['\"]\\}#ies", "\$this->load_file('\\1', 'tpl')", $this->template );}
|
||||
|
||||
$this->copy_template = $this->template;
|
||||
|
||||
$this->CacheTemplate[ $tpl_name ] = $this->template;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function load_file( $name, $include_file = "tpl" ) {
|
||||
global $db, $is_logged, $member_id, $cat_info, $config, $user_group, $category_id, $_TIME, $lang, $smartphone_detected, $dle_module;
|
||||
|
||||
$name = str_replace( '..', '', $name );
|
||||
|
||||
$url = @parse_url ($name);
|
||||
$type = explode( ".", $url['path'] );
|
||||
$type = strtolower( end( $type ) );
|
||||
|
||||
if ($type == "tpl") {return $this->sub_load_template( $name );}
|
||||
|
||||
if ($include_file == "php") {
|
||||
|
||||
if ( !$this->allow_php_include ) return;
|
||||
|
||||
if ($type != "php") return "Äëÿ ïîäêëþ÷åíèÿ äîïóñêàþòñÿ òîëüêî ôàéëû ñ ðàñøèðåíèåì .tpl èëè .php";
|
||||
|
||||
if ($url['path']{0} == "/" )$file_path = dirname (ROOT_DIR.$url['path']);
|
||||
else $file_path = dirname (ROOT_DIR."/".$url['path']);
|
||||
|
||||
$file_name = pathinfo($url['path']);
|
||||
$file_name = $file_name['basename'];
|
||||
|
||||
if ( stristr ( php_uname( "s" ) , "windows" ) === false )
|
||||
$chmod_value = @decoct(@fileperms($file_path)) % 1000;
|
||||
|
||||
if ($chmod_value == 777 ) return "Ôàéë {$url['path']} íàõîäèòñÿ â ïàïêå, êîòîðàÿ äîñòóïíà äëÿ çàïèñè (CHMOD 777).  öåëÿõ áåçîïàñíîñòè ïîäêëþ÷åíèå ôàéëîâ èç òàêèõ ïàïîê íåâîçìîæíî. Èçìåíèòå ïðàâà íà ïàïêó, ÷òîáû íà íåå íåáûëî ïðàâ íà çàïèñü.";
|
||||
if ( !file_exists($file_path."/".$file_name) ) return "Ôàéë {$url['path']} íå íàéäåí, åãî çàãðóçêà íåâîçìîæíà.";
|
||||
|
||||
if ( $url['query'] ) {parse_str( $url['query'] );}
|
||||
|
||||
ob_start();
|
||||
$tpl = new dle_template( );
|
||||
$tpl->dir = TEMPLATE_DIR;
|
||||
include $file_path."/".$file_name;
|
||||
return ob_get_clean();
|
||||
}
|
||||
return '{include file="'.$name.'"}';
|
||||
}
|
||||
|
||||
function sub_load_template( $tpl_name ) {
|
||||
|
||||
$tpl_name = totranslit( $tpl_name );
|
||||
|
||||
if( $tpl_name == '' || ! file_exists( $this->dir . DIRECTORY_SEPARATOR . $tpl_name ) ) {
|
||||
return "Îòñóòñòâóåò ôàéë øàáëîíà: " . $tpl_name ;
|
||||
return false;
|
||||
}
|
||||
$template = file_get_contents( $this->dir . DIRECTORY_SEPARATOR . $tpl_name );
|
||||
|
||||
if (strpos ( $template, "[aviable=" ) !== false) {$template = preg_replace ( "#\\[aviable=(.+?)\\](.*?)\\[/aviable\\]#ies", "\$this->check_module('\\1', '\\2')", $template );}
|
||||
if (strpos ( $template, "[not-aviable=" ) !== false) {$template = preg_replace ( "#\\[not-aviable=(.+?)\\](.*?)\\[/not-aviable\\]#ies", "\$this->check_module('\\1', '\\2', false)", $template );}
|
||||
if (strpos ( $template, "[not-group=" ) !== false) {$template = preg_replace ( "#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#ies", "\$this->check_group('\\1', '\\2', false)", $template );}
|
||||
if (strpos ( $this->template, "{if " ) !== false) {$this->template = preg_replace ( "#{if (.+?)}(.*?){/if}#ies", "$this->check_else('1', '2', false)", $this->template );}
|
||||
if (strpos ( $template, "[group=" ) !== false) {$template = preg_replace ( "#\\[group=(.+?)\\](.*?)\\[/group\\]#ies", "\$this->check_group('\\1', '\\2')", $template );}
|
||||
|
||||
return $template;
|
||||
}
|
||||
|
||||
function check_module($aviable, $block, $action = true) {
|
||||
global $dle_module;
|
||||
|
||||
$aviable = explode( '|', $aviable );
|
||||
|
||||
$block = str_replace( '\"', '"', $block );
|
||||
|
||||
if( $action ) {
|
||||
|
||||
if( ! (in_array( $dle_module, $aviable )) and ($aviable[0] != "global") ) return "";
|
||||
else return $block;
|
||||
|
||||
} else {
|
||||
|
||||
if( (in_array( $dle_module, $aviable )) ) return "";
|
||||
else return $block;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function check_group($groups, $block, $action = true) {
|
||||
global $member_id;
|
||||
|
||||
$groups = explode( ',', $groups );
|
||||
|
||||
if( $action ) {
|
||||
|
||||
if( ! in_array( $member_id['user_group'], $groups ) ) return "";
|
||||
|
||||
} else {
|
||||
|
||||
if( in_array( $member_id['user_group'], $groups ) ) return "";
|
||||
|
||||
}
|
||||
|
||||
$block = str_replace( '\"', '"', $block );
|
||||
|
||||
return $block;
|
||||
|
||||
}
|
||||
|
||||
function _clear() {
|
||||
|
||||
$this->data = array ();
|
||||
$this->block_data = array ();
|
||||
$this->copy_template = $this->template;
|
||||
|
||||
}
|
||||
|
||||
function clear() {
|
||||
|
||||
$this->data = array ();
|
||||
$this->block_data = array ();
|
||||
$this->copy_template = null;
|
||||
$this->template = null;
|
||||
|
||||
}
|
||||
|
||||
function global_clear() {
|
||||
|
||||
$this->data = array ();
|
||||
$this->block_data = array ();
|
||||
$this->result = array ();
|
||||
$this->copy_template = null;
|
||||
$this->template = null;
|
||||
|
||||
}
|
||||
|
||||
function compile($tpl) {
|
||||
if( count( $this->block_data ) ) {
|
||||
foreach ( $this->block_data as $key_find => $key_replace ) {
|
||||
$find_preg[] = $key_find;
|
||||
$replace_preg[] = $key_replace;
|
||||
}
|
||||
|
||||
$this->copy_template = preg_replace( $find_preg, $replace_preg, $this->copy_template );
|
||||
}
|
||||
|
||||
foreach ( $this->data as $key_find => $key_replace ) {
|
||||
$find[] = $key_find;
|
||||
$replace[] = $key_replace;
|
||||
}
|
||||
|
||||
$this->copy_template = str_replace( $find, $replace, $this->copy_template );
|
||||
|
||||
if( strpos( $this->copy_template, "{include file=" ) !== false ) {
|
||||
|
||||
$this->copy_template = preg_replace( "#\\{include file=['\"](.+?)['\"]\\}#ies", "\$this->load_file('\\1', 'php')", $this->copy_template );
|
||||
|
||||
}
|
||||
|
||||
if( isset( $this->result[$tpl] ) ) $this->result[$tpl] .= $this->copy_template;
|
||||
else $this->result[$tpl] = $this->copy_template;
|
||||
|
||||
$this->_clear();
|
||||
}
|
||||
|
||||
function check_else($condition, $block){
|
||||
global $GLOBALS;
|
||||
extract($GLOBALS, EXTR_SKIP, "");
|
||||
if(is_array($matches=explode("{else}",$block))) {
|
||||
$block=$matches[0];
|
||||
$else=$matches[1];
|
||||
}
|
||||
if(eval(("return $condition;"))) return str_replace( '"', '"', $block );
|
||||
return str_replace( '"', '"', $else );
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
if( ! defined( 'DATALIFEENGINE' ) ) {die( "Hacking attempt!" );}
|
||||
|
||||
class thumbnail {
|
||||
var $img;
|
||||
var $watermark_image_light;
|
||||
var $watermark_image_dark;
|
||||
|
||||
function thumbnail($imgfile) {
|
||||
//detect image format
|
||||
|
||||
$info = @getimagesize($imgfile);
|
||||
|
||||
if( $info[2] == 2 ) {
|
||||
$this->img['format'] = "JPEG";
|
||||
$this->img['src'] = @imagecreatefromjpeg( $imgfile );
|
||||
} elseif( $info[2] == 3 ) {
|
||||
$this->img['format'] = "PNG";
|
||||
$this->img['src'] = @imagecreatefrompng( $imgfile );
|
||||
} elseif( $info[2] == 1 ) {
|
||||
$this->img['format'] = "GIF";
|
||||
$this->img['src'] = @imagecreatefromgif( $imgfile );
|
||||
} else {
|
||||
echo "Not Supported File! Thumbnails can only be made from .jpg, gif and .png images!";
|
||||
@unlink( $imgfile );
|
||||
exit();
|
||||
}
|
||||
|
||||
if( !$this->img['src'] ) {
|
||||
echo "Not Supported File! Thumbnails can only be made from .jpg, gif and .png images!";
|
||||
@unlink( $imgfile );
|
||||
exit();
|
||||
|
||||
}
|
||||
|
||||
$this->img['lebar'] = @imagesx( $this->img['src'] );
|
||||
$this->img['tinggi'] = @imagesy( $this->img['src'] );
|
||||
$this->img['lebar_thumb'] = $this->img['lebar'];
|
||||
$this->img['tinggi_thumb'] = $this->img['tinggi'];
|
||||
//default quality jpeg
|
||||
$this->img['quality'] = 90;
|
||||
}
|
||||
|
||||
function size_auto($size = 100, $site = 0) {
|
||||
|
||||
$size = explode ("x", $size);
|
||||
|
||||
if ( count($size) == 2 ) {
|
||||
$size[0] = intval($size[0]);
|
||||
$size[1] = intval($size[1]);
|
||||
return $this->crop( intval($size[0]), intval($size[1]) );
|
||||
|
||||
} else {
|
||||
$size[0] = intval($size[0]);
|
||||
return $this->scale( intval($size[0]), $site);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function crop($nw, $nh) {
|
||||
|
||||
$w = $this->img['lebar'];
|
||||
$h = $this->img['tinggi'];
|
||||
|
||||
if( $w <= $nw AND $h <= $nh ) {
|
||||
$this->img['lebar_thumb'] = $w;
|
||||
$this->img['tinggi_thumb'] = $h;
|
||||
return 0;
|
||||
}
|
||||
|
||||
$nw = min($nw, $w);
|
||||
$nh = min($nh, $h);
|
||||
|
||||
$size_ratio = max($nw / $w, $nh / $h);
|
||||
|
||||
$src_w = ceil($nw / $size_ratio);
|
||||
$src_h = ceil($nh / $size_ratio);
|
||||
|
||||
$sx = floor(($w - $src_w)/2);
|
||||
$sy = floor(($h - $src_h)/2);
|
||||
|
||||
$this->img['des'] = imagecreatetruecolor($nw, $nh);
|
||||
|
||||
if ( $this->img['format'] == "PNG" ) {
|
||||
imagealphablending( $this->img['des'], false);
|
||||
imagesavealpha( $this->img['des'], true);
|
||||
}
|
||||
|
||||
imagecopyresampled($this->img['des'],$this->img['src'],0,0,$sx,$sy,$nw,$nh,$src_w,$src_h);
|
||||
|
||||
$this->img['src'] = $this->img['des'];
|
||||
return 1;
|
||||
}
|
||||
|
||||
function scale($size = 100, $site = 0) {
|
||||
|
||||
$site = intval( $site );
|
||||
|
||||
if( $this->img['lebar'] <= $size and $this->img['tinggi'] <= $size ) {
|
||||
$this->img['lebar_thumb'] = $this->img['lebar'];
|
||||
$this->img['tinggi_thumb'] = $this->img['tinggi'];
|
||||
return 0;
|
||||
}
|
||||
|
||||
switch ($site) {
|
||||
|
||||
case "1" :
|
||||
if( $this->img['lebar'] <= $size ) {
|
||||
$this->img['lebar_thumb'] = $this->img['lebar'];
|
||||
$this->img['tinggi_thumb'] = $this->img['tinggi'];
|
||||
return 0;
|
||||
} else {
|
||||
$this->img['lebar_thumb'] = $size;
|
||||
$this->img['tinggi_thumb'] = ($this->img['lebar_thumb'] / $this->img['lebar']) * $this->img['tinggi'];
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "2" :
|
||||
if( $this->img['tinggi'] <= $size ) {
|
||||
$this->img['lebar_thumb'] = $this->img['lebar'];
|
||||
$this->img['tinggi_thumb'] = $this->img['tinggi'];
|
||||
return 0;
|
||||
} else {
|
||||
$this->img['tinggi_thumb'] = $size;
|
||||
$this->img['lebar_thumb'] = ($this->img['tinggi_thumb'] / $this->img['tinggi']) * $this->img['lebar'];
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default :
|
||||
|
||||
if( $this->img['lebar'] >= $this->img['tinggi'] ) {
|
||||
$this->img['lebar_thumb'] = $size;
|
||||
$this->img['tinggi_thumb'] = ($this->img['lebar_thumb'] / $this->img['lebar']) * $this->img['tinggi'];
|
||||
|
||||
} else {
|
||||
|
||||
$this->img['tinggi_thumb'] = $size;
|
||||
$this->img['lebar_thumb'] = ($this->img['tinggi_thumb'] / $this->img['tinggi']) * $this->img['lebar'];
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
if ($this->img['lebar_thumb'] < 1 ) $this->img['lebar_thumb'] = 1;
|
||||
if ($this->img['tinggi_thumb'] < 1 ) $this->img['tinggi_thumb'] = 1;
|
||||
$this->img['des'] = imagecreatetruecolor( $this->img['lebar_thumb'], $this->img['tinggi_thumb'] );
|
||||
|
||||
if ( $this->img['format'] == "PNG" ) {
|
||||
imagealphablending( $this->img['des'], false);
|
||||
imagesavealpha( $this->img['des'], true);
|
||||
}
|
||||
|
||||
@imagecopyresampled( $this->img['des'], $this->img['src'], 0, 0, 0, 0, $this->img['lebar_thumb'], $this->img['tinggi_thumb'], $this->img['lebar'], $this->img['tinggi'] );
|
||||
|
||||
$this->img['src'] = $this->img['des'];
|
||||
return 1;
|
||||
|
||||
}
|
||||
|
||||
function jpeg_quality($quality = 90) {
|
||||
//jpeg quality
|
||||
$this->img['quality'] = $quality;
|
||||
}
|
||||
|
||||
function save($save = "") {
|
||||
|
||||
if( $this->img['format'] == "JPG" || $this->img['format'] == "JPEG" ) {
|
||||
//JPEG
|
||||
imagejpeg( $this->img['src'], $save, $this->img['quality'] );
|
||||
} elseif( $this->img['format'] == "PNG" ) {
|
||||
//PNG
|
||||
imagealphablending( $this->img['src'], false);
|
||||
imagesavealpha( $this->img['src'], true);
|
||||
imagepng( $this->img['src'], $save );
|
||||
} elseif( $this->img['format'] == "GIF" ) {
|
||||
//GIF
|
||||
imagegif( $this->img['src'], $save );
|
||||
}
|
||||
|
||||
imagedestroy( $this->img['src'] );
|
||||
}
|
||||
|
||||
function show() {
|
||||
if( $this->img['format'] == "JPG" || $this->img['format'] == "JPEG" ) {
|
||||
//JPEG
|
||||
imageJPEG( $this->img['src'], "", $this->img['quality'] );
|
||||
} elseif( $this->img['format'] == "PNG" ) {
|
||||
//PNG
|
||||
imagePNG( $this->img['src'] );
|
||||
} elseif( $this->img['format'] == "GIF" ) {
|
||||
//GIF
|
||||
imageGIF( $this->img['src'] );
|
||||
}
|
||||
|
||||
imagedestroy( $this->img['src'] );
|
||||
}
|
||||
|
||||
// *************************************************************************
|
||||
function insert_watermark($min_image) {
|
||||
global $config;
|
||||
$margin = 7;
|
||||
|
||||
$this->watermark_image_light = ROOT_DIR . '/templates/' . $config['skin'] . '/images/watermark.png';
|
||||
$this->watermark_image_dark = ROOT_DIR . '/templates/' . $config['skin'] . '/images/watermark.png';
|
||||
|
||||
$image_width = imagesx( $this->img['src'] );
|
||||
$image_height = imagesy( $this->img['src'] );
|
||||
|
||||
list ( $watermark_width, $watermark_height ) = getimagesize( $this->watermark_image_light );
|
||||
|
||||
$watermark_x = $image_width - $margin - $watermark_width + $margin;
|
||||
//$watermark_y = $image_height - $margin - $watermark_height;
|
||||
$watermark_y = $image_height - $watermark_height;
|
||||
|
||||
$watermark_x2 = $watermark_x + $watermark_width;
|
||||
$watermark_y2 = $watermark_y + $watermark_height;
|
||||
|
||||
if( $watermark_x < 0 or $watermark_y < 0 or $watermark_x2 > $image_width or $watermark_y2 > $image_height or $image_width < $min_image or $image_height < $min_image ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$test = imagecreatetruecolor( 1, 1 );
|
||||
imagecopyresampled( $test, $this->img['src'], 0, 0, $watermark_x, $watermark_y, 1, 1, $watermark_width, $watermark_height );
|
||||
$rgb = imagecolorat( $test, 0, 0 );
|
||||
|
||||
$r = ($rgb >> 16) & 0xFF;
|
||||
$g = ($rgb >> 8) & 0xFF;
|
||||
$b = $rgb & 0xFF;
|
||||
|
||||
$max = min( $r, $g, $b );
|
||||
$min = max( $r, $g, $b );
|
||||
$lightness = ( double ) (($max + $min) / 510.0);
|
||||
imagedestroy( $test );
|
||||
|
||||
$watermark_image = ($lightness < 0.5) ? $this->watermark_image_light : $this->watermark_image_dark;
|
||||
|
||||
$watermark = imagecreatefrompng( $watermark_image );
|
||||
|
||||
imagealphablending( $this->img['src'], TRUE );
|
||||
imagealphablending( $watermark, TRUE );
|
||||
|
||||
if( $this->img['format'] == "PNG" ) {
|
||||
$png8fix = imagecreatetruecolor( $image_width, $image_height );
|
||||
imagecopy( $png8fix, $this->img['src'], 0, 0, 0, 0, $image_width, $image_height );
|
||||
imagecopy( $png8fix, $watermark, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height );
|
||||
imagecopy( $this->img['src'], $png8fix, 0, 0, 0, 0, $image_width, $image_height );
|
||||
imagedestroy( $png8fix );
|
||||
}else imagecopy( $this->img['src'], $watermark, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height );
|
||||
|
||||
imagedestroy( $watermark );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,537 @@
|
||||
<?php
|
||||
class Torrent {
|
||||
const timeout = 30;
|
||||
static protected $_errors = array();
|
||||
|
||||
public function __construct ( $data = null, $meta = array(), $piece_length = 256 ) {
|
||||
if ( is_null( $data ) )
|
||||
return false;
|
||||
if ( $piece_length < 32 || $piece_length > 4096 )
|
||||
return self::set_error( new Exception( 'Invalid piece lenth, must be between 32 and 4096' ) );
|
||||
if ( is_string( $meta ) )
|
||||
$meta = array( 'announce' => $meta );
|
||||
if ( $this->build( $data, $piece_length * 1024 ) )
|
||||
$this->touch();
|
||||
else
|
||||
$meta = array_merge( $meta, $this->decode( $data ) );
|
||||
foreach( $meta as $key => $value )
|
||||
$this->{$key} = $value;
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
return $this->encode( $this );
|
||||
}
|
||||
|
||||
public function error() {
|
||||
return empty( self::$_errors ) ?
|
||||
false :
|
||||
self::$_errors[0]->getMessage();
|
||||
}
|
||||
|
||||
public function errors() {
|
||||
return empty( self::$_errors ) ?
|
||||
false :
|
||||
self::$_errors;
|
||||
}
|
||||
|
||||
public function announce ( $announce = null ) {
|
||||
if ( is_null( $announce ) )
|
||||
return ! isset( $this->{'announce-list'} ) ?
|
||||
isset( $this->announce ) ? $this->announce : null :
|
||||
$this->{'announce-list'};
|
||||
$this->touch();
|
||||
if ( is_string( $announce ) && isset( $this->announce ) )
|
||||
return $this->{'announce-list'} = self::announce_list( isset( $this->{'announce-list'} ) ? $this->{'announce-list'} : $this->announce, $announce );
|
||||
unset( $this->{'announce-list'} );
|
||||
if ( is_array( $announce ) || is_object( $announce ) )
|
||||
if ( ( $this->announce = self::first_announce( $announce ) ) && count( $announce ) > 1 )
|
||||
return $this->{'announce-list'} = self::announce_list( $announce );
|
||||
else
|
||||
return $this->announce;
|
||||
if ( ! isset( $this->announce ) && $announce )
|
||||
return $this->announce = (string) $announce;
|
||||
unset( $this->announce );
|
||||
}
|
||||
|
||||
public function comment ( $comment = null ) {
|
||||
return is_null( $comment ) ?
|
||||
isset( $this->comment ) ? $this->comment : null :
|
||||
$this->touch( $this->comment = (string) $comment );
|
||||
}
|
||||
|
||||
public function name ( $name = null ) {
|
||||
return is_null( $name ) ?
|
||||
isset( $this->info['name'] ) ? $this->info['name'] : null :
|
||||
$this->touch( $this->info['name'] = (string) $name );
|
||||
}
|
||||
|
||||
public function is_private ( $private = null ) {
|
||||
return is_null( $private ) ?
|
||||
! empty( $this->info['private'] ) :
|
||||
$this->touch( $this->info['private'] = $private ? 1 : 0 );
|
||||
}
|
||||
|
||||
public function url_list ( $urls = null ) {
|
||||
return is_null( $urls ) ?
|
||||
isset( $this->{'url-list'} ) ? $this->{'url-list'} : null :
|
||||
$this->touch( $this->{'url-list'} = is_string( $urls) ? $urls : (array) $urls );
|
||||
}
|
||||
|
||||
public function httpseeds ( $urls = null ) {
|
||||
return is_null( $urls ) ?
|
||||
isset( $this->httpseeds ) ? $this->httpseeds : null :
|
||||
$this->touch( $this->httpseeds = (array) $urls );
|
||||
}
|
||||
|
||||
public function piece_length () {
|
||||
return isset( $this->info['piece length'] ) ?
|
||||
$this->info['piece length'] :
|
||||
null;
|
||||
}
|
||||
|
||||
public function hash_info () {
|
||||
return isset( $this->info ) ?
|
||||
sha1( self::encode( $this->info ) ) :
|
||||
null;
|
||||
}
|
||||
|
||||
public function content ( $precision = null ) {
|
||||
$files = array();
|
||||
if ( isset( $this->info['files'] ) && is_array( $this->info['files'] ) )
|
||||
foreach ( $this->info['files'] as $file )
|
||||
$files[self::path( $file['path'], $this->info['name'] )] = $precision ?
|
||||
self::format( $file['length'], $precision ) :
|
||||
$file['length'];
|
||||
elseif ( isset( $this->info['name'] ) )
|
||||
$files[$this->info['name']] = $precision ?
|
||||
self::format( $this->info['length'], $precision ) :
|
||||
$this->info['length'];
|
||||
return $files;
|
||||
}
|
||||
|
||||
public function offset () {
|
||||
$files = array();
|
||||
$size = 0;
|
||||
if ( isset( $this->info['files'] ) && is_array( $this->info['files'] ) )
|
||||
foreach ( $this->info['files'] as $file )
|
||||
$files[self::path( $file['path'], $this->info['name'] )] = array(
|
||||
'startpiece' => floor( $size / $this->info['piece length'] ),
|
||||
'offset' => fmod( $size, $this->info['piece length'] ),
|
||||
'size' => $size += $file['length'],
|
||||
'endpiece' => floor( $size / $this->info['piece length'] )
|
||||
);
|
||||
elseif ( isset( $this->info['name'] ) )
|
||||
$files[$this->info['name']] = array(
|
||||
'startpiece' => 0,
|
||||
'offset' => 0,
|
||||
'size' => $this->info['length'],
|
||||
'endpiece' => floor( $this->info['length'] / $this->info['piece length'] )
|
||||
);
|
||||
return $files;
|
||||
}
|
||||
|
||||
public function size ( $precision = null ) {
|
||||
$size = 0;
|
||||
if ( isset( $this->info['files'] ) && is_array( $this->info['files'] ) )
|
||||
foreach ( $this->info['files'] as $file )
|
||||
$size += $file['length'];
|
||||
elseif ( isset( $this->info['name'] ) )
|
||||
$size = $this->info['length'];
|
||||
return is_null( $precision ) ?
|
||||
$size :
|
||||
self::format( $size, $precision );
|
||||
}
|
||||
|
||||
public function scrape ( $announce = null, $hash_info = null, $timeout = self::timeout ) {
|
||||
$packed_hash = urlencode( pack('H*', $hash_info ? $hash_info : $this->hash_info() ) );
|
||||
$handles = $scrape = array();
|
||||
if ( ! function_exists( 'curl_multi_init' ) )
|
||||
return self::set_error( new Exception( 'Install CURL with "curl_multi_init" enabled' ) );
|
||||
$curl = curl_multi_init();
|
||||
foreach ( (array) ($announce ? $announce : $this->announce()) as $tier )
|
||||
foreach ( (array) $tier as $tracker ) {
|
||||
$tracker = str_ireplace( array( 'udp://', '/announce', ':80/' ), array( 'http://', '/scrape', '/' ), $tracker );
|
||||
if ( isset( $handles[$tracker] ) )
|
||||
continue;
|
||||
$handles[$tracker] = curl_init( $tracker . '?info_hash=' . $packed_hash );
|
||||
curl_setopt( $handles[$tracker], CURLOPT_RETURNTRANSFER, true );
|
||||
curl_setopt( $handles[$tracker], CURLOPT_TIMEOUT, $timeout );
|
||||
curl_multi_add_handle( $curl, $handles[$tracker] );
|
||||
}
|
||||
do {
|
||||
while ( ( $state = curl_multi_exec( $curl, $running ) ) == CURLM_CALL_MULTI_PERFORM );
|
||||
if( $state != CURLM_OK )
|
||||
continue;
|
||||
while ( $done = curl_multi_info_read( $curl ) ) {
|
||||
$info = curl_getinfo( $done['handle'] );
|
||||
$tracker = explode( '?', $info['url'], 2 );
|
||||
$tracker = array_shift( $tracker );
|
||||
if ( empty( $info['http_code'] ) ) {
|
||||
$scrape[$tracker] = self::set_error( new Exception( 'Tracker request timeout (' . $timeout . 's)' ), true );
|
||||
continue;
|
||||
} elseif ( $info['http_code'] != 200 ) {
|
||||
$scrape[$tracker] = self::set_error( new Exception( 'Tracker request failed (' . $info['http_code'] . ' code)' ), true );
|
||||
continue;
|
||||
}
|
||||
$data = curl_multi_getcontent( $done['handle'] );
|
||||
$stats = self::decode_data( $data );
|
||||
curl_multi_remove_handle( $curl, $done['handle'] );
|
||||
$scrape[$tracker] = empty( $stats['files'] ) ?
|
||||
self::set_error( new Exception( 'Empty scrape data' ), true ) :
|
||||
array_shift( $stats['files'] ) + ( empty( $stats['flags'] ) ? array() : $stats['flags'] );
|
||||
}
|
||||
} while ( $running );
|
||||
curl_multi_close( $curl );
|
||||
return $scrape;
|
||||
}
|
||||
|
||||
public function save ( $filename = null ) {
|
||||
return file_put_contents( is_null( $filename ) ? $this->info['name'] . '.torrent' : $filename, $this->encode( $this ) );
|
||||
}
|
||||
|
||||
public function send ( $filename = null ) {
|
||||
$data = $this->encode( $this );
|
||||
header( 'Content-type: application/x-bittorrent' );
|
||||
header( 'Content-Length: ' . strlen( $data ) );
|
||||
header( 'Content-Disposition: attachment; filename="[files-sib.net]' . ( is_null( $filename ) ? $this->info['name'] . '.torrent' : $filename ) . '"' );
|
||||
exit( $data );
|
||||
}
|
||||
|
||||
public function magnet ( $html = true ) {
|
||||
$ampersand = $html ? '&' : '&';
|
||||
return sprintf( 'magnet:?xt=urn:btih:%2$s%1$sdn=%3$s%1$sxl=%4$d%1$str=%5$s', $ampersand, $this->hash_info(), urlencode( $this->name() ), $this->size(), implode( $ampersand .'tr=', self::untier( $this->announce() ) ) );
|
||||
}
|
||||
|
||||
static public function encode ( $mixed ) {
|
||||
switch ( gettype( $mixed ) ) {
|
||||
case 'integer':
|
||||
case 'double':
|
||||
return self::encode_integer( $mixed );
|
||||
case 'object':
|
||||
$mixed = get_object_vars( $mixed );
|
||||
case 'array':
|
||||
return self::encode_array( $mixed );
|
||||
default:
|
||||
return self::encode_string( (string) $mixed );
|
||||
}
|
||||
}
|
||||
|
||||
static private function encode_string ( $string ) {
|
||||
return strlen( $string ) . ':' . $string;
|
||||
}
|
||||
|
||||
static private function encode_integer ( $integer ) {
|
||||
return 'i' . $integer . 'e';
|
||||
}
|
||||
|
||||
static private function encode_array ( $array ) {
|
||||
if ( self::is_list( $array ) ) {
|
||||
$return = 'l';
|
||||
foreach ( $array as $value )
|
||||
$return .= self::encode( $value );
|
||||
} else {
|
||||
ksort( $array, SORT_STRING );
|
||||
$return = 'd';
|
||||
foreach ( $array as $key => $value )
|
||||
$return .= self::encode( strval( $key ) ) . self::encode( $value );
|
||||
}
|
||||
return $return . 'e';
|
||||
}
|
||||
|
||||
static protected function decode ( $string ) {
|
||||
$data = is_file( $string ) || self::url_exists( $string ) ?
|
||||
self::file_get_contents( $string ) :
|
||||
$string;
|
||||
return (array) self::decode_data( $data );
|
||||
}
|
||||
|
||||
static private function decode_data ( & $data ) {
|
||||
switch( self::char( $data ) ) {
|
||||
case 'i':
|
||||
$data = substr( $data, 1 );
|
||||
return self::decode_integer( $data );
|
||||
case 'l':
|
||||
$data = substr( $data, 1 );
|
||||
return self::decode_list( $data );
|
||||
case 'd':
|
||||
$data = substr( $data, 1 );
|
||||
return self::decode_dictionary( $data );
|
||||
default:
|
||||
return self::decode_string( $data );
|
||||
}
|
||||
}
|
||||
|
||||
static private function decode_dictionary ( & $data ) {
|
||||
$dictionary = array();
|
||||
$previous = null;
|
||||
while ( ( $char = self::char( $data ) ) != 'e' ) {
|
||||
if ( $char === false )
|
||||
return self::set_error( new Exception( 'Unterminated dictionary' ) );
|
||||
if ( ! ctype_digit( $char ) )
|
||||
return self::set_error( new Exception( 'Invalid dictionary key' ) );
|
||||
$key = self::decode_string( $data );
|
||||
if ( isset( $dictionary[$key] ) )
|
||||
return self::set_error( new Exception( 'Duplicate dictionary key' ) );
|
||||
if ( $key < $previous )
|
||||
return self::set_error( new Exception( 'Missorted dictionary key' ) );
|
||||
$dictionary[$key] = self::decode_data( $data );
|
||||
$previous = $key;
|
||||
}
|
||||
$data = substr( $data, 1 );
|
||||
return $dictionary;
|
||||
}
|
||||
|
||||
static private function decode_list ( & $data ) {
|
||||
$list = array();
|
||||
while ( ( $char = self::char( $data ) ) != 'e' ) {
|
||||
if ( $char === false )
|
||||
return self::set_error( new Exception( 'Unterminated list' ) );
|
||||
$list[] = self::decode_data( $data );
|
||||
}
|
||||
$data = substr( $data, 1 );
|
||||
return $list;
|
||||
}
|
||||
|
||||
static private function decode_string ( & $data ) {
|
||||
if ( self::char( $data ) === '0' && substr( $data, 1, 1 ) != ':' )
|
||||
self::set_error( new Exception( 'Invalid string length, leading zero' ) );
|
||||
if ( ! $colon = @strpos( $data, ':' ) )
|
||||
return self::set_error( new Exception( 'Invalid string length, colon not found' ) );
|
||||
$length = intval( substr( $data, 0, $colon ) );
|
||||
if ( $length + $colon + 1 > strlen( $data ) )
|
||||
return self::set_error( new Exception( 'Invalid string, input too short for string length' ) );
|
||||
$string = substr( $data, $colon + 1, $length );
|
||||
$data = substr( $data, $colon + $length + 1 );
|
||||
return $string;
|
||||
}
|
||||
|
||||
static private function decode_integer ( & $data ) {
|
||||
$start = 0;
|
||||
$end = strpos( $data, 'e');
|
||||
if ( $end === 0 )
|
||||
self::set_error( new Exception( 'Empty integer' ) );
|
||||
if ( self::char( $data ) == '-' )
|
||||
$start++;
|
||||
if ( substr( $data, $start, 1 ) == '0' && $end > $start + 1 )
|
||||
self::set_error( new Exception( 'Leading zero in integer' ) );
|
||||
if ( ! ctype_digit( substr( $data, $start, $start ? $end - 1 : $end ) ) )
|
||||
self::set_error( new Exception( 'Non-digit characters in integer' ) );
|
||||
$integer = substr( $data, 0, $end );
|
||||
$data = substr( $data, $end + 1 );
|
||||
|
||||
return 0 + $integer;
|
||||
}
|
||||
|
||||
protected function build ( $data, $piece_length ) {
|
||||
if ( is_null( $data ) )
|
||||
return false;
|
||||
elseif ( is_array( $data ) && self::is_list( $data ) )
|
||||
return $this->info = $this->files( $data, $piece_length );
|
||||
elseif ( is_dir( $data ) )
|
||||
return $this->info = $this->folder( $data, $piece_length );
|
||||
elseif ( ( is_file( $data ) || self::url_exists( $data ) ) && ! self::is_torrent( $data ) )
|
||||
return $this->info = $this->file( $data, $piece_length );
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function touch ( $void = null ) {
|
||||
$this->{'created by'} = 'Files-Sib.NET Tracker';
|
||||
$this->{'creation date'} = time();
|
||||
return $void;
|
||||
}
|
||||
|
||||
static protected function set_error ( $exception, $message = false ) {
|
||||
return ( array_unshift( self::$_errors, $exception ) && $message ) ? $exception->getMessage() : false;
|
||||
}
|
||||
|
||||
static protected function announce_list( $announce, $merge = array() ) {
|
||||
return array_map( create_function( '$a', 'return (array) $a;' ), array_merge( (array) $announce, (array) $merge ) );
|
||||
}
|
||||
|
||||
static protected function first_announce( $announce ) {
|
||||
while ( is_array( $announce ) )
|
||||
$announce = reset( $announce );
|
||||
return $announce;
|
||||
}
|
||||
|
||||
static protected function pack ( & $data ) {
|
||||
return pack('H*', sha1( $data ) ) . ( $data = null );
|
||||
}
|
||||
|
||||
static protected function path ( $path, $folder ) {
|
||||
array_unshift( $path, $folder );
|
||||
return join( DIRECTORY_SEPARATOR, $path );
|
||||
}
|
||||
|
||||
static protected function is_list ( $array ) {
|
||||
foreach ( array_keys( $array ) as $key )
|
||||
if ( ! is_int( $key ) )
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private function pieces ( $handle, $piece_length, $last = true ) {
|
||||
static $piece, $length;
|
||||
if ( empty( $length ) )
|
||||
$length = $piece_length;
|
||||
$pieces = null;
|
||||
while ( ! feof( $handle ) ) {
|
||||
if ( ( $length = strlen( $piece .= fread( $handle, $length ) ) ) == $piece_length )
|
||||
$pieces .= self::pack( $piece );
|
||||
elseif ( ( $length = $piece_length - $length ) < 0 )
|
||||
return self::set_error( new Exception( 'Invalid piece length!' ) );
|
||||
}
|
||||
fclose( $handle );
|
||||
return $pieces . ( $last && $piece ? self::pack( $piece ) : null);
|
||||
}
|
||||
|
||||
private function file ( $file, $piece_length ) {
|
||||
if ( ! $handle = self::fopen( $file, $size = self::filesize( $file ) ) )
|
||||
return self::set_error( new Exception( 'Failed to open file: "' . $file . '"' ) );
|
||||
if ( self::is_url( $file ) )
|
||||
$this->url_list( $file );
|
||||
$path = explode( DIRECTORY_SEPARATOR, $file );
|
||||
return array(
|
||||
'length' => $size,
|
||||
'name' => end( $path ),
|
||||
'piece length' => $piece_length,
|
||||
'pieces' => $this->pieces( $handle, $piece_length )
|
||||
);
|
||||
}
|
||||
|
||||
private function files ( $files, $piece_length ) {
|
||||
if ( ! self::is_url( current( $files ) ) )
|
||||
$files = array_map( 'realpath', $files );
|
||||
sort( $files );
|
||||
usort( $files, create_function( '$a,$b', 'return strrpos($a,DIRECTORY_SEPARATOR)-strrpos($b,DIRECTORY_SEPARATOR);' ) );
|
||||
$first = current( $files );
|
||||
$root = dirname( $first );
|
||||
if ( $url = self::is_url( $first ) )
|
||||
$this->url_list( dirname( $root ) . DIRECTORY_SEPARATOR );
|
||||
$path = explode( DIRECTORY_SEPARATOR, dirname( $url ? $first : realpath( $first ) ) );
|
||||
$pieces = null; $info_files = array(); $count = count( $files ) - 1;
|
||||
foreach ( $files as $i => $file ) {
|
||||
if ( $path != array_intersect_assoc( $file_path = explode( DIRECTORY_SEPARATOR, $file ), $path ) ) {
|
||||
self::set_error( new Exception( 'Files must be in the same folder: "' . $file . '" discarded' ) );
|
||||
continue;
|
||||
}
|
||||
if ( ! $handle = self::fopen( $file, $filesize = self::filesize( $file ) ) ) {
|
||||
self::set_error( new Exception( 'Failed to open file: "' . $file . '" discarded' ) );
|
||||
continue;
|
||||
}
|
||||
$pieces .= $this->pieces( $handle, $piece_length, $count == $i );
|
||||
$info_files[] = array(
|
||||
'length' => $filesize,
|
||||
'path' => array_diff( $file_path, $path )
|
||||
);
|
||||
}
|
||||
return array(
|
||||
'files' => $info_files,
|
||||
'name' => end( $path ),
|
||||
'piece length' => $piece_length,
|
||||
'pieces' => $pieces
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
private function folder ( $dir, $piece_length ) {
|
||||
return $this->files( self::scandir( $dir ), $piece_length );
|
||||
}
|
||||
|
||||
static private function char ( $data ) {
|
||||
return empty( $data ) ?
|
||||
false :
|
||||
substr( $data, 0, 1 );
|
||||
}
|
||||
|
||||
static public function format ( $size, $precision = 2 ) {
|
||||
$units = array ('octets', 'Kb', 'Mb', 'Gb', 'Tb');
|
||||
while( ( $next = next( $units ) ) && $size > 1024 )
|
||||
$size /= 1024;
|
||||
return round( $size, $precision ) . ' ' . ( $next ? prev( $units ) : end( $units ) );
|
||||
}
|
||||
|
||||
static public function filesize ( $file ) {
|
||||
if ( is_file( $file ) )
|
||||
return (double) sprintf( '%u', @filesize( $file ) );
|
||||
else if ( $content_length = preg_grep( $pattern = '#^Content-Length:\s+(\d+)$#i', (array) @get_headers( $file ) ) )
|
||||
return (int) preg_replace( $pattern, '$1', reset( $content_length ) );
|
||||
}
|
||||
|
||||
static public function fopen ( $file, $size = null ) {
|
||||
if ( ( is_null( $size ) ? self::filesize( $file ) : $size ) <= 2 * pow( 1024, 3 ) )
|
||||
return fopen( $file, 'r' );
|
||||
elseif ( PHP_OS != 'Linux' )
|
||||
return self::set_error( new Exception( 'File size is greater than 2GB. This is only supported under Linux' ) );
|
||||
elseif ( ! is_readable( $file ) )
|
||||
return false;
|
||||
else
|
||||
return popen( 'cat ' . escapeshellarg( realpath( $file ) ), 'r' );
|
||||
}
|
||||
|
||||
static public function scandir ( $dir ) {
|
||||
$paths = array();
|
||||
foreach ( scandir( $dir ) as $item )
|
||||
if ( $item != '.' && $item != '..' )
|
||||
if ( is_dir( $path = realpath( $dir . DIRECTORY_SEPARATOR . $item ) ) )
|
||||
$paths = array_merge( self::scandir( $path ), $paths );
|
||||
else
|
||||
$paths[] = $path;
|
||||
return $paths;
|
||||
}
|
||||
|
||||
static public function is_url ( $url ) {
|
||||
return preg_match( '#^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$#i', $url );
|
||||
}
|
||||
|
||||
static public function url_exists ( $url ) {
|
||||
return self::is_url( $url ) ?
|
||||
(bool) self::filesize ( $url ) :
|
||||
false;
|
||||
}
|
||||
|
||||
static public function is_torrent ( $file, $timeout = self::timeout ) {
|
||||
return ( $start = self::file_get_contents( $file, $timeout, 0, 11 ) ) && $start === 'd8:announce' || $start === 'd10:created';
|
||||
}
|
||||
|
||||
static public function file_get_contents ( $file, $timeout = self::timeout, $offset = null, $length = null ) {
|
||||
if ( is_file( $file ) || ini_get( 'allow_url_fopen' ) ) {
|
||||
$context = ! is_file( $file ) && $timeout ?
|
||||
stream_context_create( array( 'http' => array( 'timeout' => $timeout ) ) ) :
|
||||
null;
|
||||
return ! is_null( $offset ) ? $length ?
|
||||
@file_get_contents( $file, false, $context, $offset, $length ) :
|
||||
@file_get_contents( $file, false, $context, $offset ) :
|
||||
@file_get_contents( $file, false, $context );
|
||||
} elseif ( ! function_exists( 'curl_init' ) )
|
||||
return self::set_error( new Exception( 'Install CURL or enable "allow_url_fopen"' ) );
|
||||
$handle = curl_init( $file );
|
||||
if ( $timeout )
|
||||
curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
|
||||
if ( $offset || $length )
|
||||
curl_setopt( $handle, CURLOPT_RANGE, $offset . '-' . ( $length ? $offset + $length -1 : null ) );
|
||||
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, 1 );
|
||||
$content = curl_exec( $handle );
|
||||
$size = curl_getinfo( $handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD );
|
||||
curl_close( $handle );
|
||||
return ( $offset && $size == -1 ) || ( $length && $length != $size ) ? $length ?
|
||||
substr( $content, $offset, $length) :
|
||||
substr( $content, $offset) :
|
||||
$content;
|
||||
}
|
||||
|
||||
static public function untier( $announces ) {
|
||||
$list = array();
|
||||
foreach ( (array) $announces as $tier ) {
|
||||
is_array( $tier ) ?
|
||||
$list = array_merge( $list, self::untier( $tier ) ) :
|
||||
array_push( $list, $tier );
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public function upload($torrent){
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user