]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
031ccd58386a3a115038121fc6f6e461946fe93f
[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) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
52
53     /* the code above is auto generated do not remove the tag below */
54     ###END_AUTOCODE
55
56         function getProfile() {
57                 return Profile::staticGet('id', $this->profile_id);
58         }
59
60         function delete() {
61                 $this->blowCaches(true);
62                 $this->blowFavesCache(true);
63                 $this->blowInboxes();
64                 parent::delete();
65         }
66
67         function saveTags() {
68                 /* extract all #hastags */
69                 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
70                 if (!$count) {
71                         return true;
72                 }
73
74                 /* elide characters we don't want in the tag */
75                 $match[1] = str_replace(array('-', '_', '.'), '', $match[1]);
76
77                 /* Add them to the database */
78                 foreach(array_unique($match[1]) as $hashtag) {
79                         $tag = DB_DataObject::factory('Notice_tag');
80                         $tag->notice_id = $this->id;
81                         $tag->tag = $hashtag;
82                         $tag->created = $this->created;
83                         $id = $tag->insert();
84                         if (!$id) {
85                                 $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
86                                 common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
87                                 common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
88                                 return;
89                         }
90                 }
91                 return true;
92         }
93
94         static function saveNew($profile_id, $content, $source=NULL, $is_local=1, $reply_to=NULL, $uri=NULL) {
95
96                 $profile = Profile::staticGet($profile_id);
97
98         if (!$profile) {
99             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
100             return _('Problem saving notice. Unknown user.');
101         }
102
103         if (!Notice::checkEditThrottle($profile_id)) {
104             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
105                         return _('Too many notices too fast; take a breather and post again in a few minutes.');
106         }
107
108                 $banned = common_config('profile', 'banned');
109
110                 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
111                         common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
112             return _('You are banned from posting notices on this site.');
113                 }
114
115                 $notice = new Notice();
116                 $notice->profile_id = $profile_id;
117
118                 $blacklist = common_config('public', 'blacklist');
119
120                 # Blacklisted are non-false, but not 1, either
121
122                 if ($blacklist && in_array($profile_id, $blacklist)) {
123                         $notice->is_local = -1;
124                 } else {
125                         $notice->is_local = $is_local;
126                 }
127
128                 $notice->reply_to = $reply_to;
129                 $notice->created = common_sql_now();
130                 $notice->content = $content;
131                 $notice->rendered = common_render_content($notice->content, $notice);
132                 $notice->source = $source;
133                 $notice->uri = $uri;
134
135                 $id = $notice->insert();
136
137                 if (!$id) {
138                         common_log_db_error($notice, 'INSERT', __FILE__);
139                         return _('Problem saving notice.');
140                 }
141
142                 # Update the URI after the notice is in the database
143                 if (!$uri) {
144                         $orig = clone($notice);
145                         $notice->uri = common_notice_uri($notice);
146
147                         if (!$notice->update($orig)) {
148                                 common_log_db_error($notice, 'UPDATE', __FILE__);
149                                 return _('Problem saving notice.');
150                         }
151                 }
152
153                 # XXX: do we need to change this for remote users?
154
155                 common_save_replies($notice);
156                 $notice->saveTags();
157
158                 # Clear the cache for subscribed users, so they'll update at next request
159                 # XXX: someone clever could prepend instead of clearing the cache
160
161                 if (common_config('memcached', 'enabled')) {
162                         $notice->blowCaches();
163                 }
164
165                 $notice->addToInboxes();
166                 return $notice;
167         }
168
169     static function checkEditThrottle($profile_id) {
170         $profile = Profile::staticGet($profile_id);
171         if (!$profile) {
172             return false;
173         }
174         # Get the Nth notice
175         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
176         if ($notice && $notice->fetch()) {
177             # If the Nth notice was posted less than timespan seconds ago
178             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
179                 # Then we throttle
180                 return false;
181             }
182         }
183         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
184         return true;
185     }
186
187         function blowCaches($blowLast=false) {
188                 $this->blowSubsCache($blowLast);
189                 $this->blowNoticeCache($blowLast);
190                 $this->blowRepliesCache($blowLast);
191                 $this->blowPublicCache($blowLast);
192                 $this->blowTagCache($blowLast);
193         }
194
195         function blowTagCache($blowLast=false) {
196                 $cache = common_memcache();
197                 if ($cache) {
198                         $tag = new Notice_tag();
199                         $tag->notice_id = $this->id;
200                         if ($tag->find()) {
201                                 while ($tag->fetch()) {
202                                         $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
203                                         if ($blowLast) {
204                                                 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
205                                         }
206                                 }
207                         }
208                         $tag->free();
209                         unset($tag);
210                 }
211         }
212
213         function blowSubsCache($blowLast=false) {
214                 $cache = common_memcache();
215                 if ($cache) {
216                         $user = new User();
217
218                         $user->query('SELECT id ' .
219                                                  'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
220                                                  'WHERE subscription.subscribed = ' . $this->profile_id);
221
222                         while ($user->fetch()) {
223                                 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
224                                 if ($blowLast) {
225                                         $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
226                                 }
227                         }
228                         $user->free();
229                         unset($user);
230                 }
231         }
232
233         function blowNoticeCache($blowLast=false) {
234                 if ($this->is_local) {
235                         $cache = common_memcache();
236                         if ($cache) {
237                                 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
238                                 if ($blowLast) {
239                                         $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
240                                 }
241                         }
242                 }
243         }
244
245         function blowRepliesCache($blowLast=false) {
246                 $cache = common_memcache();
247                 if ($cache) {
248                         $reply = new Reply();
249                         $reply->notice_id = $this->id;
250                         if ($reply->find()) {
251                                 while ($reply->fetch()) {
252                                         $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
253                                         if ($blowLast) {
254                                                 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
255                                         }
256                                 }
257                         }
258                         $reply->free();
259                         unset($reply);
260                 }
261         }
262
263         function blowPublicCache($blowLast=false) {
264                 if ($this->is_local == 1) {
265                         $cache = common_memcache();
266                         if ($cache) {
267                                 $cache->delete(common_cache_key('public'));
268                                 if ($blowLast) {
269                                         $cache->delete(common_cache_key('public').';last');
270                                 }
271                         }
272                 }
273         }
274
275         function blowFavesCache($blowLast=false) {
276                 $cache = common_memcache();
277                 if ($cache) {
278                         $fave = new Fave();
279                         $fave->notice_id = $this->id;
280                         if ($fave->find()) {
281                                 while ($fave->fetch()) {
282                                         $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
283                                         if ($blowLast) {
284                                                 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
285                                         }
286                                 }
287                         }
288                         $fave->free();
289                         unset($fave);
290                 }
291         }
292
293         # XXX: too many args; we need to move to named params or even a separate
294         # class for notice streams
295
296         static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL) {
297
298                 if (common_config('memcached', 'enabled')) {
299
300                         # Skip the cache if this is a since_id or before_id qry
301                         if ($since_id > 0 || $before_id > 0) {
302                                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
303                         } else {
304                                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
305                         }
306                 }
307
308                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
309         }
310
311         static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order) {
312
313                 $needAnd = FALSE;
314                 $needWhere = TRUE;
315
316                 if (preg_match('/\bWHERE\b/i', $qry)) {
317                         $needWhere = FALSE;
318                         $needAnd = TRUE;
319                 }
320
321                 if ($since_id > 0) {
322
323                         if ($needWhere) {
324                         $qry .= ' WHERE ';
325                                 $needWhere = FALSE;
326                         } else {
327                                 $qry .= ' AND ';
328                         }
329
330                     $qry .= ' notice.id > ' . $since_id;
331                 }
332
333                 if ($before_id > 0) {
334
335                         if ($needWhere) {
336                         $qry .= ' WHERE ';
337                                 $needWhere = FALSE;
338                         } else {
339                                 $qry .= ' AND ';
340                         }
341
342                         $qry .= ' notice.id < ' . $before_id;
343                 }
344
345                 # Allow ORDER override
346
347                 if ($order) {
348                         $qry .= $order;
349                 } else {
350                         $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
351                 }
352
353                 if (common_config('db','type') == 'pgsql') {
354                         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
355                 } else {
356                         $qry .= ' LIMIT ' . $offset . ', ' . $limit;
357                 }
358
359                 $notice = new Notice();
360
361                 $notice->query($qry);
362
363                 return $notice;
364         }
365
366         # XXX: this is pretty long and should probably be broken up into
367         # some helper functions
368
369         static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
370
371                 # If outside our cache window, just go to the DB
372
373                 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
374                         return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
375                 }
376
377                 # Get the cache; if we can't, just go to the DB
378
379                 $cache = common_memcache();
380
381                 if (!$cache) {
382                         return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
383                 }
384
385                 # Get the notices out of the cache
386
387                 $notices = $cache->get(common_cache_key($cachekey));
388
389                 # On a cache hit, return a DB-object-like wrapper
390
391                 if ($notices !== FALSE) {
392                         $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
393                         return $wrapper;
394                 }
395
396                 # If the cache was invalidated because of new data being
397                 # added, we can try and just get the new stuff. We keep an additional
398                 # copy of the data at the key + ';last'
399
400                 # No cache hit. Try to get the *last* cached version
401
402                 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
403
404                 if ($last_notices) {
405
406                         # Reverse-chron order, so last ID is last.
407
408                         $last_id = $last_notices[0]->id;
409
410                         # XXX: this assumes monotonically increasing IDs; a fair
411                         # bet with our DB.
412
413                         $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
414                                                                                                   $last_id, NULL, $order);
415
416                         if ($new_notice) {
417                                 $new_notices = array();
418                                 while ($new_notice->fetch()) {
419                                         $new_notices[] = clone($new_notice);
420                                 }
421                                 $new_notice->free();
422                                 $notices = array_slice(array_merge($new_notices, $last_notices),
423                                                                            0, NOTICE_CACHE_WINDOW);
424
425                                 # Store the array in the cache for next time
426
427                                 $result = $cache->set(common_cache_key($cachekey), $notices);
428                                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
429
430                                 # return a wrapper of the array for use now
431
432                                 return new NoticeWrapper(array_slice($notices, $offset, $limit));
433                         }
434                 }
435
436                 # Otherwise, get the full cache window out of the DB
437
438                 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order);
439
440                 # If there are no hits, just return the value
441
442                 if (!$notice) {
443                         return $notice;
444                 }
445
446                 # Pack results into an array
447
448                 $notices = array();
449
450                 while ($notice->fetch()) {
451                         $notices[] = clone($notice);
452                 }
453
454                 $notice->free();
455
456                 # Store the array in the cache for next time
457
458                 $result = $cache->set(common_cache_key($cachekey), $notices);
459                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
460
461                 # return a wrapper of the array for use now
462
463                 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
464
465                 return $wrapper;
466         }
467
468         function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0) {
469
470                 $parts = array();
471
472                 $qry = 'SELECT * FROM notice ';
473
474                 if (common_config('public', 'localonly')) {
475                         $parts[] = 'is_local = 1';
476                 } else {
477                         # -1 == blacklisted
478                         $parts[] = 'is_local != -1';
479                 }
480
481                 if ($parts) {
482                         $qry .= ' WHERE ' . implode(' AND ', $parts);
483                 }
484
485                 return Notice::getStream($qry,
486                                                                  'public',
487                                                                  $offset, $limit, $since_id, $before_id);
488         }
489
490         function addToInboxes() {
491                 $enabled = common_config('inboxes', 'enabled');
492
493                 if ($enabled === true || $enabled === 'transitional') {
494                         $inbox = new Notice_inbox();
495                         $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
496                           'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
497                           'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
498                           'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
499                           'AND NOT EXISTS (SELECT user_id, notice_id ' .
500                           'FROM notice_inbox ' .
501                           'WHERE user_id = user.id ' .
502                           'AND notice_id = ' . $this->id . ' )';
503                         if ($enabled === 'transitional') {
504                                 $qry .= ' AND user.inboxed = 1';
505                         }
506                         $inbox->query($qry);
507                 }
508                 return;
509         }
510
511         # Delete from inboxes if we're deleted.
512
513         function blowInboxes() {
514
515                 $enabled = common_config('inboxes', 'enabled');
516
517                 if ($enabled === true || $enabled === 'transitional') {
518                         $inbox = new Notice_inbox();
519                         $inbox->notice_id = $this->id;
520                         $inbox->delete();
521                 }
522
523                 return;
524         }
525
526 }
527