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