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