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);
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 = $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) {
298 if (common_config('memcached', 'enabled')) {
300 # Skip the cache if this is a since_id or before_id qry
301 if ($since_id > 0 || $before_id > 0) {
302 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
304 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
308 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order);
311 static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order) {
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;
345 # Allow ORDER override
350 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
353 if (common_config('db','type') == 'pgsql') {
354 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
356 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
359 $notice = new Notice();
361 $notice->query($qry);
366 # XXX: this is pretty long and should probably be broken up into
367 # some helper functions
369 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
371 # If outside our cache window, just go to the DB
373 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
374 return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
377 # Get the cache; if we can't, just go to the DB
379 $cache = common_memcache();
382 return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order);
385 # Get the notices out of the cache
387 $notices = $cache->get(common_cache_key($cachekey));
389 # On a cache hit, return a DB-object-like wrapper
391 if ($notices !== FALSE) {
392 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
396 # If the cache was invalidated because of new data being
397 # added, we can try and just get the new stuff. We keep an additional
398 # copy of the data at the key + ';last'
400 # No cache hit. Try to get the *last* cached version
402 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
406 # Reverse-chron order, so last ID is last.
408 $last_id = $last_notices[0]->id;
410 # XXX: this assumes monotonically increasing IDs; a fair
413 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
414 $last_id, NULL, $order);
417 $new_notices = array();
418 while ($new_notice->fetch()) {
419 $new_notices[] = clone($new_notice);
422 $notices = array_slice(array_merge($new_notices, $last_notices),
423 0, NOTICE_CACHE_WINDOW);
425 # Store the array in the cache for next time
427 $result = $cache->set(common_cache_key($cachekey), $notices);
428 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
430 # return a wrapper of the array for use now
432 return new NoticeWrapper(array_slice($notices, $offset, $limit));
436 # Otherwise, get the full cache window out of the DB
438 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order);
440 # If there are no hits, just return the value
446 # Pack results into an array
450 while ($notice->fetch()) {
451 $notices[] = clone($notice);
456 # Store the array in the cache for next time
458 $result = $cache->set(common_cache_key($cachekey), $notices);
459 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
461 # return a wrapper of the array for use now
463 $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
468 function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0) {
472 $qry = 'SELECT * FROM notice ';
474 if (common_config('public', 'localonly')) {
475 $parts[] = 'is_local = 1';
478 $parts[] = 'is_local != -1';
482 $qry .= ' WHERE ' . implode(' AND ', $parts);
485 return Notice::getStream($qry,
487 $offset, $limit, $since_id, $before_id);
490 function addToInboxes() {
491 $enabled = common_config('inboxes', 'enabled');
493 if ($enabled === true || $enabled === 'transitional') {
494 $inbox = new Notice_inbox();
495 $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
496 'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
497 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
498 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
499 'AND NOT EXISTS (SELECT user_id, notice_id ' .
500 'FROM notice_inbox ' .
501 'WHERE user_id = user.id ' .
502 'AND notice_id = ' . $this->id . ' )';
503 if ($enabled === 'transitional') {
504 $qry .= ' AND user.inboxed = 1';
511 # Delete from inboxes if we're deleted.
513 function blowInboxes() {
515 $enabled = common_config('inboxes', 'enabled');
517 if ($enabled === true || $enabled === 'transitional') {
518 $inbox = new Notice_inbox();
519 $inbox->notice_id = $this->id;