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; // text()
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) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
60 /* the code above is auto generated do not remove the tag below */
67 return Profile::staticGet('id', $this->profile_id);
72 $this->blowCaches(true);
73 $this->blowFavesCache(true);
74 $this->blowSubsCache(true);
76 // For auditing purposes, save a record that the notice
79 $deleted = new Deleted_notice();
81 $deleted->id = $this->id;
82 $deleted->profile_id = $this->profile_id;
83 $deleted->uri = $this->uri;
84 $deleted->created = $this->created;
85 $deleted->deleted = common_sql_now();
87 $this->query('BEGIN');
91 //Null any notices that are replies to this notice
92 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
93 $related = array('Reply',
98 if (common_config('inboxes', 'enabled')) {
99 $related[] = 'Notice_inbox';
101 foreach ($related as $cls) {
103 $inst->notice_id = $this->id;
106 $result = parent::delete();
107 $this->query('COMMIT');
112 /* extract all #hastags */
113 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
118 //turn each into their canonical tag
119 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
121 for($i=0; $i<count($match[1]); $i++) {
122 $hashtags[] = common_canonical_tag($match[1][$i]);
125 /* Add them to the database */
126 foreach(array_unique($hashtags) as $hashtag) {
127 /* elide characters we don't want in the tag */
128 $this->saveTag($hashtag);
133 function saveTag($hashtag)
135 $tag = new Notice_tag();
136 $tag->notice_id = $this->id;
137 $tag->tag = $hashtag;
138 $tag->created = $this->created;
139 $id = $tag->insert();
142 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
143 $last_error->message));
148 static function saveNew($profile_id, $content, $source=null,
149 $is_local=1, $reply_to=null, $uri=null, $created=null) {
151 $profile = Profile::staticGet($profile_id);
153 $final = common_shorten_links($content);
155 if (Notice::contentTooLong($final)) {
156 common_log(LOG_INFO, 'Rejecting notice that is too long.');
157 return _('Problem saving notice. Too long.');
161 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
162 return _('Problem saving notice. Unknown user.');
165 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
166 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
167 return _('Too many notices too fast; take a breather and post again in a few minutes.');
170 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
171 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
172 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
175 $banned = common_config('profile', 'banned');
177 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
178 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
179 return _('You are banned from posting notices on this site.');
182 $notice = new Notice();
183 $notice->profile_id = $profile_id;
185 $blacklist = common_config('public', 'blacklist');
186 $autosource = common_config('public', 'autosource');
188 # Blacklisted are non-false, but not 1, either
190 if (($blacklist && in_array($profile_id, $blacklist)) ||
191 ($source && $autosource && in_array($source, $autosource))) {
192 $notice->is_local = -1;
194 $notice->is_local = $is_local;
197 if (!empty($created)) {
198 $notice->created = $created;
200 $notice->created = common_sql_now();
203 $notice->content = $final;
204 $notice->rendered = common_render_content($final, $notice);
205 $notice->source = $source;
208 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
210 if (!empty($notice->reply_to)) {
211 $reply = Notice::staticGet('id', $notice->reply_to);
212 $notice->conversation = $reply->conversation;
215 if (Event::handle('StartNoticeSave', array(&$notice))) {
217 // XXX: some of these functions write to the DB
219 $notice->query('BEGIN');
221 $id = $notice->insert();
224 common_log_db_error($notice, 'INSERT', __FILE__);
225 return _('Problem saving notice.');
228 // Update ID-dependent columns: URI, conversation
230 $orig = clone($notice);
235 $notice->uri = common_notice_uri($notice);
239 // If it's not part of a conversation, it's
240 // the beginning of a new conversation.
242 if (empty($notice->conversation)) {
243 $notice->conversation = $notice->id;
248 if (!$notice->update($orig)) {
249 common_log_db_error($notice, 'UPDATE', __FILE__);
250 return _('Problem saving notice.');
254 // XXX: do we need to change this for remote users?
256 $notice->saveReplies();
259 $notice->addToInboxes();
263 // FIXME: why do we have to re-render the content?
264 // Remove this if it's not necessary.
266 $orig2 = clone($notice);
268 $notice->rendered = common_render_content($final, $notice);
269 if (!$notice->update($orig2)) {
270 common_log_db_error($notice, 'UPDATE', __FILE__);
271 return _('Problem saving notice.');
274 $notice->query('COMMIT');
276 Event::handle('EndNoticeSave', array($notice));
279 # Clear the cache for subscribed users, so they'll update at next request
280 # XXX: someone clever could prepend instead of clearing the cache
282 $notice->blowCaches();
287 /** save all urls in the notice to the db
289 * follow redirects and save all available file information
290 * (mimetype, date, size, oembed, etc.)
294 function saveUrls() {
295 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
298 function saveUrl($data) {
299 list($url, $notice_id) = $data;
300 File::processNew($url, $notice_id);
303 static function checkDupes($profile_id, $content) {
304 $profile = Profile::staticGet($profile_id);
308 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
311 while ($notice->fetch()) {
312 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
314 } else if ($notice->content == $content) {
319 # If we get here, oldest item in cache window is not
320 # old enough for dupe limit; do direct check against DB
321 $notice = new Notice();
322 $notice->profile_id = $profile_id;
323 $notice->content = $content;
324 if (common_config('db','type') == 'pgsql')
325 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
327 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
329 $cnt = $notice->count();
333 static function checkEditThrottle($profile_id) {
334 $profile = Profile::staticGet($profile_id);
339 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
340 if ($notice && $notice->fetch()) {
341 # If the Nth notice was posted less than timespan seconds ago
342 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
347 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
351 function getUploadedAttachment() {
353 $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"';
354 $post->query($query);
356 if (empty($post->up) || empty($post->i)) {
359 $ret = array($post->up, $post->i);
365 function hasAttachments() {
367 $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);
368 $post->query($query);
370 $n_attachments = intval($post->n_attachments);
372 return $n_attachments;
375 function attachments() {
378 $f2p = new File_to_post;
379 $f2p->post_id = $this->id;
381 while ($f2p->fetch()) {
382 $f = File::staticGet($f2p->file_id);
389 function blowCaches($blowLast=false)
391 $this->blowSubsCache($blowLast);
392 $this->blowNoticeCache($blowLast);
393 $this->blowRepliesCache($blowLast);
394 $this->blowPublicCache($blowLast);
395 $this->blowTagCache($blowLast);
396 $this->blowGroupCache($blowLast);
397 $this->blowConversationCache($blowLast);
398 $profile = Profile::staticGet($this->profile_id);
399 $profile->blowNoticeCount();
402 function blowConversationCache($blowLast=false)
404 $cache = common_memcache();
406 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
409 $cache->delete($ck.';last');
414 function blowGroupCache($blowLast=false)
416 $cache = common_memcache();
418 $group_inbox = new Group_inbox();
419 $group_inbox->notice_id = $this->id;
420 if ($group_inbox->find()) {
421 while ($group_inbox->fetch()) {
422 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
424 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
426 $member = new Group_member();
427 $member->group_id = $group_inbox->group_id;
428 if ($member->find()) {
429 while ($member->fetch()) {
430 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
432 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
438 $group_inbox->free();
443 function blowTagCache($blowLast=false)
445 $cache = common_memcache();
447 $tag = new Notice_tag();
448 $tag->notice_id = $this->id;
450 while ($tag->fetch()) {
451 $tag->blowCache($blowLast);
452 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
456 $cache->delete($ck . ';last');
465 function blowSubsCache($blowLast=false)
467 $cache = common_memcache();
471 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
472 $user->query('SELECT id ' .
474 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
475 'WHERE subscription.subscribed = ' . $this->profile_id);
477 while ($user->fetch()) {
478 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
479 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
481 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
482 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
490 function blowNoticeCache($blowLast=false)
492 if ($this->is_local) {
493 $cache = common_memcache();
494 if (!empty($cache)) {
495 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
497 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
503 function blowRepliesCache($blowLast=false)
505 $cache = common_memcache();
507 $reply = new Reply();
508 $reply->notice_id = $this->id;
509 if ($reply->find()) {
510 while ($reply->fetch()) {
511 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
513 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
522 function blowPublicCache($blowLast=false)
524 if ($this->is_local == 1) {
525 $cache = common_memcache();
527 $cache->delete(common_cache_key('public'));
529 $cache->delete(common_cache_key('public').';last');
535 function blowFavesCache($blowLast=false)
537 $cache = common_memcache();
540 $fave->notice_id = $this->id;
542 while ($fave->fetch()) {
543 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
544 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
546 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
547 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
556 # XXX: too many args; we need to move to named params or even a separate
557 # class for notice streams
559 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
561 if (common_config('memcached', 'enabled')) {
563 # Skip the cache if this is a since, since_id or max_id qry
564 if ($since_id > 0 || $max_id > 0 || $since) {
565 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
567 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
571 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
574 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
579 if (preg_match('/\bWHERE\b/i', $qry)) {
593 $qry .= ' notice.id > ' . $since_id;
605 $qry .= ' notice.id <= ' . $max_id;
617 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
620 # Allow ORDER override
625 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
628 if (common_config('db','type') == 'pgsql') {
629 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
631 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
634 $notice = new Notice();
636 $notice->query($qry);
641 # XXX: this is pretty long and should probably be broken up into
642 # some helper functions
644 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
646 # If outside our cache window, just go to the DB
648 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
649 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
652 # Get the cache; if we can't, just go to the DB
654 $cache = common_memcache();
657 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
660 # Get the notices out of the cache
662 $notices = $cache->get(common_cache_key($cachekey));
664 # On a cache hit, return a DB-object-like wrapper
666 if ($notices !== false) {
667 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
671 # If the cache was invalidated because of new data being
672 # added, we can try and just get the new stuff. We keep an additional
673 # copy of the data at the key + ';last'
675 # No cache hit. Try to get the *last* cached version
677 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
681 # Reverse-chron order, so last ID is last.
683 $last_id = $last_notices[0]->id;
685 # XXX: this assumes monotonically increasing IDs; a fair
688 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
689 $last_id, null, $order, null);
692 $new_notices = array();
693 while ($new_notice->fetch()) {
694 $new_notices[] = clone($new_notice);
697 $notices = array_slice(array_merge($new_notices, $last_notices),
698 0, NOTICE_CACHE_WINDOW);
700 # Store the array in the cache for next time
702 $result = $cache->set(common_cache_key($cachekey), $notices);
703 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
705 # return a wrapper of the array for use now
707 return new ArrayWrapper(array_slice($notices, $offset, $limit));
711 # Otherwise, get the full cache window out of the DB
713 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
715 # If there are no hits, just return the value
721 # Pack results into an array
725 while ($notice->fetch()) {
726 $notices[] = clone($notice);
731 # Store the array in the cache for next time
733 $result = $cache->set(common_cache_key($cachekey), $notices);
734 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
736 # return a wrapper of the array for use now
738 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
743 function getStreamByIds($ids)
745 $cache = common_memcache();
747 if (!empty($cache)) {
749 foreach ($ids as $id) {
750 $n = Notice::staticGet('id', $id);
755 return new ArrayWrapper($notices);
757 $notice = new Notice();
758 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
759 $notice->orderBy('id DESC');
766 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
768 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
771 $offset, $limit, $since_id, $max_id, $since);
773 return Notice::getStreamByIds($ids);
776 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
778 $notice = new Notice();
780 $notice->selectAdd(); // clears it
781 $notice->selectAdd('id');
783 $notice->orderBy('id DESC');
785 if (!is_null($offset)) {
786 $notice->limit($offset, $limit);
789 if (common_config('public', 'localonly')) {
790 $notice->whereAdd('is_local = 1');
793 $notice->whereAdd('is_local != -1');
796 if ($since_id != 0) {
797 $notice->whereAdd('id > ' . $since_id);
801 $notice->whereAdd('id <= ' . $max_id);
804 if (!is_null($since)) {
805 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
810 if ($notice->find()) {
811 while ($notice->fetch()) {
812 $ids[] = $notice->id;
822 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
824 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
826 'notice:conversation_ids:'.$id,
827 $offset, $limit, $since_id, $max_id, $since);
829 return Notice::getStreamByIds($ids);
832 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
834 $notice = new Notice();
836 $notice->selectAdd(); // clears it
837 $notice->selectAdd('id');
839 $notice->conversation = $id;
841 $notice->orderBy('id DESC');
843 if (!is_null($offset)) {
844 $notice->limit($offset, $limit);
847 if ($since_id != 0) {
848 $notice->whereAdd('id > ' . $since_id);
852 $notice->whereAdd('id <= ' . $max_id);
855 if (!is_null($since)) {
856 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
861 if ($notice->find()) {
862 while ($notice->fetch()) {
863 $ids[] = $notice->id;
873 function addToInboxes()
875 $enabled = common_config('inboxes', 'enabled');
877 if ($enabled === true || $enabled === 'transitional') {
879 // XXX: loads constants
881 $inbox = new Notice_inbox();
883 $users = $this->getSubscribedUsers();
885 // FIXME: kind of ignoring 'transitional'...
886 // we'll probably stop supporting inboxless mode
891 foreach ($users as $id) {
892 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
895 $groups = $this->saveGroups();
897 foreach ($groups as $group) {
898 $users = $group->getUserMembers();
899 foreach ($users as $id) {
900 if (!array_key_exists($id, $ni)) {
901 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
908 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
911 foreach ($ni as $id => $source) {
915 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
917 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
918 Notice_inbox::gc($id);
920 if ($cnt >= MAX_BOXCARS) {
921 $inbox = new Notice_inbox();
929 $inbox = new Notice_inbox();
937 function getSubscribedUsers()
941 if(common_config('db','quote_identifiers'))
942 $user_table = '"user"';
943 else $user_table = 'user';
947 'FROM '. $user_table .' JOIN subscription '.
948 'ON '. $user_table .'.id = subscription.subscriber ' .
949 'WHERE subscription.subscribed = %d ';
951 $user->query(sprintf($qry, $this->profile_id));
955 while ($user->fetch()) {
964 function saveGroups()
968 $enabled = common_config('inboxes', 'enabled');
969 if ($enabled !== true && $enabled !== 'transitional') {
973 /* extract all !group */
974 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
975 strtolower($this->content),
981 $profile = $this->getProfile();
983 /* Add them to the database */
985 foreach (array_unique($match[1]) as $nickname) {
986 /* XXX: remote groups. */
987 $group = User_group::getForNickname($nickname);
993 // we automatically add a tag for every group name, too
995 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
996 'notice_id' => $this->id));
999 $this->saveTag($nickname);
1002 if ($profile->isMember($group)) {
1004 $result = $this->addToGroupInbox($group);
1007 common_log_db_error($gi, 'INSERT', __FILE__);
1010 $groups[] = clone($group);
1017 function addToGroupInbox($group)
1019 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1020 'notice_id' => $this->id));
1024 $gi = new Group_inbox();
1026 $gi->group_id = $group->id;
1027 $gi->notice_id = $this->id;
1028 $gi->created = $this->created;
1030 return $gi->insert();
1036 function saveReplies()
1038 // Alternative reply format
1040 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1043 // extract all @messages
1044 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1048 if ($cnt || $tname) {
1049 // XXX: is there another way to make an array copy?
1050 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1053 $sender = Profile::staticGet($this->profile_id);
1057 // store replied only for first @ (what user/notice what the reply directed,
1058 // we assume first @ is it)
1060 for ($i=0; $i<count($names); $i++) {
1061 $nickname = $names[$i];
1062 $recipient = common_relative_profile($sender, $nickname, $this->created);
1066 // Don't save replies from blocked profile to local user
1067 $recipient_user = User::staticGet('id', $recipient->id);
1068 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1071 $reply = new Reply();
1072 $reply->notice_id = $this->id;
1073 $reply->profile_id = $recipient->id;
1074 $id = $reply->insert();
1076 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1077 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1078 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1081 $replied[$recipient->id] = 1;
1085 // Hash format replies, too
1086 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1088 foreach ($match[1] as $tag) {
1089 $tagged = Profile_tag::getTagged($sender->id, $tag);
1090 foreach ($tagged as $t) {
1091 if (!$replied[$t->id]) {
1092 // Don't save replies from blocked profile to local user
1093 $t_user = User::staticGet('id', $t->id);
1094 if ($t_user && $t_user->hasBlocked($sender)) {
1097 $reply = new Reply();
1098 $reply->notice_id = $this->id;
1099 $reply->profile_id = $t->id;
1100 $id = $reply->insert();
1102 common_log_db_error($reply, 'INSERT', __FILE__);
1105 $replied[$recipient->id] = 1;
1112 foreach (array_keys($replied) as $recipient) {
1113 $user = User::staticGet('id', $recipient);
1115 mail_notify_attn($user, $this);
1120 function asAtomEntry($namespace=false, $source=false)
1122 $profile = $this->getProfile();
1124 $xs = new XMLStringer(true);
1127 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1128 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1133 $xs->elementStart('entry', $attrs);
1136 $xs->elementStart('source');
1137 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1138 $xs->element('link', array('href' => $profile->profileurl));
1139 $user = User::staticGet('id', $profile->id);
1140 if (!empty($user)) {
1141 $atom_feed = common_local_url('api',
1142 array('apiaction' => 'statuses',
1143 'method' => 'user_timeline',
1144 'argument' => $profile->nickname.'.atom'));
1145 $xs->element('link', array('rel' => 'self',
1146 'type' => 'application/atom+xml',
1147 'href' => $profile->profileurl));
1148 $xs->element('link', array('rel' => 'license',
1149 'href' => common_config('license', 'url')));
1152 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1155 $xs->elementStart('author');
1156 $xs->element('name', null, $profile->nickname);
1157 $xs->element('uri', null, $profile->profileurl);
1158 $xs->elementEnd('author');
1161 $xs->elementEnd('source');
1164 $xs->element('title', null, $this->content);
1165 $xs->element('summary', null, $this->content);
1167 $xs->element('link', array('rel' => 'alternate',
1168 'href' => $this->bestUrl()));
1170 $xs->element('id', null, $this->uri);
1172 $xs->element('published', null, common_date_w3dtf($this->created));
1173 $xs->element('updated', null, common_date_w3dtf($this->modified));
1175 if ($this->reply_to) {
1176 $reply_notice = Notice::staticGet('id', $this->reply_to);
1177 if (!empty($reply_notice)) {
1178 $xs->element('link', array('rel' => 'related',
1179 'href' => $reply_notice->bestUrl()));
1180 $xs->element('thr:in-reply-to',
1181 array('ref' => $reply_notice->uri,
1182 'href' => $reply_notice->bestUrl()));
1186 $xs->element('content', array('type' => 'html'), $this->rendered);
1188 $tag = new Notice_tag();
1189 $tag->notice_id = $this->id;
1191 while ($tag->fetch()) {
1192 $xs->element('category', array('term' => $tag->tag));
1198 $attachments = $this->attachments();
1200 foreach($attachments as $attachment){
1201 if ($attachment->isEnclosure()) {
1202 $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1203 if($attachment->title){
1204 $attributes['title']=$attachment->title;
1206 $xs->element('link', $attributes, null);
1211 $xs->elementEnd('entry');
1213 return $xs->getString();
1218 if (!empty($this->url)) {
1220 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1223 return common_local_url('shownotice',
1224 array('notice' => $this->id));
1228 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1230 $cache = common_memcache();
1232 if (empty($cache) ||
1233 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1235 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1236 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1240 $idkey = common_cache_key($cachekey);
1242 $idstr = $cache->get($idkey);
1244 if (!empty($idstr)) {
1245 // Cache hit! Woohoo!
1246 $window = explode(',', $idstr);
1247 $ids = array_slice($window, $offset, $limit);
1251 $laststr = $cache->get($idkey.';last');
1253 if (!empty($laststr)) {
1254 $window = explode(',', $laststr);
1255 $last_id = $window[0];
1256 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1257 $last_id, 0, null)));
1259 $new_window = array_merge($new_ids, $window);
1261 $new_windowstr = implode(',', $new_window);
1263 $result = $cache->set($idkey, $new_windowstr);
1264 $result = $cache->set($idkey . ';last', $new_windowstr);
1266 $ids = array_slice($new_window, $offset, $limit);
1271 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1274 $windowstr = implode(',', $window);
1276 $result = $cache->set($idkey, $windowstr);
1277 $result = $cache->set($idkey . ';last', $windowstr);
1279 $ids = array_slice($window, $offset, $limit);
1285 * Determine which notice, if any, a new notice is in reply to.
1287 * For conversation tracking, we try to see where this notice fits
1288 * in the tree. Rough algorithm is:
1290 * if (reply_to is set and valid) {
1292 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1293 * return ID of last notice by initial @name in content;
1296 * Note that all @nickname instances will still be used to save "reply" records,
1297 * so the notice shows up in the mentioned users' "replies" tab.
1299 * @param integer $reply_to ID passed in by Web or API
1300 * @param integer $profile_id ID of author
1301 * @param string $source Source tag, like 'web' or 'gwibber'
1302 * @param string $content Final notice content
1304 * @return integer ID of replied-to notice, or null for not a reply.
1307 static function getReplyTo($reply_to, $profile_id, $source, $content)
1309 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1311 // If $reply_to is specified, we check that it exists, and then
1312 // return it if it does
1314 if (!empty($reply_to)) {
1315 $reply_notice = Notice::staticGet('id', $reply_to);
1316 if (!empty($reply_notice)) {
1321 // If it's not a "low bandwidth" source (one where you can't set
1322 // a reply_to argument), we return. This is mostly web and API
1325 if (!in_array($source, $lb)) {
1329 // Is there an initial @ or T?
1331 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1332 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1333 $nickname = common_canonical_nickname($match[1]);
1338 // Figure out who that is.
1340 $sender = Profile::staticGet('id', $profile_id);
1341 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1343 if (empty($recipient)) {
1347 // Get their last notice
1349 $last = $recipient->getCurrentNotice();
1351 if (!empty($last)) {
1356 static function maxContent()
1358 $contentlimit = common_config('notice', 'contentlimit');
1359 // null => use global limit (distinct from 0!)
1360 if (is_null($contentlimit)) {
1361 $contentlimit = common_config('site', 'textlimit');
1363 return $contentlimit;
1366 static function contentTooLong($content)
1368 $contentlimit = self::maxContent();
1369 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));