3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
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.
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.
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/>.
20 if (!defined('LACONICA')) { exit(1); }
23 * Table Definition for notice
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28 * in the memcached cache. */
30 define('NOTICE_CACHE_WINDOW', 61);
32 class Notice extends Memcached_DataObject
35 /* the code below is auto generated do not remove the above tag */
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)
51 function staticGet($k,$v=null)
52 { return Memcached_DataObject::staticGet('Notice',$k,$v); }
54 /* the code above is auto generated do not remove the tag below */
59 return Profile::staticGet('id', $this->profile_id);
64 $this->blowCaches(true);
65 $this->blowFavesCache(true);
67 return parent::delete();
72 /* extract all #hastags */
73 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
78 /* elide characters we don't want in the tag */
79 $match[1] = str_replace(array('-', '_', '.'), '', $match[1]);
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;
86 $tag->created = $this->created;
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));
98 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
100 $profile = Profile::staticGet($profile_id);
103 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
104 return _('Problem saving notice. Unknown user.');
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.');
112 $banned = common_config('profile', 'banned');
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.');
119 $notice = new Notice();
120 $notice->profile_id = $profile_id;
122 $blacklist = common_config('public', 'blacklist');
124 # Blacklisted are non-false, but not 1, either
126 if ($blacklist && in_array($profile_id, $blacklist)) {
127 $notice->is_local = -1;
129 $notice->is_local = $is_local;
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;
139 $id = $notice->insert();
142 common_log_db_error($notice, 'INSERT', __FILE__);
143 return _('Problem saving notice.');
146 # Update the URI after the notice is in the database
148 $orig = clone($notice);
149 $notice->uri = common_notice_uri($notice);
151 if (!$notice->update($orig)) {
152 common_log_db_error($notice, 'UPDATE', __FILE__);
153 return _('Problem saving notice.');
157 # XXX: do we need to change this for remote users?
159 common_save_replies($notice);
161 $notice->saveGroups();
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
166 if (common_config('memcached', 'enabled')) {
167 $notice->blowCaches();
170 $notice->addToInboxes();
174 static function checkEditThrottle($profile_id) {
175 $profile = Profile::staticGet($profile_id);
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')) {
188 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
192 function blowCaches($blowLast=false)
194 $this->blowSubsCache($blowLast);
195 $this->blowNoticeCache($blowLast);
196 $this->blowRepliesCache($blowLast);
197 $this->blowPublicCache($blowLast);
198 $this->blowTagCache($blowLast);
199 $this->blowGroupCache($blowLast);
202 function blowGroupCache($blowLast=false)
204 $cache = common_memcache();
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));
212 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
216 $group_inbox->free();
221 function blowTagCache($blowLast=false)
223 $cache = common_memcache();
225 $tag = new Notice_tag();
226 $tag->notice_id = $this->id;
228 while ($tag->fetch()) {
229 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
231 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
240 function blowSubsCache($blowLast=false)
242 $cache = common_memcache();
246 $user->query('SELECT id ' .
247 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
248 'WHERE subscription.subscribed = ' . $this->profile_id);
250 while ($user->fetch()) {
251 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
253 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
261 function blowNoticeCache($blowLast=false)
263 if ($this->is_local) {
264 $cache = common_memcache();
266 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
268 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
274 function blowRepliesCache($blowLast=false)
276 $cache = common_memcache();
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));
284 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
293 function blowPublicCache($blowLast=false)
295 if ($this->is_local == 1) {
296 $cache = common_memcache();
298 $cache->delete(common_cache_key('public'));
300 $cache->delete(common_cache_key('public').';last');
306 function blowFavesCache($blowLast=false)
308 $cache = common_memcache();
311 $fave->notice_id = $this->id;
313 while ($fave->fetch()) {
314 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
316 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
325 # XXX: too many args; we need to move to named params or even a separate
326 # class for notice streams
328 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
330 if (common_config('memcached', 'enabled')) {
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);
336 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
340 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
343 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
348 if (preg_match('/\bWHERE\b/i', $qry)) {
362 $qry .= ' notice.id > ' . $since_id;
365 if ($before_id > 0) {
374 $qry .= ' notice.id < ' . $before_id;
386 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
389 # Allow ORDER override
394 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
397 if (common_config('db','type') == 'pgsql') {
398 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
400 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
403 $notice = new Notice();
405 $notice->query($qry);
410 # XXX: this is pretty long and should probably be broken up into
411 # some helper functions
413 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
415 # If outside our cache window, just go to the DB
417 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
418 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
421 # Get the cache; if we can't, just go to the DB
423 $cache = common_memcache();
426 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
429 # Get the notices out of the cache
431 $notices = $cache->get(common_cache_key($cachekey));
433 # On a cache hit, return a DB-object-like wrapper
435 if ($notices !== false) {
436 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
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'
444 # No cache hit. Try to get the *last* cached version
446 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
450 # Reverse-chron order, so last ID is last.
452 $last_id = $last_notices[0]->id;
454 # XXX: this assumes monotonically increasing IDs; a fair
457 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
458 $last_id, null, $order, null);
461 $new_notices = array();
462 while ($new_notice->fetch()) {
463 $new_notices[] = clone($new_notice);
466 $notices = array_slice(array_merge($new_notices, $last_notices),
467 0, NOTICE_CACHE_WINDOW);
469 # Store the array in the cache for next time
471 $result = $cache->set(common_cache_key($cachekey), $notices);
472 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
474 # return a wrapper of the array for use now
476 return new NoticeWrapper(array_slice($notices, $offset, $limit));
480 # Otherwise, get the full cache window out of the DB
482 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
484 # If there are no hits, just return the value
490 # Pack results into an array
494 while ($notice->fetch()) {
495 $notices[] = clone($notice);
500 # Store the array in the cache for next time
502 $result = $cache->set(common_cache_key($cachekey), $notices);
503 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
505 # return a wrapper of the array for use now
507 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
512 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
517 $qry = 'SELECT * FROM notice ';
519 if (common_config('public', 'localonly')) {
520 $parts[] = 'is_local = 1';
523 $parts[] = 'is_local != -1';
527 $qry .= ' WHERE ' . implode(' AND ', $parts);
530 return Notice::getStream($qry,
532 $offset, $limit, $since_id, $before_id, null, $since);
535 function addToInboxes()
537 $enabled = common_config('inboxes', 'enabled');
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';
557 # Delete from inboxes if we're deleted.
559 function blowInboxes()
562 $enabled = common_config('inboxes', 'enabled');
564 if ($enabled === true || $enabled === 'transitional') {
565 $inbox = new Notice_inbox();
566 $inbox->notice_id = $this->id;
573 function saveGroups()
575 $enabled = common_config('inboxes', 'enabled');
576 if ($enabled !== true && $enabled !== 'transitional') {
580 /* extract all !group */
581 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
582 strtolower($this->content),
588 $profile = $this->getProfile();
590 /* Add them to the database */
592 foreach (array_unique($match[1]) as $nickname) {
593 /* XXX: remote groups. */
594 $group = User_group::staticGet('nickname', $nickname);
600 if ($profile->isMember($group)) {
602 $gi = new Group_inbox();
604 $gi->group_id = $group->id;
605 $gi->notice_id = $this->id;
606 $gi->created = common_sql_now();
608 $result = $gi->insert();
611 common_log_db_error($gi, 'INSERT', __FILE__);
614 // FIXME: do this in an offline daemon
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';
628 $result = $inbox->query($qry);