3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, Control Yourself, 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 define('NOTICE_LOCAL_PUBLIC', 1);
33 define('NOTICE_REMOTE_OMB', 0);
34 define('NOTICE_LOCAL_NONPUBLIC', -1);
35 define('NOTICE_GATEWAY', -2);
37 define('MAX_BOXCARS', 128);
39 class Notice extends Memcached_DataObject
42 /* the code below is auto generated do not remove the above tag */
44 public $__table = 'notice'; // table name
45 public $id; // int(4) primary_key not_null
46 public $profile_id; // int(4) not_null
47 public $uri; // varchar(255) unique_key
48 public $content; // varchar(140)
49 public $rendered; // text()
50 public $url; // varchar(255)
51 public $created; // datetime() not_null
52 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
53 public $reply_to; // int(4)
54 public $is_local; // tinyint(1)
55 public $source; // varchar(32)
56 public $conversation; // int(4)
59 function staticGet($k,$v=NULL) {
60 return Memcached_DataObject::staticGet('Notice',$k,$v);
63 /* the code above is auto generated do not remove the tag below */
68 return Profile::staticGet('id', $this->profile_id);
73 $this->blowCaches(true);
74 $this->blowFavesCache(true);
75 $this->blowSubsCache(true);
77 // For auditing purposes, save a record that the notice
80 $deleted = new Deleted_notice();
82 $deleted->id = $this->id;
83 $deleted->profile_id = $this->profile_id;
84 $deleted->uri = $this->uri;
85 $deleted->created = $this->created;
86 $deleted->deleted = common_sql_now();
88 $this->query('BEGIN');
92 //Null any notices that are replies to this notice
93 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
94 $related = array('Reply',
99 if (common_config('inboxes', 'enabled')) {
100 $related[] = 'Notice_inbox';
102 foreach ($related as $cls) {
104 $inst->notice_id = $this->id;
107 $result = parent::delete();
108 $this->query('COMMIT');
113 /* extract all #hastags */
114 $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
119 /* Add them to the database */
120 foreach(array_unique($match[1]) as $hashtag) {
121 /* elide characters we don't want in the tag */
122 $this->saveTag($hashtag);
127 function saveTag($hashtag)
129 $hashtag = common_canonical_tag($hashtag);
131 $tag = new Notice_tag();
132 $tag->notice_id = $this->id;
133 $tag->tag = $hashtag;
134 $tag->created = $this->created;
135 $id = $tag->insert();
138 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
139 $last_error->message));
144 static function saveNew($profile_id, $content, $source=null,
145 $is_local=1, $reply_to=null, $uri=null, $created=null) {
147 $profile = Profile::staticGet($profile_id);
149 $final = common_shorten_links($content);
151 if (mb_strlen($final) > 140) {
152 common_log(LOG_INFO, 'Rejecting notice that is too long.');
153 return _('Problem saving notice. Too long.');
157 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
158 return _('Problem saving notice. Unknown user.');
161 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
162 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
163 return _('Too many notices too fast; take a breather and post again in a few minutes.');
166 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
167 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
168 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
171 $banned = common_config('profile', 'banned');
173 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
174 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
175 return _('You are banned from posting notices on this site.');
178 $notice = new Notice();
179 $notice->profile_id = $profile_id;
181 $blacklist = common_config('public', 'blacklist');
182 $autosource = common_config('public', 'autosource');
184 # Blacklisted are non-false, but not 1, either
186 if (($blacklist && in_array($profile_id, $blacklist)) ||
187 ($source && $autosource && in_array($source, $autosource))) {
188 $notice->is_local = -1;
190 $notice->is_local = $is_local;
193 $notice->query('BEGIN');
195 $notice->reply_to = $reply_to;
196 if (!empty($created)) {
197 $notice->created = $created;
199 $notice->created = common_sql_now();
201 $notice->content = $final;
202 $notice->rendered = common_render_content($final, $notice);
203 $notice->source = $source;
206 if (!empty($reply_to)) {
207 $reply_notice = Notice::staticGet('id', $reply_to);
208 if (!empty($reply_notice)) {
209 $notice->reply_to = $reply_to;
210 $notice->conversation = $reply_notice->conversation;
214 if (Event::handle('StartNoticeSave', array(&$notice))) {
216 $id = $notice->insert();
219 common_log_db_error($notice, 'INSERT', __FILE__);
220 return _('Problem saving notice.');
223 # Update the URI after the notice is in the database
225 $orig = clone($notice);
226 $notice->uri = common_notice_uri($notice);
228 if (!$notice->update($orig)) {
229 common_log_db_error($notice, 'UPDATE', __FILE__);
230 return _('Problem saving notice.');
234 # XXX: do we need to change this for remote users?
236 $notice->saveReplies();
239 $notice->addToInboxes();
242 $orig2 = clone($notice);
243 $notice->rendered = common_render_content($final, $notice);
244 if (!$notice->update($orig2)) {
245 common_log_db_error($notice, 'UPDATE', __FILE__);
246 return _('Problem saving notice.');
249 $notice->query('COMMIT');
251 Event::handle('EndNoticeSave', array($notice));
254 # Clear the cache for subscribed users, so they'll update at next request
255 # XXX: someone clever could prepend instead of clearing the cache
257 $notice->blowCaches();
262 /** save all urls in the notice to the db
264 * follow redirects and save all available file information
265 * (mimetype, date, size, oembed, etc.)
269 function saveUrls() {
270 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
273 function saveUrl($data) {
274 list($url, $notice_id) = $data;
275 File::processNew($url, $notice_id);
278 static function checkDupes($profile_id, $content) {
279 $profile = Profile::staticGet($profile_id);
283 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
286 while ($notice->fetch()) {
287 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
289 } else if ($notice->content == $content) {
294 # If we get here, oldest item in cache window is not
295 # old enough for dupe limit; do direct check against DB
296 $notice = new Notice();
297 $notice->profile_id = $profile_id;
298 $notice->content = $content;
299 if (common_config('db','type') == 'pgsql')
300 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
302 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
304 $cnt = $notice->count();
308 static function checkEditThrottle($profile_id) {
309 $profile = Profile::staticGet($profile_id);
314 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
315 if ($notice && $notice->fetch()) {
316 # If the Nth notice was posted less than timespan seconds ago
317 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
322 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
326 function getUploadedAttachment() {
328 $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
329 $post->query($query);
331 if (empty($post->up) || empty($post->i)) {
334 $ret = array($post->up, $post->i);
340 function hasAttachments() {
342 $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
343 $post->query($query);
345 $n_attachments = intval($post->n_attachments);
347 return $n_attachments;
350 function attachments() {
353 $f2p = new File_to_post;
354 $f2p->post_id = $this->id;
356 while ($f2p->fetch()) {
357 $f = File::staticGet($f2p->file_id);
364 function blowCaches($blowLast=false)
366 $this->blowSubsCache($blowLast);
367 $this->blowNoticeCache($blowLast);
368 $this->blowRepliesCache($blowLast);
369 $this->blowPublicCache($blowLast);
370 $this->blowTagCache($blowLast);
371 $this->blowGroupCache($blowLast);
372 $this->blowConversationCache($blowLast);
373 $profile = Profile::staticGet($this->profile_id);
374 $profile->blowNoticeCount();
377 function blowConversationCache($blowLast=false)
379 $cache = common_memcache();
381 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
384 $cache->delete($ck.';last');
389 function blowGroupCache($blowLast=false)
391 $cache = common_memcache();
393 $group_inbox = new Group_inbox();
394 $group_inbox->notice_id = $this->id;
395 if ($group_inbox->find()) {
396 while ($group_inbox->fetch()) {
397 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
399 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
401 $member = new Group_member();
402 $member->group_id = $group_inbox->group_id;
403 if ($member->find()) {
404 while ($member->fetch()) {
405 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
407 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
413 $group_inbox->free();
418 function blowTagCache($blowLast=false)
420 $cache = common_memcache();
422 $tag = new Notice_tag();
423 $tag->notice_id = $this->id;
425 while ($tag->fetch()) {
426 $tag->blowCache($blowLast);
427 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
431 $cache->delete($ck . ';last');
440 function blowSubsCache($blowLast=false)
442 $cache = common_memcache();
446 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
447 $user->query('SELECT id ' .
449 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
450 'WHERE subscription.subscribed = ' . $this->profile_id);
452 while ($user->fetch()) {
453 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
454 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
456 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
457 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
465 function blowNoticeCache($blowLast=false)
467 if ($this->is_local) {
468 $cache = common_memcache();
469 if (!empty($cache)) {
470 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
472 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
478 function blowRepliesCache($blowLast=false)
480 $cache = common_memcache();
482 $reply = new Reply();
483 $reply->notice_id = $this->id;
484 if ($reply->find()) {
485 while ($reply->fetch()) {
486 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
488 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
497 function blowPublicCache($blowLast=false)
499 if ($this->is_local == 1) {
500 $cache = common_memcache();
502 $cache->delete(common_cache_key('public'));
504 $cache->delete(common_cache_key('public').';last');
510 function blowFavesCache($blowLast=false)
512 $cache = common_memcache();
515 $fave->notice_id = $this->id;
517 while ($fave->fetch()) {
518 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
519 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
521 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
522 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
531 # XXX: too many args; we need to move to named params or even a separate
532 # class for notice streams
534 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
536 if (common_config('memcached', 'enabled')) {
538 # Skip the cache if this is a since, since_id or max_id qry
539 if ($since_id > 0 || $max_id > 0 || $since) {
540 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
542 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
546 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
549 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
554 if (preg_match('/\bWHERE\b/i', $qry)) {
568 $qry .= ' notice.id > ' . $since_id;
580 $qry .= ' notice.id <= ' . $max_id;
592 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
595 # Allow ORDER override
600 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
603 if (common_config('db','type') == 'pgsql') {
604 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
606 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
609 $notice = new Notice();
611 $notice->query($qry);
616 # XXX: this is pretty long and should probably be broken up into
617 # some helper functions
619 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
621 # If outside our cache window, just go to the DB
623 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
624 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
627 # Get the cache; if we can't, just go to the DB
629 $cache = common_memcache();
632 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
635 # Get the notices out of the cache
637 $notices = $cache->get(common_cache_key($cachekey));
639 # On a cache hit, return a DB-object-like wrapper
641 if ($notices !== false) {
642 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
646 # If the cache was invalidated because of new data being
647 # added, we can try and just get the new stuff. We keep an additional
648 # copy of the data at the key + ';last'
650 # No cache hit. Try to get the *last* cached version
652 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
656 # Reverse-chron order, so last ID is last.
658 $last_id = $last_notices[0]->id;
660 # XXX: this assumes monotonically increasing IDs; a fair
663 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
664 $last_id, null, $order, null);
667 $new_notices = array();
668 while ($new_notice->fetch()) {
669 $new_notices[] = clone($new_notice);
672 $notices = array_slice(array_merge($new_notices, $last_notices),
673 0, NOTICE_CACHE_WINDOW);
675 # Store the array in the cache for next time
677 $result = $cache->set(common_cache_key($cachekey), $notices);
678 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
680 # return a wrapper of the array for use now
682 return new ArrayWrapper(array_slice($notices, $offset, $limit));
686 # Otherwise, get the full cache window out of the DB
688 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
690 # If there are no hits, just return the value
696 # Pack results into an array
700 while ($notice->fetch()) {
701 $notices[] = clone($notice);
706 # Store the array in the cache for next time
708 $result = $cache->set(common_cache_key($cachekey), $notices);
709 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
711 # return a wrapper of the array for use now
713 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
718 function getStreamByIds($ids)
720 $cache = common_memcache();
722 if (!empty($cache)) {
724 foreach ($ids as $id) {
725 $n = Notice::staticGet('id', $id);
730 return new ArrayWrapper($notices);
732 $notice = new Notice();
733 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
734 $notice->orderBy('id DESC');
741 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
743 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
746 $offset, $limit, $since_id, $max_id, $since);
748 return Notice::getStreamByIds($ids);
751 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
753 $notice = new Notice();
755 $notice->selectAdd(); // clears it
756 $notice->selectAdd('id');
758 $notice->orderBy('id DESC');
760 if (!is_null($offset)) {
761 $notice->limit($offset, $limit);
764 if (common_config('public', 'localonly')) {
765 $notice->whereAdd('is_local = 1');
768 $notice->whereAdd('is_local != -1');
771 if ($since_id != 0) {
772 $notice->whereAdd('id > ' . $since_id);
776 $notice->whereAdd('id <= ' . $max_id);
779 if (!is_null($since)) {
780 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
785 if ($notice->find()) {
786 while ($notice->fetch()) {
787 $ids[] = $notice->id;
797 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
799 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
801 'notice:conversation_ids:'.$id,
802 $offset, $limit, $since_id, $max_id, $since);
804 return Notice::getStreamByIds($ids);
807 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
809 $notice = new Notice();
811 $notice->selectAdd(); // clears it
812 $notice->selectAdd('id');
814 $notice->conversation = $id;
816 $notice->orderBy('id DESC');
818 if (!is_null($offset)) {
819 $notice->limit($offset, $limit);
822 if ($since_id != 0) {
823 $notice->whereAdd('id > ' . $since_id);
827 $notice->whereAdd('id <= ' . $max_id);
830 if (!is_null($since)) {
831 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
836 if ($notice->find()) {
837 while ($notice->fetch()) {
838 $ids[] = $notice->id;
848 function addToInboxes()
850 $enabled = common_config('inboxes', 'enabled');
852 if ($enabled === true || $enabled === 'transitional') {
854 // XXX: loads constants
856 $inbox = new Notice_inbox();
858 $users = $this->getSubscribedUsers();
860 // FIXME: kind of ignoring 'transitional'...
861 // we'll probably stop supporting inboxless mode
866 foreach ($users as $id) {
867 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
870 $groups = $this->saveGroups();
872 foreach ($groups as $group) {
873 $users = $group->getUserMembers();
874 foreach ($users as $id) {
875 if (!array_key_exists($id, $ni)) {
876 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
883 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
886 foreach ($ni as $id => $source) {
890 $qry .= '('.$id.', '.$this->id.', '.$source.', "'.$this->created.'") ';
892 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
893 Notice_inbox::gc($id);
895 if ($cnt >= MAX_BOXCARS) {
896 $inbox = new Notice_inbox();
904 $inbox = new Notice_inbox();
912 function getSubscribedUsers()
918 'FROM user JOIN subscription '.
919 'ON user.id = subscription.subscriber ' .
920 'WHERE subscription.subscribed = %d ';
922 $user->query(sprintf($qry, $this->profile_id));
926 while ($user->fetch()) {
935 function saveGroups()
939 $enabled = common_config('inboxes', 'enabled');
940 if ($enabled !== true && $enabled !== 'transitional') {
944 /* extract all !group */
945 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
946 strtolower($this->content),
952 $profile = $this->getProfile();
954 /* Add them to the database */
956 foreach (array_unique($match[1]) as $nickname) {
957 /* XXX: remote groups. */
958 $group = User_group::getForNickname($nickname);
964 // we automatically add a tag for every group name, too
966 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
967 'notice_id' => $this->id));
970 $this->saveTag($nickname);
973 if ($profile->isMember($group)) {
975 $result = $this->addToGroupInbox($group);
978 common_log_db_error($gi, 'INSERT', __FILE__);
981 $groups[] = clone($group);
988 function addToGroupInbox($group)
990 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
991 'notice_id' => $this->id));
995 $gi = new Group_inbox();
997 $gi->group_id = $group->id;
998 $gi->notice_id = $this->id;
999 $gi->created = $this->created;
1001 return $gi->insert();
1007 function saveReplies()
1009 // Alternative reply format
1011 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1014 // extract all @messages
1015 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1019 if ($cnt || $tname) {
1020 // XXX: is there another way to make an array copy?
1021 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1024 $sender = Profile::staticGet($this->profile_id);
1028 // store replied only for first @ (what user/notice what the reply directed,
1029 // we assume first @ is it)
1031 for ($i=0; $i<count($names); $i++) {
1032 $nickname = $names[$i];
1033 $recipient = common_relative_profile($sender, $nickname, $this->created);
1037 if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
1038 $reply_for = $recipient;
1039 $recipient_notice = $reply_for->getCurrentNotice();
1040 if ($recipient_notice) {
1041 $orig = clone($this);
1042 $this->reply_to = $recipient_notice->id;
1043 $this->conversation = $recipient_notice->conversation;
1044 $this->update($orig);
1047 // Don't save replies from blocked profile to local user
1048 $recipient_user = User::staticGet('id', $recipient->id);
1049 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1052 $reply = new Reply();
1053 $reply->notice_id = $this->id;
1054 $reply->profile_id = $recipient->id;
1055 $id = $reply->insert();
1057 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1058 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1059 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1062 $replied[$recipient->id] = 1;
1066 // Hash format replies, too
1067 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1069 foreach ($match[1] as $tag) {
1070 $tagged = Profile_tag::getTagged($sender->id, $tag);
1071 foreach ($tagged as $t) {
1072 if (!$replied[$t->id]) {
1073 // Don't save replies from blocked profile to local user
1074 $t_user = User::staticGet('id', $t->id);
1075 if ($t_user && $t_user->hasBlocked($sender)) {
1078 $reply = new Reply();
1079 $reply->notice_id = $this->id;
1080 $reply->profile_id = $t->id;
1081 $id = $reply->insert();
1083 common_log_db_error($reply, 'INSERT', __FILE__);
1086 $replied[$recipient->id] = 1;
1093 // If it's not a reply, make it the root of a new conversation
1095 if (empty($this->conversation)) {
1096 $orig = clone($this);
1097 $this->conversation = $this->id;
1098 $this->update($orig);
1101 foreach (array_keys($replied) as $recipient) {
1102 $user = User::staticGet('id', $recipient);
1104 mail_notify_attn($user, $this);
1109 function asAtomEntry($namespace=false, $source=false)
1111 $profile = $this->getProfile();
1113 $xs = new XMLStringer(true);
1116 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1117 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1122 $xs->elementStart('entry', $attrs);
1125 $xs->elementStart('source');
1126 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1127 $xs->element('link', array('href' => $profile->profileurl));
1128 $user = User::staticGet('id', $profile->id);
1129 if (!empty($user)) {
1130 $atom_feed = common_local_url('api',
1131 array('apiaction' => 'statuses',
1132 'method' => 'user_timeline',
1133 'argument' => $profile->nickname.'.atom'));
1134 $xs->element('link', array('rel' => 'self',
1135 'type' => 'application/atom+xml',
1136 'href' => $profile->profileurl));
1137 $xs->element('link', array('rel' => 'license',
1138 'href' => common_config('license', 'url')));
1141 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1144 $xs->elementStart('author');
1145 $xs->element('name', null, $profile->nickname);
1146 $xs->element('uri', null, $profile->profileurl);
1147 $xs->elementEnd('author');
1150 $xs->elementEnd('source');
1153 $xs->element('title', null, $this->content);
1154 $xs->element('summary', null, $this->content);
1156 $xs->element('link', array('rel' => 'alternate',
1157 'href' => $this->bestUrl()));
1159 $xs->element('id', null, $this->uri);
1161 $xs->element('published', null, common_date_w3dtf($this->created));
1162 $xs->element('updated', null, common_date_w3dtf($this->modified));
1164 if ($this->reply_to) {
1165 $reply_notice = Notice::staticGet('id', $this->reply_to);
1166 if (!empty($reply_notice)) {
1167 $xs->element('link', array('rel' => 'related',
1168 'href' => $reply_notice->bestUrl()));
1169 $xs->element('thr:in-reply-to',
1170 array('ref' => $reply_notice->uri,
1171 'href' => $reply_notice->bestUrl()));
1175 $xs->element('content', array('type' => 'html'), $this->rendered);
1177 $tag = new Notice_tag();
1178 $tag->notice_id = $this->id;
1180 while ($tag->fetch()) {
1181 $xs->element('category', array('term' => $tag->tag));
1187 $attachments = $this->attachments();
1189 foreach($attachments as $attachment){
1190 if ($attachment->isEnclosure()) {
1191 $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1192 if($attachment->title){
1193 $attributes['title']=$attachment->title;
1195 $xs->element('link', $attributes, null);
1200 $xs->elementEnd('entry');
1202 return $xs->getString();
1207 if (!empty($this->url)) {
1209 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1212 return common_local_url('shownotice',
1213 array('notice' => $this->id));
1217 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1219 $cache = common_memcache();
1221 if (empty($cache) ||
1222 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1224 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1225 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1229 $idkey = common_cache_key($cachekey);
1231 $idstr = $cache->get($idkey);
1233 if (!empty($idstr)) {
1234 // Cache hit! Woohoo!
1235 $window = explode(',', $idstr);
1236 $ids = array_slice($window, $offset, $limit);
1240 $laststr = $cache->get($idkey.';last');
1242 if (!empty($laststr)) {
1243 $window = explode(',', $laststr);
1244 $last_id = $window[0];
1245 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1246 $last_id, 0, null)));
1248 $new_window = array_merge($new_ids, $window);
1250 $new_windowstr = implode(',', $new_window);
1252 $result = $cache->set($idkey, $new_windowstr);
1253 $result = $cache->set($idkey . ';last', $new_windowstr);
1255 $ids = array_slice($new_window, $offset, $limit);
1260 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1263 $windowstr = implode(',', $window);
1265 $result = $cache->set($idkey, $windowstr);
1266 $result = $cache->set($idkey . ';last', $windowstr);
1268 $ids = array_slice($window, $offset, $limit);