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) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
53 /* the code above is auto generated do not remove the tag below */
56 function getProfile() {
57 return Profile::staticGet('id', $this->profile_id);
61 $this->blowCaches(true);
62 $this->blowFavesCache(true);
64 return parent::delete();
68 /* extract all #hastags */
69 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
74 /* elide characters we don't want in the tag */
75 $match[1] = str_replace(array('-', '_', '.'), '', $match[1]);
77 /* Add them to the database */
78 foreach(array_unique($match[1]) as $hashtag) {
79 $tag = DB_DataObject::factory('Notice_tag');
80 $tag->notice_id = $this->id;
82 $tag->created = $this->created;
85 $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
86 common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
87 common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
94 static function saveNew($profile_id, $content, $source=null, $is_local=1, $reply_to=null, $uri=null) {
96 $profile = Profile::staticGet($profile_id);
99 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
100 return _('Problem saving notice. Unknown user.');
103 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
104 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
105 return _('Too many notices too fast; take a breather and post again in a few minutes.');
108 $banned = common_config('profile', 'banned');
110 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
111 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
112 return _('You are banned from posting notices on this site.');
115 $notice = new Notice();
116 $notice->profile_id = $profile_id;
118 $blacklist = common_config('public', 'blacklist');
120 # Blacklisted are non-false, but not 1, either
122 if ($blacklist && in_array($profile_id, $blacklist)) {
123 $notice->is_local = -1;
125 $notice->is_local = $is_local;
128 $notice->reply_to = $reply_to;
129 $notice->created = common_sql_now();
130 $notice->content = common_shorten_links($content);
131 $notice->rendered = common_render_content($notice->content, $notice);
132 $notice->source = $source;
135 $id = $notice->insert();
138 common_log_db_error($notice, 'INSERT', __FILE__);
139 return _('Problem saving notice.');
142 # Update the URI after the notice is in the database
144 $orig = clone($notice);
145 $notice->uri = common_notice_uri($notice);
147 if (!$notice->update($orig)) {
148 common_log_db_error($notice, 'UPDATE', __FILE__);
149 return _('Problem saving notice.');
153 # XXX: do we need to change this for remote users?
155 common_save_replies($notice);
158 # Clear the cache for subscribed users, so they'll update at next request
159 # XXX: someone clever could prepend instead of clearing the cache
161 if (common_config('memcached', 'enabled')) {
162 $notice->blowCaches();
165 $notice->addToInboxes();
169 static function checkEditThrottle($profile_id) {
170 $profile = Profile::staticGet($profile_id);
175 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
176 if ($notice && $notice->fetch()) {
177 # If the Nth notice was posted less than timespan seconds ago
178 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
183 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
187 function blowCaches($blowLast=false) {
188 $this->blowSubsCache($blowLast);
189 $this->blowNoticeCache($blowLast);
190 $this->blowRepliesCache($blowLast);
191 $this->blowPublicCache($blowLast);
192 $this->blowTagCache($blowLast);
195 function blowTagCache($blowLast=false) {
196 $cache = common_memcache();
198 $tag = new Notice_tag();
199 $tag->notice_id = $this->id;
201 while ($tag->fetch()) {
202 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
204 $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
213 function blowSubsCache($blowLast=false) {
214 $cache = common_memcache();
218 $user->query('SELECT id ' .
219 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
220 'WHERE subscription.subscribed = ' . $this->profile_id);
222 while ($user->fetch()) {
223 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
225 $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
233 function blowNoticeCache($blowLast=false) {
234 if ($this->is_local) {
235 $cache = common_memcache();
237 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
239 $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
245 function blowRepliesCache($blowLast=false) {
246 $cache = common_memcache();
248 $reply = new Reply();
249 $reply->notice_id = $this->id;
250 if ($reply->find()) {
251 while ($reply->fetch()) {
252 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
254 $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
263 function blowPublicCache($blowLast=false) {
264 if ($this->is_local == 1) {
265 $cache = common_memcache();
267 $cache->delete(common_cache_key('public'));
269 $cache->delete(common_cache_key('public').';last');
275 function blowFavesCache($blowLast=false) {
276 $cache = common_memcache();
279 $fave->notice_id = $this->id;
281 while ($fave->fetch()) {
282 $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
284 $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
293 # XXX: too many args; we need to move to named params or even a separate
294 # class for notice streams
296 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=null, $since=null) {
298 if (common_config('memcached', 'enabled')) {
300 # Skip the cache if this is a since, since_id or before_id qry
301 if ($since_id > 0 || $before_id > 0 || $since) {
302 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
304 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
308 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
311 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
316 if (preg_match('/\bWHERE\b/i', $qry)) {
330 $qry .= ' notice.id > ' . $since_id;
333 if ($before_id > 0) {
342 $qry .= ' notice.id < ' . $before_id;
354 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
357 # Allow ORDER override
362 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
365 if (common_config('db','type') == 'pgsql') {
366 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
368 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
371 $notice = new Notice();
373 $notice->query($qry);
378 # XXX: this is pretty long and should probably be broken up into
379 # some helper functions
381 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
383 # If outside our cache window, just go to the DB
385 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
386 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
389 # Get the cache; if we can't, just go to the DB
391 $cache = common_memcache();
394 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
397 # Get the notices out of the cache
399 $notices = $cache->get(common_cache_key($cachekey));
401 # On a cache hit, return a DB-object-like wrapper
403 if ($notices !== FALSE) {
404 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
408 # If the cache was invalidated because of new data being
409 # added, we can try and just get the new stuff. We keep an additional
410 # copy of the data at the key + ';last'
412 # No cache hit. Try to get the *last* cached version
414 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
418 # Reverse-chron order, so last ID is last.
420 $last_id = $last_notices[0]->id;
422 # XXX: this assumes monotonically increasing IDs; a fair
425 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
426 $last_id, null, $order, null);
429 $new_notices = array();
430 while ($new_notice->fetch()) {
431 $new_notices[] = clone($new_notice);
434 $notices = array_slice(array_merge($new_notices, $last_notices),
435 0, NOTICE_CACHE_WINDOW);
437 # Store the array in the cache for next time
439 $result = $cache->set(common_cache_key($cachekey), $notices);
440 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
442 # return a wrapper of the array for use now
444 return new NoticeWrapper(array_slice($notices, $offset, $limit));
448 # Otherwise, get the full cache window out of the DB
450 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
452 # If there are no hits, just return the value
458 # Pack results into an array
462 while ($notice->fetch()) {
463 $notices[] = clone($notice);
468 # Store the array in the cache for next time
470 $result = $cache->set(common_cache_key($cachekey), $notices);
471 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
473 # return a wrapper of the array for use now
475 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
480 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=null) {
484 $qry = 'SELECT * FROM notice ';
486 if (common_config('public', 'localonly')) {
487 $parts[] = 'is_local = 1';
490 $parts[] = 'is_local != -1';
494 $qry .= ' WHERE ' . implode(' AND ', $parts);
497 return Notice::getStream($qry,
499 $offset, $limit, $since_id, $before_id, null, $since);
502 function addToInboxes() {
503 $enabled = common_config('inboxes', 'enabled');
505 if ($enabled === true || $enabled === 'transitional') {
506 $inbox = new Notice_inbox();
507 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
508 'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
509 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
510 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
511 'AND NOT EXISTS (SELECT user_id, notice_id ' .
512 'FROM notice_inbox ' .
513 'WHERE user_id = user.id ' .
514 'AND notice_id = ' . $this->id . ' )';
515 if ($enabled === 'transitional') {
516 $qry .= ' AND user.inboxed = 1';
523 # Delete from inboxes if we're deleted.
525 function blowInboxes() {
527 $enabled = common_config('inboxes', 'enabled');
529 if ($enabled === true || $enabled === 'transitional') {
530 $inbox = new Notice_inbox();
531 $inbox->notice_id = $this->id;