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)
49 public $conversation; // int(4)
52 function staticGet($k,$v=NULL) {
53 return Memcached_DataObject::staticGet('Notice',$k,$v);
56 /* the code above is auto generated do not remove the tag below */
61 return Profile::staticGet('id', $this->profile_id);
66 $this->blowCaches(true);
67 $this->blowFavesCache(true);
68 $this->blowSubsCache(true);
70 $this->query('BEGIN');
71 $related = array('Reply',
76 if (common_config('inboxes', 'enabled')) {
77 $related[] = 'Notice_inbox';
79 foreach ($related as $cls) {
81 $inst->notice_id = $this->id;
84 $result = parent::delete();
85 $this->query('COMMIT');
90 /* extract all #hastags */
91 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
96 /* Add them to the database */
97 foreach(array_unique($match[1]) as $hashtag) {
98 /* elide characters we don't want in the tag */
99 $this->saveTag($hashtag);
104 function saveTag($hashtag)
106 $hashtag = common_canonical_tag($hashtag);
108 $tag = new Notice_tag();
109 $tag->notice_id = $this->id;
110 $tag->tag = $hashtag;
111 $tag->created = $this->created;
112 $id = $tag->insert();
115 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
116 $last_error->message));
121 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
123 $profile = Profile::staticGet($profile_id);
125 $final = common_shorten_links($content);
128 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
129 return _('Problem saving notice. Unknown user.');
132 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
133 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
134 return _('Too many notices too fast; take a breather and post again in a few minutes.');
137 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
138 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
139 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
142 $banned = common_config('profile', 'banned');
144 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
145 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
146 return _('You are banned from posting notices on this site.');
149 $notice = new Notice();
150 $notice->profile_id = $profile_id;
152 $blacklist = common_config('public', 'blacklist');
153 $autosource = common_config('public', 'autosource');
155 # Blacklisted are non-false, but not 1, either
157 if (($blacklist && in_array($profile_id, $blacklist)) ||
158 ($source && $autosource && in_array($source, $autosource))) {
159 $notice->is_local = -1;
161 $notice->is_local = $is_local;
164 $notice->query('BEGIN');
166 $notice->reply_to = $reply_to;
167 $notice->created = common_sql_now();
168 $notice->content = $final;
169 $notice->rendered = common_render_content($final, $notice);
170 $notice->source = $source;
173 if (!empty($reply_to)) {
174 $reply_notice = Notice::staticGet('id', $reply_to);
175 if (!empty($reply_notice)) {
176 $notice->reply_to = $reply_to;
177 $notice->conversation = $reply_notice->conversation;
181 if (Event::handle('StartNoticeSave', array(&$notice))) {
183 $id = $notice->insert();
186 common_log_db_error($notice, 'INSERT', __FILE__);
187 return _('Problem saving notice.');
190 # Update the URI after the notice is in the database
192 $orig = clone($notice);
193 $notice->uri = common_notice_uri($notice);
195 if (!$notice->update($orig)) {
196 common_log_db_error($notice, 'UPDATE', __FILE__);
197 return _('Problem saving notice.');
201 # XXX: do we need to change this for remote users?
203 $notice->saveReplies();
205 $notice->saveGroups();
207 $notice->addToInboxes();
208 $notice->query('COMMIT');
210 Event::handle('EndNoticeSave', array($notice));
213 # Clear the cache for subscribed users, so they'll update at next request
214 # XXX: someone clever could prepend instead of clearing the cache
216 if (common_config('memcached', 'enabled')) {
217 $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 blowGroupCache($blowLast=false)
283 $cache = common_memcache();
285 $group_inbox = new Group_inbox();
286 $group_inbox->notice_id = $this->id;
287 if ($group_inbox->find()) {
288 while ($group_inbox->fetch()) {
289 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
291 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
293 $member = new Group_member();
294 $member->group_id = $group_inbox->group_id;
295 if ($member->find()) {
296 while ($member->fetch()) {
297 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
299 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
305 $group_inbox->free();
310 function blowTagCache($blowLast=false)
312 $cache = common_memcache();
314 $tag = new Notice_tag();
315 $tag->notice_id = $this->id;
317 while ($tag->fetch()) {
318 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
320 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
329 function blowSubsCache($blowLast=false)
331 $cache = common_memcache();
335 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
336 $user->query('SELECT id ' .
338 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
339 'WHERE subscription.subscribed = ' . $this->profile_id);
341 while ($user->fetch()) {
342 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
344 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
352 function blowNoticeCache($blowLast=false)
354 if ($this->is_local) {
355 $cache = common_memcache();
357 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
359 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
365 function blowRepliesCache($blowLast=false)
367 $cache = common_memcache();
369 $reply = new Reply();
370 $reply->notice_id = $this->id;
371 if ($reply->find()) {
372 while ($reply->fetch()) {
373 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
375 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
384 function blowPublicCache($blowLast=false)
386 if ($this->is_local == 1) {
387 $cache = common_memcache();
389 $cache->delete(common_cache_key('public'));
391 $cache->delete(common_cache_key('public').';last');
397 function blowFavesCache($blowLast=false)
399 $cache = common_memcache();
402 $fave->notice_id = $this->id;
404 while ($fave->fetch()) {
405 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
407 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
416 # XXX: too many args; we need to move to named params or even a separate
417 # class for notice streams
419 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
421 if (common_config('memcached', 'enabled')) {
423 # Skip the cache if this is a since, since_id or before_id qry
424 if ($since_id > 0 || $before_id > 0 || $since) {
425 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
427 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
431 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
434 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
439 if (preg_match('/\bWHERE\b/i', $qry)) {
453 $qry .= ' notice.id > ' . $since_id;
456 if ($before_id > 0) {
465 $qry .= ' notice.id < ' . $before_id;
477 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
480 # Allow ORDER override
485 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
488 if (common_config('db','type') == 'pgsql') {
489 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
491 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
494 $notice = new Notice();
496 $notice->query($qry);
501 # XXX: this is pretty long and should probably be broken up into
502 # some helper functions
504 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
506 # If outside our cache window, just go to the DB
508 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
509 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
512 # Get the cache; if we can't, just go to the DB
514 $cache = common_memcache();
517 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
520 # Get the notices out of the cache
522 $notices = $cache->get(common_cache_key($cachekey));
524 # On a cache hit, return a DB-object-like wrapper
526 if ($notices !== false) {
527 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
531 # If the cache was invalidated because of new data being
532 # added, we can try and just get the new stuff. We keep an additional
533 # copy of the data at the key + ';last'
535 # No cache hit. Try to get the *last* cached version
537 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
541 # Reverse-chron order, so last ID is last.
543 $last_id = $last_notices[0]->id;
545 # XXX: this assumes monotonically increasing IDs; a fair
548 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
549 $last_id, null, $order, null);
552 $new_notices = array();
553 while ($new_notice->fetch()) {
554 $new_notices[] = clone($new_notice);
557 $notices = array_slice(array_merge($new_notices, $last_notices),
558 0, NOTICE_CACHE_WINDOW);
560 # Store the array in the cache for next time
562 $result = $cache->set(common_cache_key($cachekey), $notices);
563 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
565 # return a wrapper of the array for use now
567 return new ArrayWrapper(array_slice($notices, $offset, $limit));
571 # Otherwise, get the full cache window out of the DB
573 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
575 # If there are no hits, just return the value
581 # Pack results into an array
585 while ($notice->fetch()) {
586 $notices[] = clone($notice);
591 # Store the array in the cache for next time
593 $result = $cache->set(common_cache_key($cachekey), $notices);
594 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
596 # return a wrapper of the array for use now
598 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
603 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
608 $qry = 'SELECT * FROM notice ';
610 if (common_config('public', 'localonly')) {
611 $parts[] = 'is_local = 1';
614 $parts[] = 'is_local != -1';
618 $qry .= ' WHERE ' . implode(' AND ', $parts);
621 return Notice::getStream($qry,
623 $offset, $limit, $since_id, $before_id, null, $since);
626 function addToInboxes()
628 $enabled = common_config('inboxes', 'enabled');
630 if ($enabled === true || $enabled === 'transitional') {
631 $inbox = new Notice_inbox();
632 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
633 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
634 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
635 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
636 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
637 'AND NOT EXISTS (SELECT user_id, notice_id ' .
638 'FROM notice_inbox ' .
639 "WHERE user_id = $UT.id " .
640 'AND notice_id = ' . $this->id . ' )';
641 if ($enabled === 'transitional') {
642 $qry .= " AND $UT.inboxed = 1";
649 function saveGroups()
651 $enabled = common_config('inboxes', 'enabled');
652 if ($enabled !== true && $enabled !== 'transitional') {
656 /* extract all !group */
657 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
658 strtolower($this->content),
664 $profile = $this->getProfile();
666 /* Add them to the database */
668 foreach (array_unique($match[1]) as $nickname) {
669 /* XXX: remote groups. */
670 $group = User_group::staticGet('nickname', $nickname);
676 // we automatically add a tag for every group name, too
678 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
679 'notice_id' => $this->id));
682 $this->saveTag($nickname);
685 if ($profile->isMember($group)) {
687 $gi = new Group_inbox();
689 $gi->group_id = $group->id;
690 $gi->notice_id = $this->id;
691 $gi->created = common_sql_now();
693 $result = $gi->insert();
696 common_log_db_error($gi, 'INSERT', __FILE__);
699 // FIXME: do this in an offline daemon
701 $inbox = new Notice_inbox();
702 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
703 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
704 "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
705 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
706 'WHERE group_member.group_id = ' . $group->id . ' ' .
707 'AND NOT EXISTS (SELECT user_id, notice_id ' .
708 'FROM notice_inbox ' .
709 "WHERE user_id = $UT.id " .
710 'AND notice_id = ' . $this->id . ' )';
711 if ($enabled === 'transitional') {
712 $qry .= " AND $UT.inboxed = 1";
714 $result = $inbox->query($qry);
719 function saveReplies()
721 // Alternative reply format
723 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
726 // extract all @messages
727 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
731 if ($cnt || $tname) {
732 // XXX: is there another way to make an array copy?
733 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
736 $sender = Profile::staticGet($this->profile_id);
740 // store replied only for first @ (what user/notice what the reply directed,
741 // we assume first @ is it)
743 for ($i=0; $i<count($names); $i++) {
744 $nickname = $names[$i];
745 $recipient = common_relative_profile($sender, $nickname, $this->created);
749 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
750 $reply_for = $recipient;
751 $recipient_notice = $reply_for->getCurrentNotice();
752 if ($recipient_notice) {
753 $orig = clone($this);
754 $this->reply_to = $recipient_notice->id;
755 $this->conversation = $recipient_notice->conversation;
756 $this->update($orig);
759 // Don't save replies from blocked profile to local user
760 $recipient_user = User::staticGet('id', $recipient->id);
761 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
764 $reply = new Reply();
765 $reply->notice_id = $this->id;
766 $reply->profile_id = $recipient->id;
767 $id = $reply->insert();
769 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
770 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
771 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
774 $replied[$recipient->id] = 1;
778 // Hash format replies, too
779 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
781 foreach ($match[1] as $tag) {
782 $tagged = Profile_tag::getTagged($sender->id, $tag);
783 foreach ($tagged as $t) {
784 if (!$replied[$t->id]) {
785 // Don't save replies from blocked profile to local user
786 $t_user = User::staticGet('id', $t->id);
787 if ($t_user && $t_user->hasBlocked($sender)) {
790 $reply = new Reply();
791 $reply->notice_id = $this->id;
792 $reply->profile_id = $t->id;
793 $id = $reply->insert();
795 common_log_db_error($reply, 'INSERT', __FILE__);
798 $replied[$recipient->id] = 1;
805 // If it's not a reply, make it the root of a new conversation
807 if (empty($this->conversation)) {
808 $orig = clone($this);
809 $this->conversation = $this->id;
810 $this->update($orig);
813 foreach (array_keys($replied) as $recipient) {
814 $user = User::staticGet('id', $recipient);
816 mail_notify_attn($user, $this);