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 *
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
31{
35 private $clientId;
36
40 private $clientSecret;
41
45 private $username;
46
50 private $password;
51
55 private $accessToken;
56
60 private $userAgent;
61
65 private $authUrl = 'https://www.reddit.com/api/v1/access_token';
66
70 public $error = '';
71
75 private $posts;
76
82 public function __construct(array $authParams)
83 {
84 $this->clientId = $authParams['client_id'] ?? '';
85 $this->clientSecret = $authParams['client_secret'] ?? '';
86 $this->username = $authParams['username'] ?? '';
87 $this->password = $authParams['password'] ?? '';
88 $this->userAgent = ($authParams['name_app'] ?? '').'/0.1 by '.($authParams['username'] ?? '');
89 }
90
96 private function authenticate()
97 {
98
99 $authData = [
100 'grant_type' => 'password',
101 'username' => $this->username,
102 'password' => $this->password,
103 'scope' => 'read identity'
104 ];
105
106 $headers = [
107 'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret),
108 'Content-Type: application/x-www-form-urlencoded',
109 'User-Agent: ' . $this->userAgent
110 ];
111
112 $result = getURLContent($this->getAuthUrl(), 'POST', http_build_query($authData), 1, $headers, ['http', 'https'], 0);
113
114 if (!empty($result['content'])) {
115 $data = json_decode($result['content'], true);
116 if (isset($data['access_token'])) {
117 $this->accessToken = $data['access_token'];
118 return true;
119 } else {
120 $this->error = $data['error'] ?? 'Unknown error during authentication';
121 return false;
122 }
123 } else {
124 $this->error = 'Authentication failed. No content received.';
125 return false;
126 }
127 }
128
139 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
140 {
141 if (empty($this->accessToken) && !$this->authenticate()) {
142 return false;
143 }
144
145 $cacheFile = $cacheDir . '/' . dol_hash($urlAPI, '3');
146 $foundInCache = false;
147 $data = null;
148
149 // Check cache
150 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
151 $fileDate = dol_filemtime($cacheFile);
152 if ($fileDate >= (dol_now() - $cacheDelay)) {
153 $foundInCache = true;
154 $data = file_get_contents($cacheFile);
155 }
156 }
157
158 if (!$foundInCache) {
159 $headers = [
160 'Authorization: Bearer ' . $this->accessToken,
161 'User-Agent: ' . $this->userAgent,
162 ];
163
164 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, ['http', 'https'], 0);
165
166 if (!empty($result['content'])) {
167 $data = $result['content'];
168
169 if ($cacheDir) {
170 dol_mkdir($cacheDir);
171 file_put_contents($cacheFile, $data);
172 }
173 } else {
174 $this->error = 'Error retrieving URL ' . $urlAPI;
175 return false;
176 }
177 }
178 if (!is_null($data)) {
179 $data = json_decode($data, true);
180
181 if (is_array($data)) {
182 $this->posts = [];
183 $count = 0;
184
185 foreach ($data['data']['children'] as $postData) {
186 if ($count >= $maxNb) {
187 break;
188 }
189 $this->posts[$count] = $this->normalizeData($postData['data']);
190 $count++;
191 }
192
193 return $this->posts;
194 } else {
195 $this->error = 'Invalid data format or empty response';
196 return false;
197 }
198 } else {
199 $this->error = 'Failed to retrieve or decode data';
200 return false;
201 }
202 }
203
210 public function normalizeData($postData)
211 {
212 if (!is_array($postData)) {
213 return [];
214 }
215
216 return [
217 'id' => $postData['id'] ?? '',
218 'content' => $postData['title'] ?? '',
219 'created_at' => $this->formatDate($postData['created'] ?? ''),
220 'url' => 'https://www.reddit.com' . ($postData['permalink'] ?? ''),
221 'media_url' => $postData['thumbnail'] ?? '',
222 ];
223 }
224
230 private function formatDate($dateString)
231 {
232 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
233 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
234 }
235
241 public function getPosts()
242 {
243 return $this->posts;
244 }
245
250 public function getAuthUrl()
251 {
252 return $this->authUrl;
253 }
254}
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.