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 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
24require_once DOL_DOCUMENT_ROOT.'/core/class/socialnetworkmanager.class.php';
25
30{
34 private $clientId;
35
39 private $clientSecret;
40
44 private $username;
45
49 private $password;
50
54 private $accessToken;
55
59 private $userAgent;
60
64 private $authUrl = 'https://www.reddit.com/api/v1/access_token';
65
69 public $error = '';
70
74 private $posts;
75
81 public function __construct(array $authParams)
82 {
83 $this->clientId = $authParams['client_id'] ?? '';
84 $this->clientSecret = $authParams['client_secret'] ?? '';
85 $this->username = $authParams['username'] ?? '';
86 $this->password = $authParams['password'] ?? '';
87 $this->userAgent = ($authParams['name_app'] ?? '').'/0.1 by '.($authParams['username'] ?? '');
88 }
89
95 private function authenticate()
96 {
97
98 $authData = [
99 'grant_type' => 'password',
100 'username' => $this->username,
101 'password' => $this->password,
102 'scope' => 'read identity'
103 ];
104
105 $headers = [
106 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
107 'Content-Type: application/x-www-form-urlencoded',
108 'User-Agent: ' . $this->userAgent
109 ];
110
111 $result = getURLContent($this->getAuthUrl(), 'POST', http_build_query($authData), 1, $headers, ['http', 'https'], 0);
112
113 if (!empty($result['content'])) {
114 $data = json_decode($result['content'], true);
115 if (isset($data['access_token'])) {
116 $this->accessToken = $data['access_token'];
117 return true;
118 } else {
119 $this->error = $data['error'] ?? 'Unknown error during authentication';
120 return false;
121 }
122 } else {
123 $this->error = 'Authentication failed. No content received.';
124 return false;
125 }
126 }
127
138 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
139 {
140 if (empty($this->accessToken) && !$this->authenticate()) {
141 return false;
142 }
143
144 $cacheFile = $cacheDir . '/' . dol_hash($urlAPI, 3);
145 $foundInCache = false;
146 $data = null;
147
148 // Check cache
149 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
150 $fileDate = dol_filemtime($cacheFile);
151 if ($fileDate >= (dol_now() - $cacheDelay)) {
152 $foundInCache = true;
153 $data = file_get_contents($cacheFile);
154 }
155 }
156
157 if (!$foundInCache) {
158 $headers = [
159 'Authorization: Bearer ' . $this->accessToken,
160 'User-Agent: ' . $this->userAgent,
161 ];
162
163 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, ['http', 'https'], 0);
164
165 if (!empty($result['content'])) {
166 $data = $result['content'];
167
168 if ($cacheDir) {
169 dol_mkdir($cacheDir);
170 file_put_contents($cacheFile, $data);
171 }
172 } else {
173 $this->error = 'Error retrieving URL ' . $urlAPI;
174 return false;
175 }
176 }
177 if (!is_null($data)) {
178 $data = json_decode($data, true);
179
180 if (is_array($data)) {
181 $this->posts = [];
182 $count = 0;
183
184 foreach ($data['data']['children'] as $postData) {
185 if ($count >= $maxNb) {
186 break;
187 }
188 $this->posts[$count] = $this->normalizeData($postData['data']);
189 $count++;
190 }
191
192 return $this->posts;
193 } else {
194 $this->error = 'Invalid data format or empty response';
195 return false;
196 }
197 } else {
198 $this->error = 'Failed to retrieve or decode data';
199 return false;
200 }
201 }
202
209 public function normalizeData($postData)
210 {
211 if (!is_array($postData)) {
212 return [];
213 }
214
215 return [
216 'id' => $postData['id'] ?? '',
217 'content' => $postData['title'] ?? '',
218 'created_at' => $this->formatDate($postData['created'] ?? ''),
219 'url' => 'https://www.reddit.com' . ($postData['permalink'] ?? ''),
220 'media_url' => $postData['thumbnail'] ?? '',
221 ];
222 }
223
229 private function formatDate($dateString)
230 {
231 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
232 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
233 }
234
240 public function getPosts()
241 {
242 return $this->posts;
243 }
244
249 public function getAuthUrl()
250 {
251 return $this->authUrl;
252 }
253}
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.