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 $hashtag = common_canonical_tag($hashtag);
99 $tag = DB_DataObject::factory('Notice_tag');
100 $tag->notice_id = $this->id;
101 $tag->tag = $hashtag;
102 $tag->created = $this->created;
103 $id = $tag->insert();
105 $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
106 common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
107 common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
114 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
116 $profile = Profile::staticGet($profile_id);
119 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
120 return _('Problem saving notice. Unknown user.');
123 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
124 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
125 return _('Too many notices too fast; take a breather and post again in a few minutes.');
128 $banned = common_config('profile', 'banned');
130 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
131 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
132 return _('You are banned from posting notices on this site.');
135 $notice = new Notice();
136 $notice->profile_id = $profile_id;
138 $blacklist = common_config('public', 'blacklist');
140 # Blacklisted are non-false, but not 1, either
142 if ($blacklist && in_array($profile_id, $blacklist)) {
143 $notice->is_local = -1;
145 $notice->is_local = $is_local;
148 $notice->query('BEGIN');
150 $notice->reply_to = $reply_to;
151 $notice->created = common_sql_now();
152 $notice->content = common_shorten_links($content);
153 $notice->rendered = common_render_content($notice->content, $notice);
154 $notice->source = $source;
157 if (Event::handle('StartNoticeSave', array(&$notice))) {
159 $id = $notice->insert();
162 common_log_db_error($notice, 'INSERT', __FILE__);
163 return _('Problem saving notice.');
166 # Update the URI after the notice is in the database
168 $orig = clone($notice);
169 $notice->uri = common_notice_uri($notice);
171 if (!$notice->update($orig)) {
172 common_log_db_error($notice, 'UPDATE', __FILE__);
173 return _('Problem saving notice.');
177 # XXX: do we need to change this for remote users?
179 $notice->saveReplies();
181 $notice->saveGroups();
183 $notice->addToInboxes();
184 $notice->query('COMMIT');
186 Event::handle('EndNoticeSave', array($notice));
189 # Clear the cache for subscribed users, so they'll update at next request
190 # XXX: someone clever could prepend instead of clearing the cache
192 if (common_config('memcached', 'enabled')) {
193 $notice->blowCaches();
199 static function checkEditThrottle($profile_id) {
200 $profile = Profile::staticGet($profile_id);
205 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
206 if ($notice && $notice->fetch()) {
207 # If the Nth notice was posted less than timespan seconds ago
208 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
213 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
217 function blowCaches($blowLast=false)
219 $this->blowSubsCache($blowLast);
220 $this->blowNoticeCache($blowLast);
221 $this->blowRepliesCache($blowLast);
222 $this->blowPublicCache($blowLast);
223 $this->blowTagCache($blowLast);
224 $this->blowGroupCache($blowLast);
227 function blowGroupCache($blowLast=false)
229 $cache = common_memcache();
231 $group_inbox = new Group_inbox();
232 $group_inbox->notice_id = $this->id;
233 if ($group_inbox->find()) {
234 while ($group_inbox->fetch()) {
235 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id));
237 $cache->delete(common_cache_key('group:notices:'.$group_inbox->group_id.';last'));
239 $member = new Group_member();
240 $member->group_id = $group_inbox->group_id;
241 if ($member->find()) {
242 while ($member->fetch()) {
243 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id));
245 $cache->delete(common_cache_key('user:notices_with_friends:' . $member->profile_id . ';last'));
251 $group_inbox->free();
256 function blowTagCache($blowLast=false)
258 $cache = common_memcache();
260 $tag = new Notice_tag();
261 $tag->notice_id = $this->id;
263 while ($tag->fetch()) {
264 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
266 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
275 function blowSubsCache($blowLast=false)
277 $cache = common_memcache();
281 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
282 $user->query('SELECT id ' .
284 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
285 'WHERE subscription.subscribed = ' . $this->profile_id);
287 while ($user->fetch()) {
288 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
290 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
298 function blowNoticeCache($blowLast=false)
300 if ($this->is_local) {
301 $cache = common_memcache();
303 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
305 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
311 function blowRepliesCache($blowLast=false)
313 $cache = common_memcache();
315 $reply = new Reply();
316 $reply->notice_id = $this->id;
317 if ($reply->find()) {
318 while ($reply->fetch()) {
319 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
321 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
330 function blowPublicCache($blowLast=false)
332 if ($this->is_local == 1) {
333 $cache = common_memcache();
335 $cache->delete(common_cache_key('public'));
337 $cache->delete(common_cache_key('public').';last');
343 function blowFavesCache($blowLast=false)
345 $cache = common_memcache();
348 $fave->notice_id = $this->id;
350 while ($fave->fetch()) {
351 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
353 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
362 # XXX: too many args; we need to move to named params or even a separate
363 # class for notice streams
365 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
367 if (common_config('memcached', 'enabled')) {
369 # Skip the cache if this is a since, since_id or before_id qry
370 if ($since_id > 0 || $before_id > 0 || $since) {
371 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
373 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
377 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
380 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
385 if (preg_match('/\bWHERE\b/i', $qry)) {
399 $qry .= ' notice.id > ' . $since_id;
402 if ($before_id > 0) {
411 $qry .= ' notice.id < ' . $before_id;
423 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
426 # Allow ORDER override
431 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
434 if (common_config('db','type') == 'pgsql') {
435 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
437 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
440 $notice = new Notice();
442 $notice->query($qry);
447 # XXX: this is pretty long and should probably be broken up into
448 # some helper functions
450 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
452 # If outside our cache window, just go to the DB
454 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
455 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
458 # Get the cache; if we can't, just go to the DB
460 $cache = common_memcache();
463 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
466 # Get the notices out of the cache
468 $notices = $cache->get(common_cache_key($cachekey));
470 # On a cache hit, return a DB-object-like wrapper
472 if ($notices !== false) {
473 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
477 # If the cache was invalidated because of new data being
478 # added, we can try and just get the new stuff. We keep an additional
479 # copy of the data at the key + ';last'
481 # No cache hit. Try to get the *last* cached version
483 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
487 # Reverse-chron order, so last ID is last.
489 $last_id = $last_notices[0]->id;
491 # XXX: this assumes monotonically increasing IDs; a fair
494 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
495 $last_id, null, $order, null);
498 $new_notices = array();
499 while ($new_notice->fetch()) {
500 $new_notices[] = clone($new_notice);
503 $notices = array_slice(array_merge($new_notices, $last_notices),
504 0, NOTICE_CACHE_WINDOW);
506 # Store the array in the cache for next time
508 $result = $cache->set(common_cache_key($cachekey), $notices);
509 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
511 # return a wrapper of the array for use now
513 return new ArrayWrapper(array_slice($notices, $offset, $limit));
517 # Otherwise, get the full cache window out of the DB
519 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
521 # If there are no hits, just return the value
527 # Pack results into an array
531 while ($notice->fetch()) {
532 $notices[] = clone($notice);
537 # Store the array in the cache for next time
539 $result = $cache->set(common_cache_key($cachekey), $notices);
540 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
542 # return a wrapper of the array for use now
544 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
549 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
554 $qry = 'SELECT * FROM notice ';
556 if (common_config('public', 'localonly')) {
557 $parts[] = 'is_local = 1';
560 $parts[] = 'is_local != -1';
564 $qry .= ' WHERE ' . implode(' AND ', $parts);
567 return Notice::getStream($qry,
569 $offset, $limit, $since_id, $before_id, null, $since);
572 function addToInboxes()
574 $enabled = common_config('inboxes', 'enabled');
576 if ($enabled === true || $enabled === 'transitional') {
577 $inbox = new Notice_inbox();
578 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
579 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
580 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '" ' .
581 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
582 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
583 'AND NOT EXISTS (SELECT user_id, notice_id ' .
584 'FROM notice_inbox ' .
585 "WHERE user_id = $UT.id " .
586 'AND notice_id = ' . $this->id . ' )';
587 if ($enabled === 'transitional') {
588 $qry .= " AND $UT.inboxed = 1";
595 function saveGroups()
597 $enabled = common_config('inboxes', 'enabled');
598 if ($enabled !== true && $enabled !== 'transitional') {
602 /* extract all !group */
603 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
604 strtolower($this->content),
610 $profile = $this->getProfile();
612 /* Add them to the database */
614 foreach (array_unique($match[1]) as $nickname) {
615 /* XXX: remote groups. */
616 $group = User_group::staticGet('nickname', $nickname);
622 if ($profile->isMember($group)) {
624 $gi = new Group_inbox();
626 $gi->group_id = $group->id;
627 $gi->notice_id = $this->id;
628 $gi->created = common_sql_now();
630 $result = $gi->insert();
633 common_log_db_error($gi, 'INSERT', __FILE__);
636 // FIXME: do this in an offline daemon
638 $inbox = new Notice_inbox();
639 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
640 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
641 "SELECT $UT.id, " . $this->id . ', "' . $this->created . '", 2 ' .
642 "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
643 'WHERE group_member.group_id = ' . $group->id . ' ' .
644 'AND NOT EXISTS (SELECT user_id, notice_id ' .
645 'FROM notice_inbox ' .
646 "WHERE user_id = $UT.id " .
647 'AND notice_id = ' . $this->id . ' )';
648 if ($enabled === 'transitional') {
649 $qry .= " AND $UT.inboxed = 1";
651 $result = $inbox->query($qry);
656 function saveReplies()
658 // Alternative reply format
660 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
663 // extract all @messages
664 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
668 if ($cnt || $tname) {
669 // XXX: is there another way to make an array copy?
670 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
673 $sender = Profile::staticGet($this->profile_id);
677 // store replied only for first @ (what user/notice what the reply directed,
678 // we assume first @ is it)
680 for ($i=0; $i<count($names); $i++) {
681 $nickname = $names[$i];
682 $recipient = common_relative_profile($sender, $nickname, $this->created);
686 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
687 $reply_for = $recipient;
688 $recipient_notice = $reply_for->getCurrentNotice();
689 if ($recipient_notice) {
690 $orig = clone($this);
691 $this->reply_to = $recipient_notice->id;
692 $this->update($orig);
695 // Don't save replies from blocked profile to local user
696 $recipient_user = User::staticGet('id', $recipient->id);
697 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
700 $reply = new Reply();
701 $reply->notice_id = $this->id;
702 $reply->profile_id = $recipient->id;
703 $id = $reply->insert();
705 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
706 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
707 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
710 $replied[$recipient->id] = 1;
714 // Hash format replies, too
715 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
717 foreach ($match[1] as $tag) {
718 $tagged = Profile_tag::getTagged($sender->id, $tag);
719 foreach ($tagged as $t) {
720 if (!$replied[$t->id]) {
721 // Don't save replies from blocked profile to local user
722 $t_user = User::staticGet('id', $t->id);
723 if ($t_user && $t_user->hasBlocked($sender)) {
726 $reply = new Reply();
727 $reply->notice_id = $this->id;
728 $reply->profile_id = $t->id;
729 $id = $reply->insert();
731 common_log_db_error($reply, 'INSERT', __FILE__);