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);
67 return parent::delete();
72 /* extract all #hastags */
73 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
78 /* elide characters we don't want in the tag */
79 $match[1] = str_replace(array('-', '_', '.'), '', $match[1]);
81 /* Add them to the database */
82 foreach(array_unique($match[1]) as $hashtag) {
83 $tag = DB_DataObject::factory('Notice_tag');
84 $tag->notice_id = $this->id;
86 $tag->created = $this->created;
89 $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
90 common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
91 common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
98 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
100 $profile = Profile::staticGet($profile_id);
103 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
104 return _('Problem saving notice. Unknown user.');
107 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
108 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
109 return _('Too many notices too fast; take a breather and post again in a few minutes.');
112 $banned = common_config('profile', 'banned');
114 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
115 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
116 return _('You are banned from posting notices on this site.');
119 $notice = new Notice();
120 $notice->profile_id = $profile_id;
122 $blacklist = common_config('public', 'blacklist');
124 # Blacklisted are non-false, but not 1, either
126 if ($blacklist && in_array($profile_id, $blacklist)) {
127 $notice->is_local = -1;
129 $notice->is_local = $is_local;
132 $notice->reply_to = $reply_to;
133 $notice->created = common_sql_now();
134 $notice->content = common_shorten_links($content);
135 $notice->rendered = common_render_content($notice->content, $notice);
136 $notice->source = $source;
139 $id = $notice->insert();
142 common_log_db_error($notice, 'INSERT', __FILE__);
143 return _('Problem saving notice.');
146 # Update the URI after the notice is in the database
148 $orig = clone($notice);
149 $notice->uri = common_notice_uri($notice);
151 if (!$notice->update($orig)) {
152 common_log_db_error($notice, 'UPDATE', __FILE__);
153 return _('Problem saving notice.');
157 # XXX: do we need to change this for remote users?
159 common_save_replies($notice);
162 # Clear the cache for subscribed users, so they'll update at next request
163 # XXX: someone clever could prepend instead of clearing the cache
165 if (common_config('memcached', 'enabled')) {
166 $notice->blowCaches();
169 $notice->addToInboxes();
173 static function checkEditThrottle($profile_id) {
174 $profile = Profile::staticGet($profile_id);
179 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
180 if ($notice && $notice->fetch()) {
181 # If the Nth notice was posted less than timespan seconds ago
182 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
187 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
191 function blowCaches($blowLast=false)
193 $this->blowSubsCache($blowLast);
194 $this->blowNoticeCache($blowLast);
195 $this->blowRepliesCache($blowLast);
196 $this->blowPublicCache($blowLast);
197 $this->blowTagCache($blowLast);
200 function blowTagCache($blowLast=false)
202 $cache = common_memcache();
204 $tag = new Notice_tag();
205 $tag->notice_id = $this->id;
207 while ($tag->fetch()) {
208 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
210 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
219 function blowSubsCache($blowLast=false)
221 $cache = common_memcache();
225 $user->query('SELECT id ' .
226 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
227 'WHERE subscription.subscribed = ' . $this->profile_id);
229 while ($user->fetch()) {
230 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
232 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
240 function blowNoticeCache($blowLast=false)
242 if ($this->is_local) {
243 $cache = common_memcache();
245 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
247 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
253 function blowRepliesCache($blowLast=false)
255 $cache = common_memcache();
257 $reply = new Reply();
258 $reply->notice_id = $this->id;
259 if ($reply->find()) {
260 while ($reply->fetch()) {
261 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
263 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
272 function blowPublicCache($blowLast=false)
274 if ($this->is_local == 1) {
275 $cache = common_memcache();
277 $cache->delete(common_cache_key('public'));
279 $cache->delete(common_cache_key('public').';last');
285 function blowFavesCache($blowLast=false)
287 $cache = common_memcache();
290 $fave->notice_id = $this->id;
292 while ($fave->fetch()) {
293 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
295 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
304 # XXX: too many args; we need to move to named params or even a separate
305 # class for notice streams
307 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
309 if (common_config('memcached', 'enabled')) {
311 # Skip the cache if this is a since, since_id or before_id qry
312 if ($since_id > 0 || $before_id > 0 || $since) {
313 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
315 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
319 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
322 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
327 if (preg_match('/\bWHERE\b/i', $qry)) {
341 $qry .= ' notice.id > ' . $since_id;
344 if ($before_id > 0) {
353 $qry .= ' notice.id < ' . $before_id;
365 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
368 # Allow ORDER override
373 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
376 if (common_config('db','type') == 'pgsql') {
377 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
379 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
382 $notice = new Notice();
384 $notice->query($qry);
389 # XXX: this is pretty long and should probably be broken up into
390 # some helper functions
392 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
394 # If outside our cache window, just go to the DB
396 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
397 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
400 # Get the cache; if we can't, just go to the DB
402 $cache = common_memcache();
405 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
408 # Get the notices out of the cache
410 $notices = $cache->get(common_cache_key($cachekey));
412 # On a cache hit, return a DB-object-like wrapper
414 if ($notices !== false) {
415 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
419 # If the cache was invalidated because of new data being
420 # added, we can try and just get the new stuff. We keep an additional
421 # copy of the data at the key + ';last'
423 # No cache hit. Try to get the *last* cached version
425 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
429 # Reverse-chron order, so last ID is last.
431 $last_id = $last_notices[0]->id;
433 # XXX: this assumes monotonically increasing IDs; a fair
436 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
437 $last_id, null, $order, null);
440 $new_notices = array();
441 while ($new_notice->fetch()) {
442 $new_notices[] = clone($new_notice);
445 $notices = array_slice(array_merge($new_notices, $last_notices),
446 0, NOTICE_CACHE_WINDOW);
448 # Store the array in the cache for next time
450 $result = $cache->set(common_cache_key($cachekey), $notices);
451 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
453 # return a wrapper of the array for use now
455 return new NoticeWrapper(array_slice($notices, $offset, $limit));
459 # Otherwise, get the full cache window out of the DB
461 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
463 # If there are no hits, just return the value
469 # Pack results into an array
473 while ($notice->fetch()) {
474 $notices[] = clone($notice);
479 # Store the array in the cache for next time
481 $result = $cache->set(common_cache_key($cachekey), $notices);
482 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
484 # return a wrapper of the array for use now
486 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
491 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null)
496 $qry = 'SELECT * FROM notice ';
498 if (common_config('public', 'localonly')) {
499 $parts[] = 'is_local = 1';
502 $parts[] = 'is_local != -1';
506 $qry .= ' WHERE ' . implode(' AND ', $parts);
509 return Notice::getStream($qry,
511 $offset, $limit, $since_id, $before_id, null, $since);
514 function addToInboxes()
516 $enabled = common_config('inboxes', 'enabled');
518 if ($enabled === true || $enabled === 'transitional') {
519 $inbox = new Notice_inbox();
520 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
521 'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
522 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
523 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
524 'AND NOT EXISTS (SELECT user_id, notice_id ' .
525 'FROM notice_inbox ' .
526 'WHERE user_id = user.id ' .
527 'AND notice_id = ' . $this->id . ' )';
528 if ($enabled === 'transitional') {
529 $qry .= ' AND user.inboxed = 1';
536 # Delete from inboxes if we're deleted.
538 function blowInboxes()
541 $enabled = common_config('inboxes', 'enabled');
543 if ($enabled === true || $enabled === 'transitional') {
544 $inbox = new Notice_inbox();
545 $inbox->notice_id = $this->id;