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);
36 define('MAX_BOXCARS', 128);
38 class Notice extends Memcached_DataObject
41 /* the code below is auto generated do not remove the above tag */
43 public $__table = 'notice'; // table name
44 public $id; // int(4) primary_key not_null
45 public $profile_id; // int(4) not_null
46 public $uri; // varchar(255) unique_key
47 public $content; // varchar(140)
48 public $rendered; // text()
49 public $url; // varchar(255)
50 public $created; // datetime() not_null
51 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
52 public $reply_to; // int(4)
53 public $is_local; // tinyint(1)
54 public $source; // varchar(32)
55 public $conversation; // int(4)
58 function staticGet($k,$v=NULL) {
59 return Memcached_DataObject::staticGet('Notice',$k,$v);
62 /* the code above is auto generated do not remove the tag below */
69 return Profile::staticGet('id', $this->profile_id);
74 $this->blowCaches(true);
75 $this->blowFavesCache(true);
76 $this->blowSubsCache(true);
78 // For auditing purposes, save a record that the notice
81 $deleted = new Deleted_notice();
83 $deleted->id = $this->id;
84 $deleted->profile_id = $this->profile_id;
85 $deleted->uri = $this->uri;
86 $deleted->created = $this->created;
87 $deleted->deleted = common_sql_now();
89 $this->query('BEGIN');
93 //Null any notices that are replies to this notice
94 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
95 $related = array('Reply',
100 if (common_config('inboxes', 'enabled')) {
101 $related[] = 'Notice_inbox';
103 foreach ($related as $cls) {
105 $inst->notice_id = $this->id;
108 $result = parent::delete();
109 $this->query('COMMIT');
114 /* extract all #hastags */
115 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
120 //turn each into their canonical tag
121 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
123 for($i=0; $i<count($match[1]); $i++) {
124 $hashtags[] = common_canonical_tag($match[1][$i]);
127 /* Add them to the database */
128 foreach(array_unique($hashtags) as $hashtag) {
129 /* elide characters we don't want in the tag */
130 $this->saveTag($hashtag);
135 function saveTag($hashtag)
137 $tag = new Notice_tag();
138 $tag->notice_id = $this->id;
139 $tag->tag = $hashtag;
140 $tag->created = $this->created;
141 $id = $tag->insert();
144 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
145 $last_error->message));
150 static function saveNew($profile_id, $content, $source=null,
151 $is_local=1, $reply_to=null, $uri=null, $created=null) {
153 $profile = Profile::staticGet($profile_id);
155 $final = common_shorten_links($content);
157 if (mb_strlen($final) > 140) {
158 common_log(LOG_INFO, 'Rejecting notice that is too long.');
159 return _('Problem saving notice. Too long.');
163 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
164 return _('Problem saving notice. Unknown user.');
167 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
168 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
169 return _('Too many notices too fast; take a breather and post again in a few minutes.');
172 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
173 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
174 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
177 $banned = common_config('profile', 'banned');
179 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
180 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
181 return _('You are banned from posting notices on this site.');
184 $notice = new Notice();
185 $notice->profile_id = $profile_id;
187 $blacklist = common_config('public', 'blacklist');
188 $autosource = common_config('public', 'autosource');
190 # Blacklisted are non-false, but not 1, either
192 if (($blacklist && in_array($profile_id, $blacklist)) ||
193 ($source && $autosource && in_array($source, $autosource))) {
194 $notice->is_local = -1;
196 $notice->is_local = $is_local;
199 if (!empty($created)) {
200 $notice->created = $created;
202 $notice->created = common_sql_now();
205 $notice->content = $final;
206 $notice->rendered = common_render_content($final, $notice);
207 $notice->source = $source;
210 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
212 if (!empty($notice->reply_to)) {
213 $reply = Notice::staticGet('id', $notice->reply_to);
214 $notice->conversation = $reply->conversation;
217 if (Event::handle('StartNoticeSave', array(&$notice))) {
219 // XXX: some of these functions write to the DB
221 $notice->query('BEGIN');
223 $id = $notice->insert();
226 common_log_db_error($notice, 'INSERT', __FILE__);
227 return _('Problem saving notice.');
230 // Update ID-dependent columns: URI, conversation
232 $orig = clone($notice);
237 $notice->uri = common_notice_uri($notice);
241 // If it's not part of a conversation, it's
242 // the beginning of a new conversation.
244 if (empty($notice->conversation)) {
245 $notice->conversation = $notice->id;
250 if (!$notice->update($orig)) {
251 common_log_db_error($notice, 'UPDATE', __FILE__);
252 return _('Problem saving notice.');
256 // XXX: do we need to change this for remote users?
258 $notice->saveReplies();
261 $notice->addToInboxes();
265 // FIXME: why do we have to re-render the content?
266 // Remove this if it's not necessary.
268 $orig2 = clone($notice);
270 $notice->rendered = common_render_content($final, $notice);
271 if (!$notice->update($orig2)) {
272 common_log_db_error($notice, 'UPDATE', __FILE__);
273 return _('Problem saving notice.');
276 $notice->query('COMMIT');
278 Event::handle('EndNoticeSave', array($notice));
281 # Clear the cache for subscribed users, so they'll update at next request
282 # XXX: someone clever could prepend instead of clearing the cache
284 $notice->blowCaches();
289 /** save all urls in the notice to the db
291 * follow redirects and save all available file information
292 * (mimetype, date, size, oembed, etc.)
296 function saveUrls() {
297 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
300 function saveUrl($data) {
301 list($url, $notice_id) = $data;
302 File::processNew($url, $notice_id);
305 static function checkDupes($profile_id, $content) {
306 $profile = Profile::staticGet($profile_id);
310 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
313 while ($notice->fetch()) {
314 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
316 } else if ($notice->content == $content) {
321 # If we get here, oldest item in cache window is not
322 # old enough for dupe limit; do direct check against DB
323 $notice = new Notice();
324 $notice->profile_id = $profile_id;
325 $notice->content = $content;
326 if (common_config('db','type') == 'pgsql')
327 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
329 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
331 $cnt = $notice->count();
335 static function checkEditThrottle($profile_id) {
336 $profile = Profile::staticGet($profile_id);
341 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
342 if ($notice && $notice->fetch()) {
343 # If the Nth notice was posted less than timespan seconds ago
344 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
349 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
353 function getUploadedAttachment() {
355 $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"';
356 $post->query($query);
358 if (empty($post->up) || empty($post->i)) {
361 $ret = array($post->up, $post->i);
367 function hasAttachments() {
369 $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);
370 $post->query($query);
372 $n_attachments = intval($post->n_attachments);
374 return $n_attachments;
377 function attachments() {
380 $f2p = new File_to_post;
381 $f2p->post_id = $this->id;
383 while ($f2p->fetch()) {
384 $f = File::staticGet($f2p->file_id);
391 function blowCaches($blowLast=false)
393 $this->blowSubsCache($blowLast);
394 $this->blowNoticeCache($blowLast);
395 $this->blowRepliesCache($blowLast);
396 $this->blowPublicCache($blowLast);
397 $this->blowTagCache($blowLast);
398 $this->blowGroupCache($blowLast);
399 $this->blowConversationCache($blowLast);
400 $profile = Profile::staticGet($this->profile_id);
401 $profile->blowNoticeCount();
404 function blowConversationCache($blowLast=false)
406 $cache = common_memcache();
408 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
411 $cache->delete($ck.';last');
416 function blowGroupCache($blowLast=false)
418 $cache = common_memcache();
420 $group_inbox = new Group_inbox();
421 $group_inbox->notice_id = $this->id;
422 if ($group_inbox->find()) {
423 while ($group_inbox->fetch()) {
424 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
426 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
428 $member = new Group_member();
429 $member->group_id = $group_inbox->group_id;
430 if ($member->find()) {
431 while ($member->fetch()) {
432 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
434 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
440 $group_inbox->free();
445 function blowTagCache($blowLast=false)
447 $cache = common_memcache();
449 $tag = new Notice_tag();
450 $tag->notice_id = $this->id;
452 while ($tag->fetch()) {
453 $tag->blowCache($blowLast);
454 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
458 $cache->delete($ck . ';last');
467 function blowSubsCache($blowLast=false)
469 $cache = common_memcache();
473 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
474 $user->query('SELECT id ' .
476 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
477 'WHERE subscription.subscribed = ' . $this->profile_id);
479 while ($user->fetch()) {
480 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
481 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
483 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
484 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
492 function blowNoticeCache($blowLast=false)
494 if ($this->is_local) {
495 $cache = common_memcache();
496 if (!empty($cache)) {
497 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
499 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
505 function blowRepliesCache($blowLast=false)
507 $cache = common_memcache();
509 $reply = new Reply();
510 $reply->notice_id = $this->id;
511 if ($reply->find()) {
512 while ($reply->fetch()) {
513 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
515 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
524 function blowPublicCache($blowLast=false)
526 if ($this->is_local == 1) {
527 $cache = common_memcache();
529 $cache->delete(common_cache_key('public'));
531 $cache->delete(common_cache_key('public').';last');
537 function blowFavesCache($blowLast=false)
539 $cache = common_memcache();
542 $fave->notice_id = $this->id;
544 while ($fave->fetch()) {
545 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
546 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
548 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
549 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
558 # XXX: too many args; we need to move to named params or even a separate
559 # class for notice streams
561 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
563 if (common_config('memcached', 'enabled')) {
565 # Skip the cache if this is a since, since_id or max_id qry
566 if ($since_id > 0 || $max_id > 0 || $since) {
567 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
569 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
573 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
576 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
581 if (preg_match('/\bWHERE\b/i', $qry)) {
595 $qry .= ' notice.id > ' . $since_id;
607 $qry .= ' notice.id <= ' . $max_id;
619 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
622 # Allow ORDER override
627 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
630 if (common_config('db','type') == 'pgsql') {
631 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
633 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
636 $notice = new Notice();
638 $notice->query($qry);
643 # XXX: this is pretty long and should probably be broken up into
644 # some helper functions
646 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
648 # If outside our cache window, just go to the DB
650 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
651 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
654 # Get the cache; if we can't, just go to the DB
656 $cache = common_memcache();
659 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
662 # Get the notices out of the cache
664 $notices = $cache->get(common_cache_key($cachekey));
666 # On a cache hit, return a DB-object-like wrapper
668 if ($notices !== false) {
669 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
673 # If the cache was invalidated because of new data being
674 # added, we can try and just get the new stuff. We keep an additional
675 # copy of the data at the key + ';last'
677 # No cache hit. Try to get the *last* cached version
679 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
683 # Reverse-chron order, so last ID is last.
685 $last_id = $last_notices[0]->id;
687 # XXX: this assumes monotonically increasing IDs; a fair
690 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
691 $last_id, null, $order, null);
694 $new_notices = array();
695 while ($new_notice->fetch()) {
696 $new_notices[] = clone($new_notice);
699 $notices = array_slice(array_merge($new_notices, $last_notices),
700 0, NOTICE_CACHE_WINDOW);
702 # Store the array in the cache for next time
704 $result = $cache->set(common_cache_key($cachekey), $notices);
705 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
707 # return a wrapper of the array for use now
709 return new ArrayWrapper(array_slice($notices, $offset, $limit));
713 # Otherwise, get the full cache window out of the DB
715 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
717 # If there are no hits, just return the value
723 # Pack results into an array
727 while ($notice->fetch()) {
728 $notices[] = clone($notice);
733 # Store the array in the cache for next time
735 $result = $cache->set(common_cache_key($cachekey), $notices);
736 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
738 # return a wrapper of the array for use now
740 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
745 function getStreamByIds($ids)
747 $cache = common_memcache();
749 if (!empty($cache)) {
751 foreach ($ids as $id) {
752 $n = Notice::staticGet('id', $id);
757 return new ArrayWrapper($notices);
759 $notice = new Notice();
760 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
761 $notice->orderBy('id DESC');
768 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
770 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
773 $offset, $limit, $since_id, $max_id, $since);
775 return Notice::getStreamByIds($ids);
778 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
780 $notice = new Notice();
782 $notice->selectAdd(); // clears it
783 $notice->selectAdd('id');
785 $notice->orderBy('id DESC');
787 if (!is_null($offset)) {
788 $notice->limit($offset, $limit);
791 if (common_config('public', 'localonly')) {
792 $notice->whereAdd('is_local = 1');
795 $notice->whereAdd('is_local != -1');
798 if ($since_id != 0) {
799 $notice->whereAdd('id > ' . $since_id);
803 $notice->whereAdd('id <= ' . $max_id);
806 if (!is_null($since)) {
807 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
812 if ($notice->find()) {
813 while ($notice->fetch()) {
814 $ids[] = $notice->id;
824 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
826 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
828 'notice:conversation_ids:'.$id,
829 $offset, $limit, $since_id, $max_id, $since);
831 return Notice::getStreamByIds($ids);
834 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
836 $notice = new Notice();
838 $notice->selectAdd(); // clears it
839 $notice->selectAdd('id');
841 $notice->conversation = $id;
843 $notice->orderBy('id DESC');
845 if (!is_null($offset)) {
846 $notice->limit($offset, $limit);
849 if ($since_id != 0) {
850 $notice->whereAdd('id > ' . $since_id);
854 $notice->whereAdd('id <= ' . $max_id);
857 if (!is_null($since)) {
858 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
863 if ($notice->find()) {
864 while ($notice->fetch()) {
865 $ids[] = $notice->id;
875 function addToInboxes()
877 $enabled = common_config('inboxes', 'enabled');
879 if ($enabled === true || $enabled === 'transitional') {
881 // XXX: loads constants
883 $inbox = new Notice_inbox();
885 $users = $this->getSubscribedUsers();
887 // FIXME: kind of ignoring 'transitional'...
888 // we'll probably stop supporting inboxless mode
893 foreach ($users as $id) {
894 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
897 $groups = $this->saveGroups();
899 foreach ($groups as $group) {
900 $users = $group->getUserMembers();
901 foreach ($users as $id) {
902 if (!array_key_exists($id, $ni)) {
903 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
910 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
913 foreach ($ni as $id => $source) {
917 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
919 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
920 Notice_inbox::gc($id);
922 if ($cnt >= MAX_BOXCARS) {
923 $inbox = new Notice_inbox();
931 $inbox = new Notice_inbox();
939 function getSubscribedUsers()
943 if(common_config('db','quote_identifiers'))
944 $user_table = '"user"';
945 else $user_table = 'user';
949 'FROM '. $user_table .' JOIN subscription '.
950 'ON '. $user_table .'.id = subscription.subscriber ' .
951 'WHERE subscription.subscribed = %d ';
953 $user->query(sprintf($qry, $this->profile_id));
957 while ($user->fetch()) {
966 function saveGroups()
970 $enabled = common_config('inboxes', 'enabled');
971 if ($enabled !== true && $enabled !== 'transitional') {
975 /* extract all !group */
976 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
977 strtolower($this->content),
983 $profile = $this->getProfile();
985 /* Add them to the database */
987 foreach (array_unique($match[1]) as $nickname) {
988 /* XXX: remote groups. */
989 $group = User_group::getForNickname($nickname);
995 // we automatically add a tag for every group name, too
997 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
998 'notice_id' => $this->id));
1000 if (is_null($tag)) {
1001 $this->saveTag($nickname);
1004 if ($profile->isMember($group)) {
1006 $result = $this->addToGroupInbox($group);
1009 common_log_db_error($gi, 'INSERT', __FILE__);
1012 $groups[] = clone($group);
1019 function addToGroupInbox($group)
1021 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1022 'notice_id' => $this->id));
1026 $gi = new Group_inbox();
1028 $gi->group_id = $group->id;
1029 $gi->notice_id = $this->id;
1030 $gi->created = $this->created;
1032 return $gi->insert();
1038 function saveReplies()
1040 // Alternative reply format
1042 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1045 // extract all @messages
1046 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1050 if ($cnt || $tname) {
1051 // XXX: is there another way to make an array copy?
1052 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1055 $sender = Profile::staticGet($this->profile_id);
1059 // store replied only for first @ (what user/notice what the reply directed,
1060 // we assume first @ is it)
1062 for ($i=0; $i<count($names); $i++) {
1063 $nickname = $names[$i];
1064 $recipient = common_relative_profile($sender, $nickname, $this->created);
1068 // Don't save replies from blocked profile to local user
1069 $recipient_user = User::staticGet('id', $recipient->id);
1070 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1073 $reply = new Reply();
1074 $reply->notice_id = $this->id;
1075 $reply->profile_id = $recipient->id;
1076 $id = $reply->insert();
1078 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1079 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1080 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1083 $replied[$recipient->id] = 1;
1087 // Hash format replies, too
1088 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1090 foreach ($match[1] as $tag) {
1091 $tagged = Profile_tag::getTagged($sender->id, $tag);
1092 foreach ($tagged as $t) {
1093 if (!$replied[$t->id]) {
1094 // Don't save replies from blocked profile to local user
1095 $t_user = User::staticGet('id', $t->id);
1096 if ($t_user && $t_user->hasBlocked($sender)) {
1099 $reply = new Reply();
1100 $reply->notice_id = $this->id;
1101 $reply->profile_id = $t->id;
1102 $id = $reply->insert();
1104 common_log_db_error($reply, 'INSERT', __FILE__);
1107 $replied[$recipient->id] = 1;
1114 foreach (array_keys($replied) as $recipient) {
1115 $user = User::staticGet('id', $recipient);
1117 mail_notify_attn($user, $this);
1122 function asAtomEntry($namespace=false, $source=false)
1124 $profile = $this->getProfile();
1126 $xs = new XMLStringer(true);
1129 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1130 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1135 $xs->elementStart('entry', $attrs);
1138 $xs->elementStart('source');
1139 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1140 $xs->element('link', array('href' => $profile->profileurl));
1141 $user = User::staticGet('id', $profile->id);
1142 if (!empty($user)) {
1143 $atom_feed = common_local_url('api',
1144 array('apiaction' => 'statuses',
1145 'method' => 'user_timeline',
1146 'argument' => $profile->nickname.'.atom'));
1147 $xs->element('link', array('rel' => 'self',
1148 'type' => 'application/atom+xml',
1149 'href' => $profile->profileurl));
1150 $xs->element('link', array('rel' => 'license',
1151 'href' => common_config('license', 'url')));
1154 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1157 $xs->elementStart('author');
1158 $xs->element('name', null, $profile->nickname);
1159 $xs->element('uri', null, $profile->profileurl);
1160 $xs->elementEnd('author');
1163 $xs->elementEnd('source');
1166 $xs->element('title', null, $this->content);
1167 $xs->element('summary', null, $this->content);
1169 $xs->element('link', array('rel' => 'alternate',
1170 'href' => $this->bestUrl()));
1172 $xs->element('id', null, $this->uri);
1174 $xs->element('published', null, common_date_w3dtf($this->created));
1175 $xs->element('updated', null, common_date_w3dtf($this->modified));
1177 if ($this->reply_to) {
1178 $reply_notice = Notice::staticGet('id', $this->reply_to);
1179 if (!empty($reply_notice)) {
1180 $xs->element('link', array('rel' => 'related',
1181 'href' => $reply_notice->bestUrl()));
1182 $xs->element('thr:in-reply-to',
1183 array('ref' => $reply_notice->uri,
1184 'href' => $reply_notice->bestUrl()));
1188 $xs->element('content', array('type' => 'html'), $this->rendered);
1190 $tag = new Notice_tag();
1191 $tag->notice_id = $this->id;
1193 while ($tag->fetch()) {
1194 $xs->element('category', array('term' => $tag->tag));
1200 $attachments = $this->attachments();
1202 foreach($attachments as $attachment){
1203 if ($attachment->isEnclosure()) {
1204 $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1205 if($attachment->title){
1206 $attributes['title']=$attachment->title;
1208 $xs->element('link', $attributes, null);
1213 $xs->elementEnd('entry');
1215 return $xs->getString();
1220 if (!empty($this->url)) {
1222 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1225 return common_local_url('shownotice',
1226 array('notice' => $this->id));
1230 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1232 $cache = common_memcache();
1234 if (empty($cache) ||
1235 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1237 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1238 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1242 $idkey = common_cache_key($cachekey);
1244 $idstr = $cache->get($idkey);
1246 if (!empty($idstr)) {
1247 // Cache hit! Woohoo!
1248 $window = explode(',', $idstr);
1249 $ids = array_slice($window, $offset, $limit);
1253 $laststr = $cache->get($idkey.';last');
1255 if (!empty($laststr)) {
1256 $window = explode(',', $laststr);
1257 $last_id = $window[0];
1258 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1259 $last_id, 0, null)));
1261 $new_window = array_merge($new_ids, $window);
1263 $new_windowstr = implode(',', $new_window);
1265 $result = $cache->set($idkey, $new_windowstr);
1266 $result = $cache->set($idkey . ';last', $new_windowstr);
1268 $ids = array_slice($new_window, $offset, $limit);
1273 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1276 $windowstr = implode(',', $window);
1278 $result = $cache->set($idkey, $windowstr);
1279 $result = $cache->set($idkey . ';last', $windowstr);
1281 $ids = array_slice($window, $offset, $limit);
1287 * Determine which notice, if any, a new notice is in reply to.
1289 * For conversation tracking, we try to see where this notice fits
1290 * in the tree. Rough algorithm is:
1292 * if (reply_to is set and valid) {
1294 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1295 * return ID of last notice by initial @name in content;
1298 * Note that all @nickname instances will still be used to save "reply" records,
1299 * so the notice shows up in the mentioned users' "replies" tab.
1301 * @param integer $reply_to ID passed in by Web or API
1302 * @param integer $profile_id ID of author
1303 * @param string $source Source tag, like 'web' or 'gwibber'
1304 * @param string $content Final notice content
1306 * @return integer ID of replied-to notice, or null for not a reply.
1309 static function getReplyTo($reply_to, $profile_id, $source, $content)
1311 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1313 // If $reply_to is specified, we check that it exists, and then
1314 // return it if it does
1316 if (!empty($reply_to)) {
1317 $reply_notice = Notice::staticGet('id', $reply_to);
1318 if (!empty($reply_notice)) {
1323 // If it's not a "low bandwidth" source (one where you can't set
1324 // a reply_to argument), we return. This is mostly web and API
1327 if (!in_array($source, $lb)) {
1331 // Is there an initial @ or T?
1333 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1334 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1335 $nickname = common_canonical_nickname($match[1]);
1340 // Figure out who that is.
1342 $sender = Profile::staticGet('id', $profile_id);
1343 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1345 if (empty($recipient)) {
1349 // Get their last notice
1351 $last = $recipient->getCurrentNotice();
1353 if (!empty($last)) {