]> git.mxchange.org Git - friendica.git/blob - src/Factory/Notification/Notification.php
9f833130aaae81611121fe84f702d63fc962fa64
[friendica.git] / src / Factory / Notification / Notification.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Factory\Notification;
23
24 use Exception;
25 use Friendica\App;
26 use Friendica\App\BaseURL;
27 use Friendica\BaseFactory;
28 use Friendica\Collection\Api\Notifications as ApiNotifications;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Core\L10n;
31 use Friendica\Core\PConfig\IPConfig;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session\ISession;
34 use Friendica\Database\Database;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Post;
37 use Friendica\Module\BaseNotifications;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Object\Api\Friendica\Notification as ApiNotification;
40 use Friendica\Protocol\Activity;
41 use Friendica\Repository;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Temporal;
45 use Friendica\Util\XML;
46 use Psr\Log\LoggerInterface;
47
48 /**
49  * Factory for creating notification objects based on items
50  * Currently, there are the following types of item based notifications:
51  * - network
52  * - system
53  * - home
54  * - personal
55  */
56 class Notification extends BaseFactory
57 {
58         /** @var Database */
59         private $dba;
60         /** @var Repository\Notification */
61         private $notification;
62         /** @var BaseURL */
63         private $baseUrl;
64         /** @var L10n */
65         private $l10n;
66
67         public function __construct(LoggerInterface $logger, Database $dba, Repository\Notification $notification, BaseURL $baseUrl, L10n $l10n, App $app, IPConfig $pConfig, ISession $session)
68         {
69                 parent::__construct($logger);
70
71                 $this->dba          = $dba;
72                 $this->notification = $notification;
73                 $this->baseUrl      = $baseUrl;
74                 $this->l10n         = $l10n;
75         }
76
77         /**
78          * Format the item query in an usable array
79          *
80          * @param array $item The item from the db query
81          *
82          * @return array The item, extended with the notification-specific information
83          *
84          * @throws InternalServerErrorException
85          * @throws Exception
86          */
87         private function formatItem(array $item)
88         {
89                 $item['seen'] = ($item['unseen'] > 0 ? false : true);
90
91                 // For feed items we use the user's contact, since the avatar is mostly self choosen.
92                 if (!empty($item['network']) && $item['network'] == Protocol::FEED) {
93                         $item['author-avatar'] = $item['contact-avatar'];
94                 }
95
96                 $item['label'] = (($item['gravity'] == GRAVITY_PARENT) ? 'post' : 'comment');
97                 $item['link']  = $this->baseUrl->get(true) . '/display/' . $item['parent-guid'];
98                 $item['image'] = $item['author-avatar'];
99                 $item['url']   = $item['author-link'];
100                 $item['text']  = (($item['gravity'] == GRAVITY_PARENT)
101                         ? $this->l10n->t("%s created a new post", $item['author-name'])
102                         : $this->l10n->t("%s commented on %s's post", $item['author-name'], $item['parent-author-name']));
103                 $item['when']  = DateTimeFormat::local($item['created'], 'r');
104                 $item['ago']   = Temporal::getRelativeDate($item['created']);
105
106                 return $item;
107         }
108
109         /**
110          * @param array $item
111          *
112          * @return \Friendica\Object\Notification\Notification
113          *
114          * @throws InternalServerErrorException
115          */
116         private function createFromItem(array $item)
117         {
118                 $item = $this->formatItem($item);
119
120                 // Transform the different types of notification in an usable array
121                 switch ($item['verb'] ?? '') {
122                         case Activity::LIKE:
123                                 return new \Friendica\Object\Notification\Notification([
124                                         'label' => 'like',
125                                         'link'  => $this->baseUrl->get(true) . '/display/' . $item['parent-guid'],
126                                         'image' => $item['author-avatar'],
127                                         'url'   => $item['author-link'],
128                                         'text'  => $this->l10n->t("%s liked %s's post", $item['author-name'], $item['parent-author-name']),
129                                         'when'  => $item['when'],
130                                         'ago'   => $item['ago'],
131                                         'seen'  => $item['seen']]);
132
133                         case Activity::DISLIKE:
134                                 return new \Friendica\Object\Notification\Notification([
135                                         'label' => 'dislike',
136                                         'link'  => $this->baseUrl->get(true) . '/display/' . $item['parent-guid'],
137                                         'image' => $item['author-avatar'],
138                                         'url'   => $item['author-link'],
139                                         'text'  => $this->l10n->t("%s disliked %s's post", $item['author-name'], $item['parent-author-name']),
140                                         'when'  => $item['when'],
141                                         'ago'   => $item['ago'],
142                                         'seen'  => $item['seen']]);
143
144                         case Activity::ATTEND:
145                                 return new \Friendica\Object\Notification\Notification([
146                                         'label' => 'attend',
147                                         'link'  => $this->baseUrl->get(true) . '/display/' . $item['parent-guid'],
148                                         'image' => $item['author-avatar'],
149                                         'url'   => $item['author-link'],
150                                         'text'  => $this->l10n->t("%s is attending %s's event", $item['author-name'], $item['parent-author-name']),
151                                         'when'  => $item['when'],
152                                         'ago'   => $item['ago'],
153                                         'seen'  => $item['seen']]);
154
155                         case Activity::ATTENDNO:
156                                 return new \Friendica\Object\Notification\Notification([
157                                         'label' => 'attendno',
158                                         'link'  => $this->baseUrl->get(true) . '/display/' . $item['parent-guid'],
159                                         'image' => $item['author-avatar'],
160                                         'url'   => $item['author-link'],
161                                         'text'  => $this->l10n->t("%s is not attending %s's event", $item['author-name'], $item['parent-author-name']),
162                                         'when'  => $item['when'],
163                                         'ago'   => $item['ago'],
164                                         'seen'  => $item['seen']]);
165
166                         case Activity::ATTENDMAYBE:
167                                 return new \Friendica\Object\Notification\Notification([
168                                         'label' => 'attendmaybe',
169                                         'link'  => $this->baseUrl->get(true) . '/display/' . $item['parent-guid'],
170                                         'image' => $item['author-avatar'],
171                                         'url'   => $item['author-link'],
172                                         'text'  => $this->l10n->t("%s may attending %s's event", $item['author-name'], $item['parent-author-name']),
173                                         'when'  => $item['when'],
174                                         'ago'   => $item['ago'],
175                                         'seen'  => $item['seen']]);
176
177                         case Activity::FRIEND:
178                                 if (!isset($item['object'])) {
179                                         return new \Friendica\Object\Notification\Notification([
180                                                 'label' => 'friend',
181                                                 'link'  => $item['link'],
182                                                 'image' => $item['image'],
183                                                 'url'   => $item['url'],
184                                                 'text'  => $item['text'],
185                                                 'when'  => $item['when'],
186                                                 'ago'   => $item['ago'],
187                                                 'seen'  => $item['seen']]);
188                                 }
189
190                                 $xmlHead       = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
191                                 $obj           = XML::parseString($xmlHead . $item['object']);
192                                 $item['fname'] = $obj->title;
193
194                                 return new \Friendica\Object\Notification\Notification([
195                                         'label' => 'friend',
196                                         'link'  => $this->baseUrl->get(true) . '/display/' . $item['parent-guid'],
197                                         'image' => $item['author-avatar'],
198                                         'url'   => $item['author-link'],
199                                         'text'  => $this->l10n->t("%s is now friends with %s", $item['author-name'], $item['fname']),
200                                         'when'  => $item['when'],
201                                         'ago'   => $item['ago'],
202                                         'seen'  => $item['seen']]);
203
204                         default:
205                                 return new \Friendica\Object\Notification\Notification($item);
206                                 break;
207                 }
208         }
209
210         /**
211          * Get system notifications
212          *
213          * @param bool $seen          False => only include notifications into the query
214          *                            which aren't marked as "seen"
215          * @param int  $start         Start the query at this point
216          * @param int  $limit         Maximum number of query results
217          *
218          * @return \Friendica\Module\Notifications\Notification[]
219          */
220         public function getSystemList(bool $seen = false, int $start = 0, int $limit = BaseNotifications::DEFAULT_PAGE_LIMIT)
221         {
222                 $conditions = ['uid' => local_user()];
223
224                 if (!$seen) {
225                         $conditions['seen'] = false;
226                 }
227
228                 $params          = [];
229                 $params['order'] = ['date' => 'DESC'];
230                 $params['limit'] = [$start, $limit];
231
232                 $formattedNotifications = [];
233                 try {
234                         $notifications = $this->notification->select($conditions, $params);
235
236                         foreach ($notifications as $notification) {
237                                 $formattedNotifications[] = new \Friendica\Object\Notification\Notification([
238                                         'label' => 'notification',
239                                         'link'  => $this->baseUrl->get(true) . '/notification/' . $notification->id,
240                                         'image' => Contact::getAvatarUrlForUrl($notification->url, $notification->uid, Proxy::SIZE_MICRO),
241                                         'url'   => $notification->url,
242                                         'text'  => strip_tags(BBCode::convert($notification->msg)),
243                                         'when'  => DateTimeFormat::local($notification->date, 'r'),
244                                         'ago'   => Temporal::getRelativeDate($notification->date),
245                                         'seen'  => $notification->seen]);
246                         }
247                 } catch (Exception $e) {
248                         $this->logger->warning('Select failed.', ['conditions' => $conditions, 'exception' => $e]);
249                 }
250
251                 return $formattedNotifications;
252         }
253
254         /**
255          * Get network notifications
256          *
257          * @param bool $seen          False => only include notifications into the query
258          *                            which aren't marked as "seen"
259          * @param int  $start         Start the query at this point
260          * @param int  $limit         Maximum number of query results
261          *
262          * @return \Friendica\Object\Notification\Notification[]
263          */
264         public function getNetworkList(bool $seen = false, int $start = 0, int $limit = BaseNotifications::DEFAULT_PAGE_LIMIT)
265         {
266                 $conditions = ['wall' => false, 'uid' => local_user()];
267
268                 if (!$seen) {
269                         $conditions['unseen'] = true;
270                 }
271
272                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
273                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'gravity'];
274                 $params = ['order' => ['received' => true], 'limit' => [$start, $limit]];
275
276                 $formattedNotifications = [];
277
278                 try {
279                         $items = Post::selectForUser(local_user(), $fields, $conditions, $params);
280
281                         while ($item = $this->dba->fetch($items)) {
282                                 $formattedNotifications[] = $this->createFromItem($item);
283                         }
284                 } catch (Exception $e) {
285                         $this->logger->warning('Select failed.', ['conditions' => $conditions, 'exception' => $e]);
286                 }
287
288                 return $formattedNotifications;
289         }
290
291         /**
292          * Get personal notifications
293          *
294          * @param bool $seen          False => only include notifications into the query
295          *                            which aren't marked as "seen"
296          * @param int  $start         Start the query at this point
297          * @param int  $limit         Maximum number of query results
298          *
299          * @return \Friendica\Object\Notification\Notification[]
300          */
301         public function getPersonalList(bool $seen = false, int $start = 0, int $limit = BaseNotifications::DEFAULT_PAGE_LIMIT)
302         {
303                 $condition = ["NOT `wall` AND `uid` = ? AND `author-id` = ?", local_user(), public_contact()];
304
305                 if (!$seen) {
306                         $condition[0] .= " AND `unseen`";
307                 }
308
309                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
310                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'gravity'];
311                 $params = ['order' => ['received' => true], 'limit' => [$start, $limit]];
312
313                 $formattedNotifications = [];
314
315                 try {
316                         $items = Post::selectForUser(local_user(), $fields, $condition, $params);
317
318                         while ($item = $this->dba->fetch($items)) {
319                                 $formattedNotifications[] = $this->createFromItem($item);
320                         }
321                 } catch (Exception $e) {
322                         $this->logger->warning('Select failed.', ['conditions' => $condition, 'exception' => $e]);
323                 }
324
325                 return $formattedNotifications;
326         }
327
328         /**
329          * Get home notifications
330          *
331          * @param bool $seen          False => only include notifications into the query
332          *                            which aren't marked as "seen"
333          * @param int  $start         Start the query at this point
334          * @param int  $limit         Maximum number of query results
335          *
336          * @return \Friendica\Object\Notification\Notification[]
337          */
338         public function getHomeList(bool $seen = false, int $start = 0, int $limit = BaseNotifications::DEFAULT_PAGE_LIMIT)
339         {
340                 $condition = ['wall' => true, 'uid' => local_user()];
341
342                 if (!$seen) {
343                         $condition['unseen'] = true;
344                 }
345
346                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
347                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid', 'gravity'];
348                 $params = ['order' => ['received' => true], 'limit' => [$start, $limit]];
349
350                 $formattedNotifications = [];
351
352                 try {
353                         $items = Post::selectForUser(local_user(), $fields, $condition, $params);
354
355                         while ($item = $this->dba->fetch($items)) {
356                                 $item = $this->formatItem($item);
357
358                                 // Overwrite specific fields, not default item format
359                                 $item['label'] = 'comment';
360                                 $item['text']  = $this->l10n->t("%s commented on %s's post", $item['author-name'], $item['parent-author-name']);
361
362                                 $formattedNotifications[] = $this->createFromItem($item);
363                         }
364                 } catch (Exception $e) {
365                         $this->logger->warning('Select failed.', ['conditions' => $condition, 'exception' => $e]);
366                 }
367
368                 return $formattedNotifications;
369         }
370
371         /**
372          * @param int   $uid    The user id of the API call
373          * @param array $params Additional parameters
374          *
375          * @return ApiNotifications
376          *
377          * @throws Exception
378          */
379         public function getApiList(int $uid, array $params = ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => 50])
380         {
381                 $notifies = $this->notification->select(['uid' => $uid], $params);
382
383                 /** @var ApiNotification[] $notifications */
384                 $notifications = [];
385
386                 foreach ($notifies as $notify) {
387                         $notifications[] = new ApiNotification($notify);
388                 }
389
390                 return new ApiNotifications($notifications);
391         }
392 }