Version 1.12

This commit is contained in:
nemunaire 2009-11-01 12:00:00 +01:00
commit de31cd3e9a
1373 changed files with 156282 additions and 45238 deletions

View file

@ -0,0 +1,806 @@
<?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;
}
}
}
}
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
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 {
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
?>

View file

@ -0,0 +1,139 @@
<?php
/***************************************************************************
* class.alliance.php
* --------------------
* begin : Vendredi 10 octobre 2008
* update : Samedi 11 octobre 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Alliance extends Surface{
var $id,
$race,
$fondateur,
$sante,
$nom,
$tag,
$galaxie,
$ss,
$nom_asteroide,
$image_asteroide,
$debris_met,
$debris_cri,
$credits,
$metal,
$cristal,
$hydrogene;
/**
* Constructeur
* @param int $id id de l'alliance à importer
*
* @return void
* @access public
*/
function Alliance($id = 0){
if (!empty($id)) {
global $var___db, $config, $table_alliances;
global $alli_batimentVAR, $nomvaisnVAR;
$bdd = new bdd();
$bdd->connexion();
$bdd->escape($id);
$alli = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
if (!empty($alli)) {
$this->id = $alli["id"];
$this->race = $alli["race"];
$this->fondateur = $alli["fondateur"];
$this->sante = $alli["sante"];
$this->nom = $alli["nom"];
$this->tag = $alli["tag"];
$this->galaxie = $alli["galaxie"];
$this->ss = $alli["ss"];
$this->nom_asteroide = $alli["nom_asteroide"];
$this->image_asteroide = $alli["image_asteroide"];
$this->debris_met = $alli["debris_met"];
$this->debris_cri = $alli["debris_cri"];
$this->credits = $alli["credits"];
$this->metal = $alli["metal"];
$this->cristal = $alli["cristal"];
$this->hydrogene = $alli["hydrogene"];
foreach($alli_batimentVAR as $bat){
$this->batiments[] = $alli[$bat];
}
$this->file_bat = unserialize($alli["file_bat"]);
foreach($nomvaisnVAR as $vais){
$this->vaisseaux[] = $plan[$vais];
}
$this->file_vais = unserialize($alli["file_vais"]);
$this->actualiser();
}
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true){
//Actualisation des files d'attentes
if ($actuFile) {
$this->file_pret("alli_batiments");
$this->file_pret("vaisseaux");
}
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct(){
global $var___db, $config, $table_alliances;
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
$bdd->connexion();
for($i = 0; $i < $nb; $i++){
if (!is_array($this->{$this->modif[$i]})) {
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]})) $out[] .= $this->modif[$i]." = ".$this->{$this->modif[$i]};
else $out[] .= $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else {
if (ereg('file', $this->modif[$i])) {
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] .= $this->modif[$i]." = '$prep'";
}
else {
if ($this->modif[$i] == "batiments") $calc = "batiment";
elseif ($this->modif[$i] == "alli_batiments") $calc = "alli_batiment";
elseif ($this->modif[$i] == "technologies") $calc = "technolo";
elseif ($this->modif[$i] == "casernes")$calc = "casernen";
elseif ($this->modif[$i] == "terrestres") $calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux") $calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat") $calc = "coeff";
if (!isset(${$calc.'VAR'})) global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++){
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] .= ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out)) $plan = $bdd->unique_query("UPDATE $table_alliances SET ".implode(', ', $out)." WHERE id = ".$this->id.";");
$bdd->deconnexion();
}
}
?>

View file

@ -0,0 +1,637 @@
<?php
include_once("game/Class/class.surface.php");
/***************************************************************************
* class.asteroide.php
* ---------------------
* begin : Jeudi 25 décembre 2008
* update : Dimanche 4 janvier 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Asteroide extends Surface
{
var $fondateur,
$sante,
$nom_alliance,
$tag,
$nom_asteroide,
$image_asteroide,
$credits_alliance;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function Asteroide($id = 0)
{
if (!empty($id)) {
global $table_alliances, $SESS;
global $alli_batimentVAR, $nomvaisnVAR;
$bdd = new bdd();
//On traite le cas où l'on envoie les coordonnées
if (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$bdd->deconnexion();
}
else
die('Erreur #04 : Format de recherche d\'asteroide incorrect !');
if (!empty($plan))
{
$this->id = $plan["id"];
parent::User($SESS->values['id']); //On utilise le numéro d'utilisateur enregistré en session
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->image = $this->image_asteroide = $plan["image_asteroide"];
$this->debris_met = $plan["debris_met"];
$this->debris_cri = $plan["debris_cri"];
$this->metal = $plan["metal"];
$this->cristal = $plan["cristal"];
$this->hydrogene = $plan["hydrogene"];
foreach($alli_batimentVAR as $bat)
$this->batiments[] = $plan[$bat];
if (!empty($plan["file_bat"]))
$this->file_bat = unserialize($plan["file_bat"]);
else
$this->file_bat = new File('alli_batiments');
foreach($nomvaisnVAR as $vais)
$this->vaisseaux[] = $plan[$vais];
if (!empty($plan["file_vais"]))
$this->file_vais = unserialize($plan["file_vais"]);
else
$this->file_vais = new File('vaisseaux');
}
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true, $first = false)
{
//Actualisation des files d'attentes
if ($actuFile)
{
$this->file_ready("batiments");
$this->file_readyTechno("technologies");
$this->file_ready("casernes");
$this->file_ready("terrestres");
$this->file_ready("vaisseaux");
}
//Calcul de la capacité de stockage maximale
if (!empty($timestamp_lastSilo))
{
$this->cap = pow(2, $this->batiments[10]-1) * 100000;
$capnouv = pow(2, $this->batiments[10]) * 100000;
}
else
$this->cap = pow(2, $this->batiments[10]) * 100000;
//Calcul du temps écoulé depuis la dernière mise à jour de la planète
$temps_ecoule = time() - $this->timestamp;
$ressources = $this->production($temps_ecoule);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
{
//Si les capacité de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->metal + $ressources[0] < $capnouv)
$this->metal += $ressources[0];
}
else
{
$this->alert_ressources[0] = true;
$this->metal = $this->cap;
}
}
if ($this->cristal + $ressources[1] < $this->cap)
$this->cristal += $ressources[1];
else
{
//Si les capacité de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->cristal + $ressources[1] < $capnouv)
$this->cristal += $ressources[1];
}
else
{
$this->alert_ressources[1] = true;
$this->cristal = $this->cap;
}
}
if ($this->hydrogene + $ressources[2] < $this->cap)
$this->hydrogene += $ressources[2];
else
{
//Si les capacité de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->hydrogene + $ressources[2] < $capnouv)
$this->hydrogene += $ressources[2];
}
else
{
$this->alert_ressources[2] = true;
$this->hydrogene = $this->cap;
}
}
//Vérification de la date pour faire les actions journalières
if (date('zya') != date('zya', $this->timestamp))
{
//On évalue le moral
$this->evalMoral($first);
//Si la population est à 0, on ajoute des habitants
if ($this->population <= 0)
$this->population = 1000;
$popPlus = $this->population * 0.0153^max(1, floor((time()-$this->timestamp)/86400));
if ($this->politique == 2)
$popPlus *= 1.1; //Communisme : 10 % de population qui arrive en plus.
elseif ($this->politique == 3)
$popPlus *= 1.05; //Démocratie : 5 % de population qui arrive en plus.
if ($this->technologies[2] & 4)
$popPlus *= 1.15;
elseif ($this->technologies[2] & 2)
$popPlus *= 1.10;
elseif ($this->technologies[2] & 1)
$popPlus *= 1.05;
$this->population += $popPlus;
$this->credits += $this->population/100*exp(0.01)*25;
$this->modif[] = 'population';
}
$this->timestamp = time();
//Calcul du nombre de cases restantes
$this->casesRest = $this->cases;
foreach($this->batiments as $bat)
$this->casesRest -= $bat;
}
function setMoral($difference)
{
$this->moral += $difference;
//Ajustement du moral
if ($this->moral > 1)
$this->moral = 1;
elseif ($this->moral < 0)
$this->moral = 0;
if (!in_array("moral", $this->modif))
$this->modif[] = "moral";
}
function evalMoral($first = false)
{
//Cas de sous-production
if (($this->coeff_bat[0] + $this->coeff_bat[1] + $this->coeff_bat[2])/3 < 0.9)
{
if ($this->politique == 2)
$this->moral -= 0.10; //Communisme : démoralise 2x plus
else
$this->moral -= 0.05;
if (!in_array('moral', $this->modif))
$this->modif[] = 'moral';
}
//Surpopulation
//Surlogement
//Ajustement du moral en fonction de la politique
if ($this->politique == 1 && $this->moral > 0.7)
$this->moral = 0.7;
//On vérifie qu'on ne dépasse pas le maximum
if ($this->moral > 1)
$this->moral = 1;
if ($this->moral < 0)
$this->moral = 0;
//Isolement si besoin
if ($this->moral < 0.1)
{
//On vérifie qu'il ne s'agit pas de la planète mère
global $bdd, $table_planete;
$bdd->connexion();
$res = $bdd->unique_query("SELECT id FROM $table_planete WHERE id_user = ".$this->id_user." ORDER BY id LIMIT 1;");
$bdd->deconnexion();
if ($res['id'] != $this->id)
{
if ($this->moral <= 0.01 || $this->moral <= 0.04)
{
if ($this->moral <= 0.01)
$rand = rand(0,4);
else
$rand = rand(0,20);
//Perte de la planète
if ($rand == 1)
{
$bdd->connexion();
$bdd->query("DELETE FROM $table_planete WHERE id = ".$this->id.";");
$bdd->deconnexion();
send_mp($this->id_user, 'Perte de contrôle de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a renversé votre gouvernement en tuant tous vos gouverneurs. Vous perdez donc définitivement le contrôle de cette planète.");
if (!$first)
{
$SESS->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révolté contre vous. Vous ne contrôlez plus cette planète.');
}
}
}
elseif ($this->moral <= 0.06 || $this->moral <= 0.1)
{
if ($this->moral <= 0.06)
$rand = rand(0,2);
else
$rand = rand(0,10);
//Perte de contrôle temporaire
if ($rand == 1)
{
$debut = time() - rand(0, 3600)*4;
$fin = $debut + 86400;
$this->isolement = array($debut, $fin);
if (!in_array('isolement', $this->modif)) $this->modif[] = 'isolement';
send_mp($this->id_user, 'Perte de contrôle temporaire de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a pris le contrôle de votre planète. Vous perdez le contrôle de cette planète le temps que vos gouverneurs reprennent le pouvoir.");
if (!$first)
{
$SESS->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révoltée contre vous. Vous perdez temporairement le contrôle de cette planète.');
}
}
}
}
}
}
/**
* Vérifie si la planète est isolée ou non
*
* @return boolean
* @access public
*/
function isolement()
{
return false;
}
/**
* Calcul les ressources produites en fonction de $temps_ecoule
* @param int $temps_ecoule Temps écoulé depuis la dernière actualisation
*
* @return array
* @access public
*/
function production($temps_ecoule, $retarray = false)
{
//Accélération de la production
$temps_ecoule *= VITESSE;
//Calcul de la consomation d'énergie
if ($this->batiments[0] > 0)
$energie_m = ceil(exp(0.28*$this->batiments[0])*10);
else
$energie_m = 0;
if ($this->batiments[1] > 0)
$energie_c = ceil(exp(0.28*$this->batiments[1])*10);
else
$energie_c = 0;
if ($this->batiments[2] > 0)
$energie_h = ceil(exp(0.2849*$this->batiments[2])*13);
else
$energie_h = 0;
if ($this->batiments[3] > 0)
$energie_s = ceil(exp(0.28*$this->batiments[3])*22);
else
$energie_s = 0;
if ($this->batiments[4] > 0)
$energie_f = ceil(exp(0.297*$this->batiments[4])*25);
else
$energie_f = 0;
//Calcul de la consomation d'énergie
$this->energieConso = $energie_m * $this->coeff_bat[0] + $energie_c * $this->coeff_bat[1] + $energie_h * $this->coeff_bat[2];
$nrjmx = $energie_m + $energie_c + $energie_h;
//Calcul de la production d'énergie
$this->energie = $energie_s * $this->coeff_bat[3] + $energie_f * $this->coeff_bat[4];
if ($this->energieConso == 0)
$coeff = 0;
else
$coeff = $this->energie / $this->energieConso;
if ($coeff < 0)
$coeff = 0;
elseif ($coeff > 1)
$coeff = 1;
$Ncoeff = array();
for($i = 0; $i < 3; $i++)
{
$Ncoeff[$i] = $coeff * $this->coeff_bat[$i];
if ($Ncoeff[$i] > 1)
$Ncoeff[$i] = 1;
if ($Ncoeff[$i] < $this->coeff_bat[$i] && $this->batiments[$i] != 0)
{
$this->coeff_bat[$i] = $Ncoeff[$i];
if (!in_array('coeff_bat', $this->modif))
$this->modif[] = 'coeff_bat';
}
}
//Calcul de la consomation d'hydrogène
if ($this->batiments[4] > 0)
$conso_h = ((ceil(pow(1.34,($this->batiments[4]-1))*9)/3600)*$temps_ecoule) * $this->coeff_bat[4];
else
$conso_h = 0;
//Calcul des production de ressources
if ($this->batiments[0] <= 0 || $this->batiments[3] <= 0)
$prod_met = 0.011 * $temps_ecoule;
else
$prod_met = ((ceil(pow(1.1, $this->batiments[0]) * 35 * $this->batiments[0]) / 3600) * $temps_ecoule) * $this->coeff_bat[0] * 1.5;
if ($this->batiments[1] <= 0 || $this->batiments[3] <= 0)
$prod_cri = 0.0055 * $temps_ecoule;
else
$prod_cri = ((ceil(pow(1.1, $this->batiments[1]) * 23 * $this->batiments[1]) / 3600) * $temps_ecoule) * $this->coeff_bat[1] * 1.5;
if ($this->batiments[2] <= 0)
$prod_hy = 0;
else
$prod_hy = ((ceil(pow(1.1, $this->batiments[2]) * 14 * ($this->batiments[2] + 0.7)) / 3600) * $temps_ecoule) * $this->coeff_bat[2] * 1.5;
//Augmentation de la production en fonction des technologies
if ($this->technologies[0] &4)
{
$prod_met *= 1.15;
$prod_cri *= 1.15;
$prod_hy *= 1.15;
}
elseif ($this->technologies[0] &2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
elseif ($this->technologies[0] &1)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
//Augmentation de la production en fonction du moral
if ($this->moral > 0.9)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
elseif ($this->moral > 0.75)
{
$prod_met *= 1.02;
$prod_cri *= 1.02;
$prod_hy *= 1.02;
}
elseif ($this->moral < 0.45)
{
$prod_met *= 0.97;
$prod_cri *= 0.97;
$prod_hy *= 0.97;
}
elseif ($this->moral < 0.25)
{
$prod_met *= 0.94;
$prod_cri *= 0.94;
$prod_hy *= 0.94;
}
//Augmentation de la production en fonction de la politique
if ($this->politique == 2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
//On enlève la consomation d'hydrogène
$prod_hy -= $conso_h;
if ($retarray)
return array(array(ceil($this->coeff_bat[0]*100), ceil($this->coeff_bat[1]*100), ceil($this->coeff_bat[2]*100), ceil($this->coeff_bat[3]*100), ceil($this->coeff_bat[4]*100)), array($prod_met, $prod_cri, $prod_hy + $conso_h, $energie_s*$this->coeff_bat[3], $energie_f*$this->coeff_bat[4]), array($energie_m*$this->coeff_bat[0], $energie_c*$this->coeff_bat[1], $energie_h*$this->coeff_bat[2], $conso_h, ($energie_s*$this->coeff_bat[3] + $energie_f*$this->coeff_bat[4])-($energie_m*$this->coeff_bat[0] + $energie_c*$this->coeff_bat[1] + $energie_h*$this->coeff_bat[2])));
else
return array($prod_met, $prod_cri, $prod_hy);
}
function creer($id_user)
{
//Définition des paramètres de l'utilisateur pour la planète
$this->id_user = $id_user;
//Génération du nombre de case et de l'image en fonction de la position dans le système
if ($this->position > MAX_PLANETE*0.75)
{
$this->cases = mt_rand(200,255);
$this->image = mt_rand(1,19);
}
elseif ($this->position > MAX_PLANETE/2)
{
$this->cases = mt_rand(250,300);
$this->image = mt_rand(1,19);
}
elseif ($this->position > MAX_PLANETE/4)
{
$this->cases = mt_rand(175,260);
$this->image = mt_rand(1,19);
}
else
{
$this->cases = mt_rand(150,220);
$this->image = mt_rand(1,19);
}
//Définition des principaux paramètres de la planète
$this->nom_planete = 'Planète colonisée';
$this->timestamp = time();
$this->metal = 1000;
$this->cristal = 700;
$this->hydrogene = 0;
$this->modif = array("id_user", "nom_planete", "galaxie", "ss", "position", "image", "cases", "timestamp", "metal", "cristal", "hydrogene");
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
if (empty($this->ss) || empty($this->id_user))
return;
if ($this->id_user == 1)
var_dump($this);
global $var___db, $config, $table_planete;
if (empty($this->id))
{
$out1 = array(); $out2 = array();
$bdd = new bdd();
foreach($this->modif as $modif)
{
if ($modif == "force")
continue;
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
$out1[] = $modif;
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out2[] = $this->{$modif};
else
$out2[] = "'".$this->{$modif}."'";
}
else
{
if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out1[] = $modif;
$out2[] = "'$prep'";
}
else
{
if ($modif == "batiments")
$calc = "batiment";
elseif ($modif == "technologies")
$calc = "technolo";
elseif ($modif == "casernes")
$calc = "casernen";
elseif ($modif == "terrestres")
$calc = "nomterrn";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
elseif ($modif == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
{
$out1[] = ${$calc.'VAR'}[$j];
$out2[] = $value;
}
}
}
}
$bdd->query("INSERT INTO $table_planete (".implode(', ', $out1).", hash_planete) VALUES (".implode(', ', $out2).", SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)))");
$bdd->deconnexion();
}
else
{
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
for($i = 0; $i < $nb; $i++)
{
if ($this->modif[$i] == "force")
$out[] = "timestamp = timestamp";
elseif ($this->modif[$i] == 'technologies')
$this->modifUser[] = $this->modif[$i];
elseif (is_object($this->{$this->modif[$i]}))
{
$export = serialize($this->{$this->modif[$i]});
$bdd->escape($export);
$out[] = $this->modif[$i]." = '".$export."'";
}
elseif (!is_array($this->{$this->modif[$i]}))
{
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]}))
$out[] = $this->modif[$i]." = ".$this->{$this->modif[$i]};
else
$out[] = $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else
{
if (is_array($this->{$this->modif[$i]}) && $this->modif[$i] != "coeff_bat" && $this->modif[$i] != "vaisseaux" && $this->modif[$i] != "terrestres" && $this->modif[$i] != "casernes" && $this->modif[$i] != "technologies" && $this->modif[$i] != "batiments")
{
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] = $this->modif[$i]." = '$prep'";
}
else
{
if ($this->modif[$i] == "batiments")
$calc = "batiment";
elseif ($this->modif[$i] == "technologies")
$calc = "technolo";
elseif ($this->modif[$i] == "casernes")
$calc = "casernen";
elseif ($this->modif[$i] == "terrestres")
$calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux")
$calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++)
{
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] = ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_planete SET timestamp = ".time().", metal = ".$this->metal.", cristal = ".$this->cristal.", hydrogene = ".$this->hydrogene.", ".implode(', ', $out)." WHERE id = ".$this->id.";";
if (DEBUG) echo '<br /><br />'.$sql;
$bdd->query($sql);
}
$bdd->deconnexion();
parent::__destruct();
}
}
}
?>

View file

@ -0,0 +1,190 @@
<?php
/**
* Classe Bourse par Pierre-Olivier MERCIER
* Dernière édition le 21 Juillet 2008
* Copyright Halo-Battle Tous droits réservés
*/
class Bourse{
var $bd;
var $id;
var $nom;
var $taxeA = 1.1;
var $taxeV = 1.5;
var $metal;
var $cristal;
var $actionsUser;
var $user;
/**
* Constructor
*
* @param String $nom Nom de l'action
* @param int $user ID du joueur à charger automatiquement
*
* @access protected
*/
function Bourse($nom = "", $user = 0){
global $var___db, $config;
$db = new bdd();
$db->connexion();
$this->bd = $db;
if (!empty($nom)) {
$this->loadAction($nom, "id");
if (!empty($user)) $this->loadUser($user);
}
}
function __destruct(){
$this->bd->deconnexion();
}
function loadAction($nom, $type = "nom"){
global $table_bourse;
$this->bd->escape($nom);
$act = $this->bd->unique_query("SELECT * FROM $table_bourse WHERE $type = '$nom';");
if ($act) {
$this->id = $act['id'];
$this->nom = $act['nom'];
$this->metal = $act['metal'];
$this->cristal = $act['cristal'];
}
else erreur('Impossible de trouver cette action !', "red", '?p=bourse');
}
function loadUser($user, $type = "id"){
global $table_user;
$this->bd->escape($user);
$act = $this->bd->unique_query("SELECT id, bourse FROM $table_user WHERE $type = '$user';");
$this->user = $act['id'];
$this->traitUser($act['bourse']);
}
function traitUser($start){
$end = array();
$start = explode(';', $start);
$cnt = count($start);
for($i = 0; $i < $cnt; $i++){
$tmp = explode(':', $start[$i]);
if (!empty($tmp[1])) $end[$tmp[0]] = explode(',', $tmp[1]);
else $end[$tmp[0]] = array();
}
$this->actionsUser = $end;
}
function prixAchat($nb){
return array(floor($this->metal * $nb * $this->taxeA), floor($this->cristal * $nb * $this->taxeA));
}
function prixVente($nb){
if ($this->action() < $nb) $nb = $this->action();
return array(floor($this->metal * $nb / $this->taxeV), floor($this->cristal * $nb / $this->taxeV));
}
function addAction($nb){
$ret = array(floor($this->metal * $nb * $this->taxeA), floor($this->cristal * $nb * $this->taxeA));
$this->metal *= pow(1.1, $nb);
$this->cristal *= pow(1.1, $nb);
for($i = 0; $i < $nb; $i++){
$this->actionsUser[$this->id][] = time();
}
$this->maj();
return $ret;
}
function delAction($nb){
if ($this->action() < $nb) $nb = $this->action();
$ret = array(floor($this->metal * $nb / $this->taxeV), floor($this->cristal * $nb / $this->taxeV));
$this->metal /= pow(1.1, $nb);
$this->cristal /= pow(1.1, $nb);
for($i = 0; $i < $nb; $i++){
unset($this->actionsUser[$this->id][$i]);
}
$this->maj();
return $ret;
}
function actionIn24Hours(){
$nb = 0;
if (isset($this->actionsUser[$this->id])) {
$cnt = count($this->actionsUser[$this->id]);
for($i = 0; $i < $cnt; $i++){
if ($this->actionsUser[$this->id][$i] > time() - 86400) $nb++;
}
}
return $nb;
}
function action(){
if (isset($this->actionsUser[$this->id])) return count($this->actionsUser[$this->id]);
else return 0;
}
function maj(){
$this->majBourse();
$this->majUser();
$this->fileSave();
}
function majBourse(){
global $table_bourse;
$this->bd->query("UPDATE $table_bourse SET nom = '".$this->nom."', metal = '".$this->metal."', cristal = '".$this->cristal."' WHERE id = ".$this->id.";");
}
function majUser(){
global $table_user;
$champ = '';
foreach($this->actionsUser as $key => $cell) {
if (count($cell) > 0) {
if (empty($champ)) $champ .= $key.':'.implode(',', $cell);
else $champ .= ';'.$key.':'.implode(',', $cell);
}
}
$this->bd->query("UPDATE $table_user SET bourse = '$champ' WHERE id = ".$this->user.";");
}
function delUser($id = ""){
if (!empty($id)) $this->loadUser($id);
$champ = '';
foreach($this->actionsUser as $key => $cell) {
$cnt = count($cell);
if ($cnt > 0) {
$this->loadAction($key, "id");
$this->delAction($cnt);
}
}
}
function fileSave(){
$fichier = fopen(_FCORE."../game/cache/bourse/".$this->id.".".strftime('%Y%m%d').".bourse",'a+');
fwrite($fichier, time().';'.$this->metal.';'.$this->cristal."\n");
fclose($fichier);
}
function newGroupe($nom, $metal, $cristal, $description = ""){
global $table_bourse;
$this->bd->query("INSERT INTO $table_bourse (nom, metal, cristal, description) VALUES('$nom', '$metal', '$cristal', '$description');");
}
function editGroupe($description){
//TODO toute cette fonction !!
}
}
?>

View file

@ -0,0 +1,505 @@
<?php
/***************************************************************************
* class.combat.php
* -------------------
* begin : Samedi 26 janvier 2008
* update : Mercredi 4 juin 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Combat {
var $refflotte = 0;
var $ATvais = array();
var $ENvais = array();
var $ENres = array('metal' => 0, 'cristal' => 0, 'hydrogene' => 0);
var $ENdef = array();
var $Ntour = 0;
var $ATtactique = 0;
var $ENtactique = 0;
var $timestamp = 0;
var $vaisContenu = 0;
var $vaisContenuM = 0;
var $vaisContenuC = 0;
var $vaisContenuH = 0;
var $pillage = array(0, 0, 0);
var $debriM = 0;
var $debriC = 0;
/**
* Constructeur
* @param array $flotteAT tableau SQL des vaisseaux envoyés par l'attaquant
* @param array $flotteEN tableau SQL de la planète du défenseur
* @param array $defEN tableau SQL de la planète du défenseur
*
* @return void
* @access public
*/
function Combat($flotteAT, $flotteEN, $defEN, $tableTechno = array(0, 0)) {
include(_FCORE."hb_game/vars.php");
//Génération des vaisseaux attaquants
for ($i=1 ; $i<=12 ; $i++) {
if ($flotteAT['vaisseau_'.$i] >= 1) {
//Création des groupes
$nbvais = $flotteAT['vaisseau_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $nomvais_bc[$i-1] * (1 + $tableTechno[0]/10), $nomvais_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $nomvais_bc[$i-1] * (1 + $tableTechno[0]/10), $nomvais_pv[$i-1]);
}
$this->ATvais[] = array($i, $flotteAT['vaisseau_'.$i], $nbgroupes, $groupe, $nomvais_initiative[$i-1]);
}
}
//Définition d'autres variables de la classe concernant la flotte
$this->refflotte = $flotteAT['id'];
$this->vaisContenu = $flotteAT['contenu_max'];
$this->vaisContenuM = $flotteAT['contenu_metal'];
$this->vaisContenuC = $flotteAT['contenu_cristal'];
$this->vaisContenuH = $flotteAT['contenu_hydrogene'];
$this->timestamp = $flotteAT['start_time'] + $flotteAT['end_time'];
//Génération des vaisseaux défenseurs
for ($i=1 ; $i<=12 ; $i++) {
if ($flotteEN['vaisseau_'.$i] >= 1) {
//Création des groupes
$nbvais = $flotteEN['vaisseau_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $nomvais_bc[$i-1] * (1 + $tableTechno[1]/10), $nomvais_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $nomvais_bc[$i-1] * (1 + $tableTechno[1]/10), $nomvais_pv[$i-1]);
}
$this->ENvais[] = array($i, $flotteEN['vaisseau_'.$i], $nbgroupes, $groupe, $nomvais_initiative[$i-1]);
}
}
//Génération des défenses défenseurs
for ($i=1 ; $i<=5 ; $i++) {
if ($defEN['def_'.$i] >= 1) {
//Création des groupes
$nbvais = $defEN['def_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $defense_bc[$i-1] * (1 + $tableTechno[1]/10), $defense_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $defense_bc[$i-1] * (1 + $tableTechno[1]/10), $defense_pv[$i-1]);
}
$this->ENdef[] = array($i, $defEN['def_'.$i], $nbgroupes, $groupe, $defense_initiative[$i-1]);
}
}
}
/**
* Change la tactique de l'attaquant
* @param int $tactique numéro de la tactique choisie
*
* @return void
* @access public
*/
function changerTactiqueAT($tactique) {
$this->ATtactique = ceil($tactique);
}
/**
* Change la tactique du défenseur
* @param int $tactique numéro de la tactique choisie
*
* @return void
* @access public
*/
function changerTactiqueEN($tactique) {
$this->ENtactique = ceil($tactique);
}
/**
* Régénére les boucliers
* @param int $pourcentage pourcentage de régénération
* @param bool $attaquant régénére le bouclier de l'attaquant si true, sinon régénrére celui du défenseur
* @param bool $retour si true, renvoie true ou false si !le pourcentage a été consommé ou non, si false, retrourne ne nombre de pourcentage restant
* @param int $blindage niveau de la technologie blindage du joueur
*
* @return float pourcentage non utilisé
* @access public
*/
function regenereBC($pourcentage, $attaquant, $retour = false, $blindage = 0) {
include(_FCORE."hb_game/vars.php");
if ($attaquant) {
$count = count($this->ATvais);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ATvais[$i][0]-1;
$maxbc = $nomvais_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ATvais[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ATvais[$i][3][$j][0];
if ($this->ATvais[$i][3][$j][1] < $maxbc) {
$this->ATvais[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ATvais[$i][3][$j][0];
if ($this->ATvais[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ATvais[$i][3][$j][1] - $maxbc)*$this->ATvais[$i][3][$j][0];
$this->ATvais[$i][3][$j][1] = $maxbc;
}
}
}
if ($retour) {
if($norm != 0 && $enplus/$norm == 1) return $pourcentage;
else return false;
}
else return $enplus/$norm;
}
else {
$count = count($this->ENvais);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ENvais[$i][0]-1;
$maxbc = $nomvais_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ENvais[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ENvais[$i][3][$j][0];
if ($this->ENvais[$i][3][$j][1] < $maxbc) {
$this->ENvais[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ENvais[$i][3][$j][0];
if ($this->ENvais[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ENvais[$i][3][$j][1] - $maxbc)*$this->ENvais[$i][3][$j][0];
$this->ENvais[$i][3][$j][1] = $maxbc;
}
}
}
if ($norm != 0) $return = $enplus/$norm;
else $return = 0;
//Défenses
$count = count($this->ENdef);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ENdef[$i][0]-1;
$maxbc = $defense_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ENdef[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ENdef[$i][3][$j][0];
if ($this->ENdef[$i][3][$j][1] < $maxbc) {
$this->ENdef[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ENdef[$i][3][$j][0];
if ($this->ENdef[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ENdef[$i][3][$j][1] - $maxbc)*$this->ENdef[$i][3][$j][0];
$this->ENdef[$i][3][$j][1] = $maxbc;
}
}
}
if ($norm != 0) $return = $enplus/$norm;
else $return = 0;
if ($retour) {
if($norm != 0 && $enplus/$norm == 1) return $pourcentage;
else return false;
}
else return $return/2;
}
}
/**
* Calcul la puissance d'attaque disponible
* @param int $pourcentage pourcentage de régénération
* @param bool $attaquant calcul les points de l'attaquant si true, sinon calcul pour le défenseur
* @param int $armement niveau de la technologie armement du joueur
* @param bool $method true pour utiliser la mèthode classique, false pour utiliser la méthode d'Apocalypse Joe
*
* @return int points disponibles
* @access public
*/
function calcAttaque($pourcentage, $attaquant, $armement = 0, $method = false) {
include(_FCORE."hb_game/vars.php");
if ($method) {
if ($attaquant) {
$puissance = 0;
$count = count($this->ATvais);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $nomvais_at[$this->ATvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ATvais[$i][1];
}
return $puissance;
}
else {
$puissance = 0;
$count = count($this->ENvais);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $nomvais_at[$this->ENvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENvais[$i][1];
}
//Défenses
$count = count($this->ENdef);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $defense_at[$this->ENdef[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENdef[$i][1];
}
return $puissance;
}
}
else {
if ($attaquant) {
//Calcul du pourcentage de chaque vaisseau adverse
$vaisEff = array();
$nbvais = 0;
$countj = count($this->ENvais);
$countd = count($this->ENdef);
for ($i=0 ; $i<$countj ; $i++) {
$nbvais += $this->ENvais[$i][1];
}
for ($i=0 ; $i<$countj ; $i++) {
$vaisEff[$this->ENvais[$i][0]] = $this->ENvais[$i][1]/$nbvais;
}
$puissance = 0;
$count = count($this->ATvais);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ATvais[$i][4] > $this->Ntour) continue;
$bonus = 0;
for ($j=0 ; $j<$countj ; $j++) {
$bonus += $nomvais_rf[$this->ATvais[$i][0]-1][$this->ENvais[$i][0]-1] * $vaisEff[$this->ENvais[$i][0]];
}
for ($j=0 ; $j<$countd ; $j++) {
$bonus += 1/$countd;
}
$maxat = $nomvais_at[$this->ATvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ATvais[$i][1] * $bonus;
}
return $puissance;
}
else {
//Calcul du pourcentage de chaque vaisseau adverse
$vaisEff = array();
$nbvais = 0;
$countj = count($this->ATvais);
for ($i=0 ; $i<$countj ; $i++) {
$nbvais += $this->ATvais[$i][1];
}
for ($i=0 ; $i<$countj ; $i++) {
$vaisEff[$this->ATvais[$i][0]] = $this->ATvais[$i][1]/$nbvais;
}
$puissance = 0;
$count = count($this->ENvais);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ENvais[$i][4] > $this->Ntour) continue;
$bonus = 0;
for ($j=0 ; $j<$countj ; $j++) {
$bonus += $nomvais_rf[$this->ENvais[$i][0]-1][$this->ATvais[$i][0]-1] * $vaisEff[$this->ATvais[$i][0]];
}
$maxat = $nomvais_at[$this->ENvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENvais[$i][1] * $bonus;
}
//Défenses
$count = count($this->ENdef);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ENdef[$i][4] > $this->Ntour) continue;
$maxat = $defense_at[$this->ENdef[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENdef[$i][1];
}
return $puissance;
}
}
}
/**
* Attaque les vaisseaux adverses
* @param int $points points d'attaque disponible pour l'attaque
* @param bool $attaquant attaque le défenseur si true, sinon attaque l'attaquant
*
* @return void
* @access public
*/
function attaquerVais($points, $attaquant) {
include(_FCORE."hb_game/vars.php");
if ($attaquant) {
while($points > 0) {
// Calcul du nombre de vaisseaux et défenses à attaquer
$nbvais = 0;
$nbgroupes = 0;
$nb = count($this->ENvais);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ENvais[$i][1];
$nbgroupes += $this->ENvais[$i][2];
}
$nb = count($this->ENdef);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ENdef[$i][1];
$nbgroupes += $this->ENdef[$i][2];
}
//S'il ne reste plus de vaisseaux et de défenses, on arrête la boucle
if ($nbvais <= 0 || $nbgroupes <= 0 || $points <= 0) break;
//Calcul du nombre de points qui sera enlevé par vaisseau ou défense
$ppv = $points / $nbvais;
$points = 0;
//On lance l'attaque contre les vaisseaux
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ENvais)-1);
$l = rand(0, count($this->ENvais[$k][3])-1);
$this->ENvais[$k][3][$l][1] -= $ppv;
if ($this->ENvais[$k][3][$l][1] < 0) {
$this->ENvais[$k][3][$l][2] -= abs($this->ENvais[$k][3][$l][1]);
$this->ENvais[$k][3][$l][1] = 0;
if ($this->ENvais[$k][3][$l][2] <= 0) {
$this->debriM += $this->ENvais[$k][3][$l][0] * $nomvais_md[$this->ENvais[$k][0]];
$this->debriC += $this->ENvais[$k][3][$l][0] * $nomvais_cd[$this->ENvais[$k][0]];
$this->ENvais[$k][1] -= $this->ENvais[$k][3][$l][0];
$this->ENvais[$k][2] --;
array_splice($this->ENvais[$k][3], $l, 1);
if (!count($this->ENvais[$k][3])) {
array_splice($this->ENvais, $k, 1);
}
}
}
}
//On lance l'attaque contre les défenses
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ENdef)-1);
$l = rand(0, count($this->ENdef[$k][3])-1);
$this->ENdef[$k][3][$l][1] -= $ppv;
if ($this->ENdef[$k][3][$l][1] < 0) {
$this->ENdef[$k][3][$l][2] -= abs($this->ENdef[$k][3][$l][1]);
$this->ENdef[$k][3][$l][1] = 0;
if ($this->ENdef[$k][3][$l][2] <= 0) {
$this->debriM += $this->ENdef[$k][3][$l][0] * $nomvais_md[$this->ENdef[$k][0]];
$this->debriC += $this->ENdef[$k][3][$l][0] * $nomvais_cd[$this->ENdef[$k][0]];
$this->ENdef[$k][1] -= $this->ENdef[$k][3][$l][0];
$this->ENdef[$k][2] --;
array_splice($this->ENdef[$k][3], $l, 1);
if (!count($this->ENdef[$k][3])) {
array_splice($this->ENdef, $k, 1);
}
}
}
}
}
return count($this->ENvais) + count($this->ENdef);
}
else {
while($points > 0) {
// Calcul du nombre de vaisseaux et défenses à attaquer
$nbvais = 0;
$nbgroupes = 0;
$nb = count($this->ATvais);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ATvais[$i][1];
$nbgroupes += $this->ATvais[$i][2];
}
//S'il ne reste plus de vaisseaux et de défenses, on arrête la boucle
if ($nbvais <= 0 || $nbgroupes <= 0 || $points <= 0) break;
//Calcul du nombre de points qui sera enlevé par vaisseau ou défense
$ppv = $points / $nbvais;
$points = 0;
//On lance l'attaque
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ATvais)-1);
$l = rand(0, count($this->ATvais[$k][3])-1);
$this->ATvais[$k][3][$l][1] -= $ppv;
if ($this->ATvais[$k][3][$l][1] < 0) {
$this->ATvais[$k][3][$l][2] -= abs($this->ATvais[$k][3][$l][1]);
$this->ATvais[$k][3][$l][1] = 0;
if ($this->ATvais[$k][3][$l][2] <= 0) {
$this->debriM += $this->ATvais[$k][3][$l][0] * $nomvais_md[$this->ATvais[$k][0]];
$this->debriC += $this->ATvais[$k][3][$l][0] * $nomvais_cd[$this->ATvais[$k][0]];
$this->ATvais[$k][1] -= $this->ATvais[$k][3][$l][0];
$this->ATvais[$k][2] --;
array_splice($this->ATvais[$k][3], $l, 1);
if (!count($this->ATvais[$k][3])) {
array_splice($this->ATvais, $k, 1);
}
}
}
}
}
return count($this->ATvais);
}
}
function exportAT($pillage = false){
include(_FCORE."hb_game/vars.php");
$nb = count($this->ATvais);
$nbvais = 0; $vaisContenu = 0; $vaisseau_1 = 0; $vaisseau_2 = 0; $vaisseau_3 = 0; $vaisseau_4 = 0; $vaisseau_5 = 0; $vaisseau_6 = 0; $vaisseau_7 = 0; $vaisseau_8 = 0; $vaisseau_9 = 0; $vaisseau_10 = 0; $vaisseau_11 = 0; $vaisseau_12 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'vaisseau_'.$this->ATvais[$i][0]} += $this->ATvais[$i][1];
$nbvais += $this->ATvais[$i][1];
$this->vaisContenu += $nomvais_rs[$this->ATvais[$i][0]-1];
}
$sommeCont = $this->vaisContenuM + $this->vaisContenuC + $this->vaisContenuH;
if ($sommeCont > $this->vaisContenu) {
$retirer = $sommeCont/$this->vaisContenu;
$this->vaisContenuM = floor($this->vaisContenuM/$retirer);
$this->vaisContenuC = floor($this->vaisContenuC/$retirer);
$this->vaisContenuH = floor($this->vaisContenuH/$retirer);
}
if ($pillage) {
$ressplus = pillage($this->ENres['metal'], $this->ENres['cristal'], $this->ENres['hydrogene'], $this->vaisContenu - $this->vaisContenuM - $this->vaisContenuC - $this->vaisContenuH);
$this->vaisContenuM += $ressplus[0];
$this->vaisContenuC += $ressplus[1];
$this->vaisContenuH += $ressplus[2];
$this->pillage = array($ressplus[0], $ressplus[1], $ressplus[2]);
}
return 'nb_vais = \''.$nbvais.'\', contenu_max = \''.$this->vaisContenu.'\', contenu_metal = \''.$this->vaisContenuM.'\', contenu_cristal = \''.$this->vaisContenuC.'\', contenu_hydrogene = \''.$this->vaisContenuH.'\', vaisseau_1 = \''.$vaisseau_1.'\', vaisseau_2 = \''.$vaisseau_2.'\', vaisseau_3 = \''.$vaisseau_3.'\', vaisseau_4 = \''.$vaisseau_4.'\', vaisseau_5 = \''.$vaisseau_5.'\', vaisseau_6 = \''.$vaisseau_6.'\', vaisseau_7 = \''.$vaisseau_7.'\', vaisseau_8 = \''.$vaisseau_8.'\', vaisseau_9 = \''.$vaisseau_9.'\', vaisseau_10 = \''.$vaisseau_10.'\', vaisseau_11 = \''.$vaisseau_11.'\', vaisseau_12 = \''.$vaisseau_12.'\'';
}
function pillageSimul($metal, $cristal, $hydrogene){
$ressplus = pillage($metal, $cristal, $hydrogene, 999999);
$this->pillage = array($ressplus[0], $ressplus[1], $ressplus[2]);
}
function exportEN(){
$nb = count($this->ENvais);
$vaisseau_1 = 0; $vaisseau_2 = 0; $vaisseau_3 = 0; $vaisseau_4 = 0; $vaisseau_5 = 0; $vaisseau_6 = 0; $vaisseau_7 = 0; $vaisseau_8 = 0; $vaisseau_9 = 0; $vaisseau_10 = 0; $vaisseau_11 = 0; $vaisseau_12 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'vaisseau_'.$this->ENvais[$i][0]} += $this->ENvais[$i][1];
}
$nb = count($this->ENdef);
$def_1 = 0; $def_2 = 0; $def_3 = 0; $def_4 = 0; $def_5 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'def_'.$this->ENdef[$i][0]} += $this->ENdef[$i][1];
}
return 'vaisseau_1 = \''.$vaisseau_1.'\', vaisseau_2 = \''.$vaisseau_2.'\', vaisseau_3 = \''.$vaisseau_3.'\', vaisseau_4 = \''.$vaisseau_4.'\', vaisseau_5 = \''.$vaisseau_5.'\', vaisseau_6 = \''.$vaisseau_6.'\', vaisseau_7 = \''.$vaisseau_7.'\', vaisseau_8 = \''.$vaisseau_8.'\', vaisseau_9 = \''.$vaisseau_9.'\', vaisseau_10 = \''.$vaisseau_10.'\', vaisseau_11 = \''.$vaisseau_11.'\', vaisseau_12 = \''.$vaisseau_12.'\', def_1 = \''.$def_1.'\', def_2 = \''.$def_2.'\', def_3 = \''.$def_3.'\', def_4 = \''.$def_4.'\', def_5 = \''.$def_5.'\'';
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,128 @@
<?php
/***************************************************************************
* class.exceptionHB.php
* -----------------------
* begin : Lundi 9 février 2009
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class ExceptionHB extends Exception {
public function __construct($branche, $code = 0, $debug = true, $gerer = false) {
if ($gerer)
parent::__construct($branche, $code);
else
{
if (is_numeric($branche))
{
switch($branche)
{
case 1:
switch($code)
{
case 0:
$message = "La planète est pleine, vous ne pouvez plus construire de batiment dessus !";
break;
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de batiments.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour construire ce bâtiment.";
break;
case 3:
$message = "Le bâtiment dont vous demandez la construction est actuellement en démolition. Annulez la démolition pour lui ajouter l'aggrandir.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour construire ce bâtiment !";
break;
case 5:
$message = "Impossible d'annuler la construction de ce bâtiment, il n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Vous ne pouvez pas démolir ce batiment, il n'est pas encore construit !";
break;
case 7:
$message = "Le bâtiment dont vous demandez la démolition est actuellement en travaux. Annulez les travaux en cours pour pouvoir le démolir.";
break;
}
break;
case 2:
switch($code)
{
case 0:
$message = "Cette technologie est déjà en file d'attente, soyez patient !";
break;
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de technologies.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour rechercher cette technologie.";
break;
case 3:
$message = "Vous possédez déjà cette technologie !";
break;
case 4:
$message = "Vous n'avez pas les crédits ou ressources nécessaires pour rechercher cette technologie !";
break;
case 5:
$message = "Impossible d'annuler la recherche de cette technologie, elle n'a pas été trouvée dans la file !";
break;
}
break;
case 3:
switch($code)
{
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus d'unités.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour entraîner ces unités.";
break;
case 3:
$message = "L'unité dont vous demandez l'entraînement est actuellement en démentellement. Annulez le démentellement pour l'entraîner de nouveau.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour entraîner cette unité !";
break;
case 5:
$message = "Impossible d'annuler l'entraînement de cette unité, elle n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Vous ne pouvez pas démenteler autant d'unités !";
break;
case 7:
$message = "L'unité dont vous demandez le démentellement est actuellement en entraînement. Annulez l'entraînement en cours pour pouvoir la démenteller.";
break;
case 8:
$message = "Dépassement de capacité.<br />Vous ne pouvez pas demander la construction d'autant d'unités en même temps.";
break;
}
break;
}
}
else
$message = $branche;
if ($debug || empty($message))
$message = "Erreur #".intval($branche)."/".$code." :<br />".$message;
global $template, $page;
if (!empty($page))
$template->assign('page', $page);
$template->assign('message', $message);
$template->assign('couleur', 'red');
$template->display('game/erreur.tpl');
exit;
}
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,639 @@
<?php
include_once("game/Class/class.rapport.php");
/***************************************************************************
* class.flotte.php
* ------------------
* begin : Samedi 20 septembre 2008
* update : Samedi 20 septembre 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Flotte
{
var $id_flotte = 0,
$nom,
$start_planete,
$start_time,
$end_planete,
$end_time,
$end_type,
$ret_planete,
$ret_time,
$nb_vais,
$vaisseaux = array(),
$tactique = 0,
$mission,
$vitesse,
$statut = 0,
$last,
$contenu = array(0,0,0),
$contenuMax = 0,
$modifFlotte = array();
/**
* Constructeur
* @param int $id id de la flotte à importer
* @param bool $verrou Booléen disant si la classe doit obtenir préalablement un verrou pour la flotte.
*
* @return void
* @access public
*/
function __construct($id = 0, $verrou = true)
{
if (!empty($id))
{
global $table_flottes;
global $nomvaisnVAR, $ressoVAR;
$id = intval($id);
$bdd = new BDD();
$flotte = $bdd->unique_query("SELECT * FROM $table_flottes WHERE id = $id;");
if ($verrou)
$bdd->query("UPDATE $table_flottes SET last = ".time()." WHERE id = $id;"); //Obtention d'un vérrou de 10 seconde sur la flotte
$bdd->deconnexion();
if (!empty($flotte))
{
$this->id_flotte = $flotte["id"];
$this->nom = $flotte["nom"];
$this->start_planete = $flotte["start_planete"];
$this->start_time = $flotte["start_time"];
$this->end_planete = $flotte["end_planete"];
$this->end_type = $flotte["end_type"];
$this->end_time = $flotte["end_time"];
$this->ret_planete = $flotte["ret_planete"];
$this->ret_time = $flotte["ret_time"];
$this->tactique = $flotte["tactique"];
$this->mission = $flotte["mission"];
$this->vitesse = $flotte["vitesse"];
$this->statut = $flotte["statut"];
$this->last = $flotte["last"];
$this->nb_vais = $flotte["nb_vais"];
foreach($nomvaisnVAR as $vais)
$this->vaisseaux[] = $flotte[$vais];
$this->contenu = array($flotte["contenu_metal"], $flotte["contenu_cristal"], $flotte["contenu_hydrogene"]);
$this->calculer();
}
}
}
function calculer()
{
global $nomvais_rs;
$this->nb_vais = 0;
//Calcul de la capacité maximale d'embarquement de la flotte
foreach($this->vaisseaux as $key => $vais)
{
$this->nb_vais += $vais;
$this->contenuMax += $nomvais_rs[$key] * $vais;
}
}
function load_planete()
{
if (is_numeric($this->start_planete) && !empty($this->start_planete))
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if ($planete->id == $this->start_planete)
$this->start_planete = $planete;
else
$this->start_planete = new Planete($this->start_planete);
}
if (is_numeric($this->end_planete) && !empty($this->end_planete))
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if ($planete->id == $this->end_planete)
$this->end_planete = $planete;
else
$this->end_planete = new Planete($this->end_planete);
}
if (is_numeric($this->ret_planete) && !empty($this->ret_planete))
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if ($planete->id == $this->ret_planete)
$this->ret_planete = $planete;
else
$this->ret_planete = new Planete($this->ret_planete);
}
}
function calc_deplacement($start_galaxie, $start_systeme, $start_position, $end_galaxie, $end_systeme, $end_position, $vitesse, $returnArray = false, $returnConso = false)
{
//Si la planète de départ n'est pas chargée, on charge les planètes
if (is_numeric($this->start_planete))
$this->load_planete();
global $config, $nomvais_vitesseP, $nomvais_vitesseS, $nomvais_vitesseG, $nomvais_rs;
$this->vitesse = $vitesse;
//Calcul de la longueur du déplacement
$diff_galaxie = abs($start_galaxie - $end_galaxie);
$diff_systeme = abs($start_systeme - $end_systeme);
$diff_position = abs($start_position - $end_position);
$diff_centre_position_start = abs(ceil($config['nb_amas']/2) - $start_position);
$diff_centre_systeme_start = abs(ceil($config['nb_systeme']/2) - $start_systeme);
$diff_centre_position_end = abs(ceil($config['nb_amas']/2) - $end_position);
$diff_centre_systeme_end = abs(ceil($config['nb_systeme']/2) - $end_systeme);
//Calcul du temps de déplacement pour chaque vaisseau
$temps = array(); $conso = array(0, 0, 0);
foreach($this->vaisseaux as $key => $vais)
{
//S'il n'y a pas de vaisseaux de ce type, on ne calcul pas leur vitesse
if ($vais == 0)
continue;
//Calcul du temps de déplacement entre planètes
if ($start_systeme == $end_systeme && $start_galaxie == $end_galaxie)
{
$temps[0][$key] = (10/$nomvais_vitesseP[$key]) * (1 + 0.1 * $diff_position);
$temps[1][$key] = $temps[2][$key] = 0;
}
//Calcul du temps de déplacement entre système
elseif ($start_galaxie == $end_galaxie)
{
$temps[0][$key] = (10/$nomvais_vitesseP[$key]) * (1 + 0.1 * ($diff_centre_position_start + $diff_centre_position_end));
$temps[1][$key] = (20/$nomvais_vitesseS[$key]) * (2 + 1 * $diff_systeme);
$temps[2][$key] = 0;
}
//Calcul du temps de déplacement entre galaxies
else
{
$temps[0][$key] = (10/$nomvais_vitesseP[$key]) * (1 + 0.1 * ($diff_centre_position_start + $diff_centre_position_end));
$temps[1][$key] = (20/$nomvais_vitesseS[$key]) * (2 + 1 * ($diff_centre_systeme_start + $diff_centre_systeme_end));
$temps[2][$key] = (50/$nomvais_vitesseG[$key]) * (2 + 1.5 * $diff_galaxie);
}
//Calcul du bonus pour le réacteur à combustion
$techR = $this->start_planete->technologies[1];
if ($techR & 56)
$bonus = 0.7;
elseif ($techR & 24)
$bonus = 0.8;
elseif ($techR & 8)
$bonus = 0.9;
else
$bonus = 1;
$temps[0][$key] *= $bonus * 1/$vitesse;
$conso[0] += $vais * $temps[0][$key] * $bonus / exp($vitesse/5);
//Calcul du bonus pour le réacteur à fusion
$techR = $this->start_planete->technologies[1];
if ($techR &448)
$bonus = 0.7;
elseif ($techR &192)
$bonus = 0.8;
elseif ($techR &64)
$bonus = 0.9;
else
$bonus = 1;
$temps[1][$key] *= $bonus * 1/$vitesse;
$conso[1] += $vais * $temps[1][$key] * $bonus / exp($vitesse/7.5);
//Calcul du bonus pour le réacteur à fusion de type II
$techR = $this->start_planete->technologies[1];
if ($techR &3584)
$bonus = 0.7;
elseif ($techR &1536)
$bonus = 0.8;
elseif ($techR &512)
$bonus = 0.9;
else
$bonus = 1;
$temps[2][$key] *= $bonus * 1/$vitesse;
$conso[2] += $vais * $temps[2][$key] * $bonus / exp($vitesse/10);
}
if (!isset($this->vaisseaux[4]))
$this->vaisseaux[4] = 0;
if (!isset($this->vaisseaux[5]))
$this->vaisseaux[5] = 0;
//Si les chasseurs peuvent rentrer dans les cales des vaisseaux, on les enlèves
if ($this->contenuMax - ($this->contenu[0] + $this->contenu[1] + $this->contenu[2]) - ($this->vaisseaux[4] * $nomvais_rs[4] + $this->vaisseaux[5] * $nomvais_rs[5]) >= ($this->vaisseaux[4] + $this->vaisseaux[5]) * 200)
$temps[2][4] = $temps[2][5] = $temps[1][4] = $temps[1][5] = $temps[0][4] = $temps[0][5] = 0;
//On calcul le temps de déplacement maximal
if ($returnArray)
return $temps;
elseif ($returnConso)
return array(max($temps[0]) + max($temps[1]) + max($temps[2]), ceil($conso[0]+$conso[1]+$conso[2]));
else
return (max($temps[0]) + max($temps[1]) + max($temps[2]));
}
function check_mission()
{
//On vérifie qu'un calcul ne soit pas déjà en cours
if ($this->last >= time() - 10)
return false;
elseif ($this->start_time + $this->end_time > time())
return false;
if ($this->statut == 0)
{
switch($this->mission)
{
case 0:
$this->stationner();
break;
case 1:
$this->transporter();
break;
case 2:
$this->coloniser();
break;
case 3:
$this->attaquer();
break;
case 4:
$this->recycler();
break;
case 5:
$this->espionner();
break;
}
}
if ($this->statut == 1 && ($this->ret_time > time() || $this->start_time + $this->end_time * 2 <= time()))
$this->retourner();
return true;
}
function stationner()
{
//On décharge les ressources éventuellement contenue
$this->decharger();
//On fait atterir les vaisseaux
foreach ($this->vaisseaux as $key => $vais)
$this->end_planete->vaisseaux[$key] += $vais;
if (!in_array("vaisseaux", $this->end_planete->modif))
$this->end_planete->modif[] = "vaisseaux";
$this->modifFlotte = "DELETE";
}
function transporter()
{
$max = $this->decharger();
//Envoie du MP de confirmation au joueur
$send = new Rapport(2, $this->start_planete, $this->end_planete, $this->start_time + $this->end_time);
$send->addInfo($this->end_planete, 0);
$send->addInfo($max, 1);
$send->sendTransport();
$this->statut = 1;
$this->addModifFlotte("statut");
}
function coloniser()
{
//On vérifie que les coordonnées de la planètes sont bien enregistrée
if (empty($this->end_planete) || is_object($this->end_planete) || !preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $this->end_planete))
{
$this->load_planete();
file_log("Erreur de colonisation de la planète : ".$this->end_planete." pour le joueur : ".$this->start_planete->id_user, 2);
send_mp($this->start_planete->id_user, "Erreur de colonisation [F#01]", "Une erreur s'est produite lors de la tentative de colonisation de votre flotte, elle a fait demi-tour.");
$this->rappeler();
}
//On vérifie que la planète ne soit pas déjà colonisée
global $table_planete;
preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $this->end_planete, $position);
$bdd = new BDD();
$p = $bdd->query("SELECT * FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
if ($p)
{
$this->load_planete();
$rapport = new Rapport(2, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo(array($position[1], $position[2], $position[3]), 0);
$rapport->addInfo(false, 1);
$rapport->send();
$this->statut = 1;
$this->addModifFlotte("statut");
}
else
{
$this->load_planete();
//On crée la planète
$this->end_planete = new Planete(false);
$this->end_planete->galaxie = $position[1];
$this->end_planete->ss = $position[2];
$this->end_planete->position = $position[3];
$this->end_planete->creer($this->start_planete->id_user);
//Rembousement du carburant non utilisé (la colonisation prévois au départ un allé/retour)
$conso = $this->calc_deplacement($this->start_planete->galaxie, $this->start_planete->ss, $this->start_planete->position, $position[1], $position[2], $position[3], $this->vitesse, false, true);
$this->end_planete->hydrogene += $conso[1];
//On définit la limite de ressources pour permettre le déchargement de celles contenues dans les vaisseaux
$this->end_planete->cap = 100000;
//On enlève un vaisseau de colonisation de la liste
$this->vaisseaux[2]--;
//On fait atterir les vaisseaux et décharger les ressources
$this->decharger();
$this->atterir();
//On envoie un rapport
$rapport = new Rapport(2, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo(array($position[1], $position[2], $position[3]), 0);
$rapport->addInfo(true, 1);
$rapport->send();
}
}
function recycler()
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->end_planete))
$this->load_planete();
$coeff = ($this->contenuMax - $this->contenu[0] - $this->contenu[1] - $this->contenu[2])/($this->end_planete->debris_met + $this->end_planete->debris_cri);
if ($coeff > 1)
$coeff = 1;
$a = floor($this->end_planete->debris_met * $coeff);
$b = floor($this->end_planete->debris_cri * $coeff);
$this->contenu[0] += $a;
$this->contenu[1] += $b;
if (!in_array('contenu', $this->modifFlotte))
$this->modifFlotte[] = 'contenu';
$this->end_planete->debris_met -= $a;
$this->end_planete->debris_cri -= $b;
if (!in_array('debris_met', $this->end_planete->modif))
$this->end_planete->modif[] = 'debris_met';
if (!in_array('debris_cri', $this->end_planete->modif))
$this->end_planete->modif[] = 'debris_cri';
//Send link
$rapport = new Rapport(4, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo($this->end_planete, 0);
$rapport->addInfo(array($a, $b), 1);
$rapport->send();
$this->statut = 1;
if (!in_array('statut', $this->modifFlotte))
$this->modifFlotte[] = 'statut';
}
function espionner()
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->end_planete))
$this->load_planete();
//Extraction des niveaux technologique des deux adversaires
if (($this->start_planete->technologies[1]& 67108864) == 67108864)
$espionnage_A = 3;
elseif (($this->start_planete->technologies[1]& 33554432) == 33554432)
$espionnage_A = 3;
elseif (($this->start_planete->technologies[1]& 16777216) == 16777216)
$espionnage_A = 3;
else
$espionnage_A = 0;
if (($this->start_planete->technologies[1]& 536870912) == 536870912)
$contreespionnage_B = 3;
elseif (($this->start_planete->technologies[1]& 268435456) == 268435456)
$contreespionnage_B = 2;
elseif (($this->start_planete->technologies[1]& 134217728) == 134217728)
$contreespionnage_B = 1;
else
$contreespionnage_B = 0;
//Création du rapport
$rapport = new Rapport(5, $this->start_planete, $this->end_planete, $this->start_time + $this->end_time);
$rapport->addInfo($this->end_planete, 0);
$rapport->addInfo($contreespionnage_B/$espionnage_A/10, 1);
$rapport->addInfo($espionnage_A+2-$contreespionnage_B+1, 2);
$rapport->addInfo($contreespionnage_B, 3);
$rapport->send();
$this->statut = 1;
$this->addModifFlotte("statut");
}
function decharger($plan = "end_planete")
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->$plan))
$this->load_planete();
$max = array(0, 0, 0);
//Si on dépasse les capacités, on laisse les ressources en trop dans le cargo
if ($this->$plan->metal + $this->contenu[0] > $this->$plan->cap)
{
$max[0] = $this->$plan->cap - $this->$plan->metal;
if ($max[0] < 0) $max[0] = 0;
}
else
$max[0] = $this->contenu[0];
$this->$plan->metal += $max[0];
$this->contenu[0] -= $max[0];
if ($this->$plan->cristal + $this->contenu[1] > $this->$plan->cap)
{
$max[1] = $this->$plan->cap - $this->$plan->cristal;
if ($max[1] < 0) $max[1] = 0;
}
else
$max[1] = $this->contenu[1];
$this->$plan->cristal += $max[1];
$this->contenu[1] -= $max[1];
if ($this->$plan->hydrogene + $this->contenu[2] > $this->$plan->cap)
{
$max[2] = $this->$plan->cap - $this->$plan->hydrogene;
if ($max[2] < 0) $max[2] = 0;
}
else
$max[2] = $this->contenu[2];
$this->$plan->hydrogene += $max[2];
$this->contenu[2] -= $max[2];
$this->$plan->addModif("force");
$this->addModifFlotte("contenu");
return $max;
}
function atterir($plan = "end_planete")
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->$plan))
$this->load_planete();
if (isset($this->$plan->vaisseaux[0]))
{
foreach ($this->vaisseaux as $key => $vais)
$this->$plan->vaisseaux[$key] += $vais;
}
else
$this->$plan->vaisseaux = $this->vaisseaux;
$this->$plan->addModif("vaisseaux");
$this->modifFlotte = "DELETE";
}
function rappeler()
{
if ($this->start_time + $this->end_time >= time())
return false;
else
{
$this->end_time = time() - $this->start_time + 10;
$this->mission = 5;
if (!in_array('mission', $this->modifFlotte))
$this->modifFlotte[] = 'mission';
if (!in_array('end_time', $this->modifFlotte))
$this->modifFlotte[] = 'end_time';
return true;
}
}
function retourner()
{
//Si la planète de départ n'est pas chargée, on charge les planètes
if (is_numeric($this->start_planete))
$this->load_planete();
//Si on a demandé une planète particulière au retour
if (!empty($this->ret_time) && !empty($this->ret_planete) && !is_numeric($this->ret_planete))
{
$this->decharger("ret_planete");
$this->atterir("ret_planete");
}
//Si le retour se fait sur la planète source
else
{
$this->decharger("start_planete");
$this->atterir("start_planete");
}
$this->modifFlotte = "DELETE";
}
function addModifFlotte($modif)
{
if (!in_array($modif, $this->modifFlotte))
$this->modifFlotte[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
global $table_flottes;
if ($this->modifFlotte === "DELETE")
{
$bdd = new BDD();
$bdd->query("DELETE FROM $table_flottes WHERE id = ".$this->id_flotte.";");
$bdd->deconnexion();
}
else
{
if (empty($this->id_flotte))
{
if ($this->modifFlotte == "INSERT")
{
$out1 = ''; $out2 = '';
global $nomvaisnVAR;
foreach ($this->vaisseaux as $key => $vais)
{
$out1 .= ', '.$nomvaisnVAR[$key];
$out2 .= ', '.$vais;
}
$sql = "INSERT INTO $table_flottes (id_user, mission, start_time, start_planete, end_time, end_type, end_planete, vitesse, contenu_metal, contenu_cristal, contenu_hydrogene, tactique, nom, nb_vais$out1) VALUES ('".$this->start_planete->id_user."', '".$this->mission."', '".$this->start_time."', '".$this->start_planete->id."', '".$this->end_time."', '".$this->end_type."', '".$this->end_planete."', '".$this->vitesse."', '".$this->contenu[0]."', '".$this->contenu[1]."', '".$this->contenu[2]."', '".$this->tactique."', '".$this->nom."', ".$this->nb_vais."$out2);";
if (DEBUG) var_dump($sql);
$bdd = new BDD();
$bdd->query($sql);
$bdd->deconnexion();
}
}
elseif(isset($this->modifFlotte[0]))
{
$out = array();
$bdd = new BDD();
foreach($this->modifFlotte as $modif)
{
if (!is_array($this->{$modif}))
{
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out[] .= $modif." = ".$this->{$modif};
else
{
$bdd->escape($this->{$modif});
$out[] .= $modif." = '".$this->{$modif}."'";
}
}
else
{
if ($modif == "contenu")
$calc = "resso";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach(${$calc.'VAR'} as $key => $var)
{
$bdd->escape($this->{$modif}[$key]);
$out[] = ${$calc.'VAR'}[$key]." = ".$this->{$modif}[$key];
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_flottes SET ".implode(', ', $out).", last = 0 WHERE id = ".$this->id_flotte.";";
if (DEBUG) var_dump($sql);
$bdd->query($sql);
}
$bdd->deconnexion();
}
}
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,868 @@
<?php
//Gestion des dépendances, on importe les classes nécessaires à la classe en cours
include_once("game/Class/class.surface.php");
include_once("game/Class/class.file.php");
/***************************************************************************
* class.planete.php
* -------------------
* begin : Jeudi 21 août 2008
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Planete extends Surface
{
private $timestamp_lastSilo,
$timestamp_lastMineM,
$timestamp_lastMineC,
$timestamp_lastMineH;
public $position,
$nom_planete,
$cases,
$casesRest,
$cap,
$population,
$population_max,
$moral,
$energie,
$energieConso,
$file_tech,
$file_cas,
$file_ter,
$coeff_bat = array(),
$casernes = array(),
$terrestres = array();
/**
* Constructeur
* @param mixed $id id de la planète à importer/coordonnées
* @param bool $first Bloquer l'affichage des messages d'erreurs
*
* @return void
* @access public
*/
function __construct($id, $first = false)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_planete;
$bdd = new bdd();
//On traite le cas où l'on recoit l'ID ou les coordonnées de la planète
if ($id === false)
$bdd->deconnexion();
elseif (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT * FROM $table_planete WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT * FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche de planete incorrect !', E_USER_ERROR);
if (!empty($plan))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $plan["id"];
parent::User($plan["id_user"]);
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->position = $plan["position"];
if (!empty($plan["isolement"])) $this->isolement = unserialize($plan["isolement"]);
else $this->isolement = array();
$this->nom_planete = $plan["nom_planete"];
$this->image = $plan["image"];
$this->cases = $plan["cases"];
$this->debris_met = $plan["debris_met"];
$this->debris_cri = $plan["debris_cri"];
$this->metal = $plan["metal"];
$this->cristal = $plan["cristal"];
$this->hydrogene = $plan["hydrogene"];
$this->population = $plan["population"];
$this->moral = $plan["moral"];
$this->timestamp = $plan["timestamp"];
//Chargement des variables de conversion
global $batimentVAR, $casernenVAR, $nomterrnVAR, $nomvaisnVAR;
$this->casesRest = $this->cases; //Calcul du nombre de cases en même temps
foreach($batimentVAR as $bat)
{
$this->batiments[] = $plan[$bat];
$this->casesRest -= $plan[$bat];
}
if (!empty($plan["file_bat"]))
$this->file_bat = unserialize($plan["file_bat"]);
else
$this->file_bat = new File('batiments');
$this->coeff_bat = array($plan["coeff_mine_m"], $plan["coeff_mine_c"], $plan["coeff_mine_h"], $plan["coeff_centrale_s"], $plan["coeff_centrale_f"]);
//On vérifie que les coefficient ne soient pas supérieurs à 1 ou inférieurs à 0
for($i = 0; $i < 5; $i++)
{
if ($this->coeff_bat[$i] > 1)
$this->coeff_bat[$i] = 1;
elseif ($this->coeff_bat[$i] < 0)
$this->coeff_bat[$i] = 0;
}
if (!empty($plan["file_tech"]))
$this->file_tech = unserialize($plan["file_tech"]);
else
$this->file_tech = new File('technologies');
foreach($casernenVAR as $cas)
$this->casernes[] = $plan[$cas];
if (!empty($plan["file_cas"]))
$this->file_cas = unserialize($plan["file_cas"]);
else
$this->file_cas = new File('casernes');
foreach($nomterrnVAR as $ter)
$this->terrestres[] = $plan[$ter];
if (!empty($plan["file_ter"]))
$this->file_ter = unserialize($plan["file_ter"]);
else
$this->file_ter = new File('terrestres');
foreach($nomvaisnVAR as $vais)
$this->vaisseaux[] = $plan[$vais];
if (!empty($plan["file_vais"]))
$this->file_vais = unserialize($plan["file_vais"]);
else
$this->file_vais = new File('vaisseaux');
//Calcul de la population logée
$this->population_max = (pow($this->batiments[12],1.5)+pow($this->batiments[13],2.1))*1000+3000;
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true, $first = false)
{
//Détermination des capacités maximales
$this->cap = pow(2, $this->batiments[10]) * 100000;
//Actualisation des files d'attentes
if ($actuFile)
{
$this->file_bat->batiment_ready($this);
$this->file_tech->technologie_ready($this);
$this->file_cas->caserne_ready($this);
$this->file_ter->terrestre_ready($this);
$this->file_vais->vaisseaux_ready($this);
}
if (!empty($this->timestamp_lastSilo))
{
$this->cap = pow(2, $this->batiments[10]-1) * 100000;
$capnouv = pow(2, $this->batiments[10]) * 100000;
}
//Calcul du temps écoulé depuis la dernière mise à jour de la planète
$temps_ecoule = time() - $this->timestamp;
$ressources = $this->production($temps_ecoule);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
$this->metal = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->metal + $ressources[0] < $capnouv)
$this->metal += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->metal = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->metal = $this->cap;
}
}
if ($this->cristal + $ressources[1] < $this->cap)
$this->cristal += $ressources[1];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->cristal + $ressources[0] < $this->cap)
$this->cristal += $ressources[0];
else
$this->cristal = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->cristal + $ressources[0] < $capnouv)
$this->cristal += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->cristal = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->cristal = $this->cap;
}
}
if ($this->hydrogene + $ressources[2] < $this->cap)
$this->hydrogene += $ressources[2];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->hydrogene + $ressources[0] < $this->cap)
$this->hydrogene += $ressources[0];
else
$this->hydrogene = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->hydrogene + $ressources[0] < $capnouv)
$this->hydrogene += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->hydrogene = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->hydrogene = $this->cap;
}
}
//Vérification de la date pour faire les actions journalières
if (date('zya') != date('zya', $this->timestamp)) //Mise à jour trois fois par jour : 0h, 1h, 13h
//if (date('zy') != date('zy', $this->timestamp)) //Mise à jour une fois par jour : 0h
{
//On évalue le moral
$this->evalMoral($first);
//Si la population est à 0, on ajoute des habitants
if ($this->population <= 0)
$this->population = 1000;
$popPlus = $this->population * 0.0153^max(1, floor((time()-$this->timestamp)/86400));
if ($this->politique == 2)
$popPlus *= 1.1; //Communisme : 10 % de population qui arrive en plus.
elseif ($this->politique == 3)
$popPlus *= 1.05; //Démocratie : 5 % de population qui arrive en plus.
if ($this->technologies[2] & 4)
$popPlus *= 1.15;
elseif ($this->technologies[2] & 2)
$popPlus *= 1.10;
elseif ($this->technologies[2] & 1)
$popPlus *= 1.05;
$this->population += $popPlus;
$this->addCredits(($this->population/100*exp(0.01)*25) + ($this->population*0.01*$this->batiments[15])); //Première partie : production normale; seconde : batiment commercial
$this->addModif("population");
}
$this->timestamp = time();
}
function setMoral($difference)
{
$this->moral += $difference;
//Ajustement du moral
if ($this->moral > 1)
$this->moral = 1;
elseif ($this->moral < 0)
$this->moral = 0;
$this->addModif("moral");
}
function evalMoral($first = false)
{
$evolution = array();
//Cas de sous-production
if (($this->coeff_bat[0] + $this->coeff_bat[1] + $this->coeff_bat[2])/3 < 0.9)
{
if ($this->politique == 2)
$this->moral -= 0.10; //Communisme : démoralise 2x plus
else
$this->moral -= 0.05;
$this->addModif("moral");
}
//Surpopulation
//Surlogement
//Effets des batiments loisirs et commerces
$this->moral += 0.0025*$this->batiments[15] + 0.1*$this->batiments[16];
//Ajustement du moral en fonction de la politique
if ($this->politique == 1 && $this->moral > 0.7)
$this->moral = 0.7;
//On vérifie qu'on ne dépasse pas le maximum
if ($this->moral > 1)
$this->moral = 1;
if ($this->moral < 0)
$this->moral = 0;
//Isolement si besoin
if ($this->moral < 0.1)
{
//On vérifie qu'il ne s'agit pas de la planète mère
global $table_planete;
$bdd = new Bdd();
$bdd->reconnexion();
$res = $bdd->unique_query("SELECT id FROM $table_planete WHERE id_user = ".$this->id_user." ORDER BY id LIMIT 1;");
$bdd->deconnexion();
if ($res['id'] != $this->id)
{
if ($this->moral <= 0.04)
{
if ($this->moral <= 0.01)
$rand = rand(0,4);
else
$rand = rand(0,20);
//Perte de la planète
if ($rand == 1)
{
$bdd->reconnexion();
$bdd->query("DELETE FROM $table_planete WHERE id = ".$this->id.";");
$bdd->deconnexion();
send_mp($this->id_user, 'Perte de contrôle de '.$this->nom_planete, "Suite à une démoralisation persistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a renversé votre gouvernement en tuant tous vos gouverneurs. Vous perdez donc définitivement le contrôle de cette planète.");
if (!$first)
{
$sess->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révolté contre vous. Vous ne contrôlez plus cette planète.');
}
}
}
elseif ($this->moral <= 0.1)
{
if ($this->moral <= 0.06)
$rand = rand(0,2);
else
$rand = rand(0,10);
//Perte de contrôle temporaire
if ($rand == 1)
{
$debut = time() - rand(0, 3600)*4;
$fin = $debut + 86400;
$this->isolement = array($debut, $fin);
$this->addModif("isolement");
send_mp($this->id_user, 'Perte de contrôle temporaire de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a pris le contrôle de votre planète. Vous perdez le contrôle de cette planète le temps que vos gouverneurs reprennent le pouvoir.");
if (!$first)
{
$sess->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révoltée contre vous. Vous perdez temporairement le contrôle de cette planète.');
}
}
}
}
}
}
function checkAndRetireRessources($metal, $cristal, $hydrogene, $credits)
{
if ($this->metal >= $metal && $this->cristal >= $cristal && $this->hydrogene >= $hydrogene && $this->credits >= $credits)
{
$this->metal -= $metal;
$this->cristal -= $cristal;
$this->hydrogene -= $hydrogene;
if (!empty($credits))
{
$this->credits -= $credits;
$this->addModifUser("credits");
}
return true;
}
else
return false;
}
function addRessources($metal, $cristal, $hydrogene)
{
$perte = 0;
$this->metal += $metal;
if ($this->metal > $this->cap)
{
$perte += $this->metal - $this->cap;
$this->metal = $this->cap;
}
$this->cristal += $cristal;
if ($this->cristal > $this->cap)
{
$perte += $this->cristal - $this->cap;
$this->cristal = $this->cap;
}
$this->hydrogene += $hydrogene;
if ($this->hydrogene > $this->cap)
{
$perte += $this->hydrogene - $this->cap;
$this->hydrogene = $this->cap;
}
return $perte;
}
/**
* Vérifie si la planète est isolée ou non
*
* @return boolean
* @access public
*/
function isolement()
{
$return = false;
global $queryPlanetes;
//Détermination du numéro de la planète par rapport aux autres, dans l'ordre de colonisation
$numP = 0;
foreach ($queryPlanetes as $key => $p)
{
if ($p['id'] == $this->id)
$numP = $key + 1;
}
if ($numP >= 11)
{
if (!isset($this->isolement[0]) || (time() > $this->isolement[0] && (!isset($this->isolement[1]) || (time() > $this->isolement[1] && date('dmY') != date('dmY', $this->isolement[0])))))
{
switch($numP)
{
case 11:
$tps = 2;
break;
case 12:
$tps = 4;
break;
case 13:
$tps = 6;
break;
case 14:
$tps = 8;
break;
case 15:
$tps = 12;
break;
case 16:
$tps = 16;
break;
case 17:
$tps = 20;
break;
default:
$tps = 24;
}
$debut = mktime(rand(0, 24-$tps), 0, 0, date('n'), date('j'), date('Y'));
$fin = $debut + $tps * 3600;
$this->isolement[0] = $debut;
if (time() > $this->isolement[0])
$this->isolement[1] = $fin;
$this->addModif("isolement");
}
if (isset($this->isolement[1]) && time() < $this->isolement[1])
$return = true;
}
elseif (!isset($this->isolement[0]))
{
$this->isolement = array(0,0);
$this->addModif("isolement");
}
return $return;
}
/**
* Calcul les ressources produites en fonction de $temps_ecoule
* @param int $temps_ecoule Temps écoulé depuis la dernière actualisation
*
* @return array
* @access public
*/
function production($temps_ecoule, $retarray = false)
{
//Accélération de la production
$temps_ecoule *= VITESSE;
//Calcul de la consomation d'énergie
if ($this->batiments[0] > 0)
$energie_m = ceil(exp(0.28*$this->batiments[0])*10);
else
$energie_m = 0;
if ($this->batiments[1] > 0)
$energie_c = ceil(exp(0.28*$this->batiments[1])*10);
else
$energie_c = 0;
if ($this->batiments[2] > 0)
$energie_h = ceil(exp(0.2849*$this->batiments[2])*13);
else
$energie_h = 0;
if ($this->batiments[3] > 0)
$energie_s = ceil(exp(0.28*$this->batiments[3])*22);
else
$energie_s = 0;
if ($this->batiments[4] > 0)
$energie_f = ceil(exp(0.297*$this->batiments[4])*25);
else
$energie_f = 0;
//Calcul de la consomation d'énergie
$this->energieConso = $energie_m * $this->coeff_bat[0] + $energie_c * $this->coeff_bat[1] + $energie_h * $this->coeff_bat[2];
$nrjmx = $energie_m + $energie_c + $energie_h;
//Calcul de la production d'énergie
$this->energie = $energie_s * $this->coeff_bat[3] + $energie_f * $this->coeff_bat[4];
if ($this->energieConso == 0)
$coeff = 0;
else
$coeff = $this->energie / $this->energieConso;
if ($coeff < 0)
$coeff = 0;
elseif ($coeff > 1)
$coeff = 1;
$Ncoeff = array();
for($i = 0; $i < 3; $i++)
{
$Ncoeff[$i] = $coeff * $this->coeff_bat[$i];
if ($Ncoeff[$i] > 1)
$Ncoeff[$i] = 1;
if ($Ncoeff[$i] < $this->coeff_bat[$i] && $this->batiments[$i] != 0)
{
$this->coeff_bat[$i] = $Ncoeff[$i];
$this->addModif("coeff_bat");
}
}
//Calcul de la consomation d'hydrogène
if ($this->batiments[4] > 0)
$conso_h = ((ceil(pow(1.34,($this->batiments[4]-1))*9)/3600)*$temps_ecoule) * $this->coeff_bat[4];
else
$conso_h = 0;
//Calcul des production de ressources
if ($this->batiments[0] <= 0 || $this->batiments[3] <= 0)
$prod_met = 0.011 * $temps_ecoule;
else
$prod_met = ((ceil(pow(1.1, $this->batiments[0]) * 52 * $this->batiments[0]) / 3600) * $temps_ecoule) * $this->coeff_bat[0];
if ($this->batiments[1] <= 0 || $this->batiments[3] <= 0)
$prod_cri = 0.0055 * $temps_ecoule;
else
$prod_cri = ((ceil(pow(1.1, $this->batiments[1]) * 34 * $this->batiments[1]) / 3600) * $temps_ecoule) * $this->coeff_bat[1];
if ($this->batiments[2] <= 0)
$prod_hy = 0;
else
$prod_hy = ((ceil(pow(1.1, $this->batiments[2]) * 21 * ($this->batiments[2] + 0.7)) / 3600) * $temps_ecoule) * $this->coeff_bat[2];
//Augmentation de la production en fonction des technologies
if ($this->technologies[0] &4)
{
$prod_met *= 1.15;
$prod_cri *= 1.15;
$prod_hy *= 1.15;
}
elseif ($this->technologies[0] &2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
elseif ($this->technologies[0] &1)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
//Rendement métal
if ($this->technologies[0] &64)
$prod_met *= 1.3;
elseif ($this->technologies[0] &32)
$prod_met *= 1.2;
elseif ($this->technologies[0] &16)
$prod_met *= 1.1;
//Rendemant cristal
if ($this->technologies[0] &512)
$prod_cri *= 1.3;
elseif ($this->technologies[0] &256)
$prod_cri *= 1.2;
elseif ($this->technologies[0] &128)
$prod_cri *= 1.1;
//Rendement hydrogène
if ($this->technologies[0] &4096)
$prod_hy *= 1.3;
elseif ($this->technologies[0] &2048)
$prod_hy *= 1.2;
elseif ($this->technologies[0] &1024)
$prod_hy *= 1.1;
//Augmentation de la production en fonction du moral
if ($this->moral > 0.9)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
elseif ($this->moral > 0.75)
{
$prod_met *= 1.02;
$prod_cri *= 1.02;
$prod_hy *= 1.02;
}
elseif ($this->moral < 0.45)
{
$prod_met *= 0.97;
$prod_cri *= 0.97;
$prod_hy *= 0.97;
}
elseif ($this->moral < 0.25)
{
$prod_met *= 0.94;
$prod_cri *= 0.94;
$prod_hy *= 0.94;
}
//Augmentation de la production en fonction de la politique
if ($this->politique == 2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
//On enlève la consomation d'hydrogène
$prod_hy -= $conso_h;
if ($retarray)
return array(array(ceil($this->coeff_bat[0]*100), ceil($this->coeff_bat[1]*100), ceil($this->coeff_bat[2]*100), ceil($this->coeff_bat[3]*100), ceil($this->coeff_bat[4]*100)), array($prod_met, $prod_cri, $prod_hy + $conso_h, $energie_s*$this->coeff_bat[3], $energie_f*$this->coeff_bat[4]), array($energie_m*$this->coeff_bat[0], $energie_c*$this->coeff_bat[1], $energie_h*$this->coeff_bat[2], $conso_h, ($energie_s*$this->coeff_bat[3] + $energie_f*$this->coeff_bat[4])-($energie_m*$this->coeff_bat[0] + $energie_c*$this->coeff_bat[1] + $energie_h*$this->coeff_bat[2])));
else
return array($prod_met, $prod_cri, $prod_hy);
}
function creer($id_user)
{
global $VAR;
//Définition des paramètres de l'utilisateur pour la planète
$this->id_user = $id_user;
//Génération du nombre de case et de l'image en fonction de la position dans le système
if ($this->position > $VAR['nb_planete']*0.75)
{
$this->cases = mt_rand(200,255);
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']/2)
{
$this->cases = mt_rand(250,300);
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']/4)
{
$this->cases = mt_rand(175,260);
$this->image = mt_rand(1,19);
}
else
{
$this->cases = mt_rand(150,220);
$this->image = mt_rand(1,19);
}
//Définition des principaux paramètres de la planète
$this->nom_planete = 'Planète colonisée';
$this->metal = 1000;
$this->cristal = 700;
$this->hydrogene = 0;
$this->modif = array("id_user", "nom_planete", "galaxie", "ss", "position", "image", "cases");
}
function addModif($modif)
{
if (!in_array($modif, $this->modif))
$this->modif[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
if (empty($this->ss) || empty($this->id_user))
return;
if ($this->id_user == 1)
var_dump($this);
global $var___db, $config, $table_planete;
if (empty($this->id))
{
$out1 = array(); $out2 = array();
$bdd = new bdd();
foreach($this->modif as $modif)
{
if ($modif == "force")
continue;
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
$out1[] = $modif;
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out2[] = $this->{$modif};
else
$out2[] = "'".$this->{$modif}."'";
}
else
{
if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out1[] = $modif;
$out2[] = "'$prep'";
}
else
{
if ($modif == "batiments")
$calc = "batiment";
elseif ($modif == "technologies")
$calc = "technolo";
elseif ($modif == "casernes")
$calc = "casernen";
elseif ($modif == "terrestres")
$calc = "nomterrn";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
elseif ($modif == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
{
$out1[] = ${$calc.'VAR'}[$j];
$out2[] = $value;
}
}
}
}
$bdd->query("INSERT INTO $table_planete (".implode(', ', $out1).", hash_planete) VALUES (".implode(', ', $out2).", SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)))");
$bdd->deconnexion();
}
else
{
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
for($i = 0; $i < $nb; $i++)
{
if ($this->modif[$i] == "force")
$out[] = "timestamp = timestamp";
elseif ($this->modif[$i] == 'technologies')
$this->modifUser[] = $this->modif[$i];
elseif (is_object($this->{$this->modif[$i]}))
{
$export = serialize($this->{$this->modif[$i]});
$bdd->escape($export);
$out[] = $this->modif[$i]." = '".$export."'";
}
elseif (!is_array($this->{$this->modif[$i]}))
{
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]}))
$out[] = $this->modif[$i]." = ".$this->{$this->modif[$i]};
else
$out[] = $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else
{
if (is_array($this->{$this->modif[$i]}) && $this->modif[$i] != "coeff_bat" && $this->modif[$i] != "vaisseaux" && $this->modif[$i] != "terrestres" && $this->modif[$i] != "casernes" && $this->modif[$i] != "technologies" && $this->modif[$i] != "batiments")
{
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] = $this->modif[$i]." = '$prep'";
}
else
{
if ($this->modif[$i] == "batiments")
$calc = "batiment";
elseif ($this->modif[$i] == "technologies")
$calc = "technolo";
elseif ($this->modif[$i] == "casernes")
$calc = "casernen";
elseif ($this->modif[$i] == "terrestres")
$calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux")
$calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++)
{
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] = ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_planete SET timestamp = ".time().", metal = ".$this->metal.", cristal = ".$this->cristal.", hydrogene = ".$this->hydrogene.", ".implode(', ', $out)." WHERE id = ".$this->id.";";
if (DEBUG) echo '<br /><br />'.$sql;
$bdd->query($sql);
}
$bdd->deconnexion();
parent::__destruct();
}
}
}
?>

View file

@ -0,0 +1,796 @@
<?php
/*
* pop3.php
*
* @(#) $Header: /home/mlemos/cvsroot/pop3/pop3.php,v 1.23 2009/01/31 04:06:12 mlemos Exp $
*
*/
class pop3_class
{
var $hostname="localhost";
var $port=110;
var $tls=0;
var $quit_handshake=1;
var $error="";
var $authentication_mechanism="USER";
var $realm="";
var $workstation="";
var $join_continuation_header_lines=1;
/* Private variables - DO NOT ACCESS */
var $connection=0;
var $state="DISCONNECTED";
var $greeting="";
var $must_update=0;
var $debug=0;
var $html_debug=0;
var $next_token="";
var $message_buffer="";
var $connection_name = '';
/* Private methods - DO NOT CALL */
Function Tokenize($string,$separator="")
{
if(!strcmp($separator,""))
{
$separator=$string;
$string=$this->next_token;
}
for($character=0;$character<strlen($separator);$character++)
{
if(GetType($position=strpos($string,$separator[$character]))=="integer")
$found=(IsSet($found) ? min($found,$position) : $position);
}
if(IsSet($found))
{
$this->next_token=substr($string,$found+1);
return(substr($string,0,$found));
}
else
{
$this->next_token="";
return($string);
}
}
Function SetError($error)
{
return($this->error=$error);
}
Function OutputDebug($message)
{
$message.="\n";
if($this->html_debug)
$message=str_replace("\n","<br />\n",HtmlSpecialChars($message));
echo $message;
flush();
}
Function GetLine()
{
for($line="";;)
{
if(feof($this->connection))
return(0);
$line.=fgets($this->connection,100);
$length=strlen($line);
if($length>=2
&& substr($line,$length-2,2)=="\r\n")
{
$line=substr($line,0,$length-2);
if($this->debug)
$this->OutputDebug("S $line");
return($line);
}
}
}
Function PutLine($line)
{
if($this->debug)
$this->OutputDebug("C $line");
return(fputs($this->connection,"$line\r\n"));
}
Function OpenConnection()
{
if($this->tls)
{
$version=explode(".",function_exists("phpversion") ? phpversion() : "3.0.7");
$php_version=intval($version[0])*1000000+intval($version[1])*1000+intval($version[2]);
if($php_version<4003000)
return("establishing TLS connections requires at least PHP version 4.3.0");
if(!function_exists("extension_loaded")
|| !extension_loaded("openssl"))
return("establishing TLS connections requires the OpenSSL extension enabled");
}
if($this->hostname=="")
return($this->SetError("2 it was not specified a valid hostname"));
if($this->debug)
$this->OutputDebug("Connecting to ".$this->hostname." ...");
if(($this->connection=@fsockopen(($this->tls ? "tls://" : "").$this->hostname, $this->port, $error, $error_message))==0)
{
switch($error)
{
case -3:
return($this->SetError("-3 socket could not be created"));
case -4:
return($this->SetError("-4 dns lookup on hostname \"$hostname\" failed"));
case -5:
return($this->SetError("-5 connection refused or timed out"));
case -6:
return($this->SetError("-6 fdopen() call failed"));
case -7:
return($this->SetError("-7 setvbuf() call failed"));
default:
return($this->SetError($error." could not connect to the host \"".$this->hostname."\": ".$error_message));
}
}
return("");
}
Function CloseConnection()
{
if($this->debug)
$this->OutputDebug("Closing connection.");
if($this->connection!=0)
{
fclose($this->connection);
$this->connection=0;
}
}
/* Public methods */
/* Open method - set the object variable $hostname to the POP3 server address. */
Function Open()
{
if($this->state!="DISCONNECTED")
return($this->SetError("1 a connection is already opened"));
if(($error=$this->OpenConnection())!="")
return($error);
$greeting=$this->GetLine();
if(GetType($greeting)!="string"
|| $this->Tokenize($greeting," ")!="+OK")
{
$this->CloseConnection();
return($this->SetError("3 POP3 server greeting was not found"));
}
$this->Tokenize("<");
$this->greeting = $this->Tokenize(">");
$this->must_update=0;
$this->state="AUTHORIZATION";
return("");
}
/* Close method - this method must be called at least if there are any
messages to be deleted */
Function Close()
{
if($this->state=="DISCONNECTED")
return($this->SetError("no connection was opened"));
while($this->state=='GETMESSAGE')
{
if(strlen($error=$this->GetMessage(8000, $message, $end_of_message)))
return($error);
}
if($this->must_update
|| $this->quit_handshake)
{
if($this->PutLine("QUIT")==0)
return($this->SetError("Could not send the QUIT command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get quit command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not quit the connection: ".$this->Tokenize("\r\n")));
}
$this->CloseConnection();
$this->state="DISCONNECTED";
pop3_class::SetConnection(-1, $this->connection_name, $this);
return("");
}
/* Login method - pass the user name and password of POP account. Set
$apop to 1 or 0 wether you want to login using APOP method or not. */
Function Login($user,$password,$apop=0)
{
if($this->state!="AUTHORIZATION")
return($this->SetError("connection is not in AUTHORIZATION state"));
if($apop)
{
if(!strcmp($this->greeting,""))
return($this->SetError("Server does not seem to support APOP authentication"));
if($this->PutLine("APOP $user ".md5("<".$this->greeting.">".$password))==0)
return($this->SetError("Could not send the APOP command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get APOP login command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("APOP login failed: ".$this->Tokenize("\r\n")));
}
else
{
$authenticated=0;
if(strcmp($this->authentication_mechanism,"USER")
&& function_exists("class_exists")
&& class_exists("sasl_client_class"))
{
if(strlen($this->authentication_mechanism))
$mechanisms=array($this->authentication_mechanism);
else
{
$mechanisms=array();
if($this->PutLine("CAPA")==0)
return($this->SetError("Could not send the CAPA command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get CAPA command response"));
if(!strcmp($this->Tokenize($response," "),"+OK"))
{
for(;;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the supported authentication methods"));
switch($this->Tokenize($response," "))
{
case ".":
break 2;
case "SASL":
for($method=1;strlen($mechanism=$this->Tokenize(" "));$method++)
$mechanisms[]=$mechanism;
break;
}
}
}
}
$sasl=new sasl_client_class;
$sasl->SetCredential("user",$user);
$sasl->SetCredential("password",$password);
if(strlen($this->realm))
$sasl->SetCredential("realm",$this->realm);
if(strlen($this->workstation))
$sasl->SetCredential("workstation",$this->workstation);
do
{
$status=$sasl->Start($mechanisms,$message,$interactions);
}
while($status==SASL_INTERACT);
switch($status)
{
case SASL_CONTINUE:
break;
case SASL_NOMECH:
if(strlen($this->authentication_mechanism))
return($this->SetError("authenticated mechanism ".$this->authentication_mechanism." may not be used: ".$sasl->error));
break;
default:
return($this->SetError("Could not start the SASL authentication client: ".$sasl->error));
}
if(strlen($sasl->mechanism))
{
if($this->PutLine("AUTH ".$sasl->mechanism.(IsSet($message) ? " ".base64_encode($message) : ""))==0)
return("Could not send the AUTH command");
$response=$this->GetLine();
if(GetType($response)!="string")
return("Could not get AUTH command response");
switch($this->Tokenize($response," "))
{
case "+OK":
$response="";
break;
case "+":
$response=base64_decode($this->Tokenize("\r\n"));
break;
default:
return($this->SetError("Authentication error: ".$this->Tokenize("\r\n")));
}
for(;!$authenticated;)
{
do
{
$status=$sasl->Step($response,$message,$interactions);
}
while($status==SASL_INTERACT);
switch($status)
{
case SASL_CONTINUE:
if($this->PutLine(base64_encode($message))==0)
return("Could not send message authentication step message");
$response=$this->GetLine();
if(GetType($response)!="string")
return("Could not get authentication step message response");
switch($this->Tokenize($response," "))
{
case "+OK":
$authenticated=1;
break;
case "+":
$response=base64_decode($this->Tokenize("\r\n"));
break;
default:
return($this->SetError("Authentication error: ".$this->Tokenize("\r\n")));
}
break;
default:
return($this->SetError("Could not process the SASL authentication step: ".$sasl->error));
}
}
}
}
if(!$authenticated)
{
if($this->PutLine("USER $user")==0)
return($this->SetError("Could not send the USER command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get user login entry response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("User error: ".$this->Tokenize("\r\n")));
if($this->PutLine("PASS $password")==0)
return($this->SetError("Could not send the PASS command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get login password entry response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Password error: ".$this->Tokenize("\r\n")));
}
}
$this->state="TRANSACTION";
return("");
}
/* Statistics method - pass references to variables to hold the number of
messages in the mail box and the size that they take in bytes. */
Function Statistics(&$messages,&$size)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("STAT")==0)
return($this->SetError("Could not send the STAT command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get the statistics command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not get the statistics: ".$this->Tokenize("\r\n")));
$messages=$this->Tokenize(" ");
$size=$this->Tokenize(" ");
return("");
}
/* ListMessages method - the $message argument indicates the number of a
message to be listed. If you specify an empty string it will list all
messages in the mail box. The $unique_id flag indicates if you want
to list the each message unique identifier, otherwise it will
return the size of each message listed. If you list all messages the
result will be returned in an array. */
Function ListMessages($message,$unique_id)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($unique_id)
$list_command="UIDL";
else
$list_command="LIST";
if($this->PutLine("$list_command".($message ? " ".$message : ""))==0)
return($this->SetError("Could not send the $list_command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message list command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not get the message listing: ".$this->Tokenize("\r\n")));
if($message=="")
{
for($messages=array();;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message list response"));
if($response==".")
break;
$message=intval($this->Tokenize($response," "));
if($unique_id)
$messages[$message]=$this->Tokenize(" ");
else
$messages[$message]=intval($this->Tokenize(" "));
}
return($messages);
}
else
{
$message=intval($this->Tokenize(" "));
$value=$this->Tokenize(" ");
return($unique_id ? $value : intval($value));
}
}
/* RetrieveMessage method - the $message argument indicates the number of
a message to be listed. Pass a reference variables that will hold the
arrays of the $header and $body lines. The $lines argument tells how
many lines of the message are to be retrieved. Pass a negative number
if you want to retrieve the whole message. */
Function RetrieveMessage($message,&$headers,&$body,$lines)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($lines<0)
{
$command="RETR";
$arguments="$message";
}
else
{
$command="TOP";
$arguments="$message $lines";
}
if($this->PutLine("$command $arguments")==0)
return($this->SetError("Could not send the $command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message retrieval command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not retrieve the message: ".$this->Tokenize("\r\n")));
for($headers=$body=array(),$line=0;;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message"));
switch($response)
{
case ".":
return("");
case "":
break 2;
default:
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
break;
}
if($this->join_continuation_header_lines
&& $line>0
&& ($response[0]=="\t"
|| $response[0]==" "))
$headers[$line-1].=$response;
else
{
$headers[$line]=$response;
$line++;
}
}
for($line=0;;$line++)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message"));
switch($response)
{
case ".":
return("");
default:
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
break;
}
$body[$line]=$response;
}
return("");
}
/* OpenMessage method - the $message argument indicates the number of
a message to be opened. The $lines argument tells how many lines of
the message are to be retrieved. Pass a negative number if you want
to retrieve the whole message. */
Function OpenMessage($message, $lines=-1)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($lines<0)
{
$command="RETR";
$arguments="$message";
}
else
{
$command="TOP";
$arguments="$message $lines";
}
if($this->PutLine("$command $arguments")==0)
return($this->SetError("Could not send the $command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message retrieval command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not retrieve the message: ".$this->Tokenize("\r\n")));
$this->state="GETMESSAGE";
$this->message_buffer="";
return("");
}
/* GetMessage method - the $count argument indicates the number of bytes
to be read from an opened message. The $message returns by reference
the data read from the message. The $end_of_message argument returns
by reference a boolean value indicated whether it was reached the end
of the message. */
Function GetMessage($count, &$message, &$end_of_message)
{
if($this->state!="GETMESSAGE")
return($this->SetError("connection is not in GETMESSAGE state"));
$message="";
$end_of_message=0;
while($count>strlen($this->message_buffer)
&& !$end_of_message)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message headers"));
if(!strcmp($response,"."))
{
$end_of_message=1;
$this->state="TRANSACTION";
break;
}
else
{
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
$this->message_buffer.=$response."\r\n";
}
}
if($end_of_message
|| $count>=strlen($this->message_buffer))
{
$message=$this->message_buffer;
$this->message_buffer="";
}
else
{
$message=substr($this->message_buffer, 0, $count);
$this->message_buffer=substr($this->message_buffer, $count);
}
return("");
}
/* DeleteMessage method - the $message argument indicates the number of
a message to be marked as deleted. Messages will only be effectively
deleted upon a successful call to the Close method. */
Function DeleteMessage($message)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("DELE $message")==0)
return($this->SetError("Could not send the DELE command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message delete command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not delete the message: ".$this->Tokenize("\r\n")));
$this->must_update=1;
return("");
}
/* ResetDeletedMessages method - Reset the list of marked to be deleted
messages. No messages will be marked to be deleted upon a successful
call to this method. */
Function ResetDeletedMessages()
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("RSET")==0)
return($this->SetError("Could not send the RSET command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get reset deleted messages command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not reset deleted messages: ".$this->Tokenize("\r\n")));
$this->must_update=0;
return("");
}
/* IssueNOOP method - Just pings the server to prevent it auto-close the
connection after an idle timeout (tipically 10 minutes). Not very
useful for most likely uses of this class. It's just here for
protocol support completeness. */
Function IssueNOOP()
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("NOOP")==0)
return($this->SetError("Could not send the NOOP command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not NOOP command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not issue the NOOP command: ".$this->Tokenize("\r\n")));
return("");
}
Function &SetConnection($set, &$current_name, &$pop3)
{
static $connections = array();
if($set>0)
{
$current_name = strval(count($connections));
$connections[$current_name] = &$pop3;
}
elseif($set<0)
{
$connections[$current_name] = '';
$current_name = '';
}
elseif(IsSet($connections[$current_name])
&& GetType($connections[$current_name])!='string')
{
$connection = &$connections[$current_name];
return($connection);
}
return($pop3);
}
/* GetConnectionName method - Retrieve the name associated to an
established POP3 server connection to use as virtual host name for
use in POP3 stream wrapper URLs. */
Function GetConnectionName(&$connection_name)
{
if($this->state!="TRANSACTION")
return($this->SetError("cannot get the name of a POP3 connection that was not established and the user has logged in"));
if(strlen($this->connection_name) == 0)
pop3_class::SetConnection(1, $this->connection_name, $this);
$connection_name = $this->connection_name;
return('');
}
};
class pop3_stream
{
var $opened = 0;
var $report_errors = 1;
var $read = 0;
var $buffer = "";
var $end_of_message=1;
var $previous_connection = 0;
var $pop3;
Function SetError($error)
{
if($this->report_errors)
trigger_error($error);
return(FALSE);
}
Function ParsePath($path, &$url)
{
if(!$this->previous_connection)
{
if(IsSet($url["host"]))
$this->pop3->hostname=$url["host"];
if(IsSet($url["port"]))
$this->pop3->port=intval($url["port"]);
if(IsSet($url["scheme"])
&& !strcmp($url["scheme"],"pop3s"))
$this->pop3->tls=1;
if(!IsSet($url["user"]))
return($this->SetError("it was not specified a valid POP3 user"));
if(!IsSet($url["pass"]))
return($this->SetError("it was not specified a valid POP3 password"));
if(!IsSet($url["path"]))
return($this->SetError("it was not specified a valid mailbox path"));
}
if(IsSet($url["query"]))
{
parse_str($url["query"],$query);
if(IsSet($query["debug"]))
$this->pop3->debug = intval($query["debug"]);
if(IsSet($query["html_debug"]))
$this->pop3->html_debug = intval($query["html_debug"]);
if(!$this->previous_connection)
{
if(IsSet($query["tls"]))
$this->pop3->tls = intval($query["tls"]);
if(IsSet($query["realm"]))
$this->pop3->realm = UrlDecode($query["realm"]);
if(IsSet($query["workstation"]))
$this->pop3->workstation = UrlDecode($query["workstation"]);
if(IsSet($query["authentication_mechanism"]))
$this->pop3->realm = UrlDecode($query["authentication_mechanism"]);
}
if(IsSet($query["quit_handshake"]))
$this->pop3->quit_handshake = intval($query["quit_handshake"]);
}
return(TRUE);
}
Function stream_open($path, $mode, $options, &$opened_path)
{
$this->report_errors = (($options & STREAM_REPORT_ERRORS) !=0);
if(strcmp($mode, "r"))
return($this->SetError("the message can only be opened for reading"));
$url=parse_url($path);
$host = $url['host'];
$pop3 = &pop3_class::SetConnection(0, $host, $this->pop3);
if(IsSet($pop3))
{
$this->pop3 = &$pop3;
$this->previous_connection = 1;
}
else
$this->pop3=new pop3_class;
if(!$this->ParsePath($path, $url))
return(FALSE);
$message=substr($url["path"],1);
if(strcmp(intval($message), $message)
|| $message<=0)
return($this->SetError("it was not specified a valid message to retrieve"));
if(!$this->previous_connection)
{
if(strlen($error=$this->pop3->Open()))
return($this->SetError($error));
$this->opened = 1;
$apop = (IsSet($url["query"]["apop"]) ? intval($url["query"]["apop"]) : 0);
if(strlen($error=$this->pop3->Login(UrlDecode($url["user"]), UrlDecode($url["pass"]),$apop)))
{
$this->stream_close();
return($this->SetError($error));
}
}
if(strlen($error=$this->pop3->OpenMessage($message,-1)))
{
$this->stream_close();
return($this->SetError($error));
}
$this->end_of_message=FALSE;
if($options & STREAM_USE_PATH)
$opened_path=$path;
$this->read = 0;
$this->buffer = "";
return(TRUE);
}
Function stream_eof()
{
if($this->read==0)
return(FALSE);
return($this->end_of_message);
}
Function stream_read($count)
{
if($count<=0)
return($this->SetError("it was not specified a valid length of the message to read"));
if($this->end_of_message)
return("");
if(strlen($error=$this->pop3->GetMessage($count, $read, $this->end_of_message)))
return($this->SetError($error));
$this->read += strlen($read);
return($read);
}
Function stream_close()
{
while(!$this->end_of_message)
$this->stream_read(8000);
if($this->opened)
{
$this->pop3->Close();
$this->opened = 0;
}
}
};
?>

View file

@ -0,0 +1,359 @@
<?php
/**
* Class Rapport
*
* Génération et envoie de rapport de mission de flotte
*
*/
class Rapport{
var $table = 'mail';
var $type = 0;
var $var = array();
var $utilA = 0;
var $utilB = 0;
var $timestamp = 0;
/**
* Constructor
* @access protected
*/
function Rapport($type, $utilA, $utilB, $time)
{
global $table_mail;
$this->table = $table_mail;
$this->type = $type;
$this->utilA = $utilA;
$this->utilB = $utilB;
$this->timestamp = $time;
}
function addInfo($info, $id)
{
$this->var[$id] = $info;
}
function send()
{
if ($this->type == '3')
$this->sendCombat();
elseif ($this->type == '1')
$this->sendTransport();
elseif ($this->type == '2')
$this->sendColonisation();
elseif ($this->type == '4')
$this->sendRecyclage();
elseif ($this->type == '5')
$this->sendEspionnage();
elseif ($this->type == '6')
$this->sendAlliance();
elseif ($this->type == '7')
$this->sendAlliance2();
}
function sendEspionnage()
{
global $LANG;
$titreA = 'Rapport d\'espionnage de '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapportA = '<b>Espionnage de '.$this->var[0]->pseudo.' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
if ($this->var[2] < 1) $rapportA .= '<i>Nos sondes n\'ont pas pu récolter d\'informations sur cette planète.</i>';
else {
//Ressources
if ($this->var[2] > 1)
$rapportA .= '<table style="margin: auto;"><tr><th colspan="2">Ressources sur la planète :</th></tr><tr><td>'.$LANG[$this->var[0]->race]["ressources"]["noms"]["metal"].' :</td><td>'.$this->var[0]->metal.'</td></tr><tr><td>'.$LANG[$this->var[0]->race]["ressources"]["noms"]["cristal"].' :</td><td>'.$this->var[0]->cristal.'</td></tr><tr><td>'.$LANG[$this->var[0]->race]["ressources"]["noms"]["hydrogene"].' :</td><td>'.$this->var[0]->hydrogene.'</td></tr></table><br />';
//Bâtiments
if ($this->var[2] > 2)
{
$rapportA .= '<table style="margin: auto;"><tr><th>Niveau</th><th>Bâtiment</th></tr>';
foreach ($this->var[0]->batiments as $key => $batiment)
{
$rapportA .= '<tr><td>'.rand($batiment * (1 - $this->var[1]), $batiment * (1 + $this->var[1])).'</td><td>'.$LANG[$this->var[0]->race]["batiments"]["noms_sing"][$key].'</td></tr>';
}
$rapportA .= '</table><br />';
}
//Flottes en orbite
if ($this->var[2] > 3)
{
}
//Flottes au sol
if ($this->var[2] > 5)
{
$rapportA .= '<table style="margin: auto;"><tr><th>Nombre</th><th>Vaisseaux</th></tr>';
foreach ($this->var[0]->vaisseaux as $key => $vaisseau)
{
$rapportA .= '<tr><td>'.rand($vaisseau * (1 - $this->var[1]), $vaisseau * (1 + $this->var[1])).'</td><td>'.$LANG[$this->var[0]->race]["vaisseaux"]["noms_sing"][$key].'</td></tr>';
}
$rapportA .= '</table><br />';
}
//Défenses
if ($this->var[2] > 4)
{
$rapportA .= '<table style="margin: auto;"><tr><th>Nombre</th><th>Défenses</th></tr>';
foreach ($this->var[0]->terrestres as $key => $unite)
{
if (!Donnee::typeTerrestre($key)) $rapportA .= '<tr><td>'.rand($unite * (1 - $this->var[1]), $unite * (1 + $this->var[1])).'</td><td>'.$LANG[$this->var[0]->race]["terrestre"]["noms_sing"][$key].'</td></tr>';
}
$rapportA .= '</table><br />';
}
}
$titreB = 'Rapport de contre-espionnage';
$rapportB = 'Nous venons d\'apprendre que notre planète : '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.'] a été la cible d\'un espionnage de la part de '.$this->utilA->pseudo;
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titreA);
$db->escape($titreB);
$db->escape($rapportA);
$db->escape($rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
//On envoie un rapport au joueur espionné uniquement s'il a un contre-espionnage
if ($this->var[3] >= 1)
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user.", '$titreB', '$rapportB', '$temps')");
$db->deconnexion();
}
function sendTransport()
{
global $LANG;
$titre = 'Transport vers '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapportA = 'Vos vaisseaux ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilA->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$rapportB = 'Les vaisseaux de '.$this->utilA->pseudo.' ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilB->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapportA);
$db->escape($rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapportA', '$temps');");
if ($this->utilA->id_user != $this->utilB->id_user) $db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user.", '$titre', '$rapportB', '$temps');");
$db->deconnexion();
}
function sendColonisation()
{
$titre = 'Colonisation de ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].']';
if ($this->var[1]) $rapport = 'Votre vaisseau a atteint la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] et commence la colonisation.';
else $rapport = 'Nous n\'avons pas pu coloniser la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] car lorsque nous sommes arrivé sur place, elle était déjà colonisée.';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapport);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapport', '$temps');");
$db->deconnexion();
}
function sendRecyclage()
{
global $LANG;
$titre = 'Recyclage de '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapport = 'Vos vaisseaux récoltent '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].' et '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapport);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapport', '$temps');");
$db->deconnexion();
}
function sendCombat(){
include(_FCORE."../game/vars.php");
include_once(_FCORE."../game/function.php");
require_once(SMARTY_DIR."Smarty.class.php");
$rapportA = new Smarty();
$rapportB = new Smarty();
$rapportA->template_dir = _FCORE.'templates/templates/';
$rapportA->compile_dir = _FCORE.'templates/templates_c/';
$rapportA->config_dir = _FCORE.'templates/configs/';
$rapportA->cache_dir = _FCORE.'templates/cache/';
$rapportB->template_dir = _FCORE.'templates/templates/';
$rapportB->compile_dir = _FCORE.'templates/templates_c/';
$rapportB->config_dir = _FCORE.'templates/configs/';
$rapportB->cache_dir = _FCORE.'templates/cache/';
$this->var[4]['pseudo'] = trouvNom($this->var[4]['id_user']);
$this->var[5]['pseudo'] = trouvNom($this->var[5]['id_user']);
$rapportA->assign('tour', $this->var[3]);
$rapportA->assign('EN', $this->var[4]);
$rapportA->assign('flotte', $this->var[5]);
$rapportA->assign('vaisseaux1', $this->var[0]);
$rapportA->assign('vaisseaux2', $this->var[1]);
$rapportA->assign('defenses1', $this->var[2]);
$rapportA->assign('vaisseaux3', $this->var[7]);
$rapportA->assign('vaisseaux4', $this->var[8]);
$rapportA->assign('defenses2', $this->var[9]);
$rapportA->assign('termine', $this->var[6][0]);
$rapportA->assign('attaquantG', $this->var[6][1]);
$rapportA->assign('pillage', $this->var[11]);
$rapportA->assign('vaisBC', $nomvais_bc);
$rapportA->assign('vaisPV', $nomvais_pv);
$rapportA->assign('defBC', $defense_bc);
$rapportA->assign('defPV', $defense_pv);
$rapportA->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$rapportA->assign('ressources', $ressourc);
$rapportA->assign('nomvaisAT', $nomvaisa);
$race = trouvInfo($this->var[4]['id_user'], 'race');
include(_FCORE."../game/noms.php");
$rapportA->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$rapportA->assign('nomdefEN', $nomterra);
$rapportA = $rapportA->fetch('game/ATrapport_combat.tpl');
$rapportB->assign('tour', $this->var[3]);
$rapportB->assign('EN', $this->var[4]);
$rapportB->assign('flotte', $this->var[5]);
$rapportB->assign('vaisseaux1', $this->var[0]);
$rapportB->assign('vaisseaux2', $this->var[1]);
$rapportB->assign('defenses1', $this->var[2]);
$rapportB->assign('vaisseaux3', $this->var[7]);
$rapportB->assign('vaisseaux4', $this->var[8]);
$rapportB->assign('defenses2', $this->var[9]);
$rapportB->assign('termine', $this->var[6][0]);
$rapportB->assign('attaquantG', $this->var[6][1]);
$rapportB->assign('matchnul', $this->var[6][2]);
$rapportB->assign('pillage', $this->var[11]);
$rapportB->assign('vaisBC', $nomvais_bc);
$rapportB->assign('vaisPV', $nomvais_pv);
$rapportB->assign('defBC', $defense_bc);
$rapportB->assign('defPV', $defense_pv);
$rapportB->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$rapportB->assign('ressources', $ressourc);
$rapportB->assign('nomvaisAT', $nomvaisa);
$race = trouvInfo($this->var[4]['id_user'], 'race');
include(_FCORE."../game/noms.php");
$rapportB->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$rapportB->assign('nomdefEN', $nomterra);
$rapportB = $rapportB->fetch('game/ENrapport_combat.tpl');
$titreA = 'Combat contre '.$this->var[4]['pseudo'];
$titreB = 'Combat contre '.$this->var[5]['pseudo'];
$temps = $this->timestamp;
$db = new bdd();
$db->connexion();
$db->escape($titreA);
$db->escape($titreB);
$db->escape($rapportA);
$db->escape($rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user."', '$titreB', '$rapportB', '$temps')");
$db->deconnexion();
}
function show(){
include(_FCORE."../game/vars.php");
include_once(_FCORE."../game/function.php");
require_once(SMARTY_DIR."Smarty.class.php");
$rapportA = new Smarty();
$rapportA->template_dir = _FCORE.'templates/templates/';
$rapportA->compile_dir = _FCORE.'templates/templates_c/';
$rapportA->config_dir = _FCORE.'templates/configs/';
$rapportA->cache_dir = _FCORE.'templates/cache/';
$rapportA->assign('tour', $this->var[3]);
$rapportA->assign('EN', $this->var[4]);
$rapportA->assign('flotte', $this->var[5]);
$rapportA->assign('vaisseaux1', $this->var[0]);
$rapportA->assign('vaisseaux2', $this->var[1]);
$rapportA->assign('defenses1', $this->var[2]);
$rapportA->assign('vaisseaux3', $this->var[7]);
$rapportA->assign('vaisseaux4', $this->var[8]);
$rapportA->assign('defenses2', $this->var[9]);
$rapportA->assign('termine', $this->var[6][0]);
$rapportA->assign('attaquantG', $this->var[6][1]);
$rapportA->assign('pillage', $this->var[11]);
$rapportA->assign('debris', $this->var[12]);
$rapportA->assign('infoPLUS', $this->var[14]);
//$rapportA->assign('infoPLUS2', $this->var[15]);
$rapportA->assign('page', 'simulation');
$rapportA->assign('enligne', $this->var[13][0]);
$rapportA->assign('infos', $this->var[13][1]);
$rapportA->assign('nbinfos', $this->var[13][2]);
$rapportA->assign('count', $this->var[13][3]);
$rapportA->assign('version', $this->var[13][4]);
$rapportA->assign('tpsdejeu', $this->var[13][5]);
$rapportA->assign('vaisBC', $nomvais_bc);
$rapportA->assign('vaisPV', $nomvais_pv);
$rapportA->assign('defBC', $defense_bc);
$rapportA->assign('defPV', $defense_pv);
$rapportA->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$rapportA->assign('ressources', $ressourc);
$rapportA->assign('nomvaisAT', $nomvaisa);
$rapportA->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$rapportA->assign('nomdefEN', $nomterra);
$rapportA->assign('race', $race);
return $rapportA->fetch('game/SIMrapport_combat.tpl');
return $rapportA;
}
function sendAlliance()
{
$titreA = 'Déclaration officielle de votre alliance !';
$rapportA = 'Félicitations, votre alliance a recueilli suffisament de signature, sa déclaration est maintenant officielle !<br /><br />Vous pouvez dès maintenant administrer votre alliance en vous rendant sur la page Alliance.';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titreA);
$db->escape($rapportA);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
$db->deconnexion();
}
function sendAlliance2()
{
$titreA = 'Fondation de votre alliance !';
$rapportA = 'Pour terminer la création de votre alliance, trouvez 4 joueurs de cette galaxie sans alliance pour leur faire signer votre traité de fondation d\'alliance.<br /><br />Lien de signature : <a href="?p=alliances&amp;q=signer&amp;i='.$this->var[0].'">http://'.$_SERVER['HTTP_HOST'].'/?p=alliances&amp;q=signer&amp;i='.$this->var[0].'</a>';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titreA);
$db->escape($rapportA);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
$db->deconnexion();
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
<?php
include_once("game/Class/class.user.php");
/***************************************************************************
* class.surface.php
* -------------------
* begin : Jeudi 21 août 2008
* update : Dimanche 8 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Surface extends User
{
var $id = 0,
$galaxie,
$ss,
$image,
$debris_met,
$debris_cri,
$metal,
$cristal,
$hydrogene,
$alert_ressources = array(false, false, false),
$timestamp,
$file_bat,
$file_vais,
$isolement = false,
$batiments = array(),
$vaisseaux = array(),
$modif = array();
}
?>

View file

@ -0,0 +1,46 @@
<?php
class TinyAsteroide
{
var $id = 0,
$galaxie,
$ss,
$nom_asteroide;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_alliances;
$bdd = new BDD();
//On traite le cas où l'on recoit l'ID ou les coordonnées de l'asteroide
if (is_numeric($id))
{
$aste = $bdd->unique_query("SELECT id, galaxie, ss, nom_asteroide FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position))
{
$aste = $bdd->unique_query("SELECT id, galaxie, ss, nom_asteroide FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche d\'astéroide incorrect !', E_USER_ERROR);
if (!empty($aste))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $aste["id"];
$this->galaxie = $aste["galaxie"];
$this->ss = $aste["ss"];
$this->nom_asteroide = $aste["nom_asteroide"];
}
}
}
?>

View file

@ -0,0 +1,47 @@
<?php
class TinyPlanete{
var $id = 0,
$galaxie,
$ss,
$position,
$nom_planete;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_planete;
$bdd = new bdd();
//On traite le cas où l'on recoit l'ID ou les coordonnées de la planète
if (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT id, galaxie, ss, position, nom_planete FROM $table_planete WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT id, galaxie, ss, position, nom_planete FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche de planete incorrect !', E_USER_ERROR);
if (!empty($plan))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $plan["id"];
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->position = $plan["position"];
$this->nom_planete = $plan["nom_planete"];
}
}
}
?>

View file

@ -0,0 +1,163 @@
<?php
//Gestion des dépendances
include_once("game/Class/class.tinyasteroide.php");
/***************************************************************************
* class.user.php
* ----------------
* begin : Dimanche 7 septembre 2008
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class User{
var $id_user,
$pseudo,
$auth_level,
$race,
$alliance,
$id_alliance,
$id_grade_alliance,
$mv,
$mail,
$envoyerMail,
$last_visite,
$points,
$place_points,
$technologies = array(),
$credits,
$politique,
$politique_lastchange,
$destinationsFavoris,
$amis = array(),
$combatAT_tactique,
$combatDE_tactique,
$modifUser = array();
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function User($id = 0){
if (!empty($id)) {
global $var___db, $config, $table_user;
global $technologiesVAR;
$bdd = new bdd();
$bdd->escape($id);
$user = $bdd->unique_query("SELECT * FROM $table_user WHERE id = $id;");
$bdd->deconnexion();
if (!empty($user)) {
$this->id_user = $user["id"];
$this->pseudo = $user["pseudo"];
$this->auth_level = $user["auth_level"];
$this->race = $user["race"];
$this->mv = $user["mv"];
$this->id_alliance = $user["id_alliance"];
$this->id_grade_alliance = $user["id_grade_alliance"];
$this->mail = $user["mail"];
$this->envoyerMail = $user["envoyerMail"];
$this->last_visite = $user["last_visite"];
$this->points = $user["points"];
$this->place_points = $user["place_points"];
$this->credits = $user["credits"];
$this->politique = $user["politique"];
$this->politique_lastchange = $user["politique_lastchange"];
if (!empty($user["amis"])) $this->amis = unserialize($user["amis"]);
else $this->amis = array();
if (!empty($user["destinationsFavoris"])) $this->destinationsFavoris = unserialize($user["destinationsFavoris"]);
else $this->destinationsFavoris = array();
$this->combatAT_tactique = $user["combatAT_tactique"];
$this->combatDE_tactique = $user["combatDE_tactique"];
foreach($technologiesVAR as $tech){
$this->technologies[] = $user[$tech];
}
//Si l'ID d'alliance est défini, on charge l'alliance
if (!empty($this->id_alliance))
$this->alliance = new TinyAsteroide($this->id_alliance);
}
else die('Erreur #01 : Utilisateur recherché introuvable dans la base de données. Contactez le support technique ('.$config['mail_support'].') au plus vite en précisant le code d\'erreur.');
}
}
function addCredits($credits)
{
$this->credits += $credits;
$this->addModifUser("credits");
return 0;
}
function addModifUser($modif)
{
if (!in_array($modif, $this->modifUser))
$this->modifUser[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct(){
global $var___db, $config, $table_user;
$out = array();
$bdd = new bdd();
foreach($this->modifUser as $key => $modif)
{
if ($modif == "force")
$out[] = " ";
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
if (is_int($this->{$modif}) || is_float($this->{$modif})) $out[] .= $modif." = ".$this->{$modif};
else $out[] .= $modif." = '".$this->{$modif}."'";
}
else
{
if (ereg('file', $modif))
{
$prep = implode(';', $this->{$modif});
$bdd->escape($prep);
$out[] .= $modif." = '$prep'";
}
else
{
if ($modif == "batiments")
$calc = "batiment";
elseif ($modif == "technologies")
$calc = "technologies";
elseif ($modif == "casernes")
$calc = "casernen";
elseif ($modif == "terrestres")
$calc = "nomterrn";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++){
$bdd->escape($this->{$modif}[$j]);
$out[] .= ${$calc.'VAR'}[$j]." = ".$this->{$modif}[$j];
}
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_user SET ".implode(', ', $out)." WHERE id = ".$this->id_user.";";
if (DEBUG) echo '<br /><br />'.$sql;
$bdd->query($sql);
}
$bdd->deconnexion();
}
}
?>

View file

@ -0,0 +1,23 @@
<?php
/**
* PHPMailer language file.
* English Version
*/
$PHPMAILER_LANG = array();
$PHPMAILER_LANG["provide_address"] = 'You must provide at least one ' .
'recipient email address.';
$PHPMAILER_LANG["mailer_not_supported"] = ' mailer is not supported.';
$PHPMAILER_LANG["execute"] = 'Could not execute: ';
$PHPMAILER_LANG["instantiate"] = 'Could not instantiate mail function.';
$PHPMAILER_LANG["authenticate"] = 'SMTP Error: Could not authenticate.';
$PHPMAILER_LANG["from_failed"] = 'The following From address failed: ';
$PHPMAILER_LANG["recipients_failed"] = 'Erreur SMTP: The following ' .
'recipients failed: ';
$PHPMAILER_LANG["data_not_accepted"] = 'Erreur SMTP: Données non acceptées.';
$PHPMAILER_LANG["connect_host"] = 'Erreur SMTP: Impossible de se connecter au serveur de mail.';
$PHPMAILER_LANG["file_access"] = 'Accès au fichier impossible: ';
$PHPMAILER_LANG["file_open"] = 'File Error: Ne peut ouvrir le fichier: ';
$PHPMAILER_LANG["encoding"] = 'Type d\'encodage inconnu : ';
?>