dolibarr 24.0.0-beta
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 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26require_once DOL_DOCUMENT_ROOT.'/core/class/socialnetworkmanager.class.php';
27
28
33{
37 private $posts;
38
42 public $error = '';
43
47 private $accessToken;
48
52 private $clientId;
53
57 private $clientSecret;
58
62 private $redirectUri;
63
64
70 public function __construct($authParams)
71 {
72
73 $this->clientId = $authParams['client_id'] ?? '';
74 $this->clientSecret = $authParams['client_secret'] ?? '';
75 $this->redirectUri = $authParams['redirect_uri'] ?? '';
76 $this->accessToken = $authParams['access_token'] ?? '';
77 }
78
79
90 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
91 {
92 if (empty($this->accessToken) && isset($authParams['access_token'])) {
93 return false;
94 }
95 $cacheFile = $cacheDir.'/'.dol_hash($urlAPI, '3');
96 $foundInCache = false;
98 $data = null;
99
100 // Check cache
101 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
102 $fileDate = dol_filemtime($cacheFile);
103 if ($fileDate >= (dol_now() - $cacheDelay)) {
104 $foundInCache = true;
105 // Read file into cache (false should not happen)
106 $data = (string) file_get_contents($cacheFile);
107 }
108 }
109
110 if (!$foundInCache) {
111 $headers = [
112 'Authorization: Bearer ' . $this->accessToken,
113 'Content-Type: application/json'
114 ];
115
116 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, array('http', 'https'), 0);
117
118 if (empty($result['curl_error_no']) && $result['http_code'] == 200 && !empty($result['content'])) {
119 $data = (string) $result['content'];
120
121 if ($cacheDir) {
122 dol_mkdir($cacheDir);
123 file_put_contents($cacheFile, $data);
124 dolChmod($cacheFile);
125 }
126 } else {
127 $this->error = 'Error retrieving URL ' . $urlAPI;
128 return false;
129 }
130 }
131 if (!is_null($data)) {
132 $data = json_decode($data, true);
133 if (is_array($data)) {
134 $this->posts = [];
135 $count = 0;
136
137 foreach ($data as $postData) {
138 if ($count >= $maxNb) {
139 break;
140 }
141 $this->posts[$count] = $this->normalizeData($postData);
142 $count++;
143 }
144 return $this->posts;
145 } else {
146 $this->error = 'Invalid data format or empty response';
147 return false;
148 }
149 } else {
150 $this->error = 'Failed to retrieve or decode data';
151 return false;
152 }
153 }
154
161 public function normalizeData($postData)
162 {
163 if (!is_array($postData)) {
164 return [];
165 }
166 return [
167 'id' => $postData['id'] ?? '',
168 'content' => strip_tags($postData['content'] ?? ''),
169 'created_at' => $this->formatDate($postData['created_at'] ?? ''),
170 'url' => $postData['url'] ?? '',
171 'media_url' => $postData['media_attachments'][0]['url'] ?? ''
172 ];
173 }
174
180 private function formatDate($dateString)
181 {
182 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
183 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
184 }
185
191 public function getPosts()
192 {
193 return $this->posts;
194 }
195
200 public function getRedirectUri()
201 {
202 return $this->redirectUri;
203 }
204
209 public function getAccessToken()
210 {
211 return $this->accessToken;
212 }
213
218 public function getClientId()
219 {
220 return $this->clientId;
221 }
222
227 public function getClientSecret()
228 {
229 return $this->clientSecret;
230 }
231}
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.
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='gmt')
Return date for now.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
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, $timeoutconnect=0, $timeoutresponse=0, $otherCurlOptions=array(), $morelogsuffix='')
Function to get a content from an URL (use proxy if proxy defined).
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.