2016-06-23 23:51:08 +02:00
# MadelineProto
2016-07-14 16:32:55 +02:00
[![StyleCI ](https://styleci.io/repos/61838413/shield )](https://styleci.io/repos/61838413)
2016-08-09 23:32:34 +02:00
[![Build Status ](https://travis-ci.org/danog/MadelineProto.svg?branch=master )](https://travis-ci.org/danog/MadelineProto)
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
Created by [Daniil Gentili ](https://daniil.it ), licensed under AGPLv3.
2015-03-11 17:52:28 +01:00
2016-08-08 16:09:11 +02:00
PHP implementation of MTProto, based on [telepy ](https://github.com/griganton/telepy_old ).
2015-03-11 16:42:20 +01:00
2016-08-14 21:38:32 +02:00
This project can run on PHP 7, PHP 5.6 and HHVM.
2016-11-26 11:50:20 +01:00
Also note that MadelineProto will perform better if a big math extension like gmp o bcmath is installed.
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
This project is in beta state.
2016-10-07 00:36:18 +02:00
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
## Usage
2016-11-25 00:40:19 +01:00
### Dependencies
This project depends on [PHPStruct ](https://github.com/danog/PHPStruct ), [phpseclib ](https://github.com/phpseclib/phpseclib ), https://packagist.org/packages/paragonie/constant_time_encoding and https://packagist.org/packages/paragonie/random_compat
2016-11-25 21:52:56 +01:00
To install dependencies install composer and run:
2016-11-25 00:40:19 +01:00
```
composer update
```
In the cloned repo.
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
### Instantiation
```
2016-11-25 21:52:56 +01:00
$MadelineProto = new \danog\MadelineProto\API();
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
```
### Settings
2016-11-25 21:52:56 +01:00
The constructor accepts an optional parameter, which is the settings array. This array contains some other arrays, which are the settings for a specific MadelineProto function.
Here you can see the default values for the settings\ arrays and explanations for every setting:
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
```
$settings = [
'authorization' => [ // Authorization settings
'default_temp_auth_key_expires_in' => 31557600, // validity of temporary keys and the binding of the temporary and permanent keys
'rsa_key' => '-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
-----END RSA PUBLIC KEY-----', // RSA public key
],
'connection' => [ // List of datacenters/subdomains where to connect
'ssl_subdomains' => [ // Subdomains of web.telegram.org for https protocol
1 => 'pluto',
2 => 'venus',
3 => 'aurora',
4 => 'vesta',
5 => 'flora', // musa oh wait no :(
],
'test' => [ // Test datacenters
'ipv4' => [ // ipv4 addresses
2 => [ // The rest will be fetched using help.getConfig
'ip_address' => '149.154.167.40',
'port' => 443,
'media_only' => false,
'tcpo_only' => false
]
],
'ipv6' => [ // ipv6 addresses
2 => [ // The rest will be fetched using help.getConfig
'ip_address' => '2001:067c:04e8:f002:0000:0000:0000:000e',
'port' => 443,
'media_only' => false,
'tcpo_only' => false
]
]
],
'main' => [ // Main datacenters
'ipv4' => [ // ipv4 addresses
2 => [ // The rest will be fetched using help.getConfig
'ip_address' => '149.154.167.51',
'port' => 443,
'media_only' => false,
'tcpo_only' => false
]
],
'ipv6' => [ // ipv6 addresses
2 => [ // The rest will be fetched using help.getConfig
'ip_address' => '2001:067c:04e8:f002:0000:0000:0000:000a',
'port' => 443,
2016-11-25 21:52:56 +01:00
'media_only' => false,
'tcpo_only' => false
]
]
],
],
'connection_settings' => [ // connection settings
'all' => [ // Connection settings will be applied on datacenter ids matching the key of these settings subarrays, if the key is equal to all like in this case that will match all datacenters that haven't a custom settings subarray...
'protocol' => 'tcp_full', // can be tcp_full, tcp_abridged, tcp_intermediate, http (unsupported), https (unsupported), udp (unsupported)
'test_mode' => false, // decides whether to connect to the main telegram servers or to the testing servers (deep telegram)
'ipv6' => $this->ipv6, // decides whether to use ipv6, ipv6 attribute of API attribute of API class contains autodetected boolean
'timeout' => 10 // timeout for sockets
],
],
'app_info' => [ // obtained in https://my.telegram.org
'api_id' => 25628,
'api_hash' => '1fe17cda7d355166cdaa71f04122873c',
'device_model' => php_uname('s'),
'system_version' => php_uname('r'),
'app_version' => 'Unicorn', // 🌚
'lang_code' => 'en',
],
'tl_schema' => [ // TL scheme files
'layer' => 57, // layer version
'src' => [
'mtproto' => __DIR__ .'/TL_mtproto_v1.json', // mtproto TL scheme
'telegram' => __DIR__ .'/TL_telegram_v57.json', // telegram TL scheme
],
],
'logger' => [ // Logger settings
'logger' => 1, // 0 - No logger, 1 - Log to the default logger destination, 2 - Log to file defined in logger_param, 3 - Echo logs
'logger_param' => '/tmp/MadelineProto.log',
'logger' => 3, // overwrite previous setting and echo logs
],
'max_tries' => [
'query' => 5, // How many times should I try to call a method or send an object before throwing an exception
'authorization' => 5, // How many times should I try to generate an authorization key before throwing an exception
'response' => 5,// How many times should I try to get a response of a query before throwing an exception
],
'msg_array_limit' => [ // How big should be the arrays containing the incoming and outgoing messages?
'incoming' => 30,
'outgoing' => 30,
],
];
```
You can provide part of any subsetting array, that way the remaining arrays will be automagically set to default and undefined values of specified subsetting arrays will be set to the default values.
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
Example:
```
$settings = [
'authorization' => [ // Authorization settings
'default_temp_auth_key_expires_in' => 86400, // a day
]
]
```
Becomes:
```
$settings = [
'authorization' => [ // Authorization settings
'default_temp_auth_key_expires_in' => 86400,
'rsa_key' => '-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
-----END RSA PUBLIC KEY-----',
]
2016-11-25 21:52:56 +01:00
// The remaining subsetting arrays are the set to default
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
]
```
2016-11-25 21:52:56 +01:00
Note that only settings arrays or values of a settings array will be set to default.
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
The settings array can be accessed in the instantiated class like this:
```
$MadelineProto = new \danog\MadelineProto\API();
2016-11-25 21:52:56 +01:00
var_dump($MadelineProto->API->settings);
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
```
### Calling mtproto methods and available wrappers
A list of mtproto methods can be found [here ](https://tjhorner.com/tl-schema/#functions ).
To call an MTProto method simply call it as if it is a method of the API class, substitute namespace sepators (.) with -> if needed:
```
$MadelineProto = new \danog\MadelineProto\API();
$checkedPhone = $MadelineProto->auth->checkPhone( // auth.checkPhone becomes auth->checkPhone
[
'phone_number' => '3993838383', // Random invalid number, note that there should be no +
]
);
$ping = $MadelineProto->ping([3]); // parameter names can be omitted as long as the order specified by the TL scheme is respected
2016-11-29 01:47:59 +01:00
$message = "Hey! I'm sending this message with MadelineProto!";
$username = $MadelineProto->contacts->resolveUsername(['username' => 'pwrtelegramgroup']);
var_dump($username);
$peer = ['_' => 'inputPeerChannel', 'channel_id' => $username['peer']['channel_id'], 'access_hash' => $username['chats'][0]['access_hash']];
$sentMessage = $MadelineProto->messages->sendMessage(['peer' => $peer, 'message' => $message, 'random_id' => \danog\PHP\Struct::unpack('< q ', \phpseclib \Crypt \Random::string ( 8 ))[ 0 ]]);
var_dump($sentMessage);
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
```
The API class also provides some wrapper methods for logging in as a bot or as a normal user:
```
$sentCode = $MadelineProto->phone_login($number); // Send code
var_dump($sentCode);
echo 'Enter the code you received: ';
$code = '';
for ($x = 0; $x < $sentCode['type']['length']; $x++) {
$code .= fgetc(STDIN);
}
$authorization = $MadelineProto->complete_phone_login($code); // Complete authorization
var_dump($authorization);
2016-11-25 00:19:15 +01:00
$authorization = $MadelineProto->bot_login($token); // Note that every time you login as a bot or as a user MadelineProto will logout first, so now MadelineProto is logged in as the bot with token $token, not as the user with number $number
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
var_dump($authorization);
```
2016-11-29 01:47:59 +01:00
See testing.php for more examples.
2016-11-25 21:52:56 +01:00
### Storing sessions
An istance of MadelineProto can be safely serialized or unserialized.
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
### Exceptions
MadelineProto can throw three different exceptions:
* \danog\MadelineProto\Exception - Default exception, thrown when a php error occures and in a lot of other cases
* \danog\MadelineProto\RPCErrorException - Thrown when an RPC error occurres (an error received via the mtproto API)
2016-11-25 00:19:15 +01:00
* \danog\MadelineProto\TL\Exception - Thrown on TL serialization/deserialization errors
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
## Contributing
[Here ](https://github.com/danog/MadelineProto/projects/1 ) you can find this project's roadmap.
You can use this scheme of the structure of this project to help yourself:
2016-10-07 00:36:18 +02:00
```
src/danog/MadelineProto/
MTProtoTools/
AckHandler - Handles acknowledgement of incoming and outgoing mtproto messages
AuthKeyHandler - Handles generation of the temporary and permanent authorization keys
CallHandler - Handles synchronous calls to mtproto methods or objects, also basic response management (waits until the socket receives a response)
Crypt - Handles ige and aes encryption
MessageHandler - Handles sending and receiving of mtproto messages (packs TL serialized data with message id, auth key id and encrypts it with Crypt if needed, adds them to the arrays of incoming and outgoing messages)
MsgIdHandler - Handles message ids (checks if they are valid, adds them to the arrays of incoming and outgoing messages)
ResponseHandler - Handles the content of responses received, service messages, rpc results, errors, and stores them into the response section of the outgoing messages array)
SaltHandler - Handles server salts
SeqNoHandler - Handles sequence numbers (checks validity)
TL/
Exception - Handles exceptions in the TL namespace
TL - Handles TL serialization and deserialization
2016-11-25 21:52:56 +01:00
TLConstructor - Stores TL constructors
TLMethod - Stores TL methods
2016-11-26 14:12:36 +01:00
TLParams - Parses params
2016-11-25 21:52:56 +01:00
API - Wrapper class that instantiates the MTProto class, sets the error handler, provides a wrapper for calling mtproto methods directly as class submethods, and provides some simplified wrappers for logging in to telegram
Added APIFactory for calling namespaced mtproto methods, cleaned up testing.php and API.php, moved authorization keys, session_id, seq_no and time delta to the Connection class, added close_and_reopen method to the Connection class, improved DataCenter class, renamed Logging class to Logger, added a bit more logging, added setup_logger, switch_dc, init_authorization methods to the MTProto class, added parameter to disable automatic switching to nearest DC in write_client_info, added a try catch block in the create_auth_key method, fixed switching of DCs in wait_for_response method, added arguments check in the method calling methods, added a message id check in MessageHandler, added method_name_namespaced array in TL for APIFactory, renamed a lot of stuff and removed a few checks in the TL class, moved sendCode test call to testing.php
2016-11-16 15:05:27 +01:00
APIFactory - Provides a wrapper for calling namespaced mtproto methods directly as class submethods
2016-11-17 12:10:22 +01:00
Connection - Handles tcp/udp/http connections and wrapping payloads generated by MTProtoTools/MessageHandler into the right message according to the protocol, stores authorization keys, session id and sequence number
DataCenter - Handles mtproto datacenters (is a wrapper for Connection classes)
2016-10-07 00:36:18 +02:00
DebugTools - Various debugging tools
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
Exception - Handles exceptions and PHP errors
RPCErrorException - Handles RPC errors
2016-11-25 21:52:56 +01:00
MTProto - Extends MTProtoTools, handles initial connection, generation of authorization keys, instantiation of classes, writing of client info
2016-10-07 00:36:18 +02:00
MTProtoTools - Extends all of the classes in MTProtoTools/
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
Logger - Static logging class
2016-10-18 18:46:31 +02:00
prime.py and getpq.py - prime module (python) for p and q generation
2016-10-14 00:49:43 +02:00
PrimeModule.php - prime module (php) for p and q generation by wrapping the python module, using wolfram alpha or a built in PHP engine
2016-10-07 00:36:18 +02:00
RSA - Handles RSA public keys and signatures
Tools - Various tools (positive modulus, string2bin, python-like range)
```
Added documentation, simplified code, organized exceptions, added some more examples in testing.php, decided to unset flags in deserialized responses, moved message id arrays to Connection classes, added wrappers for logging in to telegram as a bot or as a user and for logging out, fixed deserializing of gzip packed objects, added more logging, fixed bugs, added methods to get and parse configuration, saved some fairies, fixed exporting/importing of authorization, added some wakeup methods to prevent problems during serialization, added support for ipv6 and automagical detection too. I think we can safely say this is now a beta.
2016-11-25 00:15:22 +01:00
Check out the [Contribution guide ](https://github.com/danog/MadelineProto/blob/master/CONTRIBUTING.md ) before contributing.
2015-03-11 17:52:28 +01:00