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);
55 /* the code above is auto generated do not remove the tag below */
60 return Profile::staticGet('id', $this->profile_id);
65 $this->blowCaches(true);
66 $this->blowFavesCache(true);
67 $this->blowSubsCache(true);
69 $this->query('BEGIN');
70 $related = array('Reply',
75 if (common_config('inboxes', 'enabled')) {
76 $related[] = 'Notice_inbox';
78 foreach ($related as $cls) {
80 $inst->notice_id = $this->id;
83 $result = parent::delete();
84 $this->query('COMMIT');
89 /* extract all #hastags */
90 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
95 /* Add them to the database */
96 foreach(array_unique($match[1]) as $hashtag) {
97 /* elide characters we don't want in the tag */
98 $this->saveTag($hashtag);
103 function saveTag($hashtag)
105 $hashtag = common_canonical_tag($hashtag);
107 $tag = new Notice_tag();
108 $tag->notice_id = $this->id;
109 $tag->tag = $hashtag;
110 $tag->created = $this->created;
111 $id = $tag->insert();
114 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
115 $last_error->message));
120 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
122 $profile = Profile::staticGet($profile_id);
124 $final = common_shorten_links($content);
127 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
128 return _('Problem saving notice. Unknown user.');
131 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
132 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
133 return _('Too many notices too fast; take a breather and post again in a few minutes.');
136 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
137 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
138 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
141 $banned = common_config('profile', 'banned');
143 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
144 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
145 return _('You are banned from posting notices on this site.');
148 $notice = new Notice();
149 $notice->profile_id = $profile_id;
151 $blacklist = common_config('public', 'blacklist');
152 $autosource = common_config('public', 'autosource');
154 # Blacklisted are non-false, but not 1, either
156 if (($blacklist && in_array($profile_id, $blacklist)) ||
157 ($source && $autosource && in_array($source, $autosource))) {
158 $notice->is_local = -1;
160 $notice->is_local = $is_local;
163 $notice->query('BEGIN');
165 $notice->reply_to = $reply_to;
166 $notice->created = common_sql_now();
167 $notice->content = $final;
168 $notice->rendered = common_render_content($final, $notice);
169 $notice->source = $source;
172 if (Event::handle('StartNoticeSave', array(&$notice))) {
174 $id = $notice->insert();
177 common_log_db_error($notice, 'INSERT', __FILE__);
178 return _('Problem saving notice.');
181 # Update the URI after the notice is in the database
183 $orig = clone($notice);
184 $notice->uri = common_notice_uri($notice);
186 if (!$notice->update($orig)) {
187 common_log_db_error($notice, 'UPDATE', __FILE__);
188 return _('Problem saving notice.');
192 # XXX: do we need to change this for remote users?
194 $notice->saveReplies();
196 $notice->saveGroups();
198 $notice->addToInboxes();
199 $notice->query('COMMIT');
201 Event::handle('EndNoticeSave', array($notice));
204 # Clear the cache for subscribed users, so they'll update at next request
205 # XXX: someone clever could prepend instead of clearing the cache
207 if (common_config('memcached', 'enabled')) {
208 $notice->blowCaches();
214 static function checkDupes($profile_id, $content) {
215 $profile = Profile::staticGet($profile_id);
219 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
222 while ($notice->fetch()) {
223 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
225 } else if ($notice->content == $content) {
230 # If we get here, oldest item in cache window is not
231 # old enough for dupe limit; do direct check against DB
232 $notice = new Notice();
233 $notice->profile_id = $profile_id;
234 $notice->content = $content;
235 $notice->whereAdd('now() - created < ' . common_config('notice', 'dupelimit'));
236 $cnt = $notice->count();
240 static function checkEditThrottle($profile_id) {
241 $profile = Profile::staticGet($profile_id);
246 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
247 if ($notice && $notice->fetch()) {
248 # If the Nth notice was posted less than timespan seconds ago
249 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
254 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
258 function blowCaches($blowLast=false)
260 $this->blowSubsCache($blowLast);
261 $this->blowNoticeCache($blowLast);
262 $this->blowRepliesCache($blowLast);
263 $this->blowPublicCache($blowLast);
264 $this->blowTagCache($blowLast);
265 $this->blowGroupCache($blowLast);
268 function blowGroupCache($blowLast=false)
270 $cache = common_memcache();
272 $group_inbox = new Group_inbox();
273 $group_inbox->notice_id = $this->id;
274 if ($group_inbox->find()) {
275 while ($group_inbox->fetch()) {
276 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
278 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
280 $member = new Group_member();
281 $member->group_id = $group_inbox->group_id;
282 if ($member->find()) {
283 while ($member->fetch()) {
284 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
286 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
292 $group_inbox->free();
297 function blowTagCache($blowLast=false)
299 $cache = common_memcache();
301 $tag = new Notice_tag();
302 $tag->notice_id = $this->id;
304 while ($tag->fetch()) {
305 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
307 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
316 function blowSubsCache($blowLast=false)
318 $cache = common_memcache();
322 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
323 $user->query('SELECT id ' .
325 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
326 'WHERE subscription.subscribed = ' . $this->profile_id);
328 while ($user->fetch()) {
329 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
331 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
339 function blowNoticeCache($blowLast=false)
341 if ($this->is_local) {
342 $cache = common_memcache();
344 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
346 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
352 function blowRepliesCache($blowLast=false)
354 $cache = common_memcache();
356 $reply = new Reply();
357 $reply->notice_id = $this->id;
358 if ($reply->find()) {
359 while ($reply->fetch()) {
360 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
362 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
371 function blowPublicCache($blowLast=false)
373 if ($this->is_local == 1) {
374 $cache = common_memcache();
376 $cache->delete(common_cache_key('public'));
378 $cache->delete(common_cache_key('public').';last');
384 function blowFavesCache($blowLast=false)
386 $cache = common_memcache();
389 $fave->notice_id = $this->id;
391 while ($fave->fetch()) {
392 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
394 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
403 # XXX: too many args; we need to move to named params or even a separate
404 # class for notice streams
406 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
408 if (common_config('memcached', 'enabled')) {
410 # Skip the cache if this is a since, since_id or before_id qry
411 if ($since_id > 0 || $before_id > 0 || $since) {
412 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
414 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
418 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
421 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
426 if (preg_match('/\bWHERE\b/i', $qry)) {
440 $qry .= ' notice.id > ' . $since_id;
443 if ($before_id > 0) {
452 $qry .= ' notice.id < ' . $before_id;
464 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
467 # Allow ORDER override
472 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
475 if (common_config('db','type') == 'pgsql') {
476 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
478 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
481 $notice = new Notice();
483 $notice->query($qry);
488 # XXX: this is pretty long and should probably be broken up into
489 # some helper functions
491 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
493 # If outside our cache window, just go to the DB
495 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
496 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
499 # Get the cache; if we can't, just go to the DB
501 $cache = common_memcache();
504 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
507 # Get the notices out of the cache
509 $notices = $cache->get(common_cache_key($cachekey));
511 # On a cache hit, return a DB-object-like wrapper
513 if ($notices !== false) {
514 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
518 # If the cache was invalidated because of new data being
519 # added, we can try and just get the new stuff. We keep an additional
520 # copy of the data at the key + ';last'
522 # No cache hit. Try to get the *last* cached version
524 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
528 # Reverse-chron order, so last ID is last.
530 $last_id = $last_notices[0]->id;
532 # XXX: this assumes monotonically increasing IDs; a fair
535 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
536 $last_id, null, $order, null);
539 $new_notices = array();
540 while ($new_notice->fetch()) {
541 $new_notices[] = clone($new_notice);
544 $notices = array_slice(array_merge($new_notices, $last_notices),
545 0, NOTICE_CACHE_WINDOW);
547 # Store the array in the cache for next time
549 $result = $cache->set(common_cache_key($cachekey), $notices);
550 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
552 # return a wrapper of the array for use now
554 return new ArrayWrapper(array_slice($notices, $offset, $limit));
558 # Otherwise, get the full cache window out of the DB
560 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
562 # If there are no hits, just return the value
568 # Pack results into an array
572 while ($notice->fetch()) {
573 $notices[] = clone($notice);
578 # Store the array in the cache for next time
580 $result = $cache->set(common_cache_key($cachekey), $notices);
581 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
583 # return a wrapper of the array for use now
585 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
590 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
595 $qry = 'SELECT * FROM notice ';
597 if (common_config('public', 'localonly')) {
598 $parts[] = 'is_local = 1';
601 $parts[] = 'is_local != -1';
605 $qry .= ' WHERE ' . implode(' AND ', $parts);
608 return Notice::getStream($qry,
610 $offset, $limit, $since_id, $before_id, null, $since);
613 function addToInboxes()
615 $enabled = common_config('inboxes', 'enabled');
617 if ($enabled === true || $enabled === 'transitional') {
618 $inbox = new Notice_inbox();
619 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
620 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
621 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
622 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
623 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
624 'AND NOT EXISTS (SELECT user_id, notice_id ' .
625 'FROM notice_inbox ' .
626 "WHERE user_id = $UT.id " .
627 'AND notice_id = ' . $this->id . ' )';
628 if ($enabled === 'transitional') {
629 $qry .= " AND $UT.inboxed = 1";
636 function saveGroups()
638 $enabled = common_config('inboxes', 'enabled');
639 if ($enabled !== true && $enabled !== 'transitional') {
643 /* extract all !group */
644 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
645 strtolower($this->content),
651 $profile = $this->getProfile();
653 /* Add them to the database */
655 foreach (array_unique($match[1]) as $nickname) {
656 /* XXX: remote groups. */
657 $group = User_group::staticGet('nickname', $nickname);
663 // we automatically add a tag for every group name, too
665 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
666 'notice_id' => $this->id));
669 $this->saveTag($nickname);
672 if ($profile->isMember($group)) {
674 $gi = new Group_inbox();
676 $gi->group_id = $group->id;
677 $gi->notice_id = $this->id;
678 $gi->created = common_sql_now();
680 $result = $gi->insert();
683 common_log_db_error($gi, 'INSERT', __FILE__);
686 // FIXME: do this in an offline daemon
688 $inbox = new Notice_inbox();
689 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
690 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
691 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
692 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
693 'WHERE group_member.group_id = ' . $group->id . ' ' .
694 'AND NOT EXISTS (SELECT user_id, notice_id ' .
695 'FROM notice_inbox ' .
696 "WHERE user_id = $UT.id " .
697 'AND notice_id = ' . $this->id . ' )';
698 if ($enabled === 'transitional') {
699 $qry .= " AND $UT.inboxed = 1";
701 $result = $inbox->query($qry);
706 function saveReplies()
708 // Alternative reply format
710 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
713 // extract all @messages
714 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
718 if ($cnt || $tname) {
719 // XXX: is there another way to make an array copy?
720 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
723 $sender = Profile::staticGet($this->profile_id);
727 // store replied only for first @ (what user/notice what the reply directed,
728 // we assume first @ is it)
730 for ($i=0; $i<count($names); $i++) {
731 $nickname = $names[$i];
732 $recipient = common_relative_profile($sender, $nickname, $this->created);
736 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
737 $reply_for = $recipient;
738 $recipient_notice = $reply_for->getCurrentNotice();
739 if ($recipient_notice) {
740 $orig = clone($this);
741 $this->reply_to = $recipient_notice->id;
742 $this->update($orig);
745 // Don't save replies from blocked profile to local user
746 $recipient_user = User::staticGet('id', $recipient->id);
747 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
750 $reply = new Reply();
751 $reply->notice_id = $this->id;
752 $reply->profile_id = $recipient->id;
753 $id = $reply->insert();
755 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
756 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
757 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
760 $replied[$recipient->id] = 1;
764 // Hash format replies, too
765 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
767 foreach ($match[1] as $tag) {
768 $tagged = Profile_tag::getTagged($sender->id, $tag);
769 foreach ($tagged as $t) {
770 if (!$replied[$t->id]) {
771 // Don't save replies from blocked profile to local user
772 $t_user = User::staticGet('id', $t->id);
773 if ($t_user && $t_user->hasBlocked($sender)) {
776 $reply = new Reply();
777 $reply->notice_id = $this->id;
778 $reply->profile_id = $t->id;
779 $id = $reply->insert();
781 common_log_db_error($reply, 'INSERT', __FILE__);
784 $replied[$recipient->id] = 1;
791 foreach (array_keys($replied) as $recipient) {
792 $user = User::staticGet('id', $recipient);
794 mail_notify_attn($user, $this);