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