dolibarr 21.0.0-alpha
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 if (empty($this->accessToken) && !$this->authenticate()) {
143 return false;
144 }
145
146 $cacheFile = $cacheDir . '/' . dol_hash($urlAPI, '3');
147 $foundInCache = false;
148 $data = null;
149
150 // Check cache
151 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
152 $fileDate = dol_filemtime($cacheFile);
153 if ($fileDate >= (dol_now() - $cacheDelay)) {
154 $foundInCache = true;
155 $data = file_get_contents($cacheFile);
156 }
157 }
158
159 if (!$foundInCache) {
160 $headers = [
161 'Authorization: Bearer ' . $this->accessToken,
162 'User-Agent: ' . $this->userAgent,
163 ];
164
165 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, ['http', 'https'], 0);
166
167 if (!empty($result['content'])) {
168 $data = $result['content'];
169
170 if ($cacheDir) {
171 dol_mkdir($cacheDir);
172 file_put_contents($cacheFile, $data);
173 }
174 } else {
175 $this->error = 'Error retrieving URL ' . $urlAPI;
176 return false;
177 }
178 }
179 if (!is_null($data)) {
180 $data = json_decode($data, true);
181
182 if (is_array($data)) {
183 $this->posts = [];
184 $count = 0;
185
186 foreach ($data['data']['children'] as $postData) {
187 if ($count >= $maxNb) {
188 break;
189 }
190 $this->posts[$count] = $this->normalizeData($postData['data']);
191 $count++;
192 }
193
194 return $this->posts;
195 } else {
196 $this->error = 'Invalid data format or empty response';
197 return false;
198 }
199 } else {
200 $this->error = 'Failed to retrieve or decode data';
201 return false;
202 }
203 }
204
211 public function normalizeData($postData)
212 {
213 if (!is_array($postData)) {
214 return [];
215 }
216
217 return [
218 'id' => $postData['id'] ?? '',
219 'content' => $postData['title'] ?? '',
220 'created_at' => $this->formatDate($postData['created'] ?? ''),
221 'url' => 'https://www.reddit.com' . ($postData['permalink'] ?? ''),
222 'media_url' => $postData['thumbnail'] ?? '',
223 ];
224 }
225
231 private function formatDate($dateString)
232 {
233 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
234 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
235 }
236
242 public function getPosts()
243 {
244 return $this->posts;
245 }
246
251 public function getAuthUrl()
252 {
253 return $this->authUrl;
254 }
255}
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='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.