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