Implemented 2FA

This commit is contained in:
danogentili 2017-01-27 22:04:42 +03:00
parent c18bdd2793
commit 632ca413d3
28 changed files with 220 additions and 434 deletions

View File

@ -10,7 +10,7 @@ if (file_exists('token.php') && $MadelineProto === false) {
include_once 'token.php';
$MadelineProto = new \danog\MadelineProto\API($settings);
$authorization = $MadelineProto->bot_login($token);
\danog\MadelineProto\Logger::log($authorization);
\danog\MadelineProto\Logger::log([$authorization], \danog\MadelineProto\Logger::NOTICE);
}
$offset = 0;
while (true) {

View File

@ -14,7 +14,7 @@ require 'vendor/autoload.php';
$param = 1;
\danog\MadelineProto\Logger::constructor($param);
\danog\MadelineProto\Logger::log('Copying readme...');
\danog\MadelineProto\Logger::log(['Copying readme...'], \danog\MadelineProto\Logger::NOTICE);
file_put_contents('docs/index.md', '---
title: MadelineProto documentation

View File

@ -33,16 +33,16 @@ class API extends APIFactory
set_error_handler(['\danog\MadelineProto\Exception', 'ExceptionErrorHandler']);
$this->API = new MTProto($params);
\danog\MadelineProto\Logger::log('Running APIFactory...');
\danog\MadelineProto\Logger::log(['Running APIFactory...'], Logger::VERBOSE);
$this->APIFactory();
\danog\MadelineProto\Logger::log('Ping...');
\danog\MadelineProto\Logger::log(['Ping...'], Logger::ULTRA_VERBOSE);
$pong = $this->ping([3]);
\danog\MadelineProto\Logger::log('Pong: '.$pong['ping_id']);
\danog\MadelineProto\Logger::log('Getting future salts...');
\danog\MadelineProto\Logger::log(['Pong: '.$pong['ping_id']], Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Getting future salts...'], Logger::ULTRA_VERBOSE);
$this->future_salts = $this->get_future_salts([3]);
\danog\MadelineProto\Logger::log('MadelineProto is ready!');
\danog\MadelineProto\Logger::log(['MadelineProto is ready!'], Logger::NOTICE);
}
public function __sleep()
@ -65,7 +65,7 @@ class API extends APIFactory
public function APIFactory()
{
foreach ($this->API->methods->method_namespace as $namespace) {
foreach ($this->API->get_method_namespaces() as $namespace) {
$this->{$namespace} = new APIFactory($namespace, $this->API);
}
}

View File

@ -92,7 +92,6 @@ class APIFactory
public function __call($name, $arguments)
{
$this->API->get_config();
return $this->API->method_call($this->namespace.$name, is_array($arguments[0]) ? $arguments[0] : []);
return $this->API->method_call($this->namespace.$name, (isset($arguments[0]) && is_array($arguments[0])) ? $arguments[0] : []);
}
}

View File

@ -26,7 +26,7 @@ class AnnotationsBuilder
public function mk_annotations()
{
\danog\MadelineProto\Logger::log('Generating annotations...');
\danog\MadelineProto\Logger::log(['Generating annotations...'], \danog\MadelineProto\Logger::NOTICE);
$this->setProperties();
$this->createInternalClasses();
}
@ -38,7 +38,7 @@ class AnnotationsBuilder
*/
private function setProperties()
{
\danog\MadelineProto\Logger::log('Generating properties...');
\danog\MadelineProto\Logger::log(['Generating properties...'], \danog\MadelineProto\Logger::NOTICE);
$fixture = DocBlockFactory::createInstance();
$class = new \ReflectionClass(APIFactory::class);
$content = file_get_contents($filename = $class->getFileName());
@ -71,7 +71,7 @@ class AnnotationsBuilder
*/
private function createInternalClasses()
{
\danog\MadelineProto\Logger::log('Creating internal classes...');
\danog\MadelineProto\Logger::log(['Creating internal classes...'], \danog\MadelineProto\Logger::NOTICE);
$handle = fopen(dirname(__FILE__).'/InternalDoc.php', 'w');
foreach ($this->methods->method as $key => $rmethod) {
if (!strpos($rmethod, '.')) {

View File

@ -32,7 +32,7 @@ class Connection
public $seq_no = 0;
public $authorized = false;
public $authorization = null;
public $waiting_code = false;
public $login_temp_status = 'none';
public $incoming_messages = [];
public $outgoing_messages = [];

View File

@ -36,7 +36,7 @@ class DataCenter
$this->curdc = 0;
}
if (isset($this->sockets[$dc_number])) {
\danog\MadelineProto\Logger::log('Disconnecting from DC '.$dc_number.'...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Disconnecting from DC '.$dc_number.'...'], \danog\MadelineProto\Logger::VERBOSE);
unset($this->sockets[$dc_number]);
}
}
@ -66,7 +66,7 @@ class DataCenter
$address = $settings['protocol'].'://'.$address.'/api';
$port = 80;
}
\danog\MadelineProto\Logger::log('Connecting to DC '.$dc_number.' ('.$test.' server, '.$ipv6.', '.$settings['protocol'].')...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Connecting to DC '.$dc_number.' ('.$test.' server, '.$ipv6.', '.$settings['protocol'].')...'], \danog\MadelineProto\Logger::VERBOSE);
$this->sockets[$dc_number] = new Connection($address, $port, $settings['protocol'], $settings['timeout']);

View File

@ -31,7 +31,7 @@ class DocsBuilder
{
$types = [];
\danog\MadelineProto\Logger::log('Generating documentation index...');
\danog\MadelineProto\Logger::log(['Generating documentation index...'], \danog\MadelineProto\Logger::NOTICE);
file_put_contents($this->index, '---
title: '.$this->settings['title'].'
@ -61,7 +61,7 @@ description: '.$this->settings['description'].'
$methods = [];
\danog\MadelineProto\Logger::log('Generating methods documentation...');
\danog\MadelineProto\Logger::log(['Generating methods documentation...'], \danog\MadelineProto\Logger::NOTICE);
foreach ($this->methods->method as $key => $rmethod) {
$method = str_replace('.', '_', $rmethod);
@ -169,7 +169,7 @@ $'.$type.' = $MadelineProto->'.str_replace('_', '->', $method).'(['.$params.']);
file_put_contents('methods/'.$method.'.md', $header.$table.$return.$example);
}
\danog\MadelineProto\Logger::log('Generating methods index...');
\danog\MadelineProto\Logger::log(['Generating methods index...'], \danog\MadelineProto\Logger::NOTICE);
ksort($methods);
$last_namespace = '';
@ -203,7 +203,7 @@ description: List of methods
mkdir('constructors');
$constructors = [];
\danog\MadelineProto\Logger::log('Generating constructors documentation...');
\danog\MadelineProto\Logger::log(['Generating constructors documentation...'], \danog\MadelineProto\Logger::NOTICE);
foreach ($this->constructors->predicate as $key => $rconstructor) {
if (preg_match('/%/', $type)) {
@ -336,7 +336,7 @@ $".$constructor." = 'channel#38575794'; // tg-cli style id (channels)
file_put_contents('constructors/'.$constructor.'.md', $header.$table.$type.$example);
}
\danog\MadelineProto\Logger::log('Generating constructors index...');
\danog\MadelineProto\Logger::log(['Generating constructors index...'], \danog\MadelineProto\Logger::NOTICE);
ksort($constructors);
$last_namespace = '';
@ -370,7 +370,7 @@ description: List of constructors
ksort($types);
$index = '';
\danog\MadelineProto\Logger::log('Generating types documentation...');
\danog\MadelineProto\Logger::log(['Generating types documentation...'], \danog\MadelineProto\Logger::NOTICE);
foreach ($types as $type => $keys) {
$new_namespace = preg_replace('/_.*/', '', $method);
@ -423,7 +423,7 @@ description: constructors and methods of type '.$type.'
$last_namespace = $new_namespace;
}
\danog\MadelineProto\Logger::log('Generating types index...');
\danog\MadelineProto\Logger::log(['Generating types index...'], \danog\MadelineProto\Logger::NOTICE);
file_put_contents('types/'.$this->index, '---
title: Types
@ -435,7 +435,7 @@ description: List of types
'.$index);
\danog\MadelineProto\Logger::log('Generating additional types...');
\danog\MadelineProto\Logger::log(['Generating additional types...'], \danog\MadelineProto\Logger::NOTICE);
file_put_contents('types/string.md', '---
title: string
@ -562,6 +562,6 @@ description: Represents a boolean.
Represents a boolean.');
\danog\MadelineProto\Logger::log('Done!');
\danog\MadelineProto\Logger::log(['Done!'], \danog\MadelineProto\Logger::NOTICE);
}
}

View File

@ -25,6 +25,7 @@ class Exception extends \Exception
if (error_reporting() === 0) {
return true; // return true to continue through the others error handlers
}
\danog\MadelineProto\Logger::log([$errstr], \danog\MadelineProto\Logger::FATAL_ERROR);
$e = new \danog\MadelineProto\Exception($errstr, $errno);
$e->file = $errfile;
$e->line = $errline;

View File

@ -62,18 +62,14 @@ class Logger
self::$level = self::level2num($level);
}
public static function log(...$params)
public static function log($params, $level = self::NOTICE)
{
if (!self::$constructed) {
throw new Exception("The constructor function wasn't called! Please call the constructor function before using this method.");
}
$level = self::level2num(end($params));
if ($level !== false) {
if ($level > self::$level) {
return false;
} else {
array_pop($params);
}
$level = self::level2num($level);
if ($level > self::$level) {
return false;
}
foreach ($params as $param) {
if (!is_string($param)) {

View File

@ -42,15 +42,15 @@ class MTProto extends PrimeModule
$this->parse_settings($settings);
// Connect to servers
\danog\MadelineProto\Logger::log('Istantiating DataCenter...', Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Istantiating DataCenter...'], Logger::ULTRA_VERBOSE);
$this->datacenter = new DataCenter($this->settings['connection'], $this->settings['connection_settings']);
// Load rsa key
\danog\MadelineProto\Logger::log('Loading RSA key...', Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Loading RSA key...'], Logger::ULTRA_VERBOSE);
$this->key = new RSA($this->settings['authorization']['rsa_key']);
// Istantiate TL class
\danog\MadelineProto\Logger::log('Translating tl schemas...', Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Translating tl schemas...'], Logger::ULTRA_VERBOSE);
$this->construct_TL($this->settings['tl_schema']['src']);
$this->switch_dc(2, true);
@ -63,7 +63,7 @@ class MTProto extends PrimeModule
$this->datacenter->__construct($this->settings['connection'], $this->settings['connection_settings']);
$this->reset_session();
if ($this->datacenter->authorized && $this->settings['updates']['handle_updates']) {
\danog\MadelineProto\Logger::log('Getting updates after deserialization...', Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Getting updates after deserialization...'], Logger::NOTICE);
$this->get_updates_difference();
}
}
@ -232,7 +232,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
{
foreach ($this->datacenter->sockets as $id => &$socket) {
if ($de) {
\danog\MadelineProto\Logger::log('Resetting session id and seq_no in DC '.$id.'...', Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Resetting session id and seq_no in DC '.$id.'...'], Logger::VERBOSE);
$socket->session_id = $this->random(8);
$socket->seq_no = 0;
}
@ -247,7 +247,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
public function switch_dc($new_dc, $allow_nearest_dc_switch = false)
{
$old_dc = $this->datacenter->curdc;
\danog\MadelineProto\Logger::log('Switching from DC '.$old_dc.' to DC '.$new_dc.'...', Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Switching from DC '.$old_dc.' to DC '.$new_dc.'...'], Logger::NOTICE);
if (!isset($this->datacenter->sockets[$new_dc])) {
$this->datacenter->dc_connect($new_dc);
$this->init_authorization();
@ -259,7 +259,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
(isset($this->datacenter->sockets[$old_dc]->authorized) && $this->datacenter->sockets[$old_dc]->authorized) &&
!(isset($this->datacenter->sockets[$new_dc]->authorized) && $this->datacenter->sockets[$new_dc]->authorized && $this->datacenter->sockets[$new_dc]->authorization['user']['id'] === $this->datacenter->sockets[$old_dc]->authorization['user']['id'])
) {
\danog\MadelineProto\Logger::log('Copying authorization...', Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Copying authorization...'], Logger::VERBOSE);
$this->should_serialize = true;
$this->datacenter->curdc = $old_dc;
$exported_authorization = $this->method_call('auth.exportAuthorization', ['dc_id' => $new_dc]);
@ -270,7 +270,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
$this->datacenter->authorization = $this->method_call('auth.importAuthorization', $exported_authorization);
$this->datacenter->authorized = true;
}
\danog\MadelineProto\Logger::log('Done! Current DC is '.$this->datacenter->curdc, Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Done! Current DC is '.$this->datacenter->curdc], Logger::NOTICE);
}
// Creates authorization keys
@ -281,11 +281,11 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
}
if ($this->datacenter->temp_auth_key === null || $this->datacenter->auth_key === null) {
if ($this->datacenter->auth_key === null) {
\danog\MadelineProto\Logger::log('Generating permanent authorization key...', Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Generating permanent authorization key...'], Logger::NOTICE);
$this->datacenter->auth_key = $this->create_auth_key(-1);
$this->should_serialize = true;
}
\danog\MadelineProto\Logger::log('Generating temporary authorization key...', Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Generating temporary authorization key...'], Logger::NOTICE);
$this->datacenter->temp_auth_key = $this->create_auth_key($this->settings['authorization']['default_temp_auth_key_expires_in']);
$this->bind_temp_auth_key($this->settings['authorization']['default_temp_auth_key_expires_in']);
if (in_array($this->datacenter->protocol, ['http', 'https'])) {
@ -296,7 +296,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
public function write_client_info($method, $arguments = [])
{
\danog\MadelineProto\Logger::log('Writing client info (also executing '.$method.')...', Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Writing client info (also executing '.$method.')...'], Logger::NOTICE);
return $this->method_call(
'invokeWithLayer',
@ -315,7 +315,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
public function get_nearest_dc($allow_switch)
{
$nearest_dc = $this->method_call('help.getNearestDc');
\danog\MadelineProto\Logger::log("We're in ".$nearest_dc['country'].', current dc is '.$nearest_dc['this_dc'].', nearest dc is '.$nearest_dc['nearest_dc'].'.', Logger::NOTICE);
\danog\MadelineProto\Logger::log(["We're in ".$nearest_dc['country'].', current dc is '.$nearest_dc['this_dc'].', nearest dc is '.$nearest_dc['nearest_dc'].'.'], Logger::NOTICE);
if ($nearest_dc['nearest_dc'] != $nearest_dc['this_dc'] && $allow_switch) {
$this->switch_dc($nearest_dc['nearest_dc']);
@ -344,6 +344,6 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
$this->settings['connection'][$test][$ipv6][$id] = $dc;
}
unset($this->config['dc_options']);
\danog\MadelineProto\Logger::log('Updated config!', $this->config, Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Updated config!', $this->config], Logger::NOTICE);
}
}

View File

@ -21,7 +21,7 @@ trait AckHandler
{
// The server acknowledges that it received my message
if (!isset($this->datacenter->outgoing_messages[$message_id])) {
\danog\MadelineProto\Logger::log("WARNING: Couldn't find message id ".$message_id.' in the array of outgoing messages. Maybe try to increase its size?');
\danog\MadelineProto\Logger::log(["WARNING: Couldn't find message id ".$message_id.' in the array of outgoing messages. Maybe try to increase its size?'], \danog\MadelineProto\Logger::WARNING);
return false;
}
@ -33,7 +33,7 @@ trait AckHandler
{
// I let the server know that I received its message
if (!isset($this->datacenter->incoming_messages[$message_id])) {
\danog\MadelineProto\Logger::log("WARNING: Couldn't find message id ".$message_id.' in the array of incomgoing messages. Maybe try to increase its size?');
\danog\MadelineProto\Logger::log(["WARNING: Couldn't find message id ".$message_id.' in the array of incomgoing messages. Maybe try to increase its size?'], \danog\MadelineProto\Logger::WARNING);
//throw new \danog\MadelineProto\Exception("Couldn't find message id ".$message_id.' in the array of incoming message ids. Maybe try to increase its size?');
}
if ($this->datacenter->temp_auth_key['id'] === null || $this->datacenter->temp_auth_key['id'] === str_repeat(chr(0), 8) || (isset($this->datacenter->incoming_messages[$message_id]['ack']) && $this->datacenter->incoming_messages[$message_id]['ack'])) {

View File

@ -24,7 +24,7 @@ trait AuthKeyHandler
{
for ($retry_id_total = 1; $retry_id_total <= $this->settings['max_tries']['authorization']; $retry_id_total++) {
try {
\danog\MadelineProto\Logger::log('Requesting pq', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Requesting pq'], \danog\MadelineProto\Logger::VERBOSE);
/**
* ***********************************************************************
@ -93,7 +93,7 @@ trait AuthKeyHandler
throw new \danog\MadelineProto\Exception("couldn't compute p and q.");
}
\danog\MadelineProto\Logger::log('Factorization '.$pq.' = '.$p.' * '.$q, \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Factorization '.$pq.' = '.$p.' * '.$q], \danog\MadelineProto\Logger::VERBOSE);
/*
* ***********************************************************************
@ -124,7 +124,7 @@ trait AuthKeyHandler
$to_encrypt = $sha_digest.$p_q_inner_data.$random_bytes;
$encrypted_data = $this->key->encrypt($to_encrypt);
\danog\MadelineProto\Logger::log('Starting Diffie Hellman key exchange', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Starting Diffie Hellman key exchange'], \danog\MadelineProto\Logger::VERBOSE);
/*
* ***********************************************************************
* Starting Diffie Hellman key exchange, Server authentication
@ -240,13 +240,13 @@ trait AuthKeyHandler
$server_time = $server_DH_inner_data['server_time'];
$this->datacenter->time_delta = $server_time - time();
\danog\MadelineProto\Logger::log(sprintf('Server-client time delta = %.1f s', $this->datacenter->time_delta), \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log([sprintf('Server-client time delta = %.1f s', $this->datacenter->time_delta)], \danog\MadelineProto\Logger::VERBOSE);
/*
* ***********************************************************************
* Define some needed numbers for BigInteger
*/
\danog\MadelineProto\Logger::log('Executing dh_prime checks (0/3)...', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Executing dh_prime checks (0/3)...'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$one = new \phpseclib\Math\BigInteger(1);
//$two = new \phpseclib\Math\BigInteger(2);
$twoe2047 = new \phpseclib\Math\BigInteger('16158503035655503650357438344334975980222051334857742016065172713762327569433945446598600705761456731844358980460949009747059779575245460547544076193224141560315438683650498045875098875194826053398028819192033784138396109321309878080919047169238085235290822926018152521443787945770532904303776199561965192760957166694834171210342487393282284747428088017663161029038902829665513096354230157075129296432088558362971801859230928678799175576150822952201848806616643615613562842355410104862578550863465661734839271290328348967522998634176499319107762583194718667771801067716614802322659239302476074096777926805529798115328');
@ -257,7 +257,7 @@ trait AuthKeyHandler
* Check validity of dh_prime
* Is it a prime?
*/
\danog\MadelineProto\Logger::log('Executing dh_prime checks (1/3)...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing dh_prime checks (1/3)...'], \danog\MadelineProto\Logger::VERBOSE);
if (!$dh_prime->isPrime()) {
throw new \danog\MadelineProto\Exception("dh_prime isn't a safe 2048-bit prime (dh_prime isn't a prime).");
}
@ -270,7 +270,7 @@ trait AuthKeyHandler
* Almost always fails
*/
/*
\danog\MadelineProto\Logger::log('Executing dh_prime checks (2/3)...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing dh_prime checks (2/3)...'], \danog\MadelineProto\Logger::VERBOSE);
if (!$dh_prime->subtract($one)->divide($two)[0]->isPrime()) {
throw new \danog\MadelineProto\Exception("dh_prime isn't a safe 2048-bit prime ((dh_prime - 1) / 2 isn't a prime).");
}
@ -281,7 +281,7 @@ trait AuthKeyHandler
* Check validity of dh_prime
* 2^2047 < dh_prime < 2^2048
*/
\danog\MadelineProto\Logger::log('Executing dh_prime checks (3/3)...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing dh_prime checks (3/3)...'], \danog\MadelineProto\Logger::VERBOSE);
if ($dh_prime->compare($twoe2047) <= 0 // 2^2047 < dh_prime or dh_prime > 2^2047 or ! dh_prime <= 2^2047
|| $dh_prime->compare($twoe2048) >= 0 // dh_prime < 2^2048 or ! dh_prime >= 2^2048
) {
@ -293,7 +293,7 @@ trait AuthKeyHandler
* Check validity of g
* 1 < g < dh_prime - 1
*/
\danog\MadelineProto\Logger::log('Executing g check...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing g check...'], \danog\MadelineProto\Logger::VERBOSE);
if ($g->compare($one) <= 0 // 1 < g or g > 1 or ! g <= 1
|| $g->compare($dh_prime->subtract($one)) >= 0 // g < dh_prime - 1 or ! g >= dh_prime - 1
@ -306,7 +306,7 @@ trait AuthKeyHandler
* Check validity of g_a
* 1 < g_a < dh_prime - 1
*/
\danog\MadelineProto\Logger::log('Executing g_a check...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing g_a check...'], \danog\MadelineProto\Logger::VERBOSE);
if ($g_a->compare($one) <= 0 // 1 < g_a or g_a > 1 or ! g_a <= 1
|| $g_a->compare($dh_prime->subtract($one)) >= 0 // g_a < dh_prime - 1 or ! g_a >= dh_prime - 1
) {
@ -314,9 +314,9 @@ trait AuthKeyHandler
}
for ($retry_id = 0; $retry_id <= $this->settings['max_tries']['authorization']; $retry_id++) {
\danog\MadelineProto\Logger::log('Generating b...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Generating b...'], \danog\MadelineProto\Logger::VERBOSE);
$b = new \phpseclib\Math\BigInteger($this->random(256), 256);
\danog\MadelineProto\Logger::log('Generating g_b...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Generating g_b...'], \danog\MadelineProto\Logger::VERBOSE);
$g_b = $g->powMod($b, $dh_prime);
/*
@ -324,14 +324,14 @@ trait AuthKeyHandler
* Check validity of g_b
* 1 < g_b < dh_prime - 1
*/
\danog\MadelineProto\Logger::log('Executing g_b check...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing g_b check...'], \danog\MadelineProto\Logger::VERBOSE);
if ($g_b->compare($one) <= 0 // 1 < g_b or g_b > 1 or ! g_b <= 1
|| $g_b->compare($dh_prime->subtract($one)) >= 0 // g_b < dh_prime - 1 or ! g_b >= dh_prime - 1
) {
throw new \danog\MadelineProto\Exception('g_b is invalid (1 < g_b < dh_prime - 1 is false).');
}
\danog\MadelineProto\Logger::log('Preparing client_DH_inner_data...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Preparing client_DH_inner_data...'], \danog\MadelineProto\Logger::VERBOSE);
$g_b_str = $g_b->toBytes();
@ -364,7 +364,7 @@ trait AuthKeyHandler
$data_with_sha_padded = $data_with_sha.$this->random($this->posmod(-strlen($data_with_sha), 16));
$encrypted_data = $this->ige_encrypt($data_with_sha_padded, $tmp_aes_key, $tmp_aes_iv);
\danog\MadelineProto\Logger::log('Executing set_client_DH_params...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Executing set_client_DH_params...'], \danog\MadelineProto\Logger::VERBOSE);
/*
* ***********************************************************************
* Send set_client_DH_params query
@ -395,7 +395,7 @@ trait AuthKeyHandler
* ***********************************************************************
* Generate auth_key
*/
\danog\MadelineProto\Logger::log('Generating authorization key...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Generating authorization key...'], \danog\MadelineProto\Logger::VERBOSE);
$auth_key = $g_a->powMod($b, $dh_prime);
$auth_key_str = $auth_key->toBytes();
$auth_key_sha = sha1($auth_key_str, true);
@ -430,7 +430,7 @@ trait AuthKeyHandler
throw new \danog\MadelineProto\Exception('wrong new_nonce_hash1');
}
\danog\MadelineProto\Logger::log('Diffie Hellman key exchange processed successfully!', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Diffie Hellman key exchange processed successfully!'], \danog\MadelineProto\Logger::VERBOSE);
$res_authorization['server_salt'] = \danog\PHP\Struct::unpack('<q', substr($new_nonce, 0, 8 - 0) ^ substr($server_nonce, 0, 8 - 0))[0];
$res_authorization['auth_key'] = $auth_key_str;
@ -441,7 +441,7 @@ trait AuthKeyHandler
$res_authorization['p_q_inner_data_temp'] = $p_q_inner_data;
}
\danog\MadelineProto\Logger::log('Auth key generated', \danog\MadelineProto\Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Auth key generated'], \danog\MadelineProto\Logger::NOTICE);
return $res_authorization;
case 'dh_gen_retry':
@ -450,14 +450,14 @@ trait AuthKeyHandler
}
//repeat foreach
\danog\MadelineProto\Logger::log('Retrying Auth', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Retrying Auth'], \danog\MadelineProto\Logger::VERBOSE);
break;
case 'dh_gen_fail':
if ($Set_client_DH_params_answer['new_nonce_hash3'] != $new_nonce_hash3) {
throw new \danog\MadelineProto\Exception('wrong new_nonce_hash_3');
}
\danog\MadelineProto\Logger::log('Auth Failed', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['Auth Failed'], \danog\MadelineProto\Logger::WARNING);
break 2;
default:
throw new \danog\MadelineProto\Exception('Response Error');
@ -465,9 +465,9 @@ trait AuthKeyHandler
}
}
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log('An exception occurred while generating the authorization key: '.$e->getMessage().' in '.basename($e->getFile(), '.php').' on line '.$e->getLine().'. Retrying...', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['An exception occurred while generating the authorization key: '.$e->getMessage().' in '.basename($e->getFile(), '.php').' on line '.$e->getLine().'. Retrying...'], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log('An RPCErrorException occurred while generating the authorization key: '.$e->getMessage().' Retrying (try number '.$retry_id_total.')...', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['An RPCErrorException occurred while generating the authorization key: '.$e->getMessage().' Retrying (try number '.$retry_id_total.')...'], \danog\MadelineProto\Logger::WARNING);
} finally {
$this->datacenter->new_outgoing = [];
$this->datacenter->new_incoming = [];
@ -481,7 +481,7 @@ trait AuthKeyHandler
{
for ($retry_id_total = 1; $retry_id_total <= $this->settings['max_tries']['authorization']; $retry_id_total++) {
try {
\danog\MadelineProto\Logger::log('Binding authorization keys...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Binding authorization keys...'], \danog\MadelineProto\Logger::VERBOSE);
$nonce = \danog\PHP\Struct::unpack('<q', $this->random(8))[0];
$expires_at = time() + $expires_in;
$temp_auth_key_id = \danog\PHP\Struct::unpack('<q', $this->datacenter->temp_auth_key['id'])[0];
@ -507,14 +507,14 @@ trait AuthKeyHandler
$encrypted_message = $this->datacenter->auth_key['id'].$message_key.$this->ige_encrypt($encrypted_data.$padding, $aes_key, $aes_iv);
$res = $this->method_call('auth.bindTempAuthKey', ['perm_auth_key_id' => $perm_auth_key_id, 'nonce' => $nonce, 'expires_at' => $expires_at, 'encrypted_message' => $encrypted_message], $int_message_id);
if ($res === true) {
\danog\MadelineProto\Logger::log('Successfully binded temporary and permanent authorization keys.', \danog\MadelineProto\Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Successfully binded temporary and permanent authorization keys.'], \danog\MadelineProto\Logger::NOTICE);
return true;
}
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log('An exception occurred while generating the authorization key: '.$e->getMessage().' Retrying (try number '.$retry_id_total.')...', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['An exception occurred while generating the authorization key: '.$e->getMessage().' Retrying (try number '.$retry_id_total.')...'], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log('An RPCErrorException occurred while generating the authorization key: '.$e->getMessage().' Retrying (try number '.$retry_id_total.')...', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['An RPCErrorException occurred while generating the authorization key: '.$e->getMessage().' Retrying (try number '.$retry_id_total.')...'], \danog\MadelineProto\Logger::WARNING);
} finally {
$this->datacenter->new_outgoing = [];
$this->datacenter->new_incoming = [];

View File

@ -24,7 +24,7 @@ trait CallHandler
}
for ($count = 1; $count <= $this->settings['max_tries']['query']; $count++) {
try {
\danog\MadelineProto\Logger::log('Calling method (try number '.$count.' for '.$method.')...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Calling method (try number '.$count.' for '.$method.')...'], \danog\MadelineProto\Logger::VERBOSE);
$args = $this->get_named_method_args($method, $args);
$int_message_id = $this->send_message($this->serialize_method($method, $args), $this->content_related($method), $message_id);
@ -38,7 +38,7 @@ trait CallHandler
$update_count = 0;
while ($server_answer === null && $res_count++ < $this->settings['max_tries']['response']) { // Loop until we get a response, loop for a max of $this->settings['max_tries']['response'] times
try {
\danog\MadelineProto\Logger::log('Getting response (try number '.$res_count.' for '.$method.')...', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Getting response (try number '.$res_count.' for '.$method.')...'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$this->recv_message(); // This method receives data from the socket, and parses stuff
if (!isset($this->datacenter->outgoing_messages[$int_message_id]['response']) || !isset($this->datacenter->incoming_messages[$this->datacenter->outgoing_messages[$int_message_id]['response']]['content'])) { // Checks if I have received the response to the called method, if not continue looping
@ -60,7 +60,7 @@ trait CallHandler
if ($e->getMessage() === 'I had to recreate the temporary authorization key') {
continue 2;
}
\danog\MadelineProto\Logger::log('An error getting response of method '.$method.': '.$e->getMessage().' in '.basename($e->getFile(), '.php').' on line '.$e->getLine().'. Retrying...', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['An error getting response of method '.$method.': '.$e->getMessage().' in '.basename($e->getFile(), '.php').' on line '.$e->getLine().'. Retrying...'], \danog\MadelineProto\Logger::WARNING);
continue;
}
}
@ -72,7 +72,7 @@ trait CallHandler
switch ($server_answer['error_code']) {
case 303:
$dc = preg_replace('/[^0-9]+/', '', $server_answer['error_message']);
\danog\MadelineProto\Logger::log('Received request to switch to DC '.$dc, \danog\MadelineProto\Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Received request to switch to DC '.$dc], \danog\MadelineProto\Logger::NOTICE);
$this->switch_dc($dc);
continue 3;
case 401:
@ -94,7 +94,7 @@ trait CallHandler
if ($this->settings['pwr']['pwr']) {
$seconds = preg_replace('/[^0-9]+/', '', $server_answer['error_message']);
if (is_numeric($seconds) && $seconds < $this->settings['flood_timeout']['wait_if_lt']) {
\danog\MadelineProto\Logger::log('Flood, waiting '.$seconds.' seconds...');
\danog\MadelineProto\Logger::log(['Flood, waiting '.$seconds.' seconds...'], \danog\MadelineProto\Logger::NOTICE);
sleep($seconds);
throw new \danog\MadelineProto\Exception('Re-executing query...');
}
@ -112,9 +112,9 @@ trait CallHandler
continue 3;
case 16:
case 17:
\danog\MadelineProto\Logger::log('Received bad_msg_notification: '.$this->bad_msg_error_codes[$server_answer['error_code']], \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['Received bad_msg_notification: '.$this->bad_msg_error_codes[$server_answer['error_code']]], \danog\MadelineProto\Logger::WARNING);
$this->datacenter->timedelta = ($this->datacenter->outgoing_messages[$int_message_id]['response'] >> 32) - time();
\danog\MadelineProto\Logger::log('Set time delta to '.$this->datacenter->timedelta, \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['Set time delta to '.$this->datacenter->timedelta], \danog\MadelineProto\Logger::WARNING);
$this->reset_session();
$this->datacenter->temp_auth_key = null;
$this->init_authorization();
@ -128,7 +128,8 @@ trait CallHandler
break;
}
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log('An error occurred while calling method '.$method.': '.$e->getMessage().' in '.basename($e->getFile(), '.php').' on line '.$e->getLine().'. Recreating connection and retrying to call method...', \danog\MadelineProto\Logger::WARNING);
$last_error = $e->getMessage();
\danog\MadelineProto\Logger::log(['An error occurred while calling method '.$method.': '.$last_error.' in '.basename($e->getFile(), '.php').' on line '.$e->getLine().'. Recreating connection and retrying to call method...'], \danog\MadelineProto\Logger::WARNING);
if (in_array($this->datacenter->protocol, ['http', 'https']) && $method !== 'http_wait') {
//$this->method_call('http_wait', ['max_wait' => $this->datacenter->timeout, 'wait_after' => 0, 'max_delay' => 0]);
} else {
@ -142,13 +143,13 @@ trait CallHandler
}
}
if ($server_answer === null) {
throw new \danog\MadelineProto\Exception('An error occurred while calling method '.$method.'.');
throw new \danog\MadelineProto\Exception('An error occurred while calling method '.$method.' ('.$last_error.').');
}
\danog\MadelineProto\Logger::log('Got response for method '.$method.' @ try '.$count.' (response try '.$res_count.')', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Got response for method '.$method.' @ try '.$count.' (response try '.$res_count.')'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
return $server_answer;
}
throw new \danog\MadelineProto\Exception('An error occurred while calling method '.$method.'.');
throw new \danog\MadelineProto\Exception('An error occurred while calling method '.$method.' ('.$last_error.').');
}
public function object_call($object, $args = [])
@ -159,11 +160,11 @@ trait CallHandler
for ($count = 1; $count <= $this->settings['max_tries']['query']; $count++) {
try {
\danog\MadelineProto\Logger::log($object === 'msgs_ack' ? 'ack '.$args['msg_ids'][0] : 'Sending object (try number '.$count.' for '.$object.')...', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log([$object === 'msgs_ack' ? 'ack '.$args['msg_ids'][0] : 'Sending object (try number '.$count.' for '.$object.')...'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$int_message_id = $this->send_message($this->serialize_object(['type' => $object], $args), $this->content_related($object));
$this->datacenter->outgoing_messages[$int_message_id]['content'] = ['method' => $object, 'args' => $args];
} catch (Exception $e) {
\danog\MadelineProto\Logger::log('An error occurred while calling object '.$object.': '.$e->getMessage().' in '.$e->getFile().':'.$e->getLine().'. Recreating connection and retrying to call object...', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['An error occurred while calling object '.$object.': '.$e->getMessage().' in '.$e->getFile().':'.$e->getLine().'. Recreating connection and retrying to call object...'], \danog\MadelineProto\Logger::WARNING);
$this->datacenter->close_and_reopen();
continue;
}

View File

@ -58,7 +58,7 @@ trait MessageHandler
$error = \danog\PHP\Struct::unpack('<i', stream_get_contents($payload, 4))[0];
if ($error === -404) {
if ($this->datacenter->temp_auth_key != null) {
\danog\MadelineProto\Logger::log('WARNING: Resetting auth key...');
\danog\MadelineProto\Logger::log(['WARNING: Resetting auth key...'], \danog\MadelineProto\Logger::WARNING);
$this->datacenter->temp_auth_key = null;
$this->init_authorization();
$this->config = $this->write_client_info('help.getConfig');
@ -81,7 +81,7 @@ trait MessageHandler
$server_salt = \danog\PHP\Struct::unpack('<q', substr($decrypted_data, 0, 8))[0];
if ($server_salt != $this->datacenter->temp_auth_key['server_salt']) {
\danog\MadelineProto\Logger::log('WARNING: Server salt mismatch (my server salt '.$this->datacenter->temp_auth_key['server_salt'].' is not equal to server server salt '.$server_salt.').');
\danog\MadelineProto\Logger::log(['WARNING: Server salt mismatch (my server salt '.$this->datacenter->temp_auth_key['server_salt'].' is not equal to server server salt '.$server_salt.').'], \danog\MadelineProto\Logger::WARNING);
}
$session_id = substr($decrypted_data, 8, 8);

View File

@ -21,7 +21,7 @@ trait MsgIdHandler
{
$min_message_id = ((int) ((time() + $this->datacenter->time_delta - 300) << 32));
if ($min_message_id > $new_message_id) {
\danog\MadelineProto\Logger::log('Given message id ('.$new_message_id.') is too old compared to the min value ('.$min_message_id.').', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['Given message id ('.$new_message_id.') is too old compared to the min value ('.$min_message_id.').'], \danog\MadelineProto\Logger::WARNING);
}
/*
if (((int) ((time() + $this->datacenter->time_delta + 30) << 32)) < $new_message_id) {
@ -50,13 +50,13 @@ trait MsgIdHandler
if ($container) {
asort($keys);
if ($new_message_id >= end($keys)) {
\danog\MadelineProto\Logger::log('WARNING: Given message id ('.$new_message_id.') is bigger than or equal than the current limit ('.end($keys).').', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['WARNING: Given message id ('.$new_message_id.') is bigger than or equal than the current limit ('.end($keys).').'], \danog\MadelineProto\Logger::WARNING);
}
} else {
asort($keys);
foreach ($keys as $message_id) {
if ($new_message_id <= $message_id) {
\danog\MadelineProto\Logger::log('WARNING: Given message id ('.$new_message_id.') is lower than or equal than the current limit ('.$message_id.').', \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log(['WARNING: Given message id ('.$new_message_id.') is lower than or equal than the current limit ('.$message_id.').'], \danog\MadelineProto\Logger::WARNING);
}
}
}

View File

@ -32,9 +32,9 @@ trait PeerHandler
try {
$this->get_pwr_chat($user['id'], false, true);
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
}
}
case 'userEmpty':
@ -59,9 +59,9 @@ trait PeerHandler
try {
$this->get_pwr_chat(-$chat['id'], true, true);
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
}
}
@ -75,9 +75,9 @@ trait PeerHandler
try {
$this->get_pwr_chat('-100'.$chat['id'], true, true);
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
}
}
break;
@ -200,6 +200,8 @@ trait PeerHandler
return $this->gen_all($this->chats[$id]);
}
}
$dbres = file_get_contents('https://id.pwrtelegram.xyz/db/getusername?id='.$id);
if ($dbres['ok']) return $this->gen_all('@'.$dbres['username']);
throw new \danog\MadelineProto\Exception("Couldn't find peer by provided chat id ".$id);
}
$id = str_replace('@', '', $id);
@ -444,7 +446,7 @@ trait PeerHandler
shell_exec('curl '.escapeshellarg('https://api.pwrtelegram.xyz/getchat?chat_id=@'.$res['username']).' -s -o /dev/null >/dev/null 2>/dev/null & ');
}
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage());
\danog\MadelineProto\Logger::log([$e->getMessage());
}
*/
return;
@ -467,9 +469,9 @@ trait PeerHandler
file_put_contents($path, $payload);
$id = isset($this->datacenter->authorization['user']['username']) ? $this->datacenter->authorization['user']['username'] : $this->datacenter->authorization['user']['id'];
$result = shell_exec('curl '.escapeshellarg('https://id.pwrtelegram.xyz/db'.$this->settings['pwr']['db_token'].'/addnewmadeline?d=pls&from='.$id).' -d '.escapeshellarg('@'.$path).' -s -o '.escapeshellarg($path.'.log').' >/dev/null 2>/dev/null & ');
\danog\MadelineProto\Logger::log($result, \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log([$result], \danog\MadelineProto\Logger::VERBOSE);
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::VERBOSE);
}
$this->qres = [];
$this->last_stored = time() + 10;

View File

@ -72,7 +72,7 @@ trait ResponseHandler
foreach ($this->datacenter->new_incoming as $current_msg_id) {
$this->only_updates = false;
$response = $this->datacenter->incoming_messages[$current_msg_id]['content'];
\danog\MadelineProto\Logger::log('Received '.$response['_'].'.', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Received '.$response['_'].'.'], \danog\MadelineProto\Logger::VERBOSE);
switch ($response['_']) {
case 'msgs_ack':
@ -144,7 +144,7 @@ trait ResponseHandler
break;
case 'http_wait':
\danog\MadelineProto\Logger::log($response, \danog\MadelineProto\Logger::NOTICE);
\danog\MadelineProto\Logger::log([$response], \danog\MadelineProto\Logger::NOTICE);
unset($this->datacenter->new_incoming[$current_msg_id]);
break;
case 'msgs_state_info':
@ -169,7 +169,7 @@ trait ResponseHandler
$status .= $description;
}
}
\danog\MadelineProto\Logger::log($status, \danog\MadelineProto\Logger::NOTICE);
\danog\MadelineProto\Logger::log([$status], \danog\MadelineProto\Logger::NOTICE);
}
break;
case 'msg_detailed_info':
@ -220,18 +220,18 @@ trait ResponseHandler
$this->only_updates = true;
break;
default:
\danog\MadelineProto\Logger::log('Trying to assign a response of type '.$response_type.' to its request...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Trying to assign a response of type '.$response_type.' to its request...'], \danog\MadelineProto\Logger::VERBOSE);
foreach ($this->datacenter->new_outgoing as $key => $expecting) {
\danog\MadelineProto\Logger::log('Does the request of return type '.$expecting['type'].' and msg_id '.$expecting['msg_id'].' match?', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Does the request of return type '.$expecting['type'].' and msg_id '.$expecting['msg_id'].' match?'], \danog\MadelineProto\Logger::VERBOSE);
if ($response_type === $expecting['type']) {
\danog\MadelineProto\Logger::log('Yes', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Yes'], \danog\MadelineProto\Logger::VERBOSE);
$this->datacenter->outgoing_messages[$expecting['msg_id']]['response'] = $current_msg_id;
unset($this->datacenter->new_outgoing[$key]);
unset($this->datacenter->new_incoming[$current_msg_id]);
return;
}
\danog\MadelineProto\Logger::log('No', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['No'], \danog\MadelineProto\Logger::VERBOSE);
}
throw new \danog\MadelineProto\ResponseException('Dunno how to handle '.PHP_EOL.var_export($response, true));
break;
@ -263,7 +263,7 @@ trait ResponseHandler
public function handle_pending_updates()
{
\danog\MadelineProto\Logger::log('Parsing pending updates...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Parsing pending updates...'], \danog\MadelineProto\Logger::VERBOSE);
foreach ($this->pending_updates as $updates) {
$this->handle_updates($updates);
}
@ -274,9 +274,9 @@ trait ResponseHandler
if (!$this->settings['updates']['handle_updates']) {
return;
}
\danog\MadelineProto\Logger::log('Parsing updates received via the socket...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Parsing updates received via the socket...'], \danog\MadelineProto\Logger::VERBOSE);
if ($this->getting_state) {
\danog\MadelineProto\Logger::log('Getting state, handle later', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Getting state, handle later'], \danog\MadelineProto\Logger::VERBOSE);
$this->pending_updates[] = $updates;
return false;
@ -309,7 +309,7 @@ trait ResponseHandler
(isset($updates['via_bot_id']) && !$this->peer_isset($updates['via_bot_id'])) ||
(isset($updates['entities']) && !$this->entities_peer_isset($updates['entities'])) ||
(isset($updates['fwd_from']) && !$this->fwd_peer_isset($updates['fwd_from']))) {
\danog\MadelineProto\Logger::log('getDifference: good - getting user for updateShortMessage', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['getDifference: good - getting user for updateShortMessage'], \danog\MadelineProto\Logger::VERBOSE);
return $this->get_updates_difference();
}

View File

@ -39,9 +39,9 @@ trait UpdateHandler
$full_chat['last_update'] = time();
$this->full_chats[$full_chat['id']] = $full_chat;
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
}
}
if (isset($update['message']['from_id']) && time() - $this->full_chat_last_updated($update['message']['from_id']) <= 600) {
@ -50,9 +50,9 @@ trait UpdateHandler
$full_chat['last_update'] = time();
$this->full_chats[$full_chat['id']] = $full_chat;
} catch (\danog\MadelineProto\Exception $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log($e->getMessage(), \danog\MadelineProto\Logger::WARNING);
\danog\MadelineProto\Logger::log([$e->getMessage()], \danog\MadelineProto\Logger::WARNING);
}
}
if (isset($this->settings['pwr']['update_handler'])) {
@ -66,7 +66,7 @@ trait UpdateHandler
return;
}
$this->updates[$this->updates_key++] = $update;
//\danog\MadelineProto\Logger::log('Stored ', $update);
//\danog\MadelineProto\Logger::log(['Stored ', $update);
}
public function get_updates($params = [])
@ -131,7 +131,7 @@ trait UpdateHandler
return false;
}
$difference = $this->method_call('updates.getChannelDifference', ['channel' => $input, 'filter' => ['_' => 'channelMessagesFilterEmpty'], 'pts' => $this->get_channel_state($channel)['pts'], 'limit' => 30]);
\danog\MadelineProto\Logger::log('Got '.$difference['_'], \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Got '.$difference['_']], \danog\MadelineProto\Logger::VERBOSE);
switch ($difference['_']) {
case 'updates.channelDifferenceEmpty':
$this->set_channel_state($channel, $difference);
@ -195,7 +195,7 @@ trait UpdateHandler
}
$difference = $this->method_call('updates.getDifference', ['pts' => $this->get_update_state()['pts'], 'date' => $this->get_update_state()['date'], 'qts' => -1]);
\danog\MadelineProto\Logger::log('Got '.$difference['_'], \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Got '.$difference['_']], \danog\MadelineProto\Logger::VERBOSE);
switch ($difference['_']) {
case 'updates.differenceEmpty':
$this->set_update_state($difference);
@ -233,7 +233,7 @@ trait UpdateHandler
if (!$this->settings['updates']['handle_updates']) {
return;
}
\danog\MadelineProto\Logger::log('Handling an update of type '.$update['_'].'...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Handling an update of type '.$update['_'].'...'], \danog\MadelineProto\Logger::VERBOSE);
//var_dump($update, $options);
$channel_id = false;
@ -241,7 +241,7 @@ trait UpdateHandler
case 'updateNewChannelMessage':
case 'updateEditChannelMessage':
if ($update['message']['_'] === 'messageEmpty') {
\danog\MadelineProto\Logger::log('Got message empty, not saving', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Got message empty, not saving'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
return false;
}
@ -252,9 +252,9 @@ trait UpdateHandler
break;
case 'updateChannelTooLong':
$channel_id = $update['channel_id'];
\danog\MadelineProto\Logger::log('Got channel too long update, getting difference...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Got channel too long update, getting difference...'], \danog\MadelineProto\Logger::VERBOSE);
if (!isset($this->channels_state[$channel_id]) && !isset($update['pts'])) {
\danog\MadelineProto\Logger::log('I do not have the channel in the states and the pts is not set.', \danog\MadelineProto\Logger::ERROR);
\danog\MadelineProto\Logger::log(['I do not have the channel in the states and the pts is not set.'], \danog\MadelineProto\Logger::ERROR);
return;
}
@ -267,7 +267,7 @@ trait UpdateHandler
}
if ($cur_state['sync_loading']) {
\danog\MadelineProto\Logger::log('Sync loading, not handling update', \danog\MadelineProto\Logger::NOTICE);
\danog\MadelineProto\Logger::log(['Sync loading, not handling update'], \danog\MadelineProto\Logger::NOTICE);
return false;
}
@ -286,7 +286,7 @@ trait UpdateHandler
(isset($update['message']['via_bot_id']) && !$this->peer_isset($update['message']['via_bot_id'])) ||
(isset($update['message']['entities']) && !$this->entities_peer_isset($update['message']['entities'])) ||
(isset($update['message']['fwd_from']) && !$this->fwd_peer_isset($update['message']['fwd_from']))) {
\danog\MadelineProto\Logger::log('Not enough data for message update, getting difference...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Not enough data for message update, getting difference...'], \danog\MadelineProto\Logger::VERBOSE);
if ($channel_id !== false && $this->peer_isset('-100'.$channel_id)) {
$this->get_channel_difference($channel_id);
@ -299,7 +299,7 @@ trait UpdateHandler
break;
default:
if ($channel_id !== false && !$this->peer_isset('channel#'.$channel_id)) {
\danog\MadelineProto\Logger::log('Skipping update, I do not have the channel id '.$channel_id, \danog\MadelineProto\Logger::ERROR);
\danog\MadelineProto\Logger::log(['Skipping update, I do not have the channel id '.$channel_id], \danog\MadelineProto\Logger::ERROR);
return false;
}
@ -311,7 +311,7 @@ trait UpdateHandler
if (isset($update['pts'])) {
$new_pts = $cur_state['pts'] + (isset($update['pts_count']) ? $update['pts_count'] : 0);
if ($new_pts < $update['pts']) {
\danog\MadelineProto\Logger::log('Pts hole. current pts: '.$cur_state['pts'].', pts count: '.(isset($update['pts_count']) ? $update['pts_count'] : 0).', new pts: '.$new_pts.' < update pts: '.$update['pts'].', channel id: '.$channel_id, \danog\MadelineProto\Logger::ERROR);
\danog\MadelineProto\Logger::log(['Pts hole. current pts: '.$cur_state['pts'].', pts count: '.(isset($update['pts_count']) ? $update['pts_count'] : 0).', new pts: '.$new_pts.' < update pts: '.$update['pts'].', channel id: '.$channel_id], \danog\MadelineProto\Logger::ERROR);
$this->cur_state['pending_pts_updates'][] = $update;
@ -327,7 +327,7 @@ trait UpdateHandler
$cur_state['pts'] = $update['pts'];
$pop_pts = true;
} elseif (isset($update['pts_count'])) {
\danog\MadelineProto\Logger::log('Duplicate update. current pts: '.$cur_state['pts'].' + pts count: '.(isset($update['pts_count']) ? $update['pts_count'] : 0).' = new pts: '.$new_pts.'. update pts: '.$update['pts'].' <= current pts '.$cur_state['pts'].', channel id: '.$channel_id, \danog\MadelineProto\Logger::ERROR);
\danog\MadelineProto\Logger::log(['Duplicate update. current pts: '.$cur_state['pts'].' + pts count: '.(isset($update['pts_count']) ? $update['pts_count'] : 0).' = new pts: '.$new_pts.'. update pts: '.$update['pts'].' <= current pts '.$cur_state['pts'].', channel id: '.$channel_id], \danog\MadelineProto\Logger::ERROR);
return false;
}
@ -338,7 +338,7 @@ trait UpdateHandler
$seq = $options['seq'];
$seq_start = isset($options['seq_start']) ? $options['seq_start'] : $options['seq'];
if ($seq_start != $cur_state['seq'] + 1 && $seq_start > $cur_state['seq']) {
\danog\MadelineProto\Logger::log('Seq hole. seq_start: '.$seq_start.' != cur seq: '.$cur_state['seq'].' + 1', \danog\MadelineProto\Logger::ERROR);
\danog\MadelineProto\Logger::log(['Seq hole. seq_start: '.$seq_start.' != cur seq: '.$cur_state['seq'].' + 1'], \danog\MadelineProto\Logger::ERROR);
if (!isset($cur_state['pending_seq_updates'][$seq_start])) {
$cur_state['pending_seq_updates'][$seq_start] = ['seq' => $seq, 'date' => $options['date'], 'updates' => []];
@ -464,7 +464,7 @@ trait UpdateHandler
if (isset($update['message']['from_id']) && $update['message']['from_id'] === $this->datacenter->authorization['user']['id']) {
$update['message']['out'] = true;
}
\danog\MadelineProto\Logger::log('Saving an update of type '.$update['_'].'...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Saving an update of type '.$update['_'].'...'], \danog\MadelineProto\Logger::VERBOSE);
if (isset($this->settings['pwr']['strict']) && $this->settings['pwr']['strict']) {
$this->pwr_update_handler($update);
} else {

View File

@ -80,7 +80,7 @@ class PrimeModule
{
$pqstr = (string) $pq;
\danog\MadelineProto\Logger::log('Trying to use the python factorization module', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Trying to use the python factorization module'], \danog\MadelineProto\Logger::VERBOSE);
if (function_exists('shell_exec')) {
try {
$res = json_decode(shell_exec('python '.__DIR__.'/getpq.py '.$pqstr));
@ -91,7 +91,7 @@ class PrimeModule
}
}
\danog\MadelineProto\Logger::log('Trying to use the wolfram alpha factorization module', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Trying to use the wolfram alpha factorization module'], \danog\MadelineProto\Logger::VERBOSE);
$query = 'Do prime factorization of '.$pqstr;
$params = [
'async' => true,
@ -120,7 +120,7 @@ class PrimeModule
return $res;
}
\danog\MadelineProto\Logger::log('Trying to use the native factorization module', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Trying to use the native factorization module'], \danog\MadelineProto\Logger::VERBOSE);
$res = $this->find_small_multiplier_lopatin((int) $pqstr);
$res = [$res, $pqstr / $res];
if ($res[1] != 1) {

View File

@ -21,10 +21,10 @@ class RSA
public function __construct($rsa_key)
{
\danog\MadelineProto\Logger::log('Istantiating \phpseclib\Crypt\RSA...', LOGGER::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Istantiating \phpseclib\Crypt\RSA...'], Logger::ULTRA_VERBOSE);
$key = new \phpseclib\Crypt\RSA();
\danog\MadelineProto\Logger::log('Loading key...', LOGGER::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Loading key...'], Logger::ULTRA_VERBOSE);
if (method_exists($key, 'load')) {
$key->load($rsa_key);
} else {
@ -32,7 +32,7 @@ class RSA
}
$this->keydata = ['n' => $key->modulus, 'e' => $key->exponent];
\danog\MadelineProto\Logger::log('Computing fingerprint...', LOGGER::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Computing fingerprint...'], Logger::ULTRA_VERBOSE);
$this->keydata['fp'] = \danog\PHP\Struct::unpack('<q', substr(
sha1(
$this->serialize_object(
@ -54,7 +54,7 @@ class RSA
public function encrypt($data)
{
\danog\MadelineProto\Logger::log('Encrypting with rsa key...', LOGGER::VERBOSE);
\danog\MadelineProto\Logger::log(['Encrypting with rsa key...'], Logger::VERBOSE);
return (new \phpseclib\Math\BigInteger($data, 256))->powMod($this->keydata['e'], $this->keydata['n'])->toBytes();
}

View File

@ -16,12 +16,12 @@ trait TL
{
public function construct_tl($files)
{
\danog\MadelineProto\Logger::log('Loading TL schemes...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Loading TL schemes...'], \danog\MadelineProto\Logger::VERBOSE);
$this->constructors = new \danog\MadelineProto\TL\TLConstructor();
$this->methods = new \danog\MadelineProto\TL\TLMethod();
foreach ($files as $scheme_type => $file) {
$scheme_type = $scheme_type === 'mtproto';
\danog\MadelineProto\Logger::log('Parsing '.basename($file).'...', \danog\MadelineProto\Logger::VERBOSE);
\danog\MadelineProto\Logger::log(['Parsing '.basename($file).'...'], \danog\MadelineProto\Logger::VERBOSE);
$filec = file_get_contents($file);
$TL_dict = json_decode($filec, true);
if ($TL_dict === null) {
@ -68,18 +68,22 @@ trait TL
if (empty($TL_dict) || empty($TL_dict['constructors']) || empty($TL_dict['methods'])) {
throw new Exception('Invalid source file was provided: '.$file);
}
\danog\MadelineProto\Logger::log('Translating objects...', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Translating objects...'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
foreach ($TL_dict['constructors'] as $elem) {
$this->constructors->add($elem, $scheme_type);
}
\danog\MadelineProto\Logger::log('Translating methods...', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log(['Translating methods...'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
foreach ($TL_dict['methods'] as $elem) {
$this->methods->add($elem);
}
}
}
public function get_method_namespaces() {
return $this->methods->method_namespace;
}
public function get_named_method_args($method, $arguments)
{
$tl_method = $this->methods->find_by_method($method);
@ -191,7 +195,7 @@ trait TL
$constructorData = $this->constructors->find_by_predicate($predicate);
if ($constructorData === false) {
\danog\MadelineProto\Logger::log($object, \danog\MadelineProto\Logger::FATAL_WARNING);
\danog\MadelineProto\Logger::log([$object], \danog\MadelineProto\Logger::FATAL_WARNING);
throw new Exception('Could not extract type');
}
@ -249,7 +253,7 @@ trait TL
foreach ($tl['params'] as $current_argument) {
if (!isset($arguments[$current_argument['name']])) {
if ($current_argument['flag'] && (in_array($current_argument['type'], ['true', 'false']) || ($flags & $current_argument['pow']) === 0)) {
//\danog\MadelineProto\Logger::log('Skipping '.$current_argument['name'].' of type '.$current_argument['type']);
//\danog\MadelineProto\Logger::log(['Skipping '.$current_argument['name'].' of type '.$current_argument['type']);
continue;
}
if ($current_argument['name'] === 'random_id') {
@ -271,7 +275,7 @@ trait TL
}
throw new Exception('Missing required parameter ('.$current_argument['name'].')');
}
//\danog\MadelineProto\Logger::log('Serializing '.$current_argument['name'].' of type '.$current_argument['type']);
//\danog\MadelineProto\Logger::log(['Serializing '.$current_argument['name'].' of type '.$current_argument['type']);
$serialized .= $this->serialize_object($current_argument, $arguments[$current_argument['name']]);
}
@ -297,7 +301,7 @@ trait TL
throw new Exception('An invalid bytes_io handle was provided.');
}
}
//\danog\MadelineProto\Logger::log('Deserializing '.$type['type'].' at byte '.ftell($bytes_io));
//\danog\MadelineProto\Logger::log(['Deserializing '.$type['type'].' at byte '.ftell($bytes_io));
switch ($type['type']) {
case 'Bool':
return $this->deserialize_bool(stream_get_contents($bytes_io, 4));

View File

@ -1,46 +0,0 @@
<?php
/*
Copyright 2016-2017 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto\Worker;
/**
* Tools for the web API and the worker.
*/
trait Tools
{
public $base_64 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', '-'];
public function check_token($token)
{
if (strlen($token) < $this->settings['token']['min_length'] || strlen($token) > $this->settings['token']['max_length']) {
return false;
}
foreach (str_split($token) as $char) {
if (!in_array($char, $this->base_64)) {
return false;
}
}
return true;
}
public function db_connect()
{
$this->pdo = new \PDO($this->settings['db']['connection'], $this->settings['db']['user'], $this->settings['db']['password'], [\PDO::ATTR_EMULATE_PREPARES => false, \PDO::ATTR_TIMEOUT => 2, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING]);
}
public function send_buffer()
{
ob_flush();
flush();
}
}

View File

@ -1,153 +0,0 @@
<?php
/*
Copyright 2016-2017 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto\Worker;
/**
* worker.
*/
trait Worker
{
public $last_serialization = 0;
public function start_worker_sync($worker)
{
$this->db_connect();
set_time_limit(0);
ignore_user_abort(1);
$this->lock_file = fopen($this->sessions_dir.$worker, 'c+');
$got_lock = flock($this->lock_file, LOCK_EX | LOCK_NB, $wouldblock);
if ($this->lock_file === false || (!$got_lock && !$wouldblock)) {
return ['ok' => false, 'error_code' => 400, "Couldn't open/lock session file"];
}
if (!$got_lock && $wouldblock) {
return ['ok' => true, 'result' => 'This worker is already running'];
}
// Deserialize contents if needed
fseek($this->lock_file, 0);
$result = stream_get_contents($this->lock_file);
if ($result !== '') {
try {
$this->MadelineProto = unserialize($result);
} catch (\danog\MadelineProto\Exception $e) {
error_log('An error occurred while deserializing '.$worker);
$this->MadelineProto = new \danog\MadelineProto\API(['logger' => ['logger' => 2, 'logger_param' => $this->sessions_dir.$worker.'.log']]);
}
} else {
$this->MadelineProto = new \danog\MadelineProto\API(['logger' => ['logger' => 2, 'logger_param' => $this->sessions_dir.$worker.'.log']]);
}
$this->serialize_worker();
$stop = false;
/*
echo json_encode(['ok' => true, 'result' => 'Worker started successfully!']);
*/
while (true) {
$actions = $this->pdo->prepare('SELECT * FROM worker_jobs WHERE worker = ? AND processed = ?');
$actions->execute([$worker, (int) false]);
$actions = $actions->fetchAll();
foreach ($actions as $action) {
$result = ['ok' => false, 'error_code' => 404, 'error_description' => 'The method '.$this->method.' does not exist'];
$params = json_decode($action['params']);
try {
switch ($action['method']) {
case 'stop_worker':
$stop = true;
$result = ['ok' => true, 'result' => 'Worker stopped'];
break;
case 'bot_login':
$result = ['ok' => true, 'result' => $this->MadelineProto->bot_login($settings['other']['params']['token'])];
break;
case 'phone_login':
$result = ['ok' => true, 'result' => $this->MadelineProto->phone_login($settings['other']['params']['number'])];
break;
case 'complete_phone_login':
$result = ['ok' => true, 'result' => $this->MadelineProto->complete_phone_login($settings['other']['params']['code'])];
break;
default:
if ($this->MadelineProto->API->methods->find_by_method($this->method) !== false) {
$result = ['ok' => true, 'result' => $this->MadelineProto->API->method_call($this->method, $settings['other']['params'])];
}
}
} catch (\danog\MadelineProto\ResponseException $e) {
$result = ['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())];
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\Exception $e) {
$result = ['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())];
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\RPCErrorException $e) {
$result = ['ok' => false, 'error_code' => $e->getCode(), 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())];
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\TL\Exception $e) {
$result = ['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())];
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
}
$result['req_id'] = $action;
$this->pdo->prepare('UPDATE worker_jobs SET response=?, processed=? WHERE request_id=?')->execute([json_encode($result), (int) true, $action['request_id']]);
}
try {
$this->MadelineProto->API->recv_message();
} catch (\danog\MadelineProto\ResponseException $e) {
echo json_encode(['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\Exception $e) {
if (preg_match('/Wrong length was read/', $e->getMessage())) {
continue;
}
echo json_encode(['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\RPCErrorException $e) {
echo json_encode(['ok' => false, 'error_code' => $e->getCode(), 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\TL\Exception $e) {
echo json_encode(['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
}
$this->serialize_worker();
if (empty($actions)) {
usleep(250000);
}
if ($stop) {
break;
}
}
flock($this->lock_file, LOCK_UN);
fclose($this->lock_file);
return ['ok' => true, 'result' => 'Worker stopped successfully!'];
}
public function serialize_worker()
{
if (time() - $this->last_serialization < $this->settings['workers']['serialization_interval']) {
return false;
}
ftruncate($this->lock_file, 0);
rewind($this->lock_file);
$serialized = serialize($this->MadelineProto);
fwrite($this->lock_file, $serialized);
$this->last_serialization = time();
return true;
}
}

View File

@ -1,58 +0,0 @@
<?php
/*
Copyright 2016-2017 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto\Worker;
/**
* Tools for the worker.
*/
trait WorkerTools
{
public function check_all_workers()
{
$result = ['ok' => true, 'result' => []];
foreach (glob($this->sessions_dir.'*') as $session) {
if (stripos($session, '.log') !== false) {
continue;
}
$session = basename($session);
$result['result'][] = $this->check_worker($session);
}
return $result;
}
public function start_worker_async($worker, $recursive = true)
{
shell_exec('curl '.escapeshellarg($this->settings['other']['endpoint'].$worker.'/start_worker_sync').' > /dev/null 2> /dev/null & ');
sleep(30);
return $this->check_worker($worker, $recursive);
}
public function check_worker($worker, $recursive = true)
{
$this->lock_file = fopen($this->sessions_dir.$worker, 'c+');
$got_lock = flock($this->lock_file, LOCK_EX | LOCK_NB, $wouldblock);
if ($this->lock_file === false || (!$got_lock && !$wouldblock)) {
return ['ok' => false, 'error_code' => 400, "Couldn't open/lock session file"];
}
if (!$got_lock && $wouldblock) {
return ['ok' => true, 'result' => ['active' => true]];
}
if ($recursive) { // If worker is turned off and $recursive
return $this->start_worker_async($worker, false);
}
return ['ok' => true, 'result' => ['active' => false]];
}
}

View File

@ -416,7 +416,7 @@ trait FilesHandler
}
if ($cb === null) {
$cb = function ($percent) {
\danog\MadelineProto\Logger::log('Upload status: '.$percent.'%');
\danog\MadelineProto\Logger::log(['Upload status: '.$percent.'%'], \danog\MadelineProto\Logger::NOTICE);
};
}
$part_size = 512 * 1024;
@ -539,7 +539,7 @@ trait FilesHandler
{
if ($cb === null) {
$cb = function ($percent) {
\danog\MadelineProto\Logger::log('Download status: '.$percent.'%');
\danog\MadelineProto\Logger::log(['Download status: '.$percent.'%'], \danog\MadelineProto\Logger::NOTICE);
};
}
$info = $this->get_download_info($message_media);
@ -554,7 +554,7 @@ trait FilesHandler
$percent = 0;
while ($percent < 100) {
$real_part_size = ($offset + $part_size > $end) ? $part_size - (($offset + $part_size) - $end) : $part_size;
\danog\MadelineProto\Logger::log($real_part_size, $offset);
\danog\MadelineProto\Logger::log([$real_part_size, $offset], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$res = $this->API->method_call('upload.getFile', ['location' => $info['InputFileLocation'], 'offset' => $offset, 'limit' => $real_part_size], null, true);
$dc = 1;
while ($res['type']['_'] === 'storage.fileUnknown' && $res['bytes'] === '') {
@ -563,8 +563,8 @@ trait FilesHandler
$dc++;
}
\danog\MadelineProto\Logger::log(fwrite($stream, $res['bytes']));
\danog\MadelineProto\Logger::log($offset, $size, ftell($stream));
\danog\MadelineProto\Logger::log([fwrite($stream, $res['bytes'])], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
\danog\MadelineProto\Logger::log([$offset, $size, ftell($stream)], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$cb($percent = ($offset += $real_part_size) * 100 / $size);
}

View File

@ -25,7 +25,7 @@ trait Login
$this->API->datacenter->authorized = false;
$this->API->datacenter->authorization = null;
$this->API->updates = [];
\danog\MadelineProto\Logger::log('Logged out successfully!');
\danog\MadelineProto\Logger::log(['Logged out successfully!'], \danog\MadelineProto\Logger::NOTICE);
$this->API->should_serialize = true;
@ -35,10 +35,10 @@ trait Login
public function bot_login($token)
{
if ($this->API->datacenter->authorized) {
\danog\MadelineProto\Logger::log('This instance of MadelineProto is already logged in. Logging out first...');
\danog\MadelineProto\Logger::log(['This instance of MadelineProto is already logged in. Logging out first...'], \danog\MadelineProto\Logger::NOTICE);
$this->logout();
}
\danog\MadelineProto\Logger::log('Logging in as a bot...');
\danog\MadelineProto\Logger::log(['Logging in as a bot...'], \danog\MadelineProto\Logger::NOTICE);
$this->API->datacenter->authorization = $this->API->method_call(
'auth.importBotAuthorization',
[
@ -55,7 +55,7 @@ trait Login
if (!isset($this->API->settings['pwr']['pwr']) || !$this->API->settings['pwr']['pwr']) {
file_get_contents('https://api.pwrtelegram.xyz/bot'.$token.'/getme');
}
\danog\MadelineProto\Logger::log('Logged in successfully!');
\danog\MadelineProto\Logger::log(['Logged in successfully!'], \danog\MadelineProto\Logger::NOTICE);
return $this->API->datacenter->authorization;
}
@ -63,10 +63,10 @@ trait Login
public function phone_login($number, $sms_type = 5)
{
if ($this->API->datacenter->authorized) {
\danog\MadelineProto\Logger::log('This instance of MadelineProto is already logged in. Logging out first...');
\danog\MadelineProto\Logger::log(['This instance of MadelineProto is already logged in. Logging out first...'], \danog\MadelineProto\Logger::NOTICE);
$this->logout();
}
\danog\MadelineProto\Logger::log('Sending code...');
\danog\MadelineProto\Logger::log(['Sending code...'], \danog\MadelineProto\Logger::NOTICE);
$this->API->datacenter->authorization = $this->API->method_call(
'auth.sendCode',
[
@ -78,36 +78,69 @@ trait Login
]
);
$this->API->datacenter->authorization['phone_number'] = $number;
$this->API->datacenter->waiting_code = true;
$this->API->datacenter->login_temp_status = 'waiting_code';
$this->API->should_serialize = true;
$this->API->updates = [];
$this->API->updates_key = 0;
\danog\MadelineProto\Logger::log('Code sent successfully! Once you receive the code you should use the complete_phone_login function.');
\danog\MadelineProto\Logger::log(['Code sent successfully! Once you receive the code you should use the complete_phone_login function.'], \danog\MadelineProto\Logger::NOTICE);
return $this->API->datacenter->authorization;
}
public function complete_phone_login($code)
{
if (!$this->API->datacenter->waiting_code) {
if ($this->API->datacenter->login_temp_status !== 'waiting_code') {
throw new \danog\MadelineProto\Exception("I'm not waiting for the code! Please call the phone_login method first");
}
\danog\MadelineProto\Logger::log('Logging in as a normal user...');
$this->API->datacenter->authorization = $this->API->method_call(
'auth.signIn',
[
'phone_number' => $this->API->datacenter->authorization['phone_number'],
'phone_code_hash' => $this->API->datacenter->authorization['phone_code_hash'],
'phone_code' => $code,
]
);
$this->API->datacenter->waiting_code = false;
$this->API->datacenter->login_temp_status = 'none';
\danog\MadelineProto\Logger::log(['Logging in as a normal user...'], \danog\MadelineProto\Logger::NOTICE);
try {
$authorization = $this->API->method_call(
'auth.signIn',
[
'phone_number' => $this->API->datacenter->authorization['phone_number'],
'phone_code_hash' => $this->API->datacenter->authorization['phone_code_hash'],
'phone_code' => $code,
]
);
} catch (\danog\MadelineProto\RPCErrorException $e) {
if ($e->getMessage() === 'SESSION_PASSWORD_NEEDED') {
\danog\MadelineProto\Logger::log(['2FA enabled, you will have to call the complete_2fa_login function...'], \danog\MadelineProto\Logger::NOTICE);
$this->API->datacenter->login_temp_status = 'waiting_password';
return $this->API->datacenter->authorization = $this->account->getPassword();
}
throw $e;
}
$this->API->datacenter->authorization = $authorization;
$this->API->datacenter->authorized = true;
$this->API->get_updates_state();
$this->API->should_serialize = true;
\danog\MadelineProto\Logger::log('Logged in successfully!');
\danog\MadelineProto\Logger::log(['Logged in successfully!'], \danog\MadelineProto\Logger::NOTICE);
return $this->API->datacenter->authorization;
}
public function complete_2fa_login($password)
{
if ($this->API->datacenter->login_temp_status !== 'waiting_password') {
throw new \danog\MadelineProto\Exception("I'm not waiting for the password! Please call the phone_login and the complete_phone_login methods first!");
}
$this->API->datacenter->login_temp_status = 'none';
\danog\MadelineProto\Logger::log(['Logging in as a normal user...'], \danog\MadelineProto\Logger::NOTICE);
$this->API->datacenter->authorization = $this->API->method_call(
'auth.checkPassword',
[
'password_hash' => hash('sha256', $this->API->datacenter->authorization['current_salt'].$password.$this->API->datacenter->authorization['current_salt'], true),
]
);
$this->API->datacenter->authorized = true;
$this->API->get_updates_state();
$this->API->should_serialize = true;
\danog\MadelineProto\Logger::log(['Logged in successfully!'], \danog\MadelineProto\Logger::NOTICE);
return $this->API->datacenter->authorization;
}

View File

@ -37,13 +37,20 @@ if ($MadelineProto === false) {
'phone_number' => getenv('MTPROTO_NUMBER'),
]
);
\danog\MadelineProto\Logger::log($checkedPhone);
\danog\MadelineProto\Logger::log([$checkedPhone], \danog\MadelineProto\Logger::NOTICE);
$sentCode = $MadelineProto->phone_login(getenv('MTPROTO_NUMBER'));
\danog\MadelineProto\Logger::log($sentCode);
\danog\MadelineProto\Logger::log([$sentCode], \danog\MadelineProto\Logger::NOTICE);
echo 'Enter the code you received: ';
$code = fgets(STDIN, (isset($sentCode['type']['length']) ? $sentCode['type']['length'] : 5) + 1);
$authorization = $MadelineProto->complete_phone_login($code);
\danog\MadelineProto\Logger::log($authorization);
\danog\MadelineProto\Logger::log([$authorization], \danog\MadelineProto\Logger::NOTICE);
if ($authorization['_'] === 'account.noPassword') {
throw new \danog\MadelineProto\Exception('2FA is enabled but no password is set!');
}
if ($authorization['_'] === 'account.password') {
\danog\MadelineProto\Logger::log(['2FA is enabled'], \danog\MadelineProto\Logger::NOTICE);
$authorization = $MadelineProto->complete_2fa_login(readline("Please enter your password (hint ".$authorization['hint'].'): '));
}
echo 'Serializing MadelineProto to session.madeline...'.PHP_EOL;
echo 'Wrote '.\danog\MadelineProto\Serialization::serialize('session.madeline', $MadelineProto).' bytes'.PHP_EOL;
} else $MadelineProto->bot_login(getenv('BOT_TOKEN'));
@ -90,9 +97,9 @@ $media['document'] = ['_' => 'inputMediaUploadedDocument', 'file' => $inputFile,
foreach (json_decode(getenv('TEST_DESTINATION_GROUPS'), true) as $peer) {
$sentMessage = $MadelineProto->messages->sendMessage(['peer' => $peer, 'message' => $message, 'entities' => [['_' => 'inputMessageEntityMentionName', 'offset' => 0, 'length' => strlen($message), 'user_id' => $mention]]]);
\danog\MadelineProto\Logger::log($sentMessage);
\danog\MadelineProto\Logger::log([$sentMessage], \danog\MadelineProto\Logger::NOTICE);
foreach ($media as $type => $inputMedia) {
\danog\MadelineProto\Logger::log($MadelineProto->messages->sendMedia(['peer' => $peer, 'media' => $inputMedia]));
\danog\MadelineProto\Logger::log([$MadelineProto->messages->sendMedia(['peer' => $peer, 'media' => $inputMedia])], \danog\MadelineProto\Logger::NOTICE);
}
}
@ -106,7 +113,7 @@ echo 'Size of MadelineProto instance is '.strlen(serialize($MadelineProto)).' by
if ($bot_token = getenv('BOT_TOKEN')) {
$MadelineProto = new \danog\MadelineProto\API($settings);
$authorization = $MadelineProto->bot_login($bot_token);
\danog\MadelineProto\Logger::log($authorization);
\danog\MadelineProto\Logger::log([$authorization], \danog\MadelineProto\Logger::NOTICE);
}
$message = 'yay';
$mention = $MadelineProto->get_info(getenv('TEST_USERNAME')); // Returns an array with all of the constructors that can be extracted from a username or an id
@ -114,7 +121,7 @@ $mention = $mention['user_id']; // Selects only the numeric user id
foreach (json_decode(getenv('TEST_DESTINATION_GROUPS'), true) as $peer) {
$sentMessage = $MadelineProto->messages->sendMessage(['peer' => $peer, 'message' => $message, 'entities' => [['_' => 'inputMessageEntityMentionName', 'offset' => 0, 'length' => strlen($message), 'user_id' => $mention]]]);
\danog\MadelineProto\Logger::log($sentMessage);
\danog\MadelineProto\Logger::log([$sentMessage], \danog\MadelineProto\Logger::NOTICE);
}
sleep(5);
var_dump($MadelineProto->API->get_updates());