]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
bfd22e6f0b5c39cd75e8466ee4a9b7293d29036d
[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         common_save_replies($notice);
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                 }
215             }
216             $group_inbox->free();
217             unset($group_inbox);
218         }
219     }
220
221     function blowTagCache($blowLast=false)
222     {
223         $cache = common_memcache();
224         if ($cache) {
225             $tag = new Notice_tag();
226             $tag->notice_id = $this->id;
227             if ($tag->find()) {
228                 while ($tag->fetch()) {
229                     $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
230                     if ($blowLast) {
231                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
232                     }
233                 }
234             }
235             $tag->free();
236             unset($tag);
237         }
238     }
239
240     function blowSubsCache($blowLast=false)
241     {
242         $cache = common_memcache();
243         if ($cache) {
244             $user = new User();
245
246             $user->query('SELECT id ' .
247                          'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
248                          'WHERE subscription.subscribed = ' . $this->profile_id);
249
250             while ($user->fetch()) {
251                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
252                 if ($blowLast) {
253                     $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
254                 }
255             }
256             $user->free();
257             unset($user);
258         }
259     }
260
261     function blowNoticeCache($blowLast=false)
262     {
263         if ($this->is_local) {
264             $cache = common_memcache();
265             if ($cache) {
266                 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
267                 if ($blowLast) {
268                     $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
269                 }
270             }
271         }
272     }
273
274     function blowRepliesCache($blowLast=false)
275     {
276         $cache = common_memcache();
277         if ($cache) {
278             $reply = new Reply();
279             $reply->notice_id = $this->id;
280             if ($reply->find()) {
281                 while ($reply->fetch()) {
282                     $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
283                     if ($blowLast) {
284                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
285                     }
286                 }
287             }
288             $reply->free();
289             unset($reply);
290         }
291     }
292
293     function blowPublicCache($blowLast=false)
294     {
295         if ($this->is_local == 1) {
296             $cache = common_memcache();
297             if ($cache) {
298                 $cache->delete(common_cache_key('public'));
299                 if ($blowLast) {
300                     $cache->delete(common_cache_key('public').';last');
301                 }
302             }
303         }
304     }
305
306     function blowFavesCache($blowLast=false)
307     {
308         $cache = common_memcache();
309         if ($cache) {
310             $fave = new Fave();
311             $fave->notice_id = $this->id;
312             if ($fave->find()) {
313                 while ($fave->fetch()) {
314                     $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
315                     if ($blowLast) {
316                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
317                     }
318                 }
319             }
320             $fave->free();
321             unset($fave);
322         }
323     }
324
325     # XXX: too many args; we need to move to named params or even a separate
326     # class for notice streams
327
328     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
329
330         if (common_config('memcached', 'enabled')) {
331
332             # Skip the cache if this is a since, since_id or before_id qry
333             if ($since_id > 0 || $before_id > 0 || $since) {
334                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
335             } else {
336                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
337             }
338         }
339
340         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
341     }
342
343     static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
344
345         $needAnd = false;
346         $needWhere = true;
347
348         if (preg_match('/\bWHERE\b/i', $qry)) {
349             $needWhere = false;
350             $needAnd = true;
351         }
352
353         if ($since_id > 0) {
354
355             if ($needWhere) {
356                 $qry .= ' WHERE ';
357                 $needWhere = false;
358             } else {
359                 $qry .= ' AND ';
360             }
361
362             $qry .= ' notice.id > ' . $since_id;
363         }
364
365         if ($before_id > 0) {
366
367             if ($needWhere) {
368                 $qry .= ' WHERE ';
369                 $needWhere = false;
370             } else {
371                 $qry .= ' AND ';
372             }
373
374             $qry .= ' notice.id < ' . $before_id;
375         }
376
377         if ($since) {
378
379             if ($needWhere) {
380                 $qry .= ' WHERE ';
381                 $needWhere = false;
382             } else {
383                 $qry .= ' AND ';
384             }
385
386             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
387         }
388
389         # Allow ORDER override
390
391         if ($order) {
392             $qry .= $order;
393         } else {
394             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
395         }
396
397         if (common_config('db','type') == 'pgsql') {
398             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
399         } else {
400             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
401         }
402
403         $notice = new Notice();
404
405         $notice->query($qry);
406
407         return $notice;
408     }
409
410     # XXX: this is pretty long and should probably be broken up into
411     # some helper functions
412
413     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
414
415         # If outside our cache window, just go to the DB
416
417         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
418             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
419         }
420
421         # Get the cache; if we can't, just go to the DB
422
423         $cache = common_memcache();
424
425         if (!$cache) {
426             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
427         }
428
429         # Get the notices out of the cache
430
431         $notices = $cache->get(common_cache_key($cachekey));
432
433         # On a cache hit, return a DB-object-like wrapper
434
435         if ($notices !== false) {
436             $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
437             return $wrapper;
438         }
439
440         # If the cache was invalidated because of new data being
441         # added, we can try and just get the new stuff. We keep an additional
442         # copy of the data at the key + ';last'
443
444         # No cache hit. Try to get the *last* cached version
445
446         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
447
448         if ($last_notices) {
449
450             # Reverse-chron order, so last ID is last.
451
452             $last_id = $last_notices[0]->id;
453
454             # XXX: this assumes monotonically increasing IDs; a fair
455             # bet with our DB.
456
457             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
458                                                   $last_id, null, $order, null);
459
460             if ($new_notice) {
461                 $new_notices = array();
462                 while ($new_notice->fetch()) {
463                     $new_notices[] = clone($new_notice);
464                 }
465                 $new_notice->free();
466                 $notices = array_slice(array_merge($new_notices, $last_notices),
467                                        0, NOTICE_CACHE_WINDOW);
468
469                 # Store the array in the cache for next time
470
471                 $result = $cache->set(common_cache_key($cachekey), $notices);
472                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
473
474                 # return a wrapper of the array for use now
475
476                 return new NoticeWrapper(array_slice($notices, $offset, $limit));
477             }
478         }
479
480         # Otherwise, get the full cache window out of the DB
481
482         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
483
484         # If there are no hits, just return the value
485
486         if (!$notice) {
487             return $notice;
488         }
489
490         # Pack results into an array
491
492         $notices = array();
493
494         while ($notice->fetch()) {
495             $notices[] = clone($notice);
496         }
497
498         $notice->free();
499
500         # Store the array in the cache for next time
501
502         $result = $cache->set(common_cache_key($cachekey), $notices);
503         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
504
505         # return a wrapper of the array for use now
506
507         $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
508
509         return $wrapper;
510     }
511
512     function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
513     {
514
515         $parts = array();
516
517         $qry = 'SELECT * FROM notice ';
518
519         if (common_config('public', 'localonly')) {
520             $parts[] = 'is_local = 1';
521         } else {
522             # -1 == blacklisted
523             $parts[] = 'is_local != -1';
524         }
525
526         if ($parts) {
527             $qry .= ' WHERE ' . implode(' AND ', $parts);
528         }
529
530         return Notice::getStream($qry,
531                                  'public',
532                                  $offset, $limit, $since_id, $before_id, null, $since);
533     }
534
535     function addToInboxes()
536     {
537         $enabled = common_config('inboxes', 'enabled');
538
539         if ($enabled === true || $enabled === 'transitional') {
540             $inbox = new Notice_inbox();
541             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
542               'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
543               'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
544               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
545               'AND NOT EXISTS (SELECT user_id, notice_id ' .
546               'FROM notice_inbox ' .
547               'WHERE user_id = user.id ' .
548               'AND notice_id = ' . $this->id . ' )';
549             if ($enabled === 'transitional') {
550                 $qry .= ' AND user.inboxed = 1';
551             }
552             $inbox->query($qry);
553         }
554         return;
555     }
556
557     # Delete from inboxes if we're deleted.
558
559     function blowInboxes()
560     {
561
562         $enabled = common_config('inboxes', 'enabled');
563
564         if ($enabled === true || $enabled === 'transitional') {
565             $inbox = new Notice_inbox();
566             $inbox->notice_id = $this->id;
567             $inbox->delete();
568         }
569
570         return;
571     }
572
573     function saveGroups()
574     {
575         $enabled = common_config('inboxes', 'enabled');
576         if ($enabled !== true && $enabled !== 'transitional') {
577             return;
578         }
579
580         /* extract all !group */
581         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
582                                 strtolower($this->content),
583                                 $match);
584         if (!$count) {
585             return true;
586         }
587
588         $profile = $this->getProfile();
589
590         /* Add them to the database */
591
592         foreach (array_unique($match[1]) as $nickname) {
593             /* XXX: remote groups. */
594             $group = User_group::staticGet('nickname', $nickname);
595
596             if (!$group) {
597                 continue;
598             }
599
600             if ($profile->isMember($group)) {
601
602                 $gi = new Group_inbox();
603
604                 $gi->group_id  = $group->id;
605                 $gi->notice_id = $this->id;
606                 $gi->created   = common_sql_now();
607
608                 $result = $gi->insert();
609
610                 if (!$result) {
611                     common_log_db_error($gi, 'INSERT', __FILE__);
612                 }
613
614                 // FIXME: do this in an offline daemon
615
616                 $inbox = new Notice_inbox();
617                 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
618                   'SELECT user.id, ' . $this->id . ', "' . $this->created . '", 2 ' .
619                   'FROM user JOIN group_member ON user.id = group_member.profile_id ' .
620                   'WHERE group_member.group_id = ' . $group->id . ' ' .
621                   'AND NOT EXISTS (SELECT user_id, notice_id ' .
622                   'FROM notice_inbox ' .
623                   'WHERE user_id = user.id ' .
624                   'AND notice_id = ' . $this->id . ' )';
625                 if ($enabled === 'transitional') {
626                     $qry .= ' AND user.inboxed = 1';
627                 }
628                 $result = $inbox->query($qry);
629             }
630         }
631     }
632 }