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);
125 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
126 return _('Problem saving notice. Unknown user.');
129 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
130 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
131 return _('Too many notices too fast; take a breather and post again in a few minutes.');
134 $banned = common_config('profile', 'banned');
136 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
137 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
138 return _('You are banned from posting notices on this site.');
141 $notice = new Notice();
142 $notice->profile_id = $profile_id;
144 $blacklist = common_config('public', 'blacklist');
145 $autosource = common_config('public', 'autosource');
147 # Blacklisted are non-false, but not 1, either
149 if (($blacklist && in_array($profile_id, $blacklist)) ||
150 ($source && $autosource && in_array($source, $autosource))) {
151 $notice->is_local = -1;
153 $notice->is_local = $is_local;
156 $notice->query('BEGIN');
158 $notice->reply_to = $reply_to;
159 $notice->created = common_sql_now();
160 $notice->content = common_shorten_links($content);
161 $notice->rendered = common_render_content($notice->content, $notice);
162 $notice->source = $source;
165 if (Event::handle('StartNoticeSave', array(&$notice))) {
167 $id = $notice->insert();
170 common_log_db_error($notice, 'INSERT', __FILE__);
171 return _('Problem saving notice.');
174 # Update the URI after the notice is in the database
176 $orig = clone($notice);
177 $notice->uri = common_notice_uri($notice);
179 if (!$notice->update($orig)) {
180 common_log_db_error($notice, 'UPDATE', __FILE__);
181 return _('Problem saving notice.');
185 # XXX: do we need to change this for remote users?
187 $notice->saveReplies();
189 $notice->saveGroups();
191 $notice->addToInboxes();
192 $notice->query('COMMIT');
194 Event::handle('EndNoticeSave', array($notice));
197 # Clear the cache for subscribed users, so they'll update at next request
198 # XXX: someone clever could prepend instead of clearing the cache
200 if (common_config('memcached', 'enabled')) {
201 $notice->blowCaches();
207 static function checkEditThrottle($profile_id) {
208 $profile = Profile::staticGet($profile_id);
213 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
214 if ($notice && $notice->fetch()) {
215 # If the Nth notice was posted less than timespan seconds ago
216 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
221 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
225 function blowCaches($blowLast=false)
227 $this->blowSubsCache($blowLast);
228 $this->blowNoticeCache($blowLast);
229 $this->blowRepliesCache($blowLast);
230 $this->blowPublicCache($blowLast);
231 $this->blowTagCache($blowLast);
232 $this->blowGroupCache($blowLast);
235 function blowGroupCache($blowLast=false)
237 $cache = common_memcache();
239 $group_inbox = new Group_inbox();
240 $group_inbox->notice_id = $this->id;
241 if ($group_inbox->find()) {
242 while ($group_inbox->fetch()) {
243 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
245 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
247 $member = new Group_member();
248 $member->group_id = $group_inbox->group_id;
249 if ($member->find()) {
250 while ($member->fetch()) {
251 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
253 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
259 $group_inbox->free();
264 function blowTagCache($blowLast=false)
266 $cache = common_memcache();
268 $tag = new Notice_tag();
269 $tag->notice_id = $this->id;
271 while ($tag->fetch()) {
272 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
274 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
283 function blowSubsCache($blowLast=false)
285 $cache = common_memcache();
289 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
290 $user->query('SELECT id ' .
292 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
293 'WHERE subscription.subscribed = ' . $this->profile_id);
295 while ($user->fetch()) {
296 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
298 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
306 function blowNoticeCache($blowLast=false)
308 if ($this->is_local) {
309 $cache = common_memcache();
311 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
313 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
319 function blowRepliesCache($blowLast=false)
321 $cache = common_memcache();
323 $reply = new Reply();
324 $reply->notice_id = $this->id;
325 if ($reply->find()) {
326 while ($reply->fetch()) {
327 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
329 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
338 function blowPublicCache($blowLast=false)
340 if ($this->is_local == 1) {
341 $cache = common_memcache();
343 $cache->delete(common_cache_key('public'));
345 $cache->delete(common_cache_key('public').';last');
351 function blowFavesCache($blowLast=false)
353 $cache = common_memcache();
356 $fave->notice_id = $this->id;
358 while ($fave->fetch()) {
359 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
361 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
370 # XXX: too many args; we need to move to named params or even a separate
371 # class for notice streams
373 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
375 if (common_config('memcached', 'enabled')) {
377 # Skip the cache if this is a since, since_id or before_id qry
378 if ($since_id > 0 || $before_id > 0 || $since) {
379 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
381 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
385 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
388 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
393 if (preg_match('/\bWHERE\b/i', $qry)) {
407 $qry .= ' notice.id > ' . $since_id;
410 if ($before_id > 0) {
419 $qry .= ' notice.id < ' . $before_id;
431 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
434 # Allow ORDER override
439 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
442 if (common_config('db','type') == 'pgsql') {
443 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
445 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
448 $notice = new Notice();
450 $notice->query($qry);
455 # XXX: this is pretty long and should probably be broken up into
456 # some helper functions
458 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
460 # If outside our cache window, just go to the DB
462 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
463 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
466 # Get the cache; if we can't, just go to the DB
468 $cache = common_memcache();
471 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
474 # Get the notices out of the cache
476 $notices = $cache->get(common_cache_key($cachekey));
478 # On a cache hit, return a DB-object-like wrapper
480 if ($notices !== false) {
481 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
485 # If the cache was invalidated because of new data being
486 # added, we can try and just get the new stuff. We keep an additional
487 # copy of the data at the key + ';last'
489 # No cache hit. Try to get the *last* cached version
491 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
495 # Reverse-chron order, so last ID is last.
497 $last_id = $last_notices[0]->id;
499 # XXX: this assumes monotonically increasing IDs; a fair
502 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
503 $last_id, null, $order, null);
506 $new_notices = array();
507 while ($new_notice->fetch()) {
508 $new_notices[] = clone($new_notice);
511 $notices = array_slice(array_merge($new_notices, $last_notices),
512 0, NOTICE_CACHE_WINDOW);
514 # Store the array in the cache for next time
516 $result = $cache->set(common_cache_key($cachekey), $notices);
517 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
519 # return a wrapper of the array for use now
521 return new ArrayWrapper(array_slice($notices, $offset, $limit));
525 # Otherwise, get the full cache window out of the DB
527 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
529 # If there are no hits, just return the value
535 # Pack results into an array
539 while ($notice->fetch()) {
540 $notices[] = clone($notice);
545 # Store the array in the cache for next time
547 $result = $cache->set(common_cache_key($cachekey), $notices);
548 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
550 # return a wrapper of the array for use now
552 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
557 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
562 $qry = 'SELECT * FROM notice ';
564 if (common_config('public', 'localonly')) {
565 $parts[] = 'is_local = 1';
568 $parts[] = 'is_local != -1';
572 $qry .= ' WHERE ' . implode(' AND ', $parts);
575 return Notice::getStream($qry,
577 $offset, $limit, $since_id, $before_id, null, $since);
580 function addToInboxes()
582 $enabled = common_config('inboxes', 'enabled');
584 if ($enabled === true || $enabled === 'transitional') {
585 $inbox = new Notice_inbox();
586 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
587 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
588 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '" ' .
589 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
590 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
591 'AND NOT EXISTS (SELECT user_id, notice_id ' .
592 'FROM notice_inbox ' .
593 "WHERE user_id = $UT.id " .
594 'AND notice_id = ' . $this->id . ' )';
595 if ($enabled === 'transitional') {
596 $qry .= " AND $UT.inboxed = 1";
603 function saveGroups()
605 $enabled = common_config('inboxes', 'enabled');
606 if ($enabled !== true && $enabled !== 'transitional') {
610 /* extract all !group */
611 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
612 strtolower($this->content),
618 $profile = $this->getProfile();
620 /* Add them to the database */
622 foreach (array_unique($match[1]) as $nickname) {
623 /* XXX: remote groups. */
624 $group = User_group::staticGet('nickname', $nickname);
630 // we automatically add a tag for every group name, too
632 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
633 'notice_id' => $this->id));
636 $this->saveTag($nickname);
639 if ($profile->isMember($group)) {
641 $gi = new Group_inbox();
643 $gi->group_id = $group->id;
644 $gi->notice_id = $this->id;
645 $gi->created = common_sql_now();
647 $result = $gi->insert();
650 common_log_db_error($gi, 'INSERT', __FILE__);
653 // FIXME: do this in an offline daemon
655 $inbox = new Notice_inbox();
656 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
657 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
658 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '", 2 ' .
659 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
660 'WHERE group_member.group_id = ' . $group->id . ' ' .
661 'AND NOT EXISTS (SELECT user_id, notice_id ' .
662 'FROM notice_inbox ' .
663 "WHERE user_id = $UT.id " .
664 'AND notice_id = ' . $this->id . ' )';
665 if ($enabled === 'transitional') {
666 $qry .= " AND $UT.inboxed = 1";
668 $result = $inbox->query($qry);
673 function saveReplies()
675 // Alternative reply format
677 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
680 // extract all @messages
681 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
685 if ($cnt || $tname) {
686 // XXX: is there another way to make an array copy?
687 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
690 $sender = Profile::staticGet($this->profile_id);
694 // store replied only for first @ (what user/notice what the reply directed,
695 // we assume first @ is it)
697 for ($i=0; $i<count($names); $i++) {
698 $nickname = $names[$i];
699 $recipient = common_relative_profile($sender, $nickname, $this->created);
703 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
704 $reply_for = $recipient;
705 $recipient_notice = $reply_for->getCurrentNotice();
706 if ($recipient_notice) {
707 $orig = clone($this);
708 $this->reply_to = $recipient_notice->id;
709 $this->update($orig);
712 // Don't save replies from blocked profile to local user
713 $recipient_user = User::staticGet('id', $recipient->id);
714 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
717 $reply = new Reply();
718 $reply->notice_id = $this->id;
719 $reply->profile_id = $recipient->id;
720 $id = $reply->insert();
722 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
723 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
724 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
727 $replied[$recipient->id] = 1;
731 // Hash format replies, too
732 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
734 foreach ($match[1] as $tag) {
735 $tagged = Profile_tag::getTagged($sender->id, $tag);
736 foreach ($tagged as $t) {
737 if (!$replied[$t->id]) {
738 // Don't save replies from blocked profile to local user
739 $t_user = User::staticGet('id', $t->id);
740 if ($t_user && $t_user->hasBlocked($sender)) {
743 $reply = new Reply();
744 $reply->notice_id = $this->id;
745 $reply->profile_id = $t->id;
746 $id = $reply->insert();
748 common_log_db_error($reply, 'INSERT', __FILE__);
751 $replied[$recipient->id] = 1;
758 foreach (array_keys($replied) as $recipient) {
759 $user = User::staticGet('id', $recipient);
761 mail_notify_attn($user, $this);