Commit ad2da87d authored by Max Koder's avatar Max Koder

v 1.0a2

parent 4a7b6439
/tootophp/tootophp.json
\ No newline at end of file
<?php
require 'tootophp\autoload.php';
// Setting up your instance
$tootoPHP = new TootoPHP\TootoPHP('mastodon.xyz');
// Setting up your App name and your website
$app = $tootoPHP->registerApp('TootoPHP', 'http://max-koder.fr');
if ( $app === false) {
throw new Exception('Problem during register app');
}
echo $app->getAuthUrl();
// Copy this URL and open it.
// Allow App to use Mastodon and copy the given token
\ No newline at end of file
<?php
require 'tootophp\autoload.php';
$tootoPHP = new TootoPHP\TootoPHP('mastodon.xyz');
$app = $tootoPHP->registerApp('TootoPHP', 'http://max-koder.fr');
if ( $app === false) {
throw new Exception('Problem during register app');
}
$token = $app->getAccessToken('write_here_your_token_got_in_step_1');
$bearer_token = $app->authentify("your_email@mail.com", "Your_Password");
// Now Token is registered in JSON file
\ No newline at end of file
<?php
/**
* TootoPHP
*/
/**
* TootoPHP is a simple class to get toots from a specified Mastodon instance
* and use them with PHP
*
* @author Maxence Cauderlier
* @link http://max-koder.fr
* @license http://opensource.org/licenses/MIT The MIT License
*/
class TootoPHP
{
/** @var string Atom File URL */
protected $xmlFileURL;
/** @var \DOMDocument Atom DOMDocument */
protected $dom;
/** @var \DomNodeList Feed Node List */
protected $feed;
/** @var string User URL */
public $uri;
/** @var string User Name */
public $name;
/** @var string User Email */
public $email;
/** @var string User Summary */
public $summary;
/** @var string User Alternate */
public $alternate;
/** @var string User Avatar URL */
public $avatar;
/** @var string User Header URL */
public $header;
/** @var boolean Is error */
public $on_error = false;
/**
* Constructor
*
* Test if instance and name are ok
*
* @param string $instance
* @param string $name
*/
public function __construct($instance, $name)
{
$this->xmlFileURL = 'https://' . $instance . '/users/' . $name . '.atom';
$file_headers = @get_headers($this->xmlFileURL);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$this->on_error = true;
return false;
}
$this->loadXMLFile($this->xmlFileURL);
$this->getUserInfos();
}
/**
* Load DOM from XML document
*/
protected function loadXMLFile($url)
{
$this->dom = new DOMDocument();
$this->dom->load($url);
$this->feed = $this->dom->getElementsByTagName('feed')->item(0);
}
/**
* Get Author Infos
*/
protected function getUserInfos()
{
$author = $this->feed->getElementsByTagName('author')->item(0);
$this->uri = $author->getElementsByTagName('uri')->item(0)->nodeValue;
$this->name = $author->getElementsByTagName('name')->item(0)->nodeValue;
$this->email = $author->getElementsByTagName('email')->item(0)->nodeValue;
$this->summary = $author->getElementsByTagName('summary')->item(0)->nodeValue;
foreach ($author->getElementsByTagName('link') as $link) {
if ($link->hasAttribute("rel")) {
$this->{$link->getAttribute('rel')} = $link->getAttribute('href');
}
}
}
/**
* Get many toots by timestamp order DESC
* param must be an integer greater than 0
* return an array of entries with :
* 'published' : Publish timestamp
* 'updated' : Last modification timestamp
* 'title' : Entry title
* 'content' : Entry content
* 'pic' : Array with pictures URL
*
* @param integer $number_of_toots
* @return array
*/
public function getToots($number_of_toots = 5)
{
$actualToot = 0;
$entries = [];
foreach ($this->feed->getElementsByTagName('entry') as $entry) {
if ($actualToot >= $number_of_toots) break;
$entries[$actualToot] = [];
$entries[$actualToot]['published'] = strtotime($entry->getElementsByTagName('published')->item(0)->nodeValue);
$entries[$actualToot]['updated'] = strtotime($entry->getElementsByTagName('updated')->item(0)->nodeValue);
$entries[$actualToot]['title'] = $entry->getElementsByTagName('title')->item(0)->nodeValue;
$entries[$actualToot]['content'] = $entry->getElementsByTagName('content')->item(0)->nodeValue;
$entries[$actualToot]['pic'] = [];
foreach ($entry->getElementsByTagName('link') as $link) {
if ($link->hasAttribute("rel") && $link->getAttribute('rel') === 'enclosure') {
$entries[$actualToot]['pic'][] = $link->getAttribute('href');
}
}
$actualToot ++;
}
return $entries;
}
}
<?php
require 'tootophp\autoload.php';
$tootoPHP = new TootoPHP\TootoPHP('mastodon.xyz');
$app = $tootoPHP->registerApp('TootoPHP', 'http://max-koder.fr');
if ( $app === false) {
throw new Exception('Problem during register app');
}
var_dump($app->getUser());
//var_dump($app->getFavourites());
//var_dump($app->getAccount(1));
//var_dump($app->getFollowers(1629));
//var_dump($app->postStatus('This status is posted by #PHP'));
\ No newline at end of file
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* HttpRequest
*
* @author Maxence Cauderlier
* @link http://max-koder.fr
* @link https://framagit.org/MaxKoder/TootoPHP
* @package TootoPHP
* @license http://opensource.org/licenses/MIT The MIT License
*/
namespace TootoPHP;
/**
* TootoPHP is a simple class to get toots from a specified Mastodon instance
* and use them with PHP
* @author Maxence Cauderlier
* @link http://max-koder.fr
* @license http://opensource.org/licenses/MIT The MIT License
* HttpRequest is a way to do http requests and get responses
*/
class HttpRequest
{
......@@ -29,34 +30,78 @@ class HttpRequest
* @var string
*/
public $domainURL;
/**
* Debugging mode
* @var boolean
* Setting up domain and API URL
*
* @param string $domain
*/
public $debug = false;
public function __construct($domain)
{
$this->domainURL = 'https://' . $domain . '/';
$this->apiURL = 'api/v1/';
}
/**
* Do a POST http request and return response.
*
* For URL, domain will be automatically added.
* Array headers and params will be automatically encoded for request.
*
* If response is JSON format, it will be decoded before return
*
* @param string $url
* @param array $headers
* @param array $params
* @return mixed
*/
public function post($url, $headers = [], $params = [])
{
return $this->request('POST', $url, $headers, json_encode($params));
return $this->request(
'POST',
$url,
$headers,
json_encode($params)
);
}
public function get($url = "", $headers = array(),$parameters = array()){
//Sen the request and return response
/**
* Do a GET http request and return response.
*
* For URL, domain will be automatically added.
* Array headers and params will be automatically encoded for request.
*
* If response is JSON format, it will be decoded before return
*
* @param string $url
* @param array $headers
* @param array $params
* @return mixed
*/
public function get($url, $headers = [],$params = [])
{
return $this->request(
"GET",
'GET',
$url,
$headers,
$parameters
$params
);
}
/**
* Do a http request and return response.
*
* For URL, domain will be automatically added.
* Array headers and params will be automatically encoded for request.
*
* If response is JSON format, it will be decoded before return
*
* @param string $method POST or GET
* @param string $url
* @param array $headers
* @param array $params
* @return mixed
*/
protected function request($method, $url, $headers = [], $params = [])
{
$opts = $this->getDefaultOpts($method);
......@@ -80,6 +125,12 @@ class HttpRequest
}
}
/**
* Encode Parameters before HTTP request
*
* @param array $params
* @return string
*/
protected function encodeParameters($params)
{
if (is_array($params) && count($params) > 0) {
......@@ -96,6 +147,12 @@ class HttpRequest
}
}
/**
* Encode Headers before HTTP request
*
* @param array $headers
* @return string
*/
protected function encodeHeaders($headers)
{
if (is_array($headers) && count($headers) > 0) {
......@@ -110,6 +167,12 @@ class HttpRequest
return null;
}
/**
* Get Defaults Options to create the Stream Context
*
* @param string $method POST or GET
* @return array
*/
protected function getDefaultOpts($method)
{
return [
......
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* TootoPHP
*
* @author Maxence Cauderlier
* @link http://max-koder.fr
* @link https://framagit.org/MaxKoder/TootoPHP
* @package TootoPHP
* @license http://opensource.org/licenses/MIT The MIT License
*/
namespace TootoPHP;
/**
* TootoPHP is a simple class to get toots from a specified Mastodon instance
* and use them with PHP
* @author Maxence Cauderlier
* @link http://max-koder.fr
* @license http://opensource.org/licenses/MIT The MIT License
* TootoPHP is a class to dialog with Mastodon API
*/
class TootoPHP
{
......@@ -138,24 +139,24 @@ class TootoPHP
* Access Token is granted to authentify user, and gave by getAuthUrl method
* by accepting app is using Mastodon
*
* @param string $auth_code
* @param string $authCode
* @return boolean|string
*/
public function getAccessToken($auth_code)
public function getAccessToken($authCode)
{
if (is_array($this->appCredentials) && isset($this->appCredentials["client_id"])) {
if (is_array($this->appCredentials) && isset($this->appCredentials['client_id'])) {
// Exchange Access Token for our Auth Token
$token = $this->http->post(
"oauth/token", $this->headers,
'oauth/token', $this->headers,
[
"grant_type" => "authorization_code",
"redirect_uri" => "urn:ietf:wg:oauth:2.0:oob",
"client_id" => $this->appCredentials["client_id"],
"client_secret" => $this->appCredentials["client_secret"],
"code" => $auth_code
'grant_type' => 'authorization_code',
'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob',
'client_id' => $this->appCredentials['client_id'],
'client_secret' => $this->appCredentials['client_secret'],
'code' => $authCode
]
);
//Save our Token
// Save our Token
return $this->catchBearerToken($token);
}
return false;
......@@ -174,20 +175,46 @@ class TootoPHP
$this->authUser($userName, $password);
}
/**
* Get authenticated user
*
* @return array
*/
public function getUser()
{
if (empty($this->userInfos)) {
//Create our object
$user_info = $this->http->get(
"api/v1/accounts/verify_credentials", $this->headers, null
$user = $this->http->get(
$this->http->apiURL . 'accounts/verify_credentials',
$this->headers,
null
);
if (is_array($user_info) && isset($user_info["username"])) {
return $user_info;
var_dump($user);
echo 'ooo';
if (is_array($user) && isset($user['username'])) {
$this->userInfos = $user;
}
}
return $this->userInfos;
}
/**
* Get authenticated user ID
*
* @return string
*/
public function getUserID()
{
$user = $this->getUser();
return $user['id'];
}
/**
* Get authenticated user favourites
*
* Return as an array all user's favourites status
*
* @return array
*/
public function getFavourites()
{
return $this->http->get(
......@@ -197,6 +224,14 @@ class TootoPHP
);
}
/**
* Get an account by his ID
*
* Return account as an array
*
* @param string $id
* @return array
*/
public function getAccount($id)
{
return $this->http->get(
......@@ -206,15 +241,35 @@ class TootoPHP
);
}
/**
* Post a new status
*
* Post a new status in Mastodon instance
* Actuallay, only text is allowed
* Return entire status as an array
*
* @param string $content
* @return array
*/
public function postStatus($content)
{
return $this->http->post($this->http->apiURL . 'statuses',
return $this->http->post(
$this->http->apiURL . 'statuses',
$this->headers,
[
'status' => $content
]);
]
);
}
/**
* Get user's followers by his ID
*
* Return all followers as an array
*
* @param string $id
* @return array
*/
public function getFollowers($id)
{
return $this->http->get(
......@@ -224,47 +279,70 @@ class TootoPHP
);
}
private function authUser($username = null, $password = null)
/**
* Authentify user
*
* Authentify user to get access token
* If successfull, save token and return it
*
* @param string $userName
* @param string $password
* @return boolean|string
*/
protected function authUser($userName = null, $password = null)
{
if (!empty($username) && !empty($password)) {
if (!empty($userName) && !empty($password)) {
if (is_array($this->credentials) && isset($this->credentials['client_id'])) {
//Request access token in exchange for our Authorization token
// Get authentified token
$token = $this->http->post(
'oauth/token', $this->headers, array(
'grant_type' => 'password',
'client_id' => $this->credentials['client_id'],
'client_secret' => $this->credentials['client_secret'],
'username' => $username,
'password' => $password,
)
'oauth/token',
$this->headers,
[
'grant_type' => 'password',
'client_id' => $this->credentials['client_id'],
'client_secret' => $this->credentials['client_secret'],
'username' => $userName,
'password' => $password,
]
);
//Save our token info
// Save our Token
return $this->catchBearerToken($token);
}
}
return false;
}
/**
* Catch the 'access_token' from a token
*
* Get access token to save it from a token
* Return Access Token
*
* @param array $token
* @return boolean|string
*/
protected function catchBearerToken($token = null)
{
if (!empty($token) && isset($token["access_token"])) {
if (!empty($token) && isset($token['access_token'])) {
// Add Token to AppCredentials and save it
$this->appCredentials["bearer"] = $token["access_token"];
$this->headers["Authorization"] = "Bearer " . $token["access_token"];
$this->appCredentials['bearer'] = $token['access_token'];
$this->headers['Authorization'] = 'Bearer ' . $token['access_token'];
$this->saveCredentialsToJSON($this->appCredentials);
return $token["access_token"];
return $token['access_token'];
}
return false;
}
protected function loadCredentialsByJSON()
{
$content = file_get_contents($this->jsonFile);
return json_decode($content, true);
}
/**
* Create new App
*
* Create new application with credentials given in 'registerApp' method
* and save IDs in the JSON file to use them later.
*
* Return true if success
*
* @return boolean
*/
protected function createApp()
{
$credentials = $this->http->post($this->http->apiURL . 'apps', $this->headers, $this->credentials);
......@@ -274,9 +352,30 @@ class TootoPHP
return $this->saveCredentialsToJSON($credentials);
}
/**
* Save credentials in the JSON file
*
* Return true if success
*
* @param array $credentials
* @return boolean
*/
protected function saveCredentialsToJSON($credentials)
{
return file_put_contents($this->jsonFile, json_encode($credentials, JSON_PRETTY_PRINT));
}
/**
* Load credentials by JSON
*
* Credentials are saved in JSON to save many requests
*
* @return array
*/
protected function loadCredentialsByJSON()
{
$content = file_get_contents($this->jsonFile);
return json_decode($content, true);
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment