Clean up code

This commit is contained in:
Daniil Gentili 2017-01-26 02:52:04 +01:00
parent 563b0f614e
commit 5a879f9c06
18 changed files with 48 additions and 224 deletions

View File

@ -1,41 +0,0 @@
---
title: contest.saveDeveloperInfo
description: contest.saveDeveloperInfo parameters, return type and example
---
## Method: contest.saveDeveloperInfo
[Back to methods index](index.md)
### Parameters:
| Name | Type | Required |
|----------|:-------------:|---------:|
|vk\_id|[int](../types/int.md) | Required|
|name|[string](../types/string.md) | Required|
|phone\_number|[string](../types/string.md) | Required|
|age|[int](../types/int.md) | Required|
|city|[string](../types/string.md) | Required|
### Return type: [Bool](../types/Bool.md)
### Example:
```
$MadelineProto = new \danog\MadelineProto\API();
if (isset($token)) {
$this->bot_login($token);
}
if (isset($number)) {
$sentCode = $MadelineProto->phone_login($number);
echo 'Enter the code you received: ';
$code = '';
for ($x = 0; $x < $sentCode['type']['length']; $x++) {
$code .= fgetc(STDIN);
}
$MadelineProto->complete_phone_login($code);
}
$Bool = $MadelineProto->contest->saveDeveloperInfo(['vk_id' => int, 'name' => string, 'phone_number' => string, 'age' => int, 'city' => string, ]);
```

View File

@ -179,9 +179,6 @@ $MadelineProto->[contacts->search](contacts_search.md)(\['q' => [string](../type
$MadelineProto->[contacts->unblock](contacts_unblock.md)(\['id' => [InputUser](../types/InputUser.md), \]) == [$Bool](../types/Bool.md)<a name="contacts_unblock"></a>
***
<br><br>$MadelineProto->[contest->saveDeveloperInfo](contest_saveDeveloperInfo.md)(\['vk_id' => [int](../types/int.md), 'name' => [string](../types/string.md), 'phone_number' => [string](../types/string.md), 'age' => [int](../types/int.md), 'city' => [string](../types/string.md), \]) == [$Bool](../types/Bool.md)<a name="contest_saveDeveloperInfo"></a>
***
<br><br>$MadelineProto->[help->getAppChangelog](help_getAppChangelog.md)(\[\]) == [$help\_AppChangelog](../types/help_AppChangelog.md)<a name="help_getAppChangelog"></a>

View File

@ -80,12 +80,6 @@ class APIFactory
* @var auth
*/
public $auth;
/**
* @internal this is a internal property generated by build_docs.php, don't change manually
*
* @var contest
*/
public $contest;
public $namespace;
public $API;

View File

@ -61,7 +61,7 @@ class Connection
if (!(get_resource_type($this->sock) == 'file' || get_resource_type($this->sock) == 'stream')) {
throw new Exception("Connection: couldn't connect to socket.");
}
$this->write($this->string2bin('\xef'));
$this->write(chr(239));
break;
case 'tcp_intermediate':
$this->sock = fsockopen('tcp://'.$ip.':'.$port);
@ -69,7 +69,7 @@ class Connection
if (!(get_resource_type($this->sock) == 'file' || get_resource_type($this->sock) == 'stream')) {
throw new Exception("Connection: couldn't connect to socket.");
}
$this->write($this->string2bin('\xee\xee\xee\xee'));
$this->write(str_repeat(chr(238), 4));
break;
case 'tcp_full':
$this->sock = fsockopen('tcp://'.$ip.':'.$port);

View File

@ -1,54 +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;
class DebugTools
{
/**
* Function to dump the hex version of a string.
*
* @param $what What to dump.
*/
public static function hex_dump(...$what)
{
foreach ($what as $w) {
\danog\MadelienProto\Logger::log(bin2hex($w));
}
}
/**
* Function to visualize byte streams. Split into bytes, print to console.
* :param bs: BYTE STRING.
*/
public static function vis($bs)
{
$bs = str_split($bs);
$symbols_in_one_line = 8;
$n = floor(len($bs) / $symbols_in_one_line);
$i = 0;
foreach (pyjslib_range($n) as $i) {
echo $i * $symbols_in_one_line.' | '.implode(' ',
array_map(function ($el) {
return bin2hex($el);
}, array_slice($bs, $i * $symbols_in_one_line, ($i + 1) * $symbols_in_one_line))
).PHP_EOL;
}
if (len($bs) % $symbols_in_one_line != 0) {
echo($i + 1) * $symbols_in_one_line.' | '.implode(' ',
array_map(function ($el) {
return bin2hex($el);
}, array_slice($bs, ($i + 1) * $symbols_in_one_line))
).PHP_EOL;
}
}
}

View File

@ -7,22 +7,6 @@
namespace danog\MadelineProto;
interface contest
{
/**
* @param array params [
* int vk_id,
* string name,
* string phone_number,
* int age,
* string city,
* ]
*
* @return bool
*/
public function saveDeveloperInfo(array $params);
}
interface auth
{
/**

View File

@ -30,6 +30,7 @@ class MTProto extends PrimeModule
use \danog\MadelineProto\MTProtoTools\UpdateHandler;
use \danog\MadelineProto\TL\TL;
use \danog\MadelineProto\Tools;
use \danog\MadelineProto\RSA;
public $settings = [];
public $config = ['expires' => -1];
@ -50,7 +51,7 @@ class MTProto extends PrimeModule
// Load rsa key
\danog\MadelineProto\Logger::log('Loading RSA key...');
$this->key = new RSA($this->settings['authorization']['rsa_key']);
$this->key = $this->loadKey($this->settings['authorization']['rsa_key']);
// Istantiate TL class
\danog\MadelineProto\Logger::log('Translating tl schemas...');
@ -212,7 +213,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
];
$settings = array_replace_recursive($default_settings, $settings);
if (isset($settings['connection_settings']['all'])) {
foreach ($this->range(1, 6) as $n) {
for ($n = 1; $n <= 6; $n++) {
if (!isset($settings['connection_settings'][$n])) {
$settings['connection_settings'][$n] = $settings['connection_settings']['all'];
}
@ -235,7 +236,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.'...');
$socket->session_id = \danog\MadelineProto\Tools::random(8);
$socket->session_id = $this->random(8);
$socket->seq_no = 0;
}
$socket->incoming_messages = [];
@ -279,7 +280,7 @@ Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
public function init_authorization()
{
if ($this->datacenter->session_id == null) {
$this->datacenter->session_id = \danog\MadelineProto\Tools::random(8);
$this->datacenter->session_id = $this->random(8);
}
if ($this->datacenter->temp_auth_key == null || $this->datacenter->auth_key == null) {
if ($this->datacenter->auth_key == null) {

View File

@ -36,7 +36,7 @@ trait AckHandler
\danog\MadelineProto\Logger::log("WARNING: Couldn't find message id ".$message_id.' in the array of incomgoing messages. Maybe try to increase its size?');
//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'] == $this->string2bin('\x00\x00\x00\x00\x00\x00\x00\x00') || (isset($this->datacenter->incoming_messages[$message_id]['ack']) && $this->datacenter->incoming_messages[$message_id]['ack'])) {
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'])) {
return;
}

View File

@ -43,7 +43,7 @@ trait AuthKeyHandler
* Vector long $server_public_key_fingerprints : This is a list of public RSA key fingerprints
* ]
*/
$nonce = \danog\MadelineProto\Tools::random(16);
$nonce = $this->random(16);
$ResPQ = $this->method_call('req_pq',
[
'nonce' => $nonce,
@ -64,7 +64,7 @@ trait AuthKeyHandler
*/
foreach ($ResPQ['server_public_key_fingerprints'] as $curfp) {
$curfp_biginteger = new \phpseclib\Math\BigInteger($curfp);
if ($this->key->fp->equals($curfp_biginteger)) {
if ($this->key['fp']->equals($curfp_biginteger)) {
$public_key_fingerprint = $curfp;
break;
}
@ -103,7 +103,7 @@ trait AuthKeyHandler
$p_bytes = \danog\PHP\Struct::pack('>I', (string) $p);
$q_bytes = \danog\PHP\Struct::pack('>I', (string) $q);
$new_nonce = \danog\MadelineProto\Tools::random(32);
$new_nonce = $this->random(32);
$data_unserialized = [
'pq' => $pq_bytes,
@ -121,9 +121,9 @@ trait AuthKeyHandler
* Encrypt serialized object
*/
$sha_digest = sha1($p_q_inner_data, true);
$random_bytes = \danog\MadelineProto\Tools::random(255 - strlen($p_q_inner_data) - strlen($sha_digest));
$random_bytes = $this->random(255 - strlen($p_q_inner_data) - strlen($sha_digest));
$to_encrypt = $sha_digest.$p_q_inner_data.$random_bytes;
$encrypted_data = $this->key->encrypt($to_encrypt);
$encrypted_data = $this->RSA_encrypt($to_encrypt, $this->key);
\danog\MadelineProto\Logger::log('Starting Diffie Hellman key exchange');
/*
@ -314,9 +314,9 @@ trait AuthKeyHandler
throw new \danog\MadelineProto\Exception('g_a is invalid (1 < g_a < dh_prime - 1 is false).');
}
foreach ($this->range(0, $this->settings['max_tries']['authorization']) as $retry_id) {
for ($retry_id = 0; $retry_id <= $this->settings['max_tries']['authorization']; $retry_id++) {
\danog\MadelineProto\Logger::log('Generating b...');
$b = new \phpseclib\Math\BigInteger(\danog\MadelineProto\Tools::random(256), 256);
$b = new \phpseclib\Math\BigInteger($this->random(256), 256);
\danog\MadelineProto\Logger::log('Generating g_b...');
$g_b = $g->powMod($b, $dh_prime);
@ -362,7 +362,7 @@ trait AuthKeyHandler
* encrypt client_DH_inner_data
*/
$data_with_sha = sha1($data, true).$data;
$data_with_sha_padded = $data_with_sha.\danog\MadelineProto\Tools::random($this->posmod(-strlen($data_with_sha), 16));
$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...');
@ -483,7 +483,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...');
$nonce = \danog\PHP\Struct::unpack('<q', \danog\MadelineProto\Tools::random(8))[0];
$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];
$perm_auth_key_id = \danog\PHP\Struct::unpack('<q', $this->datacenter->auth_key['id'])[0];
@ -501,9 +501,9 @@ trait AuthKeyHandler
$message_id = \danog\PHP\Struct::pack('<Q', $int_message_id);
$seq_no = 0;
$encrypted_data = \danog\MadelineProto\Tools::random(16).$message_id.\danog\PHP\Struct::pack('<II', $seq_no, strlen($message_data)).$message_data;
$encrypted_data = $this->random(16).$message_id.\danog\PHP\Struct::pack('<II', $seq_no, strlen($message_data)).$message_data;
$message_key = substr(sha1($encrypted_data, true), -16);
$padding = \danog\MadelineProto\Tools::random($this->posmod(-strlen($encrypted_data), 16));
$padding = $this->random($this->posmod(-strlen($encrypted_data), 16));
list($aes_key, $aes_iv) = $this->aes_calculate($message_key, $this->datacenter->auth_key['auth_key']);
$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);

View File

@ -22,7 +22,7 @@ trait CallHandler
if (!is_array($args)) {
throw new \danog\MadelineProto\Exception("Arguments aren't an array.");
}
foreach (range(1, $this->settings['max_tries']['query']) as $count) {
for ($count = 1; $count <= $this->settings['max_tries']['query']; $count++) {
try {
\danog\MadelineProto\Logger::log('Calling method (try number '.$count.' for '.$method.')...');
@ -158,7 +158,7 @@ trait CallHandler
throw new \danog\MadelineProto\Exception("Arguments aren't an array.");
}
foreach (range(1, $this->settings['max_tries']['query']) as $count) {
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.')...');
$int_message_id = $this->send_message($this->serialize_object(['type' => $object], $args), $this->content_related($object));

View File

@ -65,7 +65,7 @@ trait Crypt
$ivp = substr($iv, 0, $blocksize);
$ivp2 = substr($iv, $blocksize);
$ciphered = '';
foreach ($this->range(0, strlen($message), $blocksize) as $i) {
for ($i = 0; $i <= strlen($message); $i += $blocksize) {
$indata = substr($message, $i, $blocksize);
if ($operation == 'decrypt') {
$xored = $indata ^ $ivp2;

View File

@ -32,12 +32,12 @@ trait MessageHandler
$message_id = \danog\PHP\Struct::pack('<Q', $int_message_id);
if ($this->datacenter->temp_auth_key['auth_key'] == null || $this->datacenter->temp_auth_key['server_salt'] == null) {
$message = $this->string2bin('\x00\x00\x00\x00\x00\x00\x00\x00').$message_id.\danog\PHP\Struct::pack('<I', strlen($message_data)).$message_data;
$message = str_repeat(chr(0), 8).$message_id.\danog\PHP\Struct::pack('<I', strlen($message_data)).$message_data;
} else {
$seq_no = $this->generate_seq_no($content_related);
$encrypted_data = \danog\PHP\Struct::pack('<q', $this->datacenter->temp_auth_key['server_salt']).$this->datacenter->session_id.$message_id.\danog\PHP\Struct::pack('<II', $seq_no, strlen($message_data)).$message_data;
$message_key = substr(sha1($encrypted_data, true), -16);
$padding = \danog\MadelineProto\Tools::random($this->posmod(-strlen($encrypted_data), 16));
$padding = $this->random($this->posmod(-strlen($encrypted_data), 16));
list($aes_key, $aes_iv) = $this->aes_calculate($message_key, $this->datacenter->temp_auth_key['auth_key']);
$message = $this->datacenter->temp_auth_key['id'].$message_key.$this->ige_encrypt($encrypted_data.$padding, $aes_key, $aes_iv);
$this->datacenter->outgoing_messages[$int_message_id]['seq_no'] = $seq_no;
@ -69,7 +69,7 @@ trait MessageHandler
throw new \danog\MadelineProto\RPCErrorException($error, $error);
}
$auth_key_id = stream_get_contents($payload, 8);
if ($auth_key_id == $this->string2bin('\x00\x00\x00\x00\x00\x00\x00\x00')) {
if ($auth_key_id == str_repeat(chr(0), 8)) {
list($message_id, $message_length) = \danog\PHP\Struct::unpack('<QI', stream_get_contents($payload, 12));
$this->check_message_id($message_id, false);
$message_data = stream_get_contents($payload, $message_length);

View File

@ -18,12 +18,12 @@ class PrimeModule
public function find_small_multiplier_lopatin($what)
{
$g = 0;
foreach ($this->range(3) as $i) {
for ($i = 0; $i < 3; $i++) {
$q = (rand(0, 127) & 15) + 17;
$x = rand(0, 1000000000) + 1;
$y = $x;
$lim = 1 << ($i + 18);
foreach ($this->range(1, $lim) as $j) {
for ($j = 1; $j <= $lim; $j++) {
list($a, $b, $c) = [$x, $x, $q];
while ($b != 0) {
if (($b & 1) != 0) {

View File

@ -12,17 +12,9 @@ If not, see <http://www.gnu.org/licenses/>.
namespace danog\MadelineProto;
class RSA
trait RSA
{
use \danog\MadelineProto\TL\TL;
use \danog\MadelineProto\Tools;
public $n; // phpseclib\Math\BigInteger class
public $e; // phpseclib\Math\BigInteger class
public $fp; // phpseclib\Math\BigInteger class
public $fp_bytes; // bytes
public function __construct($rsa_key)
public function loadKey($rsa_key)
{
\danog\MadelineProto\Logger::log('Istantiating \phpseclib\Crypt\RSA...');
$key = new \phpseclib\Crypt\RSA();
@ -33,20 +25,19 @@ class RSA
} else {
$key->loadKey($rsa_key);
}
$this->n = $key->modulus;
$this->e = $key->exponent;
$keydata = ['n' => $key->modulus, 'e' => $key->exponent];
\danog\MadelineProto\Logger::log('Computing fingerprint...');
$this->fp_bytes = substr(
$keydata['fp_bytes'] = substr(
sha1(
$this->serialize_object(
['type' => 'bytes'],
$this->n->toBytes()
$keydata['n']->toBytes()
)
.
$this->serialize_object(
['type' => 'bytes'],
$this->e->toBytes()
$keydata['e']->toBytes()
),
true
),
@ -54,14 +45,14 @@ class RSA
);
\danog\MadelineProto\Logger::log('Generating BigInteger object for fingerprint...');
$this->fp = new \phpseclib\Math\BigInteger(strrev($this->fp_bytes), -256);
$keydata['fp'] = new \phpseclib\Math\BigInteger(strrev($keydata['fp_bytes']), -256);
return $keydata;
}
public function encrypt($data)
public function RSA_encrypt($data, $keydata)
{
\danog\MadelineProto\Logger::log('Encrypting with rsa key...');
$bigintdata = new \phpseclib\Math\BigInteger($data, 256);
return $bigintdata->powMod($this->e, $this->n)->toBytes();
return (new \phpseclib\Math\BigInteger($data, 256))->powMod($keydata['e'], $keydata['n'])->toBytes();
}
}

View File

@ -30,7 +30,8 @@ trait TL
$tl_file = explode("\n", $filec);
$key = 0;
foreach ($tl_file as $line) {
if ($line == '' || preg_match('|^//|', $line)) {
$line = preg_replace(['|//.*|', '|^\s+$|'], '', $line);
if ($line == '') {
continue;
}
if ($line == '---functions---') {
@ -150,7 +151,7 @@ trait TL
$concat .= $object;
$concat .= pack('@'.$this->posmod((-$l - 1), 4));
} else {
$concat .= $this->string2bin('\xfe');
$concat .= chr(254);
$concat .= substr(\danog\PHP\Struct::pack('<i', $l), 0, 3);
$concat .= $object;
$concat .= pack('@'.$this->posmod(-$l, 4));
@ -254,16 +255,16 @@ trait TL
if ($current_argument['name'] == 'random_id') {
switch ($current_argument['type']) {
case 'long':
$serialized .= \danog\MadelineProto\Tools::random(8);
$serialized .= $this->random(8);
continue 2;
case 'int':
$serialized .= \danog\MadelineProto\Tools::random(4);
$serialized .= $this->random(4);
continue 2;
case 'Vector t':
if (isset($arguments['id'])) {
$serialized .= \danog\PHP\Struct::pack('<i', $this->constructors->find_by_predicate('vector')['id']);
$serialized .= \danog\PHP\Struct::pack('<i', count($arguments['id']));
$serialized .= \danog\MadelineProto\Tools::random(8 * count($arguments['id']));
$serialized .= $this->random(8 * count($arguments['id']));
continue 2;
}
}
@ -321,7 +322,7 @@ trait TL
throw new Exception('Length is too big');
}
if ($l == 254) {
$long_len = \danog\PHP\Struct::unpack('<I', stream_get_contents($bytes_io, 3).$this->string2bin('\x00'))[0];
$long_len = \danog\PHP\Struct::unpack('<I', stream_get_contents($bytes_io, 3).chr(0))[0];
$x = stream_get_contents($bytes_io, $long_len);
$resto = $this->posmod(-$long_len, 4);
if ($resto > 0) {

View File

@ -1,7 +1,3 @@
---functions---
contest.saveDeveloperInfo#9a5f6e95 vk_id:int name:string phone_number:string age:int city:string = Bool;
///////////////////////////////
///////// Main application API
///////////////////////////////

View File

@ -17,7 +17,7 @@ namespace danog\MadelineProto;
*/
trait Tools
{
public static function random($length)
public function random($length)
{
if ($length === 0) {
return '';
@ -30,7 +30,7 @@ trait Tools
* posmod(numeric,numeric) : numeric
* Works just like the % (modulus) operator, only returns always a postive number.
*/
public static function posmod($a, $b)
public function posmod($a, $b)
{
$resto = $a % $b;
if ($resto < 0) {
@ -40,17 +40,7 @@ trait Tools
return $resto;
}
public static function fread_all($handle)
{
$pos = ftell($handle);
fseek($handle, 0);
$content = stream_get_contents($handle, fstat($handle)['size']);
fseek($handle, $pos);
return $content;
}
public static function fopen_and_write($filename, $mode, $data)
public function fopen_and_write($filename, $mode, $data)
{
$handle = fopen($filename, $mode);
fwrite($handle, $data);
@ -58,39 +48,4 @@ trait Tools
return $handle;
}
public static function string2bin($string)
{
$res = null;
foreach (explode('\\', $string) as $s) {
if ($s != null && strlen($s) == 3) {
$res .= hex2bin(substr($s, 1));
}
}
return $res;
}
// taken from mochikit: range( [start,] stop[, step] )
public static function range($start, $stop = null, $step = 1)
{
if ($stop === null) {
$stop = $start;
$start = 0;
}
if ($stop <= $start && $step < 0) {
$arr = range($stop, $start, -$step);
array_pop($arr);
return array_reverse($arr, false);
}
if ($step > 1 && $step > ($stop - $start)) {
$arr = [$start];
} else {
$arr = range($start, $stop, $step);
array_pop($arr);
}
return $arr;
}
}

View File

@ -424,7 +424,7 @@ trait FilesHandler
$part_num = 0;
$method = $file_size > 10 * 1024 * 1024 ? 'upload.saveBigFilePart' : 'upload.saveFilePart';
$constructor = $file_size > 10 * 1024 * 1024 ? 'inputFileBig' : 'inputFile';
$file_id = \danog\PHP\Struct::unpack('<q', \danog\MadelineProto\Tools::random(8))[0];
$file_id = \danog\PHP\Struct::unpack('<q', $this->API->random(8))[0];
$f = fopen($file, 'r');
fseek($f, 0);
while (ftell($f) !== $file_size) {