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);
66 $this->blowSubsCache(true);
68 $this->query('BEGIN');
69 $related = array('Reply',
74 if (common_config('inboxes', 'enabled')) {
75 $related[] = 'Notice_inbox';
77 foreach ($related as $cls) {
79 $inst->notice_id = $this->id;
82 $result = parent::delete();
83 $this->query('COMMIT');
88 /* extract all #hastags */
89 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
94 /* Add them to the database */
95 foreach(array_unique($match[1]) as $hashtag) {
96 /* elide characters we don't want in the tag */
97 $this->saveTag($hashtag);
102 function saveTag($hashtag)
104 $hashtag = common_canonical_tag($hashtag);
106 $tag = new Notice_tag();
107 $tag->notice_id = $this->id;
108 $tag->tag = $hashtag;
109 $tag->created = $this->created;
110 $id = $tag->insert();
113 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
114 $last_error->message));
119 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
121 $profile = Profile::staticGet($profile_id);
124 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
125 return _('Problem saving notice. Unknown user.');
128 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
129 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
130 return _('Too many notices too fast; take a breather and post again in a few minutes.');
133 $banned = common_config('profile', 'banned');
135 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
136 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
137 return _('You are banned from posting notices on this site.');
140 $notice = new Notice();
141 $notice->profile_id = $profile_id;
143 $blacklist = common_config('public', 'blacklist');
144 $autosource = common_config('public', 'autosource');
146 # Blacklisted are non-false, but not 1, either
148 if (($blacklist && in_array($profile_id, $blacklist)) ||
149 ($source && $autosource && in_array($source, $autosource))) {
150 $notice->is_local = -1;
152 $notice->is_local = $is_local;
155 $notice->query('BEGIN');
157 $notice->reply_to = $reply_to;
158 $notice->created = common_sql_now();
159 $notice->content = common_shorten_links($content);
160 $notice->rendered = common_render_content($notice->content, $notice);
161 $notice->source = $source;
164 if (Event::handle('StartNoticeSave', array(&$notice))) {
166 $id = $notice->insert();
169 common_log_db_error($notice, 'INSERT', __FILE__);
170 return _('Problem saving notice.');
173 # Update the URI after the notice is in the database
175 $orig = clone($notice);
176 $notice->uri = common_notice_uri($notice);
178 if (!$notice->update($orig)) {
179 common_log_db_error($notice, 'UPDATE', __FILE__);
180 return _('Problem saving notice.');
184 # XXX: do we need to change this for remote users?
186 $notice->saveReplies();
188 $notice->saveGroups();
190 $notice->addToInboxes();
191 $notice->query('COMMIT');
193 Event::handle('EndNoticeSave', array($notice));
196 # Clear the cache for subscribed users, so they'll update at next request
197 # XXX: someone clever could prepend instead of clearing the cache
199 if (common_config('memcached', 'enabled')) {
200 $notice->blowCaches();
206 static function checkEditThrottle($profile_id) {
207 $profile = Profile::staticGet($profile_id);
212 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
213 if ($notice && $notice->fetch()) {
214 # If the Nth notice was posted less than timespan seconds ago
215 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
220 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
224 function blowCaches($blowLast=false)
226 $this->blowSubsCache($blowLast);
227 $this->blowNoticeCache($blowLast);
228 $this->blowRepliesCache($blowLast);
229 $this->blowPublicCache($blowLast);
230 $this->blowTagCache($blowLast);
231 $this->blowGroupCache($blowLast);
234 function blowGroupCache($blowLast=false)
236 $cache = common_memcache();
238 $group_inbox = new Group_inbox();
239 $group_inbox->notice_id = $this->id;
240 if ($group_inbox->find()) {
241 while ($group_inbox->fetch()) {
242 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
244 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
246 $member = new Group_member();
247 $member->group_id = $group_inbox->group_id;
248 if ($member->find()) {
249 while ($member->fetch()) {
250 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
252 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
258 $group_inbox->free();
263 function blowTagCache($blowLast=false)
265 $cache = common_memcache();
267 $tag = new Notice_tag();
268 $tag->notice_id = $this->id;
270 while ($tag->fetch()) {
271 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
273 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
282 function blowSubsCache($blowLast=false)
284 $cache = common_memcache();
288 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
289 $user->query('SELECT id ' .
291 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
292 'WHERE subscription.subscribed = ' . $this->profile_id);
294 while ($user->fetch()) {
295 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
297 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
305 function blowNoticeCache($blowLast=false)
307 if ($this->is_local) {
308 $cache = common_memcache();
310 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
312 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
318 function blowRepliesCache($blowLast=false)
320 $cache = common_memcache();
322 $reply = new Reply();
323 $reply->notice_id = $this->id;
324 if ($reply->find()) {
325 while ($reply->fetch()) {
326 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
328 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
337 function blowPublicCache($blowLast=false)
339 if ($this->is_local == 1) {
340 $cache = common_memcache();
342 $cache->delete(common_cache_key('public'));
344 $cache->delete(common_cache_key('public').';last');
350 function blowFavesCache($blowLast=false)
352 $cache = common_memcache();
355 $fave->notice_id = $this->id;
357 while ($fave->fetch()) {
358 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
360 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
369 # XXX: too many args; we need to move to named params or even a separate
370 # class for notice streams
372 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
374 if (common_config('memcached', 'enabled')) {
376 # Skip the cache if this is a since, since_id or before_id qry
377 if ($since_id > 0 || $before_id > 0 || $since) {
378 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
380 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
384 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
387 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
392 if (preg_match('/\bWHERE\b/i', $qry)) {
406 $qry .= ' notice.id > ' . $since_id;
409 if ($before_id > 0) {
418 $qry .= ' notice.id < ' . $before_id;
430 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
433 # Allow ORDER override
438 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
441 if (common_config('db','type') == 'pgsql') {
442 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
444 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
447 $notice = new Notice();
449 $notice->query($qry);
454 # XXX: this is pretty long and should probably be broken up into
455 # some helper functions
457 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
459 # If outside our cache window, just go to the DB
461 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
462 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
465 # Get the cache; if we can't, just go to the DB
467 $cache = common_memcache();
470 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
473 # Get the notices out of the cache
475 $notices = $cache->get(common_cache_key($cachekey));
477 # On a cache hit, return a DB-object-like wrapper
479 if ($notices !== false) {
480 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
484 # If the cache was invalidated because of new data being
485 # added, we can try and just get the new stuff. We keep an additional
486 # copy of the data at the key + ';last'
488 # No cache hit. Try to get the *last* cached version
490 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
494 # Reverse-chron order, so last ID is last.
496 $last_id = $last_notices[0]->id;
498 # XXX: this assumes monotonically increasing IDs; a fair
501 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
502 $last_id, null, $order, null);
505 $new_notices = array();
506 while ($new_notice->fetch()) {
507 $new_notices[] = clone($new_notice);
510 $notices = array_slice(array_merge($new_notices, $last_notices),
511 0, NOTICE_CACHE_WINDOW);
513 # Store the array in the cache for next time
515 $result = $cache->set(common_cache_key($cachekey), $notices);
516 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
518 # return a wrapper of the array for use now
520 return new ArrayWrapper(array_slice($notices, $offset, $limit));
524 # Otherwise, get the full cache window out of the DB
526 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
528 # If there are no hits, just return the value
534 # Pack results into an array
538 while ($notice->fetch()) {
539 $notices[] = clone($notice);
544 # Store the array in the cache for next time
546 $result = $cache->set(common_cache_key($cachekey), $notices);
547 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
549 # return a wrapper of the array for use now
551 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
556 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
561 $qry = 'SELECT * FROM notice ';
563 if (common_config('public', 'localonly')) {
564 $parts[] = 'is_local = 1';
567 $parts[] = 'is_local != -1';
571 $qry .= ' WHERE ' . implode(' AND ', $parts);
574 return Notice::getStream($qry,
576 $offset, $limit, $since_id, $before_id, null, $since);
579 function addToInboxes()
581 $enabled = common_config('inboxes', 'enabled');
583 if ($enabled === true || $enabled === 'transitional') {
584 $inbox = new Notice_inbox();
585 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
586 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
587 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '" ' .
588 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
589 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
590 'AND NOT EXISTS (SELECT user_id, notice_id ' .
591 'FROM notice_inbox ' .
592 "WHERE user_id = $UT.id " .
593 'AND notice_id = ' . $this->id . ' )';
594 if ($enabled === 'transitional') {
595 $qry .= " AND $UT.inboxed = 1";
602 function saveGroups()
604 $enabled = common_config('inboxes', 'enabled');
605 if ($enabled !== true && $enabled !== 'transitional') {
609 /* extract all !group */
610 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
611 strtolower($this->content),
617 $profile = $this->getProfile();
619 /* Add them to the database */
621 foreach (array_unique($match[1]) as $nickname) {
622 /* XXX: remote groups. */
623 $group = User_group::staticGet('nickname', $nickname);
629 // we automatically add a tag for every group name, too
631 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
632 'notice_id' => $this->id));
635 $this->saveTag($nickname);
638 if ($profile->isMember($group)) {
640 $gi = new Group_inbox();
642 $gi->group_id = $group->id;
643 $gi->notice_id = $this->id;
644 $gi->created = common_sql_now();
646 $result = $gi->insert();
649 common_log_db_error($gi, 'INSERT', __FILE__);
652 // FIXME: do this in an offline daemon
654 $inbox = new Notice_inbox();
655 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
656 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
657 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '", 2 ' .
658 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
659 'WHERE group_member.group_id = ' . $group->id . ' ' .
660 'AND NOT EXISTS (SELECT user_id, notice_id ' .
661 'FROM notice_inbox ' .
662 "WHERE user_id = $UT.id " .
663 'AND notice_id = ' . $this->id . ' )';
664 if ($enabled === 'transitional') {
665 $qry .= " AND $UT.inboxed = 1";
667 $result = $inbox->query($qry);
672 function saveReplies()
674 // Alternative reply format
676 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
679 // extract all @messages
680 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
684 if ($cnt || $tname) {
685 // XXX: is there another way to make an array copy?
686 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
689 $sender = Profile::staticGet($this->profile_id);
693 // store replied only for first @ (what user/notice what the reply directed,
694 // we assume first @ is it)
696 for ($i=0; $i<count($names); $i++) {
697 $nickname = $names[$i];
698 $recipient = common_relative_profile($sender, $nickname, $this->created);
702 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
703 $reply_for = $recipient;
704 $recipient_notice = $reply_for->getCurrentNotice();
705 if ($recipient_notice) {
706 $orig = clone($this);
707 $this->reply_to = $recipient_notice->id;
708 $this->update($orig);
711 // Don't save replies from blocked profile to local user
712 $recipient_user = User::staticGet('id', $recipient->id);
713 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
716 $reply = new Reply();
717 $reply->notice_id = $this->id;
718 $reply->profile_id = $recipient->id;
719 $id = $reply->insert();
721 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
722 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
723 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
726 $replied[$recipient->id] = 1;
730 // Hash format replies, too
731 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
733 foreach ($match[1] as $tag) {
734 $tagged = Profile_tag::getTagged($sender->id, $tag);
735 foreach ($tagged as $t) {
736 if (!$replied[$t->id]) {
737 // Don't save replies from blocked profile to local user
738 $t_user = User::staticGet('id', $t->id);
739 if ($t_user && $t_user->hasBlocked($sender)) {
742 $reply = new Reply();
743 $reply->notice_id = $this->id;
744 $reply->profile_id = $t->id;
745 $id = $reply->insert();
747 common_log_db_error($reply, 'INSERT', __FILE__);