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 //Null any notices that are replies to this notice
71 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
72 $related = array('Reply',
77 if (common_config('inboxes', 'enabled')) {
78 $related[] = 'Notice_inbox';
80 foreach ($related as $cls) {
82 $inst->notice_id = $this->id;
85 $result = parent::delete();
86 $this->query('COMMIT');
91 /* extract all #hastags */
92 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
97 /* Add them to the database */
98 foreach(array_unique($match[1]) as $hashtag) {
99 /* elide characters we don't want in the tag */
100 $this->saveTag($hashtag);
105 function saveTag($hashtag)
107 $hashtag = common_canonical_tag($hashtag);
109 $tag = new Notice_tag();
110 $tag->notice_id = $this->id;
111 $tag->tag = $hashtag;
112 $tag->created = $this->created;
113 $id = $tag->insert();
116 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
117 $last_error->message));
122 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
124 $profile = Profile::staticGet($profile_id);
126 $final = common_shorten_links($content);
129 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
130 return _('Problem saving notice. Unknown user.');
133 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
134 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
135 return _('Too many notices too fast; take a breather and post again in a few minutes.');
138 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
139 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
140 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
143 $banned = common_config('profile', 'banned');
145 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
146 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
147 return _('You are banned from posting notices on this site.');
150 $notice = new Notice();
151 $notice->profile_id = $profile_id;
153 $blacklist = common_config('public', 'blacklist');
154 $autosource = common_config('public', 'autosource');
156 # Blacklisted are non-false, but not 1, either
158 if (($blacklist && in_array($profile_id, $blacklist)) ||
159 ($source && $autosource && in_array($source, $autosource))) {
160 $notice->is_local = -1;
162 $notice->is_local = $is_local;
165 $notice->query('BEGIN');
167 $notice->reply_to = $reply_to;
168 $notice->created = common_sql_now();
169 $notice->content = $final;
170 $notice->rendered = common_render_content($final, $notice);
171 $notice->source = $source;
174 if (Event::handle('StartNoticeSave', array(&$notice))) {
176 $id = $notice->insert();
179 common_log_db_error($notice, 'INSERT', __FILE__);
180 return _('Problem saving notice.');
183 # Update the URI after the notice is in the database
185 $orig = clone($notice);
186 $notice->uri = common_notice_uri($notice);
188 if (!$notice->update($orig)) {
189 common_log_db_error($notice, 'UPDATE', __FILE__);
190 return _('Problem saving notice.');
194 # XXX: do we need to change this for remote users?
196 $notice->saveReplies();
198 $notice->saveGroups();
200 if (!common_config('queues', 'enabled')) {
201 $notice->addToInboxes();
204 $notice->query('COMMIT');
206 Event::handle('EndNoticeSave', array($notice));
209 # Clear the cache for subscribed users, so they'll update at next request
210 # XXX: someone clever could prepend instead of clearing the cache
212 if (common_config('memcached', 'enabled')) {
213 if (common_config('queues', 'enabled')) {
214 $notice->blowAuthorCaches();
216 $notice->blowCaches();
223 static function checkDupes($profile_id, $content) {
224 $profile = Profile::staticGet($profile_id);
228 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
231 while ($notice->fetch()) {
232 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
234 } else if ($notice->content == $content) {
239 # If we get here, oldest item in cache window is not
240 # old enough for dupe limit; do direct check against DB
241 $notice = new Notice();
242 $notice->profile_id = $profile_id;
243 $notice->content = $content;
244 if (common_config('db','type') == 'pgsql')
245 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
247 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
249 $cnt = $notice->count();
253 static function checkEditThrottle($profile_id) {
254 $profile = Profile::staticGet($profile_id);
259 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
260 if ($notice && $notice->fetch()) {
261 # If the Nth notice was posted less than timespan seconds ago
262 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
267 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
271 function blowCaches($blowLast=false)
273 $this->blowSubsCache($blowLast);
274 $this->blowNoticeCache($blowLast);
275 $this->blowRepliesCache($blowLast);
276 $this->blowPublicCache($blowLast);
277 $this->blowTagCache($blowLast);
278 $this->blowGroupCache($blowLast);
281 function blowAuthorCaches($blowLast=false)
283 // Clear the user's cache
284 $cache = common_memcache();
286 $user = User::staticGet($this->profile_id);
288 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
290 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
296 $this->blowNoticeCache($blowLast);
297 $this->blowPublicCache($blowLast);
300 function blowGroupCache($blowLast=false)
302 $cache = common_memcache();
304 $group_inbox = new Group_inbox();
305 $group_inbox->notice_id = $this->id;
306 if ($group_inbox->find()) {
307 while ($group_inbox->fetch()) {
308 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
310 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
312 $member = new Group_member();
313 $member->group_id = $group_inbox->group_id;
314 if ($member->find()) {
315 while ($member->fetch()) {
316 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
318 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
324 $group_inbox->free();
329 function blowTagCache($blowLast=false)
331 $cache = common_memcache();
333 $tag = new Notice_tag();
334 $tag->notice_id = $this->id;
336 while ($tag->fetch()) {
337 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
339 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
348 function blowSubsCache($blowLast=false)
350 $cache = common_memcache();
354 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
355 $user->query('SELECT id ' .
357 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
358 'WHERE subscription.subscribed = ' . $this->profile_id);
360 while ($user->fetch()) {
361 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
363 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
371 function blowNoticeCache($blowLast=false)
373 if ($this->is_local) {
374 $cache = common_memcache();
376 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
378 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
384 function blowRepliesCache($blowLast=false)
386 $cache = common_memcache();
388 $reply = new Reply();
389 $reply->notice_id = $this->id;
390 if ($reply->find()) {
391 while ($reply->fetch()) {
392 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
394 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
403 function blowPublicCache($blowLast=false)
405 if ($this->is_local == 1) {
406 $cache = common_memcache();
408 $cache->delete(common_cache_key('public'));
410 $cache->delete(common_cache_key('public').';last');
416 function blowFavesCache($blowLast=false)
418 $cache = common_memcache();
421 $fave->notice_id = $this->id;
423 while ($fave->fetch()) {
424 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
426 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
435 # XXX: too many args; we need to move to named params or even a separate
436 # class for notice streams
438 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
440 if (common_config('memcached', 'enabled')) {
442 # Skip the cache if this is a since, since_id or before_id qry
443 if ($since_id > 0 || $before_id > 0 || $since) {
444 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
446 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
450 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
453 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
458 if (preg_match('/\bWHERE\b/i', $qry)) {
472 $qry .= ' notice.id > ' . $since_id;
475 if ($before_id > 0) {
484 $qry .= ' notice.id < ' . $before_id;
496 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
499 # Allow ORDER override
504 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
507 if (common_config('db','type') == 'pgsql') {
508 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
510 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
513 $notice = new Notice();
515 $notice->query($qry);
520 # XXX: this is pretty long and should probably be broken up into
521 # some helper functions
523 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
525 # If outside our cache window, just go to the DB
527 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
528 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
531 # Get the cache; if we can't, just go to the DB
533 $cache = common_memcache();
536 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
539 # Get the notices out of the cache
541 $notices = $cache->get(common_cache_key($cachekey));
543 # On a cache hit, return a DB-object-like wrapper
545 if ($notices !== false) {
546 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
550 # If the cache was invalidated because of new data being
551 # added, we can try and just get the new stuff. We keep an additional
552 # copy of the data at the key + ';last'
554 # No cache hit. Try to get the *last* cached version
556 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
560 # Reverse-chron order, so last ID is last.
562 $last_id = $last_notices[0]->id;
564 # XXX: this assumes monotonically increasing IDs; a fair
567 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
568 $last_id, null, $order, null);
571 $new_notices = array();
572 while ($new_notice->fetch()) {
573 $new_notices[] = clone($new_notice);
576 $notices = array_slice(array_merge($new_notices, $last_notices),
577 0, NOTICE_CACHE_WINDOW);
579 # Store the array in the cache for next time
581 $result = $cache->set(common_cache_key($cachekey), $notices);
582 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
584 # return a wrapper of the array for use now
586 return new ArrayWrapper(array_slice($notices, $offset, $limit));
590 # Otherwise, get the full cache window out of the DB
592 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
594 # If there are no hits, just return the value
600 # Pack results into an array
604 while ($notice->fetch()) {
605 $notices[] = clone($notice);
610 # Store the array in the cache for next time
612 $result = $cache->set(common_cache_key($cachekey), $notices);
613 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
615 # return a wrapper of the array for use now
617 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
622 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
627 $qry = 'SELECT * FROM notice ';
629 if (common_config('public', 'localonly')) {
630 $parts[] = 'is_local = 1';
633 $parts[] = 'is_local != -1';
637 $qry .= ' WHERE ' . implode(' AND ', $parts);
640 return Notice::getStream($qry,
642 $offset, $limit, $since_id, $before_id, null, $since);
645 function addToInboxes()
647 $enabled = common_config('inboxes', 'enabled');
649 if ($enabled === true || $enabled === 'transitional') {
650 $inbox = new Notice_inbox();
651 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
652 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
653 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
654 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
655 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
656 'AND NOT EXISTS (SELECT user_id, notice_id ' .
657 'FROM notice_inbox ' .
658 "WHERE user_id = $UT.id " .
659 'AND notice_id = ' . $this->id . ' )';
660 if ($enabled === 'transitional') {
661 $qry .= " AND $UT.inboxed = 1";
668 function saveGroups()
670 $enabled = common_config('inboxes', 'enabled');
671 if ($enabled !== true && $enabled !== 'transitional') {
675 /* extract all !group */
676 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
677 strtolower($this->content),
683 $profile = $this->getProfile();
685 /* Add them to the database */
687 foreach (array_unique($match[1]) as $nickname) {
688 /* XXX: remote groups. */
689 $group = User_group::staticGet('nickname', $nickname);
695 // we automatically add a tag for every group name, too
697 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
698 'notice_id' => $this->id));
701 $this->saveTag($nickname);
704 if ($profile->isMember($group)) {
706 $gi = new Group_inbox();
708 $gi->group_id = $group->id;
709 $gi->notice_id = $this->id;
710 $gi->created = common_sql_now();
712 $result = $gi->insert();
715 common_log_db_error($gi, 'INSERT', __FILE__);
718 // FIXME: do this in an offline daemon
720 $inbox = new Notice_inbox();
721 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
722 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
723 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
724 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
725 'WHERE group_member.group_id = ' . $group->id . ' ' .
726 'AND NOT EXISTS (SELECT user_id, notice_id ' .
727 'FROM notice_inbox ' .
728 "WHERE user_id = $UT.id " .
729 'AND notice_id = ' . $this->id . ' )';
730 if ($enabled === 'transitional') {
731 $qry .= " AND $UT.inboxed = 1";
733 $result = $inbox->query($qry);
738 function saveReplies()
740 // Alternative reply format
742 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
745 // extract all @messages
746 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
750 if ($cnt || $tname) {
751 // XXX: is there another way to make an array copy?
752 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
755 $sender = Profile::staticGet($this->profile_id);
759 // store replied only for first @ (what user/notice what the reply directed,
760 // we assume first @ is it)
762 for ($i=0; $i<count($names); $i++) {
763 $nickname = $names[$i];
764 $recipient = common_relative_profile($sender, $nickname, $this->created);
768 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
769 $reply_for = $recipient;
770 $recipient_notice = $reply_for->getCurrentNotice();
771 if ($recipient_notice) {
772 $orig = clone($this);
773 $this->reply_to = $recipient_notice->id;
774 $this->update($orig);
777 // Don't save replies from blocked profile to local user
778 $recipient_user = User::staticGet('id', $recipient->id);
779 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
782 $reply = new Reply();
783 $reply->notice_id = $this->id;
784 $reply->profile_id = $recipient->id;
785 $id = $reply->insert();
787 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
788 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
789 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
792 $replied[$recipient->id] = 1;
796 // Hash format replies, too
797 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
799 foreach ($match[1] as $tag) {
800 $tagged = Profile_tag::getTagged($sender->id, $tag);
801 foreach ($tagged as $t) {
802 if (!$replied[$t->id]) {
803 // Don't save replies from blocked profile to local user
804 $t_user = User::staticGet('id', $t->id);
805 if ($t_user && $t_user->hasBlocked($sender)) {
808 $reply = new Reply();
809 $reply->notice_id = $this->id;
810 $reply->profile_id = $t->id;
811 $id = $reply->insert();
813 common_log_db_error($reply, 'INSERT', __FILE__);
816 $replied[$recipient->id] = 1;
823 foreach (array_keys($replied) as $recipient) {
824 $user = User::staticGet('id', $recipient);
826 mail_notify_attn($user, $this);
831 function asAtomEntry($namespace=false, $source=false)
833 $profile = $this->getProfile();
835 $xs = new XMLStringer(true);
838 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
839 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
844 $xs->elementStart('entry', $attrs);
847 $xs->elementStart('source');
848 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
849 $xs->element('link', array('href' => $profile->profileurl));
850 $user = User::staticGet('id', $profile->id);
852 $atom_feed = common_local_url('api',
853 array('apiaction' => 'statuses',
854 'method' => 'user_timeline',
855 'argument' => $profile->nickname.'.atom'));
856 $xs->element('link', array('rel' => 'self',
857 'type' => 'application/atom+xml',
858 'href' => $profile->profileurl));
859 $xs->element('link', array('rel' => 'license',
860 'href' => common_config('license', 'url')));
863 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
866 $xs->elementStart('author');
867 $xs->element('name', null, $profile->nickname);
868 $xs->element('uri', null, $profile->profileurl);
869 $xs->elementEnd('author');
872 $xs->elementEnd('source');
875 $xs->element('title', null, $this->content);
876 $xs->element('summary', null, $this->content);
878 $xs->element('link', array('rel' => 'alternate',
879 'href' => $this->bestUrl()));
881 $xs->element('id', null, $this->uri);
883 $xs->element('published', null, common_date_w3dtf($this->created));
884 $xs->element('updated', null, common_date_w3dtf($this->modified));
886 if ($this->reply_to) {
887 $reply_notice = Notice::staticGet('id', $this->reply_to);
888 if (!empty($reply_notice)) {
889 $xs->element('link', array('rel' => 'related',
890 'href' => $reply_notice->bestUrl()));
891 $xs->element('thr:in-reply-to',
892 array('ref' => $reply_notice->uri,
893 'href' => $reply_notice->bestUrl()));
897 $xs->element('content', array('type' => 'html'), $this->rendered);
899 $tag = new Notice_tag();
900 $tag->notice_id = $this->id;
902 while ($tag->fetch()) {
903 $xs->element('category', array('term' => $tag->tag));
908 $xs->elementEnd('entry');
910 return $xs->getString();
915 if (!empty($this->url)) {
917 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
920 return common_local_url('shownotice',
921 array('notice' => $this->id));