dolibarr 23.0.4
reddithandler.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 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
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
32{
36 private $clientId;
37
41 private $clientSecret;
42
46 private $username;
47
51 private $password;
52
56 private $accessToken;
57
61 private $userAgent;
62
66 private $authUrl = 'https://www.reddit.com/api/v1/access_token';
67
71 public $error = '';
72
76 private $posts = [];
77
83 public function __construct(array $authParams)
84 {
85 $this->clientId = $authParams['client_id'] ?? '';
86 $this->clientSecret = $authParams['client_secret'] ?? '';
87 $this->username = $authParams['username'] ?? '';
88 $this->password = $authParams['password'] ?? '';
89 $this->userAgent = ($authParams['name_app'] ?? '').'/0.1 by '.($authParams['username'] ?? '');
90 }
91
97 private function authenticate()
98 {
99
100 $authData = [
101 'grant_type' => 'password',
102 'username' => $this->username,
103 'password' => $this->password,
104 'scope' => 'read identity'
105 ];
106
107 $headers = [
108 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
109 'Content-Type: application/x-www-form-urlencoded',
110 'User-Agent: ' . $this->userAgent
111 ];
112
113 $result = getURLContent($this->getAuthUrl(), 'POST', http_build_query($authData), 1, $headers, ['http', 'https'], 0);
114
115 if (!empty($result['content'])) {
116 $data = json_decode($result['content'], true);
117 if (isset($data['access_token'])) {
118 $this->accessToken = $data['access_token'];
119 return true;
120 } else {
121 $this->error = $data['error'] ?? 'Unknown error during authentication';
122 return false;
123 }
124 } else {
125 $this->error = 'Authentication failed. No content received.';
126 return false;
127 }
128 }
129
140 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
141 {
142 $cacheFile = $cacheDir . '/' . dol_hash($urlAPI, '3');
143 $foundInCache = false;
144 $data = null;
145
146 // Check cache
147 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
148 $fileDate = dol_filemtime($cacheFile);
149 if ($fileDate >= (dol_now() - $cacheDelay)) {
150 $foundInCache = true;
151 $data = file_get_contents($cacheFile);
152 }
153 }
154
155 if (!$foundInCache) {
156 // Authenticate only when the API must be called (not at each display when the cache is used)
157 if (empty($this->accessToken) && !$this->authenticate()) {
158 return false;
159 }
160
161 $headers = [
162 'Authorization: Bearer ' . $this->accessToken,
163 'User-Agent: ' . $this->userAgent,
164 ];
165
166 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, ['http', 'https'], 0);
167
168 if (!empty($result['content'])) {
169 $data = $result['content'];
170
171 if ($cacheDir) {
172 dol_mkdir($cacheDir);
173 file_put_contents($cacheFile, $data);
174 dolChmod($cacheFile);
175 }
176 } else {
177 $this->error = 'Error retrieving URL ' . $urlAPI;
178 return false;
179 }
180 }
181 if (!is_null($data)) {
182 $data = json_decode($data, true);
183
184 if (is_array($data) && isset($data['data']['children']) && is_array($data['data']['children'])) {
185 $this->posts = [];
186 $count = 0;
187
188 foreach ($data['data']['children'] as $postData) {
189 if ($count >= $maxNb) {
190 break;
191 }
192 $this->posts[$count] = $this->normalizeData($postData['data'] ?? []);
193 $count++;
194 }
195
196 return $this->posts;
197 } else {
198 $this->error = 'Invalid data format or empty response';
199 return false;
200 }
201 } else {
202 $this->error = 'Failed to retrieve or decode data';
203 return false;
204 }
205 }
206
213 public function normalizeData($postData)
214 {
215 if (!is_array($postData)) {
216 return [];
217 }
218
219 return [
220 'id' => $postData['id'] ?? '',
221 'content' => $postData['title'] ?? '',
222 'created_at' => $this->formatDate($postData['created'] ?? ''),
223 'url' => 'https://www.reddit.com' . ($postData['permalink'] ?? ''),
224 'media_url' => $postData['thumbnail'] ?? '',
225 ];
226 }
227
233 private function formatDate($dateString)
234 {
235 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
236 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
237 }
238
244 public function getPosts()
245 {
246 return $this->posts;
247 }
248
253 public function getAuthUrl()
254 {
255 return $this->authUrl;
256 }
257}
Class for handler Reddit.
__construct(array $authParams)
Constructor to initialize RedditHandler.
normalizeData($postData)
Normalize the data fetched from the Reddit API.
fetch($urlAPI, $maxNb=5, $cacheDelay=60, $cacheDir='', $authParams=[])
Fetch Reddit API to retrieve posts.
getPosts()
Get the list of retrieved posts.
authenticate()
Authenticate with Reddit to get an access token.
formatDate($dateString)
Format date for normalize date.
getAuthUrl()
Get url for authenticate with Reddit.
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())
Function to get a content from an URL (use proxy if proxy defined).
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.