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