]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
minilist for groups
[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
162         # Clear the cache for subscribed users, so they'll update at next request
163         # XXX: someone clever could prepend instead of clearing the cache
164
165         if (common_config('memcached', 'enabled')) {
166             $notice->blowCaches();
167         }
168
169         $notice->addToInboxes();
170         return $notice;
171     }
172
173     static function checkEditThrottle($profile_id) {
174         $profile = Profile::staticGet($profile_id);
175         if (!$profile) {
176             return false;
177         }
178         # Get the Nth notice
179         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
180         if ($notice && $notice->fetch()) {
181             # If the Nth notice was posted less than timespan seconds ago
182             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
183                 # Then we throttle
184                 return false;
185             }
186         }
187         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
188         return true;
189     }
190
191     function blowCaches($blowLast=false)
192     {
193         $this->blowSubsCache($blowLast);
194         $this->blowNoticeCache($blowLast);
195         $this->blowRepliesCache($blowLast);
196         $this->blowPublicCache($blowLast);
197         $this->blowTagCache($blowLast);
198     }
199
200     function blowTagCache($blowLast=false)
201     {
202         $cache = common_memcache();
203         if ($cache) {
204             $tag = new Notice_tag();
205             $tag->notice_id = $this->id;
206             if ($tag->find()) {
207                 while ($tag->fetch()) {
208                     $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
209                     if ($blowLast) {
210                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
211                     }
212                 }
213             }
214             $tag->free();
215             unset($tag);
216         }
217     }
218
219     function blowSubsCache($blowLast=false)
220     {
221         $cache = common_memcache();
222         if ($cache) {
223             $user = new User();
224
225             $user->query('SELECT id ' .
226                          'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
227                          'WHERE subscription.subscribed = ' . $this->profile_id);
228
229             while ($user->fetch()) {
230                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
231                 if ($blowLast) {
232                     $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
233                 }
234             }
235             $user->free();
236             unset($user);
237         }
238     }
239
240     function blowNoticeCache($blowLast=false)
241     {
242         if ($this->is_local) {
243             $cache = common_memcache();
244             if ($cache) {
245                 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
246                 if ($blowLast) {
247                     $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
248                 }
249             }
250         }
251     }
252
253     function blowRepliesCache($blowLast=false)
254     {
255         $cache = common_memcache();
256         if ($cache) {
257             $reply = new Reply();
258             $reply->notice_id = $this->id;
259             if ($reply->find()) {
260                 while ($reply->fetch()) {
261                     $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
262                     if ($blowLast) {
263                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
264                     }
265                 }
266             }
267             $reply->free();
268             unset($reply);
269         }
270     }
271
272     function blowPublicCache($blowLast=false)
273     {
274         if ($this->is_local == 1) {
275             $cache = common_memcache();
276             if ($cache) {
277                 $cache->delete(common_cache_key('public'));
278                 if ($blowLast) {
279                     $cache->delete(common_cache_key('public').';last');
280                 }
281             }
282         }
283     }
284
285     function blowFavesCache($blowLast=false)
286     {
287         $cache = common_memcache();
288         if ($cache) {
289             $fave = new Fave();
290             $fave->notice_id = $this->id;
291             if ($fave->find()) {
292                 while ($fave->fetch()) {
293                     $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
294                     if ($blowLast) {
295                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
296                     }
297                 }
298             }
299             $fave->free();
300             unset($fave);
301         }
302     }
303
304     # XXX: too many args; we need to move to named params or even a separate
305     # class for notice streams
306
307     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
308
309         if (common_config('memcached', 'enabled')) {
310
311             # Skip the cache if this is a since, since_id or before_id qry
312             if ($since_id > 0 || $before_id > 0 || $since) {
313                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
314             } else {
315                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
316             }
317         }
318
319         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
320     }
321
322     static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
323
324         $needAnd = false;
325         $needWhere = true;
326
327         if (preg_match('/\bWHERE\b/i', $qry)) {
328             $needWhere = false;
329             $needAnd = true;
330         }
331
332         if ($since_id > 0) {
333
334             if ($needWhere) {
335                 $qry .= ' WHERE ';
336                 $needWhere = false;
337             } else {
338                 $qry .= ' AND ';
339             }
340
341             $qry .= ' notice.id > ' . $since_id;
342         }
343
344         if ($before_id > 0) {
345
346             if ($needWhere) {
347                 $qry .= ' WHERE ';
348                 $needWhere = false;
349             } else {
350                 $qry .= ' AND ';
351             }
352
353             $qry .= ' notice.id < ' . $before_id;
354         }
355
356         if ($since) {
357
358             if ($needWhere) {
359                 $qry .= ' WHERE ';
360                 $needWhere = false;
361             } else {
362                 $qry .= ' AND ';
363             }
364
365             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
366         }
367
368         # Allow ORDER override
369
370         if ($order) {
371             $qry .= $order;
372         } else {
373             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
374         }
375
376         if (common_config('db','type') == 'pgsql') {
377             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
378         } else {
379             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
380         }
381
382         $notice = new Notice();
383
384         $notice->query($qry);
385
386         return $notice;
387     }
388
389     # XXX: this is pretty long and should probably be broken up into
390     # some helper functions
391
392     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
393
394         # If outside our cache window, just go to the DB
395
396         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
397             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
398         }
399
400         # Get the cache; if we can't, just go to the DB
401
402         $cache = common_memcache();
403
404         if (!$cache) {
405             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
406         }
407
408         # Get the notices out of the cache
409
410         $notices = $cache->get(common_cache_key($cachekey));
411
412         # On a cache hit, return a DB-object-like wrapper
413
414         if ($notices !== false) {
415             $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
416             return $wrapper;
417         }
418
419         # If the cache was invalidated because of new data being
420         # added, we can try and just get the new stuff. We keep an additional
421         # copy of the data at the key + ';last'
422
423         # No cache hit. Try to get the *last* cached version
424
425         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
426
427         if ($last_notices) {
428
429             # Reverse-chron order, so last ID is last.
430
431             $last_id = $last_notices[0]->id;
432
433             # XXX: this assumes monotonically increasing IDs; a fair
434             # bet with our DB.
435
436             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
437                                                   $last_id, null, $order, null);
438
439             if ($new_notice) {
440                 $new_notices = array();
441                 while ($new_notice->fetch()) {
442                     $new_notices[] = clone($new_notice);
443                 }
444                 $new_notice->free();
445                 $notices = array_slice(array_merge($new_notices, $last_notices),
446                                        0, NOTICE_CACHE_WINDOW);
447
448                 # Store the array in the cache for next time
449
450                 $result = $cache->set(common_cache_key($cachekey), $notices);
451                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
452
453                 # return a wrapper of the array for use now
454
455                 return new NoticeWrapper(array_slice($notices, $offset, $limit));
456             }
457         }
458
459         # Otherwise, get the full cache window out of the DB
460
461         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
462
463         # If there are no hits, just return the value
464
465         if (!$notice) {
466             return $notice;
467         }
468
469         # Pack results into an array
470
471         $notices = array();
472
473         while ($notice->fetch()) {
474             $notices[] = clone($notice);
475         }
476
477         $notice->free();
478
479         # Store the array in the cache for next time
480
481         $result = $cache->set(common_cache_key($cachekey), $notices);
482         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
483
484         # return a wrapper of the array for use now
485
486         $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
487
488         return $wrapper;
489     }
490
491     function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
492     {
493
494         $parts = array();
495
496         $qry = 'SELECT * FROM notice ';
497
498         if (common_config('public', 'localonly')) {
499             $parts[] = 'is_local = 1';
500         } else {
501             # -1 == blacklisted
502             $parts[] = 'is_local != -1';
503         }
504
505         if ($parts) {
506             $qry .= ' WHERE ' . implode(' AND ', $parts);
507         }
508
509         return Notice::getStream($qry,
510                                  'public',
511                                  $offset, $limit, $since_id, $before_id, null, $since);
512     }
513
514     function addToInboxes()
515     {
516         $enabled = common_config('inboxes', 'enabled');
517
518         if ($enabled === true || $enabled === 'transitional') {
519             $inbox = new Notice_inbox();
520             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
521               'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
522               'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
523               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
524               'AND NOT EXISTS (SELECT user_id, notice_id ' .
525               'FROM notice_inbox ' .
526               'WHERE user_id = user.id ' .
527               'AND notice_id = ' . $this->id . ' )';
528             if ($enabled === 'transitional') {
529                 $qry .= ' AND user.inboxed = 1';
530             }
531             $inbox->query($qry);
532         }
533         return;
534     }
535
536     # Delete from inboxes if we're deleted.
537
538     function blowInboxes()
539     {
540
541         $enabled = common_config('inboxes', 'enabled');
542
543         if ($enabled === true || $enabled === 'transitional') {
544             $inbox = new Notice_inbox();
545             $inbox->notice_id = $this->id;
546             $inbox->delete();
547         }
548
549         return;
550     }
551
552 }
553