dolibarr 21.0.0-beta
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
51 private function isCookieValid()
52 {
53 return !empty($this->getCookieFromParams());
54 }
55
60 private function getCookieFromParams()
61 {
62 foreach ($this->params as $key => $value) {
63 if (stripos($key, 'cookie') !== false && !empty($value)) {
64 return $value;
65 }
66 }
67 return null;
68 }
69
80 public function fetch($urlAPI, $maxNb = 5, $cacheDelay = 60, $cacheDir = '', $authParams = [])
81 {
82
83 // Set authParams to the class attribute
84 $this->params = $authParams;
85
86 if (!$this->isCookieValid()) {
87 $this->error = 'Invalid or missing authentication parameters';
88 return false;
89 }
90
91 $cacheFile = $cacheDir.'/'.dol_hash($urlAPI, '3');
92 $foundInCache = false;
93 $data = null;
94
95 // Check cache
96 if ($cacheDelay > 0 && $cacheDir && dol_is_file($cacheFile)) {
97 $fileDate = dol_filemtime($cacheFile);
98 if ($fileDate >= (dol_now() - $cacheDelay)) {
99 $foundInCache = true;
100 $data = file_get_contents($cacheFile);
101 }
102 }
103
104 if (!$foundInCache) {
105 $headers = [
106 'Cookie: ' . $this->getCookieFromParams(),
107 'Accept: application/json'
108 ];
109
110 $result = getURLContent($urlAPI, 'GET', '', 1, $headers, array('http', 'https'), 0);
111 if (!empty($result['content'])) {
112 $data = $result['content'];
113 if ($cacheDir) {
114 dol_mkdir($cacheDir);
115 file_put_contents($cacheFile, $data);
116 }
117 } else {
118 $this->error = 'Error retrieving URL ' . $urlAPI;
119 return false;
120 }
121 }
122
123 $data = json_decode((string) $data, true);
124 if (!is_null($data)) {
125 if (is_array($data)) {
126 $this->posts = [];
127 $count = 0;
128
129 foreach ($data as $postData) {
130 if ($count >= $maxNb) {
131 break;
132 }
133 $this->posts[$count] = $this->normalizeData($postData);
134 $count++;
135 }
136 return true;
137 } else {
138 $this->error = 'Invalid data format or empty response';
139 return false;
140 }
141 } else {
142 $this->error = 'Failed to retrieve or decode data';
143 return false;
144 }
145 }
146
153 public function normalizeData($postData)
154 {
155 if (!is_array($postData)) {
156 return [];
157 }
158
159 return [
160 'id' => $postData['guid'] ?? '',
161 'content' => strip_tags($postData['text'] ?? $postData['title'] ?? ''),
162 'created_at' => $this->formatDate($postData['created_at'] ?? ''),
163 'url' => 'https://diaspora-fr.org/posts/' . ($postData['guid'] ?? ''), 'media_url' => !empty($postData['photos']) && isset($postData['photos'][0]['url']) ? $postData['photos'][0]['url'] : '',
164 'author_name' => $postData['author']['name'] ?? '',
165 'author_avatar' => $postData['author']['avatar']['small'] ?? ''
166 ];
167 }
168
174 private function formatDate($dateString)
175 {
176 $timestamp = is_numeric($dateString) ? (int) $dateString : strtotime($dateString);
177 return $timestamp > 0 ? dol_print_date($timestamp, "dayhour", 'tzuserrel') : 'Invalid Date';
178 }
179
185 public function getPosts()
186 {
187 return $this->posts;
188 }
189}
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='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.