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 if (common_config('db','type') == 'pgsql')
236 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
238 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
240 $cnt = $notice->count();
244 static function checkEditThrottle($profile_id) {
245 $profile = Profile::staticGet($profile_id);
250 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
251 if ($notice && $notice->fetch()) {
252 # If the Nth notice was posted less than timespan seconds ago
253 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
258 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
262 function blowCaches($blowLast=false)
264 $this->blowSubsCache($blowLast);
265 $this->blowNoticeCache($blowLast);
266 $this->blowRepliesCache($blowLast);
267 $this->blowPublicCache($blowLast);
268 $this->blowTagCache($blowLast);
269 $this->blowGroupCache($blowLast);
272 function blowGroupCache($blowLast=false)
274 $cache = common_memcache();
276 $group_inbox = new Group_inbox();
277 $group_inbox->notice_id = $this->id;
278 if ($group_inbox->find()) {
279 while ($group_inbox->fetch()) {
280 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
282 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
284 $member = new Group_member();
285 $member->group_id = $group_inbox->group_id;
286 if ($member->find()) {
287 while ($member->fetch()) {
288 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
290 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
296 $group_inbox->free();
301 function blowTagCache($blowLast=false)
303 $cache = common_memcache();
305 $tag = new Notice_tag();
306 $tag->notice_id = $this->id;
308 while ($tag->fetch()) {
309 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
311 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
320 function blowSubsCache($blowLast=false)
322 $cache = common_memcache();
326 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
327 $user->query('SELECT id ' .
329 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
330 'WHERE subscription.subscribed = ' . $this->profile_id);
332 while ($user->fetch()) {
333 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
335 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
343 function blowNoticeCache($blowLast=false)
345 if ($this->is_local) {
346 $cache = common_memcache();
348 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
350 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
356 function blowRepliesCache($blowLast=false)
358 $cache = common_memcache();
360 $reply = new Reply();
361 $reply->notice_id = $this->id;
362 if ($reply->find()) {
363 while ($reply->fetch()) {
364 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
366 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
375 function blowPublicCache($blowLast=false)
377 if ($this->is_local == 1) {
378 $cache = common_memcache();
380 $cache->delete(common_cache_key('public'));
382 $cache->delete(common_cache_key('public').';last');
388 function blowFavesCache($blowLast=false)
390 $cache = common_memcache();
393 $fave->notice_id = $this->id;
395 while ($fave->fetch()) {
396 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
398 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
407 # XXX: too many args; we need to move to named params or even a separate
408 # class for notice streams
410 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
412 if (common_config('memcached', 'enabled')) {
414 # Skip the cache if this is a since, since_id or before_id qry
415 if ($since_id > 0 || $before_id > 0 || $since) {
416 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
418 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
422 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
425 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
430 if (preg_match('/\bWHERE\b/i', $qry)) {
444 $qry .= ' notice.id > ' . $since_id;
447 if ($before_id > 0) {
456 $qry .= ' notice.id < ' . $before_id;
468 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
471 # Allow ORDER override
476 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
479 if (common_config('db','type') == 'pgsql') {
480 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
482 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
485 $notice = new Notice();
487 $notice->query($qry);
492 # XXX: this is pretty long and should probably be broken up into
493 # some helper functions
495 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
497 # If outside our cache window, just go to the DB
499 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
500 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
503 # Get the cache; if we can't, just go to the DB
505 $cache = common_memcache();
508 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
511 # Get the notices out of the cache
513 $notices = $cache->get(common_cache_key($cachekey));
515 # On a cache hit, return a DB-object-like wrapper
517 if ($notices !== false) {
518 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
522 # If the cache was invalidated because of new data being
523 # added, we can try and just get the new stuff. We keep an additional
524 # copy of the data at the key + ';last'
526 # No cache hit. Try to get the *last* cached version
528 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
532 # Reverse-chron order, so last ID is last.
534 $last_id = $last_notices[0]->id;
536 # XXX: this assumes monotonically increasing IDs; a fair
539 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
540 $last_id, null, $order, null);
543 $new_notices = array();
544 while ($new_notice->fetch()) {
545 $new_notices[] = clone($new_notice);
548 $notices = array_slice(array_merge($new_notices, $last_notices),
549 0, NOTICE_CACHE_WINDOW);
551 # Store the array in the cache for next time
553 $result = $cache->set(common_cache_key($cachekey), $notices);
554 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
556 # return a wrapper of the array for use now
558 return new ArrayWrapper(array_slice($notices, $offset, $limit));
562 # Otherwise, get the full cache window out of the DB
564 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
566 # If there are no hits, just return the value
572 # Pack results into an array
576 while ($notice->fetch()) {
577 $notices[] = clone($notice);
582 # Store the array in the cache for next time
584 $result = $cache->set(common_cache_key($cachekey), $notices);
585 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
587 # return a wrapper of the array for use now
589 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
594 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
599 $qry = 'SELECT * FROM notice ';
601 if (common_config('public', 'localonly')) {
602 $parts[] = 'is_local = 1';
605 $parts[] = 'is_local != -1';
609 $qry .= ' WHERE ' . implode(' AND ', $parts);
612 return Notice::getStream($qry,
614 $offset, $limit, $since_id, $before_id, null, $since);
617 function addToInboxes()
619 $enabled = common_config('inboxes', 'enabled');
621 if ($enabled === true || $enabled === 'transitional') {
622 $inbox = new Notice_inbox();
623 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
624 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
625 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
626 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
627 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
628 'AND NOT EXISTS (SELECT user_id, notice_id ' .
629 'FROM notice_inbox ' .
630 "WHERE user_id = $UT.id " .
631 'AND notice_id = ' . $this->id . ' )';
632 if ($enabled === 'transitional') {
633 $qry .= " AND $UT.inboxed = 1";
640 function saveGroups()
642 $enabled = common_config('inboxes', 'enabled');
643 if ($enabled !== true && $enabled !== 'transitional') {
647 /* extract all !group */
648 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
649 strtolower($this->content),
655 $profile = $this->getProfile();
657 /* Add them to the database */
659 foreach (array_unique($match[1]) as $nickname) {
660 /* XXX: remote groups. */
661 $group = User_group::staticGet('nickname', $nickname);
667 // we automatically add a tag for every group name, too
669 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
670 'notice_id' => $this->id));
673 $this->saveTag($nickname);
676 if ($profile->isMember($group)) {
678 $gi = new Group_inbox();
680 $gi->group_id = $group->id;
681 $gi->notice_id = $this->id;
682 $gi->created = common_sql_now();
684 $result = $gi->insert();
687 common_log_db_error($gi, 'INSERT', __FILE__);
690 // FIXME: do this in an offline daemon
692 $inbox = new Notice_inbox();
693 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
694 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
695 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
696 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
697 'WHERE group_member.group_id = ' . $group->id . ' ' .
698 'AND NOT EXISTS (SELECT user_id, notice_id ' .
699 'FROM notice_inbox ' .
700 "WHERE user_id = $UT.id " .
701 'AND notice_id = ' . $this->id . ' )';
702 if ($enabled === 'transitional') {
703 $qry .= " AND $UT.inboxed = 1";
705 $result = $inbox->query($qry);
710 function saveReplies()
712 // Alternative reply format
714 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
717 // extract all @messages
718 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
722 if ($cnt || $tname) {
723 // XXX: is there another way to make an array copy?
724 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
727 $sender = Profile::staticGet($this->profile_id);
731 // store replied only for first @ (what user/notice what the reply directed,
732 // we assume first @ is it)
734 for ($i=0; $i<count($names); $i++) {
735 $nickname = $names[$i];
736 $recipient = common_relative_profile($sender, $nickname, $this->created);
740 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
741 $reply_for = $recipient;
742 $recipient_notice = $reply_for->getCurrentNotice();
743 if ($recipient_notice) {
744 $orig = clone($this);
745 $this->reply_to = $recipient_notice->id;
746 $this->update($orig);
749 // Don't save replies from blocked profile to local user
750 $recipient_user = User::staticGet('id', $recipient->id);
751 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
754 $reply = new Reply();
755 $reply->notice_id = $this->id;
756 $reply->profile_id = $recipient->id;
757 $id = $reply->insert();
759 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
760 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
761 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
764 $replied[$recipient->id] = 1;
768 // Hash format replies, too
769 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
771 foreach ($match[1] as $tag) {
772 $tagged = Profile_tag::getTagged($sender->id, $tag);
773 foreach ($tagged as $t) {
774 if (!$replied[$t->id]) {
775 // Don't save replies from blocked profile to local user
776 $t_user = User::staticGet('id', $t->id);
777 if ($t_user && $t_user->hasBlocked($sender)) {
780 $reply = new Reply();
781 $reply->notice_id = $this->id;
782 $reply->profile_id = $t->id;
783 $id = $reply->insert();
785 common_log_db_error($reply, 'INSERT', __FILE__);
788 $replied[$recipient->id] = 1;
795 foreach (array_keys($replied) as $recipient) {
796 $user = User::staticGet('id', $recipient);
798 mail_notify_attn($user, $this);
803 function asAtomEntry($namespace=false, $source=false)
805 $profile = $this->getProfile();
807 $xs = new XMLStringer(true);
810 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
811 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
816 $xs->elementStart('entry', $attrs);
819 $xs->elementStart('source');
820 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
821 $xs->element('link', array('href' => $profile->profileurl));
822 $user = User::staticGet('id', $profile->id);
824 $atom_feed = common_local_url('api',
825 array('apiaction' => 'statuses',
826 'method' => 'user_timeline',
827 'argument' => $profile->nickname.'.atom'));
828 $xs->element('link', array('rel' => 'self',
829 'type' => 'application/atom+xml',
830 'href' => $profile->profileurl));
831 $xs->element('link', array('rel' => 'license',
832 'href' => common_config('license', 'url')));
835 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
838 $xs->elementStart('author');
839 $xs->element('name', null, $profile->nickname);
840 $xs->element('uri', null, $profile->profileurl);
841 $xs->elementEnd('author');
844 $xs->elementEnd('source');
847 $xs->element('title', null, $this->content);
848 $xs->element('summary', null, $this->content);
850 $xs->element('link', array('rel' => 'alternate',
851 'href' => $this->bestUrl()));
853 $xs->element('id', null, $this->uri);
855 $xs->element('published', null, common_date_w3dtf($this->created));
856 $xs->element('updated', null, common_date_w3dtf($this->modified));
858 if ($this->reply_to) {
859 $reply_notice = Notice::staticGet('id', $this->reply_to);
860 if (!empty($reply_notice)) {
861 $xs->element('link', array('rel' => 'related',
862 'href' => $reply_notice->bestUrl()));
863 $xs->element('thr:in-reply-to',
864 array('ref' => $reply_notice->uri,
865 'href' => $reply_notice->bestUrl()));
869 $xs->element('content', array('type' => 'html'), $this->rendered);
871 $tag = new Notice_tag();
872 $tag->notice_id = $this->id;
874 while ($tag->fetch()) {
875 $xs->element('category', array('term' => $tag->tag));
880 $xs->elementEnd('entry');
882 return $xs->getString();
887 if (!empty($this->url)) {
889 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
892 return common_local_url('shownotice',
893 array('notice' => $this->id));