dolibarr 21.0.0-alpha
mastodonhandler.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2024 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
25require_once DOL_DOCUMENT_ROOT.'/core/class/socialnetworkmanager.class.php';
26
27
32{
36 private $posts;
37
41 public $error = '';
42
46 private $accessToken;
47
51 private $clientId;
52
56 private $clientSecret;
57
61 private $redirectUri;
62
63
69 public function __construct($authParams)
70 {
71
72 $this->clientId = $authParams['client_id'] ?? '';
73 $this->clientSecret = $authParams['client_secret'] ?? '';
74 $this->redirectUri = $authParams['redirect_uri'] ?? '';
75 $this->accessToken = $authParams['access_token'] ?? '';
76 }
77
78
89 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
90 {
91 if (empty($this->accessToken) && isset($authParams['access_token'])) {
92 return false;
93 }
94 $cacheFile = $cacheDir.'/'.dol_hash($urlAPI, 3);
95 $foundInCache = false;
96 $data = null;
97
98 // Check cache
99 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
100 $fileDate = dol_filemtime($cacheFile);
101 if ($fileDate >= (dol_now() - $cacheDelay)) {
102 $foundInCache = true;
103 $data = file_get_contents($cacheFile);
104 }
105 }
106
107 if (!$foundInCache) {
108 $headers = [
109 'Authorization: Bearer ' . $this->accessToken,
110 'Content-Type: application/json'
111 ];
112
113 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, array('http', 'https'), 0);
114 if (!empty($result['content'])) {
115 $data = $result['content'];
116
117 if ($cacheDir) {
118 dol_mkdir($cacheDir);
119 file_put_contents($cacheFile, $data);
120 }
121 } else {
122 $this->error = 'Error retrieving URL ' . $urlAPI;
123 return false;
124 }
125 }
126 if (!is_null($data)) {
127 $data = json_decode($data, true);
128 if (is_array($data)) {
129 $this->posts = [];
130 $count = 0;
131
132 foreach ($data as $postData) {
133 if ($count >= $maxNb) {
134 break;
135 }
136 $this->posts[$count] = $this->normalizeData($postData);
137 $count++;
138 }
139 return $this->posts;
140 } else {
141 $this->error = 'Invalid data format or empty response';
142 return false;
143 }
144 } else {
145 $this->error = 'Failed to retrieve or decode data';
146 return false;
147 }
148 }
149
156 public function normalizeData($postData)
157 {
158 if (!is_array($postData)) {
159 return [];
160 }
161 return [
162 'id' => $postData['id'] ?? '',
163 'content' => strip_tags($postData['content'] ?? ''),
164 'created_at' => $this->formatDate($postData['created_at'] ?? ''),
165 'url' => $postData['url'] ?? '',
166 'media_url' => $postData['media_attachments'][0]['url'] ?? ''
167 ];
168 }
169
175 private function formatDate($dateString)
176 {
177 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
178 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
179 }
180
186 public function getPosts()
187 {
188 return $this->posts;
189 }
190
195 public function getRedirectUri()
196 {
197 return $this->redirectUri;
198 }
199
204 public function getAccessToken()
205 {
206 return $this->accessToken;
207 }
208
213 public function getClientId()
214 {
215 return $this->clientId;
216 }
217
222 public function getClientSecret()
223 {
224 return $this->clientSecret;
225 }
226}
Class for handler Mastodon.
formatDate($dateString)
Format date for normalize date.
getClientSecret()
Getter for secret client.
__construct($authParams)
Constructor to set the necessary credentials.
normalizeData($postData)
Normalize data of retrieved posts.
getClientId()
Getter for client Id.
fetch($urlAPI, $maxNb=5, $cacheDelay=60, $cacheDir='', $authParams=[])
Fetch posts from Mastodon API using the access token.
getPosts()
Get the list of retrieved posts.
getAccessToken()
Getter for access token.
getRedirectUri()
Getter for url to redirect.
dol_filemtime($pathoffile)
Return time of a file.
dol_is_file($pathoffile)
Return if path is a file.
dol_now($mode='auto')
Return date for now.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.