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);
126 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
127 return _('Problem saving notice. Unknown user.');
130 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
131 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
132 return _('Too many notices too fast; take a breather and post again in a few minutes.');
135 $banned = common_config('profile', 'banned');
137 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
138 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
139 return _('You are banned from posting notices on this site.');
142 $notice = new Notice();
143 $notice->profile_id = $profile_id;
145 $blacklist = common_config('public', 'blacklist');
146 $autosource = common_config('public', 'autosource');
148 # Blacklisted are non-false, but not 1, either
150 if (($blacklist && in_array($profile_id, $blacklist)) ||
151 ($source && $autosource && in_array($source, $autosource))) {
152 $notice->is_local = -1;
154 $notice->is_local = $is_local;
157 $notice->query('BEGIN');
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 (!empty($reply_to)) {
166 $reply_notice = Notice::staticGet('id', $reply_to);
167 if (!empty($reply_notice)) {
168 $notice->reply_to = $reply_to;
169 $notice->conversation = $reply_notice->conversation;
173 if (Event::handle('StartNoticeSave', array(&$notice))) {
175 $id = $notice->insert();
178 common_log_db_error($notice, 'INSERT', __FILE__);
179 return _('Problem saving notice.');
182 # Update the URI after the notice is in the database
184 $orig = clone($notice);
185 $notice->uri = common_notice_uri($notice);
187 if (!$notice->update($orig)) {
188 common_log_db_error($notice, 'UPDATE', __FILE__);
189 return _('Problem saving notice.');
193 # XXX: do we need to change this for remote users?
195 $notice->saveReplies();
197 $notice->saveGroups();
199 $notice->addToInboxes();
200 $notice->query('COMMIT');
202 Event::handle('EndNoticeSave', array($notice));
205 # Clear the cache for subscribed users, so they'll update at next request
206 # XXX: someone clever could prepend instead of clearing the cache
208 if (common_config('memcached', 'enabled')) {
209 $notice->blowCaches();
215 static function checkEditThrottle($profile_id) {
216 $profile = Profile::staticGet($profile_id);
221 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
222 if ($notice && $notice->fetch()) {
223 # If the Nth notice was posted less than timespan seconds ago
224 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
229 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
233 function blowCaches($blowLast=false)
235 $this->blowSubsCache($blowLast);
236 $this->blowNoticeCache($blowLast);
237 $this->blowRepliesCache($blowLast);
238 $this->blowPublicCache($blowLast);
239 $this->blowTagCache($blowLast);
240 $this->blowGroupCache($blowLast);
243 function blowGroupCache($blowLast=false)
245 $cache = common_memcache();
247 $group_inbox = new Group_inbox();
248 $group_inbox->notice_id = $this->id;
249 if ($group_inbox->find()) {
250 while ($group_inbox->fetch()) {
251 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
253 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
255 $member = new Group_member();
256 $member->group_id = $group_inbox->group_id;
257 if ($member->find()) {
258 while ($member->fetch()) {
259 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
261 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
267 $group_inbox->free();
272 function blowTagCache($blowLast=false)
274 $cache = common_memcache();
276 $tag = new Notice_tag();
277 $tag->notice_id = $this->id;
279 while ($tag->fetch()) {
280 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
282 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
291 function blowSubsCache($blowLast=false)
293 $cache = common_memcache();
297 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
298 $user->query('SELECT id ' .
300 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
301 'WHERE subscription.subscribed = ' . $this->profile_id);
303 while ($user->fetch()) {
304 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
306 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
314 function blowNoticeCache($blowLast=false)
316 if ($this->is_local) {
317 $cache = common_memcache();
319 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
321 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
327 function blowRepliesCache($blowLast=false)
329 $cache = common_memcache();
331 $reply = new Reply();
332 $reply->notice_id = $this->id;
333 if ($reply->find()) {
334 while ($reply->fetch()) {
335 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
337 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
346 function blowPublicCache($blowLast=false)
348 if ($this->is_local == 1) {
349 $cache = common_memcache();
351 $cache->delete(common_cache_key('public'));
353 $cache->delete(common_cache_key('public').';last');
359 function blowFavesCache($blowLast=false)
361 $cache = common_memcache();
364 $fave->notice_id = $this->id;
366 while ($fave->fetch()) {
367 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
369 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
378 # XXX: too many args; we need to move to named params or even a separate
379 # class for notice streams
381 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
383 if (common_config('memcached', 'enabled')) {
385 # Skip the cache if this is a since, since_id or before_id qry
386 if ($since_id > 0 || $before_id > 0 || $since) {
387 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
389 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
393 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
396 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
401 if (preg_match('/\bWHERE\b/i', $qry)) {
415 $qry .= ' notice.id > ' . $since_id;
418 if ($before_id > 0) {
427 $qry .= ' notice.id < ' . $before_id;
439 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
442 # Allow ORDER override
447 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
450 if (common_config('db','type') == 'pgsql') {
451 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
453 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
456 $notice = new Notice();
458 $notice->query($qry);
463 # XXX: this is pretty long and should probably be broken up into
464 # some helper functions
466 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
468 # If outside our cache window, just go to the DB
470 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
471 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
474 # Get the cache; if we can't, just go to the DB
476 $cache = common_memcache();
479 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
482 # Get the notices out of the cache
484 $notices = $cache->get(common_cache_key($cachekey));
486 # On a cache hit, return a DB-object-like wrapper
488 if ($notices !== false) {
489 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
493 # If the cache was invalidated because of new data being
494 # added, we can try and just get the new stuff. We keep an additional
495 # copy of the data at the key + ';last'
497 # No cache hit. Try to get the *last* cached version
499 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
503 # Reverse-chron order, so last ID is last.
505 $last_id = $last_notices[0]->id;
507 # XXX: this assumes monotonically increasing IDs; a fair
510 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
511 $last_id, null, $order, null);
514 $new_notices = array();
515 while ($new_notice->fetch()) {
516 $new_notices[] = clone($new_notice);
519 $notices = array_slice(array_merge($new_notices, $last_notices),
520 0, NOTICE_CACHE_WINDOW);
522 # Store the array in the cache for next time
524 $result = $cache->set(common_cache_key($cachekey), $notices);
525 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
527 # return a wrapper of the array for use now
529 return new ArrayWrapper(array_slice($notices, $offset, $limit));
533 # Otherwise, get the full cache window out of the DB
535 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
537 # If there are no hits, just return the value
543 # Pack results into an array
547 while ($notice->fetch()) {
548 $notices[] = clone($notice);
553 # Store the array in the cache for next time
555 $result = $cache->set(common_cache_key($cachekey), $notices);
556 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
558 # return a wrapper of the array for use now
560 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
565 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
570 $qry = 'SELECT * FROM notice ';
572 if (common_config('public', 'localonly')) {
573 $parts[] = 'is_local = 1';
576 $parts[] = 'is_local != -1';
580 $qry .= ' WHERE ' . implode(' AND ', $parts);
583 return Notice::getStream($qry,
585 $offset, $limit, $since_id, $before_id, null, $since);
588 function addToInboxes()
590 $enabled = common_config('inboxes', 'enabled');
592 if ($enabled === true || $enabled === 'transitional') {
593 $inbox = new Notice_inbox();
594 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
595 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
596 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '" ' .
597 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
598 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
599 'AND NOT EXISTS (SELECT user_id, notice_id ' .
600 'FROM notice_inbox ' .
601 "WHERE user_id = $UT.id " .
602 'AND notice_id = ' . $this->id . ' )';
603 if ($enabled === 'transitional') {
604 $qry .= " AND $UT.inboxed = 1";
611 function saveGroups()
613 $enabled = common_config('inboxes', 'enabled');
614 if ($enabled !== true && $enabled !== 'transitional') {
618 /* extract all !group */
619 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
620 strtolower($this->content),
626 $profile = $this->getProfile();
628 /* Add them to the database */
630 foreach (array_unique($match[1]) as $nickname) {
631 /* XXX: remote groups. */
632 $group = User_group::staticGet('nickname', $nickname);
638 // we automatically add a tag for every group name, too
640 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
641 'notice_id' => $this->id));
644 $this->saveTag($nickname);
647 if ($profile->isMember($group)) {
649 $gi = new Group_inbox();
651 $gi->group_id = $group->id;
652 $gi->notice_id = $this->id;
653 $gi->created = common_sql_now();
655 $result = $gi->insert();
658 common_log_db_error($gi, 'INSERT', __FILE__);
661 // FIXME: do this in an offline daemon
663 $inbox = new Notice_inbox();
664 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
665 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
666 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '", 2 ' .
667 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
668 'WHERE group_member.group_id = ' . $group->id . ' ' .
669 'AND NOT EXISTS (SELECT user_id, notice_id ' .
670 'FROM notice_inbox ' .
671 "WHERE user_id = $UT.id " .
672 'AND notice_id = ' . $this->id . ' )';
673 if ($enabled === 'transitional') {
674 $qry .= " AND $UT.inboxed = 1";
676 $result = $inbox->query($qry);
681 function saveReplies()
683 // Alternative reply format
685 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
688 // extract all @messages
689 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
693 if ($cnt || $tname) {
694 // XXX: is there another way to make an array copy?
695 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
698 $sender = Profile::staticGet($this->profile_id);
702 // store replied only for first @ (what user/notice what the reply directed,
703 // we assume first @ is it)
705 for ($i=0; $i<count($names); $i++) {
706 $nickname = $names[$i];
707 $recipient = common_relative_profile($sender, $nickname, $this->created);
711 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
712 $reply_for = $recipient;
713 $recipient_notice = $reply_for->getCurrentNotice();
714 if ($recipient_notice) {
715 $orig = clone($this);
716 $this->reply_to = $recipient_notice->id;
717 $this->conversation = $recipient_notice->conversation;
718 $this->update($orig);
721 // Don't save replies from blocked profile to local user
722 $recipient_user = User::staticGet('id', $recipient->id);
723 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
726 $reply = new Reply();
727 $reply->notice_id = $this->id;
728 $reply->profile_id = $recipient->id;
729 $id = $reply->insert();
731 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
732 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
733 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
736 $replied[$recipient->id] = 1;
740 // Hash format replies, too
741 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
743 foreach ($match[1] as $tag) {
744 $tagged = Profile_tag::getTagged($sender->id, $tag);
745 foreach ($tagged as $t) {
746 if (!$replied[$t->id]) {
747 // Don't save replies from blocked profile to local user
748 $t_user = User::staticGet('id', $t->id);
749 if ($t_user && $t_user->hasBlocked($sender)) {
752 $reply = new Reply();
753 $reply->notice_id = $this->id;
754 $reply->profile_id = $t->id;
755 $id = $reply->insert();
757 common_log_db_error($reply, 'INSERT', __FILE__);
760 $replied[$recipient->id] = 1;
767 // If it's not a reply, make it the root of a new conversation
769 if (empty($this->conversation)) {
770 $orig = clone($this);
771 $this->conversation = $this->id;
772 $this->update($orig);
775 foreach (array_keys($replied) as $recipient) {
776 $user = User::staticGet('id', $recipient);
778 mail_notify_attn($user, $this);