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