]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Add events for filtering and logging new notices
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero 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 Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for notice
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28  * in the memcached cache. */
29
30 define('NOTICE_CACHE_WINDOW', 61);
31
32 class Notice extends Memcached_DataObject
33 {
34     ###START_AUTOCODE
35     /* the code below is auto generated do not remove the above tag */
36
37     public $__table = 'notice';                             // table name
38     public $id;                                 // int(4)    primary_key not_null
39     public $profile_id;                         // int(4)     not_null
40     public $uri;                             // varchar(255)  unique_key
41     public $content;                         // varchar(140)
42     public $rendered;                         // text()
43     public $url;                             // varchar(255)
44     public $created;                         // datetime()     not_null
45     public $modified;                         // timestamp()      not_null default_CURRENT_TIMESTAMP
46     public $reply_to;                         // int(4)
47     public $is_local;                         // tinyint(1)
48     public $source;                             // varchar(32)
49
50     /* Static get */
51     function staticGet($k,$v=null)
52     { return Memcached_DataObject::staticGet('Notice',$k,$v); }
53
54     /* the code above is auto generated do not remove the tag below */
55     ###END_AUTOCODE
56
57     function getProfile()
58     {
59         return Profile::staticGet('id', $this->profile_id);
60     }
61
62     function delete()
63     {
64         $this->blowCaches(true);
65         $this->blowFavesCache(true);
66         $this->blowSubsCache(true);
67
68         $this->query('BEGIN');
69         $related = array('Reply',
70                          'Fave',
71                          'Notice_tag',
72                          'Group_inbox',
73                          'Queue_item');
74         if (common_config('inboxes', 'enabled')) {
75             $related[] = 'Notice_inbox';
76         }
77         foreach ($related as $cls) {
78             $inst = new $cls();
79             $inst->notice_id = $this->id;
80             $inst->delete();
81         }
82         $result = parent::delete();
83         $this->query('COMMIT');
84     }
85
86     function saveTags()
87     {
88         /* extract all #hastags */
89         $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
90         if (!$count) {
91             return true;
92         }
93
94         /* Add them to the database */
95         foreach(array_unique($match[1]) as $hashtag) {
96             /* elide characters we don't want in the tag */
97             $hashtag = common_canonical_tag($hashtag);
98
99             $tag = DB_DataObject::factory('Notice_tag');
100             $tag->notice_id = $this->id;
101             $tag->tag = $hashtag;
102             $tag->created = $this->created;
103             $id = $tag->insert();
104             if (!$id) {
105                 $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
106                 common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
107                 common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
108                 return;
109             }
110         }
111         return true;
112     }
113
114     static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
115
116         $profile = Profile::staticGet($profile_id);
117
118         if (!$profile) {
119             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
120             return _('Problem saving notice. Unknown user.');
121         }
122
123         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
124             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
125             return _('Too many notices too fast; take a breather and post again in a few minutes.');
126         }
127
128         $banned = common_config('profile', 'banned');
129
130         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
131             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
132             return _('You are banned from posting notices on this site.');
133         }
134
135         $notice = new Notice();
136         $notice->profile_id = $profile_id;
137
138         $blacklist = common_config('public', 'blacklist');
139
140         # Blacklisted are non-false, but not 1, either
141
142         if ($blacklist && in_array($profile_id, $blacklist)) {
143             $notice->is_local = -1;
144         } else {
145             $notice->is_local = $is_local;
146         }
147
148                 $notice->query('BEGIN');
149
150         $notice->reply_to = $reply_to;
151         $notice->created = common_sql_now();
152         $notice->content = common_shorten_links($content);
153         $notice->rendered = common_render_content($notice->content, $notice);
154         $notice->source = $source;
155         $notice->uri = $uri;
156
157         if (Event::handle('StartNoticeSave', array(&$notice))) {
158
159             $id = $notice->insert();
160
161             if (!$id) {
162                 common_log_db_error($notice, 'INSERT', __FILE__);
163                 return _('Problem saving notice.');
164             }
165
166             # Update the URI after the notice is in the database
167             if (!$uri) {
168                 $orig = clone($notice);
169                 $notice->uri = common_notice_uri($notice);
170
171                 if (!$notice->update($orig)) {
172                     common_log_db_error($notice, 'UPDATE', __FILE__);
173                     return _('Problem saving notice.');
174                 }
175             }
176
177             # XXX: do we need to change this for remote users?
178
179             $notice->saveReplies();
180             $notice->saveTags();
181             $notice->saveGroups();
182
183             $notice->addToInboxes();
184             $notice->query('COMMIT');
185
186             Event::handle('EndNoticeSave', array($notice));
187         }
188
189         # Clear the cache for subscribed users, so they'll update at next request
190         # XXX: someone clever could prepend instead of clearing the cache
191
192         if (common_config('memcached', 'enabled')) {
193             $notice->blowCaches();
194         }
195
196         return $notice;
197     }
198
199     static function checkEditThrottle($profile_id) {
200         $profile = Profile::staticGet($profile_id);
201         if (!$profile) {
202             return false;
203         }
204         # Get the Nth notice
205         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
206         if ($notice && $notice->fetch()) {
207             # If the Nth notice was posted less than timespan seconds ago
208             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
209                 # Then we throttle
210                 return false;
211             }
212         }
213         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
214         return true;
215     }
216
217     function blowCaches($blowLast=false)
218     {
219         $this->blowSubsCache($blowLast);
220         $this->blowNoticeCache($blowLast);
221         $this->blowRepliesCache($blowLast);
222         $this->blowPublicCache($blowLast);
223         $this->blowTagCache($blowLast);
224         $this->blowGroupCache($blowLast);
225     }
226
227     function blowGroupCache($blowLast=false)
228     {
229         $cache = common_memcache();
230         if ($cache) {
231             $group_inbox = new Group_inbox();
232             $group_inbox->notice_id = $this->id;
233             if ($group_inbox->find()) {
234                 while ($group_inbox->fetch()) {
235                     $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
236                     if ($blowLast) {
237                         $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
238                     }
239                     $member = new Group_member();
240                     $member->group_id = $group_inbox->group_id;
241                     if ($member->find()) {
242                         while ($member->fetch()) {
243                             $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
244                             if ($blowLast) {
245                                 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
246                             }
247                         }
248                     }
249                 }
250             }
251             $group_inbox->free();
252             unset($group_inbox);
253         }
254     }
255
256     function blowTagCache($blowLast=false)
257     {
258         $cache = common_memcache();
259         if ($cache) {
260             $tag = new Notice_tag();
261             $tag->notice_id = $this->id;
262             if ($tag->find()) {
263                 while ($tag->fetch()) {
264                     $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
265                     if ($blowLast) {
266                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
267                     }
268                 }
269             }
270             $tag->free();
271             unset($tag);
272         }
273     }
274
275     function blowSubsCache($blowLast=false)
276     {
277         $cache = common_memcache();
278         if ($cache) {
279             $user = new User();
280
281             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
282             $user->query('SELECT id ' .
283
284                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
285                          'WHERE subscription.subscribed = ' . $this->profile_id);
286
287             while ($user->fetch()) {
288                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
289                 if ($blowLast) {
290                     $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
291                 }
292             }
293             $user->free();
294             unset($user);
295         }
296     }
297
298     function blowNoticeCache($blowLast=false)
299     {
300         if ($this->is_local) {
301             $cache = common_memcache();
302             if ($cache) {
303                 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
304                 if ($blowLast) {
305                     $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
306                 }
307             }
308         }
309     }
310
311     function blowRepliesCache($blowLast=false)
312     {
313         $cache = common_memcache();
314         if ($cache) {
315             $reply = new Reply();
316             $reply->notice_id = $this->id;
317             if ($reply->find()) {
318                 while ($reply->fetch()) {
319                     $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
320                     if ($blowLast) {
321                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
322                     }
323                 }
324             }
325             $reply->free();
326             unset($reply);
327         }
328     }
329
330     function blowPublicCache($blowLast=false)
331     {
332         if ($this->is_local == 1) {
333             $cache = common_memcache();
334             if ($cache) {
335                 $cache->delete(common_cache_key('public'));
336                 if ($blowLast) {
337                     $cache->delete(common_cache_key('public').';last');
338                 }
339             }
340         }
341     }
342
343     function blowFavesCache($blowLast=false)
344     {
345         $cache = common_memcache();
346         if ($cache) {
347             $fave = new Fave();
348             $fave->notice_id = $this->id;
349             if ($fave->find()) {
350                 while ($fave->fetch()) {
351                     $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
352                     if ($blowLast) {
353                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
354                     }
355                 }
356             }
357             $fave->free();
358             unset($fave);
359         }
360     }
361
362     # XXX: too many args; we need to move to named params or even a separate
363     # class for notice streams
364
365     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
366
367         if (common_config('memcached', 'enabled')) {
368
369             # Skip the cache if this is a since, since_id or before_id qry
370             if ($since_id > 0 || $before_id > 0 || $since) {
371                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
372             } else {
373                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
374             }
375         }
376
377         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
378     }
379
380     static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
381
382         $needAnd = false;
383         $needWhere = true;
384
385         if (preg_match('/\bWHERE\b/i', $qry)) {
386             $needWhere = false;
387             $needAnd = true;
388         }
389
390         if ($since_id > 0) {
391
392             if ($needWhere) {
393                 $qry .= ' WHERE ';
394                 $needWhere = false;
395             } else {
396                 $qry .= ' AND ';
397             }
398
399             $qry .= ' notice.id > ' . $since_id;
400         }
401
402         if ($before_id > 0) {
403
404             if ($needWhere) {
405                 $qry .= ' WHERE ';
406                 $needWhere = false;
407             } else {
408                 $qry .= ' AND ';
409             }
410
411             $qry .= ' notice.id < ' . $before_id;
412         }
413
414         if ($since) {
415
416             if ($needWhere) {
417                 $qry .= ' WHERE ';
418                 $needWhere = false;
419             } else {
420                 $qry .= ' AND ';
421             }
422
423             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
424         }
425
426         # Allow ORDER override
427
428         if ($order) {
429             $qry .= $order;
430         } else {
431             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
432         }
433
434         if (common_config('db','type') == 'pgsql') {
435             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
436         } else {
437             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
438         }
439
440         $notice = new Notice();
441
442         $notice->query($qry);
443
444         return $notice;
445     }
446
447     # XXX: this is pretty long and should probably be broken up into
448     # some helper functions
449
450     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
451
452         # If outside our cache window, just go to the DB
453
454         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
455             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
456         }
457
458         # Get the cache; if we can't, just go to the DB
459
460         $cache = common_memcache();
461
462         if (!$cache) {
463             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
464         }
465
466         # Get the notices out of the cache
467
468         $notices = $cache->get(common_cache_key($cachekey));
469
470         # On a cache hit, return a DB-object-like wrapper
471
472         if ($notices !== false) {
473             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
474             return $wrapper;
475         }
476
477         # If the cache was invalidated because of new data being
478         # added, we can try and just get the new stuff. We keep an additional
479         # copy of the data at the key + ';last'
480
481         # No cache hit. Try to get the *last* cached version
482
483         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
484
485         if ($last_notices) {
486
487             # Reverse-chron order, so last ID is last.
488
489             $last_id = $last_notices[0]->id;
490
491             # XXX: this assumes monotonically increasing IDs; a fair
492             # bet with our DB.
493
494             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
495                                                   $last_id, null, $order, null);
496
497             if ($new_notice) {
498                 $new_notices = array();
499                 while ($new_notice->fetch()) {
500                     $new_notices[] = clone($new_notice);
501                 }
502                 $new_notice->free();
503                 $notices = array_slice(array_merge($new_notices, $last_notices),
504                                        0, NOTICE_CACHE_WINDOW);
505
506                 # Store the array in the cache for next time
507
508                 $result = $cache->set(common_cache_key($cachekey), $notices);
509                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
510
511                 # return a wrapper of the array for use now
512
513                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
514             }
515         }
516
517         # Otherwise, get the full cache window out of the DB
518
519         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
520
521         # If there are no hits, just return the value
522
523         if (!$notice) {
524             return $notice;
525         }
526
527         # Pack results into an array
528
529         $notices = array();
530
531         while ($notice->fetch()) {
532             $notices[] = clone($notice);
533         }
534
535         $notice->free();
536
537         # Store the array in the cache for next time
538
539         $result = $cache->set(common_cache_key($cachekey), $notices);
540         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
541
542         # return a wrapper of the array for use now
543
544         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
545
546         return $wrapper;
547     }
548
549     function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
550     {
551
552         $parts = array();
553
554         $qry = 'SELECT * FROM notice ';
555
556         if (common_config('public', 'localonly')) {
557             $parts[] = 'is_local = 1';
558         } else {
559             # -1 == blacklisted
560             $parts[] = 'is_local != -1';
561         }
562
563         if ($parts) {
564             $qry .= ' WHERE ' . implode(' AND ', $parts);
565         }
566
567         return Notice::getStream($qry,
568                                  'public',
569                                  $offset, $limit, $since_id, $before_id, null, $since);
570     }
571
572     function addToInboxes()
573     {
574         $enabled = common_config('inboxes', 'enabled');
575
576         if ($enabled === true || $enabled === 'transitional') {
577             $inbox = new Notice_inbox();
578             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
579             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
580               "SELECT $UT.id, " . $this->id . ', "' . $this->created . '" ' .
581               "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
582               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
583               'AND NOT EXISTS (SELECT user_id, notice_id ' .
584               'FROM notice_inbox ' .
585               "WHERE user_id = $UT.id " .
586               'AND notice_id = ' . $this->id . ' )';
587             if ($enabled === 'transitional') {
588                 $qry .= " AND $UT.inboxed = 1";
589             }
590             $inbox->query($qry);
591         }
592         return;
593     }
594
595     function saveGroups()
596     {
597         $enabled = common_config('inboxes', 'enabled');
598         if ($enabled !== true && $enabled !== 'transitional') {
599             return;
600         }
601
602         /* extract all !group */
603         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
604                                 strtolower($this->content),
605                                 $match);
606         if (!$count) {
607             return true;
608         }
609
610         $profile = $this->getProfile();
611
612         /* Add them to the database */
613
614         foreach (array_unique($match[1]) as $nickname) {
615             /* XXX: remote groups. */
616             $group = User_group::staticGet('nickname', $nickname);
617
618             if (!$group) {
619                 continue;
620             }
621
622             if ($profile->isMember($group)) {
623
624                 $gi = new Group_inbox();
625
626                 $gi->group_id  = $group->id;
627                 $gi->notice_id = $this->id;
628                 $gi->created   = common_sql_now();
629
630                 $result = $gi->insert();
631
632                 if (!$result) {
633                     common_log_db_error($gi, 'INSERT', __FILE__);
634                 }
635
636                 // FIXME: do this in an offline daemon
637
638                 $inbox = new Notice_inbox();
639                 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
640                 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
641                   "SELECT $UT.id, " . $this->id . ', "' . $this->created . '", 2 ' .
642                   "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
643                   'WHERE group_member.group_id = ' . $group->id . ' ' .
644                   'AND NOT EXISTS (SELECT user_id, notice_id ' .
645                   'FROM notice_inbox ' .
646                   "WHERE user_id = $UT.id " .
647                   'AND notice_id = ' . $this->id . ' )';
648                 if ($enabled === 'transitional') {
649                     $qry .= " AND $UT.inboxed = 1";
650                 }
651                 $result = $inbox->query($qry);
652             }
653         }
654     }
655
656     function saveReplies()
657     {
658         // Alternative reply format
659         $tname = false;
660         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
661             $tname = $match[1];
662         }
663         // extract all @messages
664         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
665
666         $names = array();
667
668         if ($cnt || $tname) {
669             // XXX: is there another way to make an array copy?
670             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
671         }
672
673         $sender = Profile::staticGet($this->profile_id);
674
675         $replied = array();
676
677         // store replied only for first @ (what user/notice what the reply directed,
678         // we assume first @ is it)
679
680         for ($i=0; $i<count($names); $i++) {
681             $nickname = $names[$i];
682             $recipient = common_relative_profile($sender, $nickname, $this->created);
683             if (!$recipient) {
684                 continue;
685             }
686             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
687                 $reply_for = $recipient;
688                 $recipient_notice = $reply_for->getCurrentNotice();
689                 if ($recipient_notice) {
690                     $orig = clone($this);
691                     $this->reply_to = $recipient_notice->id;
692                     $this->update($orig);
693                 }
694             }
695             // Don't save replies from blocked profile to local user
696             $recipient_user = User::staticGet('id', $recipient->id);
697             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
698                 continue;
699             }
700             $reply = new Reply();
701             $reply->notice_id = $this->id;
702             $reply->profile_id = $recipient->id;
703             $id = $reply->insert();
704             if (!$id) {
705                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
706                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
707                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
708                 return;
709             } else {
710                 $replied[$recipient->id] = 1;
711             }
712         }
713
714         // Hash format replies, too
715         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
716         if ($cnt) {
717             foreach ($match[1] as $tag) {
718                 $tagged = Profile_tag::getTagged($sender->id, $tag);
719                 foreach ($tagged as $t) {
720                     if (!$replied[$t->id]) {
721                         // Don't save replies from blocked profile to local user
722                         $t_user = User::staticGet('id', $t->id);
723                         if ($t_user && $t_user->hasBlocked($sender)) {
724                             continue;
725                         }
726                         $reply = new Reply();
727                         $reply->notice_id = $this->id;
728                         $reply->profile_id = $t->id;
729                         $id = $reply->insert();
730                         if (!$id) {
731                             common_log_db_error($reply, 'INSERT', __FILE__);
732                             return;
733                         }
734                     }
735                 }
736             }
737         }
738     }
739 }