dolibarr 25.0.0-alpha
diasporahandler.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';
31{
35 private $posts = [];
36
40 public $error = '';
41
45 private $params = [];
46
50 private $podUrl = '';
51
56 private function isCookieValid()
57 {
58 return !empty($this->getCookieFromParams());
59 }
60
65 private function getCookieFromParams()
66 {
67 foreach ($this->params as $key => $value) {
68 if (stripos($key, 'cookie') !== false && !empty($value)) {
69 return $value;
70 }
71 }
72 return null;
73 }
74
85 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
86 {
87
88 // Set authParams to the class attribute
89 $this->params = $authParams;
90
91 $parsedUrl = parse_url($urlAPI);
92 $this->podUrl = empty($parsedUrl['host']) ? '' : ($parsedUrl['scheme'] ?? 'https').'://'.$parsedUrl['host'].(empty($parsedUrl['port']) ? '' : ':'.$parsedUrl['port']);
93
94 if (!$this->isCookieValid()) {
95 $this->error = 'Invalid or missing authentication parameters';
96 return false;
97 }
98
99 $cacheFile = $cacheDir.'/'.dol_hash($urlAPI, '3');
100 $foundInCache = false;
101 $data = null;
102
103 // Check cache
104 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
105 $fileDate = dol_filemtime($cacheFile);
106 if ($fileDate >= (dol_now() - $cacheDelay)) {
107 $foundInCache = true;
108 $data = file_get_contents($cacheFile);
109 }
110 }
111
112 if (!$foundInCache) {
113 $headers = [
114 'Cookie: ' . $this->getCookieFromParams(),
115 'Accept: application/json'
116 ];
117
118 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, array('http', 'https'), 0);
119 if (!empty($result['content'])) {
120 $data = $result['content'];
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
132 $data = json_decode((string) $data, true);
133 if (!is_null($data)) {
134 if (is_array($data)) {
135 $this->posts = [];
136 $count = 0;
137
138 foreach ($data as $postData) {
139 if ($count >= $maxNb) {
140 break;
141 }
142 $this->posts[$count] = $this->normalizeData($postData);
143 $count++;
144 }
145 return true;
146 } else {
147 $this->error = 'Invalid data format or empty response';
148 return false;
149 }
150 } else {
151 $this->error = 'Failed to retrieve or decode data';
152 return false;
153 }
154 }
155
162 public function normalizeData($postData)
163 {
164 if (!is_array($postData)) {
165 return [];
166 }
167
168 return [
169 'id' => $postData['guid'] ?? '',
170 'content' => strip_tags($postData['text'] ?? $postData['title'] ?? ''),
171 'created_at' => $this->formatDate($postData['created_at'] ?? ''),
172 'url' => (empty($postData['guid']) ? '' : $this->podUrl.'/posts/'.$postData['guid']),
173 'media_url' => !empty($postData['photos']) && isset($postData['photos'][0]['url']) ? $postData['photos'][0]['url'] : '',
174 'author_name' => $postData['author']['name'] ?? '',
175 'author_avatar' => $postData['author']['avatar']['small'] ?? ''
176 ];
177 }
178
184 private function formatDate($dateString)
185 {
186 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
187 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
188 }
189
195 public function getPosts()
196 {
197 return $this->posts;
198 }
199}
Class for handling Diaspora API interactions.
getCookieFromParams()
Get the cookie value from params, regardless of the exact key name.
normalizeData($postData)
Normalize data of retrieved posts.
getPosts()
Get the list of retrieved posts.
formatDate($dateString)
Format date for normalize date.
fetch($urlAPI, $maxNb=5, $cacheDelay=60, $cacheDir='', $authParams=[])
Fetch Social Network API to retrieve posts.
isCookieValid()
Check if the provided cookie in params is valid.
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).
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.