]> git.mxchange.org Git - friendica.git/blob - include/NotificationsManager.php
notifications.php: move more code to NotificationsManager
[friendica.git] / include / NotificationsManager.php
1 <?php
2 /**
3  * @file include/NotificationsManager.php
4  */
5 require_once('include/html2plain.php');
6 require_once("include/datetime.php");
7 require_once("include/bbcode.php");
8 require_once("include/dbm.php");
9
10 /**
11  * @brief Read and write notifications from/to database
12  */
13 class NotificationsManager {
14         private $a;
15
16         public function __construct() {
17                 $this->a = get_app();
18         }
19
20         /**
21          * @brief set some extra note properties
22          *
23          * @param array $notes array of note arrays from db
24          * @return array Copy of input array with added properties
25          * 
26          * Set some extra properties to note array from db:
27          *  - timestamp as int in default TZ
28          *  - date_rel : relative date string
29          *  - msg_html: message as html string
30          *  - msg_plain: message as plain text string
31          */
32         private function _set_extra($notes) {
33                 $rets = array();
34                 foreach($notes as $n) {
35                         $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
36                         $n['timestamp'] = strtotime($local_time);
37                         $n['date_rel'] = relative_date($n['date']);
38                                 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
39                                 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
40
41                         $rets[] = $n;
42                 }
43                 return $rets;
44         }
45
46
47         /**
48          * @brief get all notifications for local_user()
49          *
50          * @param array $filter optional Array "column name"=>value: filter query by columns values
51          * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
52          * @param string $limit optional Query limits
53          *
54          * @return array of results or false on errors
55          */
56         public function getAll($filter = array(), $order="-date", $limit="") {
57                 $filter_str = array();
58                 $filter_sql = "";
59                 foreach($filter as $column => $value) {
60                         $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
61                 }
62                 if (count($filter_str)>0) {
63                         $filter_sql = "AND ".implode(" AND ", $filter_str);
64                 }
65
66                 $aOrder = explode(" ", $order);
67                 $asOrder = array();
68                 foreach($aOrder as $o) {
69                         $dir = "asc";
70                         if ($o[0]==="-") {
71                                 $dir = "desc";
72                                 $o = substr($o,1);
73                         }
74                         if ($o[0]==="+") {
75                                 $dir = "asc";
76                                 $o = substr($o,1);
77                         }
78                         $asOrder[] = "$o $dir";
79                 }
80                 $order_sql = implode(", ", $asOrder);
81
82                 if ($limit!="") $limit = " LIMIT ".$limit;
83
84                         $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
85                                 intval(local_user())
86                         );
87                 if ($r!==false && count($r)>0) return $this->_set_extra($r);
88                 return false;
89         }
90
91         /**
92          * @brief get one note for local_user() by $id value
93          *
94          * @param int $id
95          * @return array note values or null if not found
96          */
97         public function getByID($id) {
98                 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
99                         intval($id),
100                         intval(local_user())
101                 );
102                 if($r!==false && count($r)>0) {
103                         return $this->_set_extra($r)[0];
104                 }
105                 return null;
106         }
107
108         /**
109          * @brief set seen state of $note of local_user()
110          *
111          * @param array $note
112          * @param bool $seen optional true or false, default true
113          * @return bool true on success, false on errors
114          */
115         public function setSeen($note, $seen = true) {
116                 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
117                         intval($seen),
118                         dbesc($note['link']),
119                         intval($note['parent']),
120                         dbesc($note['otype']),
121                         intval(local_user())
122                 );
123         }
124
125         /**
126          * @brief set seen state of all notifications of local_user()
127          *
128          * @param bool $seen optional true or false. default true
129          * @return bool true on success, false on error
130          */
131         public function setAllSeen($seen = true) {
132                 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
133                         intval($seen),
134                         intval(local_user())
135                 );
136         }
137
138         /**
139          * @brief List of pages for the Notifications TabBar
140          * 
141          * @param app $a The 
142          * @return array with with notifications TabBar data
143          */
144         public function getTabs() {
145                 $tabs = array(
146                         array(
147                                 'label' => t('System'),
148                                 'url'=>'notifications/system',
149                                 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
150                                 'id' => 'system-tab',
151                                 'accesskey' => 'y',
152                         ),
153                         array(
154                                 'label' => t('Network'),
155                                 'url'=>'notifications/network',
156                                 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
157                                 'id' => 'network-tab',
158                                 'accesskey' => 'w',
159                         ),
160                         array(
161                                 'label' => t('Personal'),
162                                 'url'=>'notifications/personal',
163                                 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
164                                 'id' => 'personal-tab',
165                                 'accesskey' => 'r',
166                         ),
167                         array(
168                                 'label' => t('Home'),
169                                 'url' => 'notifications/home',
170                                 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
171                                 'id' => 'home-tab',
172                                 'accesskey' => 'h',
173                         ),
174                         array(
175                                 'label' => t('Introductions'),
176                                 'url' => 'notifications/intros',
177                                 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
178                                 'id' => 'intro-tab',
179                                 'accesskey' => 'i',
180                         ),
181                 );
182
183                 return $tabs;
184         }
185
186         public function format($notifs, $ident = "") {
187
188                 $notif = array();
189                 $arr = array();
190
191                 if (dbm::is_result($notifs)) {
192
193                         foreach ($notifs as $it) {
194                                 if($it['unseen'])
195                                         $it['seen'] = ($it['unseen'] > 0 ? false : true);
196
197                                 switch ($ident) {
198                                         case 'system':
199                                                 $default_item_label = 'notify';
200                                                 $default_item_link = app::get_baseurl(true).'/notify/view/'. $it['id'];
201                                                 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
202                                                 $default_item_text = strip_tags(bbcode($it['msg']));
203                                                 $default_item_when = relative_date($it['date']);
204                                                 $default_tpl = $tpl_notify;
205                                                 break;
206
207                                         case 'home':
208                                                 $default_item_label = 'comment';
209                                                 $default_item_link = app::get_baseurl(true).'/display/'.$it['pguid'];
210                                                 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
211                                                 $default_item_text = sprintf( t("%s commented on %s's post"), $it['author-name'], $it['pname']);
212                                                 $default_item_when = relative_date($it['created']);
213                                                 $default_tpl = $tpl_item_comments;
214                                                 break;
215
216                                         default:
217                                                 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
218                                                 $default_item_link = app::get_baseurl(true).'/display/'.$it['pguid'];
219                                                 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
220                                                 $default_item_text = (($it['id'] == $it['parent'])
221                                                                         ? sprintf( t("%s created a new post"), $it['author-name'])
222                                                                         : sprintf( t("%s commented on %s's post"), $it['author-name'], $it['pname']));
223                                                 $default_item_when = relative_date($it['created']);
224                                                 $default_tpl = (($it['id'] == $it['parent']) ? $tpl_item_posts : $tpl_item_comments);
225
226                                 }
227
228                                 switch($it['verb']){
229                                         case ACTIVITY_LIKE:
230                                                 $notif = array(
231                                                         //'$item_link' => $a->get_baseurl(true).'/display/'.$a->user['nickname']."/".$it['parent'],
232                                                         'label' => 'like',
233                                                         'link' => app::get_baseurl(true).'/display/'.$it['pguid'],
234                                                         '$image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
235                                                         'text' => sprintf( t("%s liked %s's post"), $it['author-name'], $it['pname']),
236                                                         'when' => relative_date($it['created']),
237                                                         'seen' => $it['seen']
238                                                 );
239                                                 break;
240
241                                         case ACTIVITY_DISLIKE:
242                                                 $notif = array(
243                                                         //'$item_link' => $a->get_baseurl(true).'/display/'.$a->user['nickname']."/".$it['parent'],
244                                                         'label' => 'dislike',
245                                                         'link' => app::get_baseurl(true).'/display/'.$it['pguid'],
246                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
247                                                         'text' => sprintf( t("%s disliked %s's post"), $it['author-name'], $it['pname']),
248                                                         'when' => relative_date($it['created']),
249                                                         'seen' => $it['seen']
250                                                 );
251                                                 break;
252
253                                         case ACTIVITY_FRIEND:
254                                                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
255                                                 $obj = parse_xml_string($xmlhead.$it['object']);
256                                                 $it['fname'] = $obj->title;
257
258                                                 $notif = array(
259                                                         //'$item_link' => $a->get_baseurl(true).'/display/'.$a->user['nickname']."/".$it['parent'],
260                                                         'label' => 'friend',
261                                                         'link' => app::get_baseurl(true).'/display/'.$it['pguid'],
262                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
263                                                         'text' => sprintf( t("%s is now friends with %s"), $it['author-name'], $it['fname']),
264                                                         'when' => relative_date($it['created']),
265                                                         'seen' => $it['seen']
266                                                 );
267                                                 break;
268
269                                         default:
270                                                 $notif = array(
271                                                         //'$item_link' => $a->get_baseurl(true).'/display/'.$a->user['nickname']."/".$it['parent'],
272                                                         'label' => $default_item_label,
273                                                         'link' => $default_item_link,
274                                                         'image' => $default_item_image,
275                                                         'text' => $default_item_text,
276                                                         'when' => $default_item_when,
277                                                         'seen' => $it['seen']
278                                                 );
279                                 }
280
281                                 $arr[] = $notif;
282                         }
283                 }
284
285                 return $arr;
286
287         }
288
289         private function networkTotal($seen = 0) {
290                 if($seen === 0)
291                         $sql_seen = " AND `item`.`unseen` = 1 ";
292
293                 $r = q("SELECT COUNT(*) AS `total`
294                                 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
295                                 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
296                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
297                                 $sql_seen",
298                         intval(local_user())
299                 );
300
301                 if(dbm::is_result($r))
302                         return $r[0]['total'];
303
304                 return 0;
305         }
306
307         public function networkNotifs($seen = 0) {
308                 $ident = 'network';
309                 $total = $this->networkTotal($seen);
310
311                 if($seen === 0)
312                         $sql_seen = " AND `item`.`unseen` = 1 ";
313
314
315                 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
316                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
317                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
318                                 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
319                                 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
320                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
321                                 $sql_seen
322                                 ORDER BY `item`.`created` DESC",
323                         intval(local_user())
324                 );
325
326                 if(dbm::is_result($r)) {
327                         $notifs = $this->format($r, $ident);
328                         $arr = array (
329                                 'notifications' => $notifs,
330                                 'ident' => $ident,
331                                 'total' => $total,
332                         );
333
334                         return $arr;
335                 }
336         }
337
338         private function systemTotal($seen = 0) {
339                 if($seen === 0)
340                         $sql_seen = " AND `seen` = 0 ";
341
342                 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
343                         intval(local_user())
344                 );
345
346                 if(dbm::is_result($r))
347                         return $r[0]['total'];
348
349                 return 0;
350         }
351
352         public function systemNotifs($seen = 0) {
353                 $ident = 'system';
354                 $total = $this->systemTotal($seen);
355
356                 if($seen === 0)
357                         $sql_seen = " AND `seen` = 0 ";
358
359                 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $sql_seen ORDER BY `date` DESC",
360                         intval(local_user())
361                 );
362
363                 if(dbm::is_result($r)) {
364                         $notifs = $this->format($r, $ident);
365                         $arr = array (
366                                 'notifications' => $notifs,
367                                 'ident' => $ident,
368                                 'total' => $total,
369                         );
370
371                         return $arr;
372                 }
373         }
374
375         private function _personal_sql_extra() {
376                 $myurl = app::get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
377                 $myurl = substr($myurl,strpos($myurl,'://')+3);
378                 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
379                 $diasp_url = str_replace('/profile/','/u/',$myurl);
380                 $sql_extra .= sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
381                         dbesc($myurl . '$'),
382                         dbesc($myurl . '\\]'),
383                         dbesc($diasp_url . '\\]')
384                 );
385
386                 return $sql_extra;
387         }
388
389         private function personalTotal($seen = 0) {
390                 $sql_extra .= $this->_personal_sql_extra();
391
392                 if($seen === 0)
393                         $sql_seen = " AND `item`.`unseen` = 1 ";
394
395                 $r = q("SELECT COUNT(*) AS `total`
396                                 FROM `item` INNER JOIN `item` AS `pitem` ON  `pitem`.`id`=`item`.`parent`
397                                 WHERE `item`.`visible` = 1
398                                 $sql_extra
399                                 $sql_seen
400                                 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
401                         intval(local_user())
402                 );
403
404                 if(dbm::is_result($r))
405                         return $r[0]['total'];
406
407                 return 0;
408         }
409         public function personalNotifs($seen = 0) {
410                 $ident = 'personal';
411                 $total = 0;
412                 $sql_extra .= $this->_personal_sql_extra();
413
414                 if($seen === 0)
415                         $sql_seen = " AND `item`.`unseen` = 1 ";
416
417                 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
418                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`, 
419                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`, 
420                                 FROM `item` INNER JOIN `item` AS `pitem` ON  `pitem`.`id`=`item`.`parent`
421                                 WHERE `item`.`visible` = 1
422                                 $sql_extra
423                                 $sql_seen
424                                 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 
425                                 ORDER BY `item`.`created` DESC" ,
426                         intval(local_user())
427                 );
428
429                 if(dbm::is_result($r)) {
430                         $notifs = $this->format($r, $ident);
431                         $arr = array (
432                                 'notifications' => $notifs,
433                                 'ident' => $ident,
434                                 'total' => $total,
435                         );
436
437                         return $arr;
438                 }
439         }
440
441         private function homeTotal($seen = 0) {
442                 if($seen === 0)
443                         $sql_seen = " AND `item`.`unseen` = 1 ";
444
445                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
446                                 WHERE ``item`.`visible` = 1 AND
447                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
448                                 $sql_seen",
449                         intval(local_user())
450                 );
451
452                 if(dbm::is_result($r))
453                         return $r['total'];
454
455                 return 0;
456         }
457
458         public function homeNotifs($seen = 0) {
459                 $ident = 'home';
460                 $total = $this->homeTotal($seen);
461
462                 if($seen === 0)
463                         $sql_seen = " AND `item`.`unseen` = 1 ";
464
465                 $total = $this->homeTotal($seen);
466
467                 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
468                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` as `object`,
469                                 `pitem`.`author-name` as `pname`, `pitem`.`author-link` as `plink`, `pitem`.`guid` as `pguid`
470                                 FROM `item` INNER JOIN `item` as `pitem` ON `pitem`.`id`=`item`.`parent`
471                                 WHERE `item`.`visible` = 1 AND
472                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
473                                 $sql_seen
474                                 ORDER BY `item`.`created` DESC",
475                         intval(local_user())
476                 );
477
478                 if(dbm::is_result($r)) {
479                         $notifs = $this->format($r, $ident);
480                         $arr = array (
481                                 'notifications' => $notifs,
482                                 'ident' => $ident,
483                                 'total' => $total,
484                         );
485
486                         return $arr;
487                 }
488         }
489 }