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