Commit 4a7b6439 authored by Max Koder's avatar Max Koder

v 1.0a

parent c3967eaa
<?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.
*/
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
*/
class HttpRequest
{
/**
* Mastodon API URL
* @var string
*/
public $apiURL;
/**
* Mastodon Instance URL
* @var string
*/
public $domainURL;
/**
* Debugging mode
* @var boolean
*/
public $debug = false;
public function __construct($domain)
{
$this->domainURL = 'https://' . $domain . '/';
$this->apiURL = 'api/v1/';
}
public function post($url, $headers = [], $params = [])
{
return $this->request('POST', $url, $headers, json_encode($params));
}
public function get($url = "", $headers = array(),$parameters = array()){
//Sen the request and return response
return $this->request(
"GET",
$url,
$headers,
$parameters
);
}
protected function request($method, $url, $headers = [], $params = [])
{
$opts = $this->getDefaultOpts($method);
$opts['http']['content'] = $this->encodeParameters($params);
$opts['http']['header'] = $this->encodeHeaders($headers);
$context = stream_context_create($opts);
$response = @file_get_contents($this->domainURL . $url, null, $context);
if ($response !== false) {
$json = json_decode($response, true);
}
else {
return false;
}
if ($json !== null) {
return $json;
}
else {
return $response;
}
}
protected function encodeParameters($params)
{
if (is_array($params) && count($params) > 0) {
// Many parameters, encode them
$paramsString = '';
foreach ($params as $key => $value) {
$paramsString .= '&' . urlencode($key) . '=' . urlencode($value);
}
// Remove first '&'
return substr($paramsString, 1);
} elseif ($params) {
// return original
return $params;
}
}
protected function encodeHeaders($headers)
{
if (is_array($headers) && count($headers) > 0) {
// Many headers, encode them
$headersString = '';
foreach ($headers as $key => $value) {
$headersString .= "{$key}: {$value}\r\n";
}
// Return trimmed string
return trim($headersString);
}
return null;
}
protected function getDefaultOpts($method)
{
return [
'http' => [
'content' => '',
'header' => '',
'method' => $method,
'timeout' => 30,
'user_agent' => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
],
'ssl' => [
'ciphers' => 'HIGH',
'verify_host' => false,
'verify_peer' => false,
],
];
}
}
<?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.
*/
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
*/
class TootoPHP
{
/**
* Mastodon Instance Name, like 'mastodon.social'
* @var string
*/
protected $domain;
/**
* Path to the JSON file
* @var string
*/
protected $jsonFile;
/**
* HttpRequest Instance
* @var \TootoPHP\HttpRequest
*/
protected $http;
/**
* Defaults headers for HttpRequest
* @var array
*/
protected $headers = [
'Content-Type' => 'application/json; charset=utf-8',
'Accept' => '*/*'
];
/**
* Credentials to register App
* @var array
*/
protected $credentials = [
'client_name' => '',
'redirect_uris' => 'urn:ietf:wg:oauth:2.0:oob',
'scopes' => 'read write follow',
'website' => ''
];
/**
* Credentials to use Mastodon API
* @var array
*/
protected $appCredentials = [];
/**
* Authenticated User infos
* @var array
*/
private $userInfos = [];
/**
* Setting Domain, like 'mastodon.social'
* @param string $domain
*/
public function __construct($domain = 'mastodon.social')
{
$this->domain = $domain;
// Store credentials in JSON file, in 'tootophp' dir
$this->jsonFile = __DIR__ . DIRECTORY_SEPARATOR . 'tootophp.json';
}
/**
* Register Application
*
* $applicationName is name of your app, like 'TootoPHP'
* $websiteURL is website URL, like 'http://max-koder.fr
*
* @param string $applicationName
* @param string $websiteURL
* @return boolean|$this
*/
public function registerApp($applicationName, $websiteURL = '')
{
$this->credentials['client_name'] = $applicationName;
$this->credentials['website'] = $websiteURL;
$this->http = new HttpRequest($this->domain);
if (!is_file($this->jsonFile)) {
// Create new App
$writeApp = $this->createApp();
if ($writeApp === false) {
return false;
}
}
// Get AppCredentials by JSON
$this->appCredentials = $this->loadCredentialsByJSON();
if (isset($this->appCredentials['bearer'])) {
$this->headers['Authorization'] = 'Bearer ' . $this->appCredentials['bearer'];
}
return $this;
}
/**
* Get Authorization URL
*
* After Register App, Authorization URL provide a page to accept App use Mastodon
* And return an auth code for method getAccessToken
* @return boolean|string
*/
public function getAuthUrl()
{
if (is_array($this->appCredentials) && isset($this->appCredentials['client_id'])) {
// Get Authorization URL
return $this->http->domainURL . 'oauth/authorize/?' . http_build_query([
'client_id' => $this->appCredentials['client_id'],
'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob',
'response_type' => 'code',
'scope' => 'read write follow',
]);
}
return false;
}
/**
* Get Access Token
*
* Access Token is granted to authentify user, and gave by getAuthUrl method
* by accepting app is using Mastodon
*
* @param string $auth_code
* @return boolean|string
*/
public function getAccessToken($auth_code)
{
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,
[
"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
]
);
//Save our Token
return $this->catchBearerToken($token);
}
return false;
}
/**
* Authentify User
*
* You have to authentify to API before using Mastodon
*
* @param type $userName
* @param type $password
*/
public function authentify($userName, $password)
{
$this->authUser($userName, $password);
}
public function getUser()
{
if (empty($this->userInfos)) {
//Create our object
$user_info = $this->http->get(
"api/v1/accounts/verify_credentials", $this->headers, null
);
if (is_array($user_info) && isset($user_info["username"])) {
return $user_info;
}
}
return $this->userInfos;
}
public function getFavourites()
{
return $this->http->get(
$this->http->apiURL . 'favourites',
$this->headers,
null
);
}
public function getAccount($id)
{
return $this->http->get(
$this->http->apiURL . 'accounts/' . $id,
$this->headers,
null
);
}
public function postStatus($content)
{
return $this->http->post($this->http->apiURL . 'statuses',
$this->headers,
[
'status' => $content
]);
}
public function getFollowers($id)
{
return $this->http->get(
$this->http->apiURL . 'accounts/' . $id . '/followers',
$this->headers,
null
);
}
private function authUser($username = null, $password = null)
{
if (!empty($username) && !empty($password)) {
if (is_array($this->credentials) && isset($this->credentials['client_id'])) {
//Request access token in exchange for our Authorization 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,
)
);
//Save our token info
return $this->catchBearerToken($token);
}
}
return false;
}
protected function catchBearerToken($token = null)
{
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->saveCredentialsToJSON($this->appCredentials);
return $token["access_token"];
}
return false;
}
protected function loadCredentialsByJSON()
{
$content = file_get_contents($this->jsonFile);
return json_decode($content, true);
}
protected function createApp()
{
$credentials = $this->http->post($this->http->apiURL . 'apps', $this->headers, $this->credentials);
if ($credentials === false) {
return false;
}
return $this->saveCredentialsToJSON($credentials);
}
protected function saveCredentialsToJSON($credentials)
{
return file_put_contents($this->jsonFile, json_encode($credentials, JSON_PRETTY_PRINT));
}
}
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'TootoPHP.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'HttpRequest.php';
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