3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, 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/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @license GNU Affero General Public License http://www.gnu.org/licenses/
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
40 * Table Definition for notice
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45 * in the memcached cache. */
47 define('NOTICE_CACHE_WINDOW', 61);
49 define('MAX_BOXCARS', 128);
51 class Notice extends Memcached_DataObject
54 /* the code below is auto generated do not remove the above tag */
56 public $__table = 'notice'; // table name
57 public $id; // int(4) primary_key not_null
58 public $profile_id; // int(4) multiple_key not_null
59 public $uri; // varchar(255) unique_key
60 public $content; // text
61 public $rendered; // text
62 public $url; // varchar(255)
63 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
64 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
65 public $reply_to; // int(4)
66 public $is_local; // int(4)
67 public $source; // varchar(32)
68 public $conversation; // int(4)
69 public $lat; // decimal(10,7)
70 public $lon; // decimal(10,7)
71 public $location_id; // int(4)
72 public $location_ns; // int(4)
73 public $repeat_of; // int(4)
76 function staticGet($k,$v=NULL)
78 return Memcached_DataObject::staticGet('Notice',$k,$v);
81 /* the code above is auto generated do not remove the tag below */
85 const LOCAL_PUBLIC = 1;
87 const LOCAL_NONPUBLIC = -1;
92 return Profile::staticGet('id', $this->profile_id);
97 $this->blowCaches(true);
98 $this->blowFavesCache(true);
99 $this->blowSubsCache(true);
101 // For auditing purposes, save a record that the notice
104 $deleted = new Deleted_notice();
106 $deleted->id = $this->id;
107 $deleted->profile_id = $this->profile_id;
108 $deleted->uri = $this->uri;
109 $deleted->created = $this->created;
110 $deleted->deleted = common_sql_now();
112 $this->query('BEGIN');
116 //Null any notices that are replies to this notice
117 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
119 //Null any notices that are repeats of this notice
120 //XXX: probably need to uncache these, too
122 $this->query(sprintf("UPDATE notice set repeat_of = null WHERE repeat_of = %d", $this->id));
124 $related = array('Reply',
131 foreach ($related as $cls) {
133 $inst->notice_id = $this->id;
136 $result = parent::delete();
137 $this->query('COMMIT');
142 /* extract all #hastags */
143 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
148 //turn each into their canonical tag
149 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
151 for($i=0; $i<count($match[1]); $i++) {
152 $hashtags[] = common_canonical_tag($match[1][$i]);
155 /* Add them to the database */
156 foreach(array_unique($hashtags) as $hashtag) {
157 /* elide characters we don't want in the tag */
158 $this->saveTag($hashtag);
163 function saveTag($hashtag)
165 $tag = new Notice_tag();
166 $tag->notice_id = $this->id;
167 $tag->tag = $hashtag;
168 $tag->created = $this->created;
169 $id = $tag->insert();
172 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
173 $last_error->message));
179 * Save a new notice and push it out to subscribers' inboxes.
180 * Poster's permissions are checked before sending.
182 * @param int $profile_id Profile ID of the poster
183 * @param string $content source message text; links may be shortened
184 * per current user's preference
185 * @param string $source source key ('web', 'api', etc)
186 * @param array $options Associative array of optional properties:
187 * string 'created' timestamp of notice; defaults to now
188 * int 'is_local' source/gateway ID, one of:
189 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
190 * Notice::REMOTE_OMB - Sent from a remote OMB service;
191 * hide from public timeline but show in
192 * local "and friends" timelines
193 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
194 * Notice::GATEWAY - From another non-OMB service;
195 * will not appear in public views
196 * float 'lat' decimal latitude for geolocation
197 * float 'lon' decimal longitude for geolocation
198 * int 'location_id' geoname identifier
199 * int 'location_ns' geoname namespace to interpret location_id
200 * int 'reply_to'; notice ID this is a reply to
201 * int 'repeat_of'; notice ID this is a repeat of
202 * string 'uri' permalink to notice; defaults to local notice URL
205 * @throws ClientException
207 static function saveNew($profile_id, $content, $source, $options=null) {
208 $defaults = array('uri' => null,
210 'repeat_of' => null);
212 if (!empty($options)) {
213 $options = $options + $defaults;
217 if (!isset($is_local)) {
218 $is_local = Notice::LOCAL_PUBLIC;
221 $profile = Profile::staticGet($profile_id);
223 $final = common_shorten_links($content);
225 if (Notice::contentTooLong($final)) {
226 throw new ClientException(_('Problem saving notice. Too long.'));
229 if (empty($profile)) {
230 throw new ClientException(_('Problem saving notice. Unknown user.'));
233 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
234 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
235 throw new ClientException(_('Too many notices too fast; take a breather '.
236 'and post again in a few minutes.'));
239 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
240 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
241 throw new ClientException(_('Too many duplicate messages too quickly;'.
242 ' take a breather and post again in a few minutes.'));
245 if (!$profile->hasRight(Right::NEWNOTICE)) {
246 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
247 throw new ClientException(_('You are banned from posting notices on this site.'));
250 $notice = new Notice();
251 $notice->profile_id = $profile_id;
253 $autosource = common_config('public', 'autosource');
255 # Sandboxed are non-false, but not 1, either
257 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
258 ($source && $autosource && in_array($source, $autosource))) {
259 $notice->is_local = Notice::LOCAL_NONPUBLIC;
261 $notice->is_local = $is_local;
264 if (!empty($created)) {
265 $notice->created = $created;
267 $notice->created = common_sql_now();
270 $notice->content = $final;
271 $notice->rendered = common_render_content($final, $notice);
272 $notice->source = $source;
275 // Handle repeat case
277 if (isset($repeat_of)) {
278 $notice->repeat_of = $repeat_of;
279 $notice->reply_to = $repeat_of;
281 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
284 if (!empty($notice->reply_to)) {
285 $reply = Notice::staticGet('id', $notice->reply_to);
286 $notice->conversation = $reply->conversation;
289 if (!empty($lat) && !empty($lon)) {
294 if (!empty($location_ns) && !empty($location_id)) {
295 $notice->location_id = $location_id;
296 $notice->location_ns = $location_ns;
299 if (Event::handle('StartNoticeSave', array(&$notice))) {
301 // XXX: some of these functions write to the DB
303 $notice->query('BEGIN');
305 $id = $notice->insert();
308 common_log_db_error($notice, 'INSERT', __FILE__);
309 throw new ServerException(_('Problem saving notice.'));
312 // Update ID-dependent columns: URI, conversation
314 $orig = clone($notice);
319 $notice->uri = common_notice_uri($notice);
323 // If it's not part of a conversation, it's
324 // the beginning of a new conversation.
326 if (empty($notice->conversation)) {
327 $notice->conversation = $notice->id;
332 if (!$notice->update($orig)) {
333 common_log_db_error($notice, 'UPDATE', __FILE__);
334 throw new ServerException(_('Problem saving notice.'));
338 // XXX: do we need to change this for remote users?
342 $notice->addToInboxes();
346 $notice->query('COMMIT');
348 Event::handle('EndNoticeSave', array($notice));
351 # Clear the cache for subscribed users, so they'll update at next request
352 # XXX: someone clever could prepend instead of clearing the cache
354 $notice->blowCaches();
359 /** save all urls in the notice to the db
361 * follow redirects and save all available file information
362 * (mimetype, date, size, oembed, etc.)
366 function saveUrls() {
367 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
370 function saveUrl($data) {
371 list($url, $notice_id) = $data;
372 File::processNew($url, $notice_id);
375 static function checkDupes($profile_id, $content) {
376 $profile = Profile::staticGet($profile_id);
377 if (empty($profile)) {
380 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
381 if (!empty($notice)) {
383 while ($notice->fetch()) {
384 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
386 } else if ($notice->content == $content) {
391 # If we get here, oldest item in cache window is not
392 # old enough for dupe limit; do direct check against DB
393 $notice = new Notice();
394 $notice->profile_id = $profile_id;
395 $notice->content = $content;
396 if (common_config('db','type') == 'pgsql')
397 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
399 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
401 $cnt = $notice->count();
405 static function checkEditThrottle($profile_id) {
406 $profile = Profile::staticGet($profile_id);
407 if (empty($profile)) {
411 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
412 if ($notice && $notice->fetch()) {
413 # If the Nth notice was posted less than timespan seconds ago
414 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
419 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
423 function getUploadedAttachment() {
425 $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"';
426 $post->query($query);
428 if (empty($post->up) || empty($post->i)) {
431 $ret = array($post->up, $post->i);
437 function hasAttachments() {
439 $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);
440 $post->query($query);
442 $n_attachments = intval($post->n_attachments);
444 return $n_attachments;
447 function attachments() {
450 $f2p = new File_to_post;
451 $f2p->post_id = $this->id;
453 while ($f2p->fetch()) {
454 $f = File::staticGet($f2p->file_id);
461 function blowCaches($blowLast=false)
463 $this->blowSubsCache($blowLast);
464 $this->blowNoticeCache($blowLast);
465 $this->blowRepliesCache($blowLast);
466 $this->blowPublicCache($blowLast);
467 $this->blowTagCache($blowLast);
468 $this->blowGroupCache($blowLast);
469 $this->blowConversationCache($blowLast);
470 $this->blowRepeatCache();
471 $profile = Profile::staticGet($this->profile_id);
472 $profile->blowNoticeCount();
475 function blowRepeatCache()
477 if (!empty($this->repeat_of)) {
478 $cache = common_memcache();
479 if (!empty($cache)) {
480 // XXX: only blow if <100 in cache
481 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
482 $result = $cache->delete($ck);
484 $user = User::staticGet('id', $this->profile_id);
487 $uk = common_cache_key('user:repeated_by_me:'.$user->id);
493 $original = Notice::staticGet('id', $this->repeat_of);
495 if (!empty($original)) {
496 $originalUser = User::staticGet('id', $original->profile_id);
497 if (!empty($originalUser)) {
498 $ouk = common_cache_key('user:repeats_of_me:'.$originalUser->id);
499 $cache->delete($ouk);
500 $originalUser->free();
501 unset($originalUser);
507 $ni = new Notice_inbox();
509 $ni->notice_id = $this->id;
512 while ($ni->fetch()) {
513 $tmk = common_cache_key('user:repeated_to_me:'.$ni->user_id);
514 $cache->delete($tmk);
524 function blowConversationCache($blowLast=false)
526 $cache = common_memcache();
528 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
531 $cache->delete($ck.';last');
536 function blowGroupCache($blowLast=false)
538 $cache = common_memcache();
540 $group_inbox = new Group_inbox();
541 $group_inbox->notice_id = $this->id;
542 if ($group_inbox->find()) {
543 while ($group_inbox->fetch()) {
544 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
546 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
548 $member = new Group_member();
549 $member->group_id = $group_inbox->group_id;
550 if ($member->find()) {
551 while ($member->fetch()) {
552 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
553 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id));
554 if (empty($this->repeat_of)) {
555 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id));
556 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id));
559 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
560 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id . ';last'));
561 if (empty($this->repeat_of)) {
562 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id . ';last'));
563 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id . ';last'));
570 $group_inbox->free();
575 function blowTagCache($blowLast=false)
577 $cache = common_memcache();
579 $tag = new Notice_tag();
580 $tag->notice_id = $this->id;
582 while ($tag->fetch()) {
583 $tag->blowCache($blowLast);
584 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
588 $cache->delete($ck . ';last');
597 function blowSubsCache($blowLast=false)
599 $cache = common_memcache();
603 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
604 $user->query('SELECT id ' .
606 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
607 'WHERE subscription.subscribed = ' . $this->profile_id);
609 while ($user->fetch()) {
610 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
611 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
612 if (empty($this->repeat_of)) {
613 $cache->delete(common_cache_key('user:friends_timeline:'.$user->id));
614 $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id));
617 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
618 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
619 if (empty($this->repeat_of)) {
620 $cache->delete(common_cache_key('user:friends_timeline:'.$user->id.';last'));
621 $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id.';last'));
630 function blowNoticeCache($blowLast=false)
632 if ($this->is_local) {
633 $cache = common_memcache();
634 if (!empty($cache)) {
635 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
637 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
643 function blowRepliesCache($blowLast=false)
645 $cache = common_memcache();
647 $reply = new Reply();
648 $reply->notice_id = $this->id;
649 if ($reply->find()) {
650 while ($reply->fetch()) {
651 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
653 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
662 function blowPublicCache($blowLast=false)
664 if ($this->is_local == Notice::LOCAL_PUBLIC) {
665 $cache = common_memcache();
667 $cache->delete(common_cache_key('public'));
669 $cache->delete(common_cache_key('public').';last');
675 function blowFavesCache($blowLast=false)
677 $cache = common_memcache();
680 $fave->notice_id = $this->id;
682 while ($fave->fetch()) {
683 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
684 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
686 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
687 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
696 function getStreamByIds($ids)
698 $cache = common_memcache();
700 if (!empty($cache)) {
702 foreach ($ids as $id) {
703 $n = Notice::staticGet('id', $id);
708 return new ArrayWrapper($notices);
710 $notice = new Notice();
712 //if no IDs requested, just return the notice object
715 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
721 while ($notice->fetch()) {
722 $temp[$notice->id] = clone($notice);
727 foreach ($ids as $id) {
728 if (array_key_exists($id, $temp)) {
729 $wrapped[] = $temp[$id];
733 return new ArrayWrapper($wrapped);
737 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
739 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
742 $offset, $limit, $since_id, $max_id, $since);
744 return Notice::getStreamByIds($ids);
747 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
749 $notice = new Notice();
751 $notice->selectAdd(); // clears it
752 $notice->selectAdd('id');
754 $notice->orderBy('id DESC');
756 if (!is_null($offset)) {
757 $notice->limit($offset, $limit);
760 if (common_config('public', 'localonly')) {
761 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
763 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
764 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
765 $notice->whereAdd('is_local !='. Notice::GATEWAY);
768 if ($since_id != 0) {
769 $notice->whereAdd('id > ' . $since_id);
773 $notice->whereAdd('id <= ' . $max_id);
776 if (!is_null($since)) {
777 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
782 if ($notice->find()) {
783 while ($notice->fetch()) {
784 $ids[] = $notice->id;
794 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
796 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
798 'notice:conversation_ids:'.$id,
799 $offset, $limit, $since_id, $max_id, $since);
801 return Notice::getStreamByIds($ids);
804 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
806 $notice = new Notice();
808 $notice->selectAdd(); // clears it
809 $notice->selectAdd('id');
811 $notice->conversation = $id;
813 $notice->orderBy('id DESC');
815 if (!is_null($offset)) {
816 $notice->limit($offset, $limit);
819 if ($since_id != 0) {
820 $notice->whereAdd('id > ' . $since_id);
824 $notice->whereAdd('id <= ' . $max_id);
827 if (!is_null($since)) {
828 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
833 if ($notice->find()) {
834 while ($notice->fetch()) {
835 $ids[] = $notice->id;
845 function addToInboxes()
847 // XXX: loads constants
849 $inbox = new Notice_inbox();
851 $users = $this->getSubscribedUsers();
853 // FIXME: kind of ignoring 'transitional'...
854 // we'll probably stop supporting inboxless mode
859 foreach ($users as $id) {
860 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
863 $groups = $this->saveGroups();
864 $profile = $this->getProfile();
866 foreach ($groups as $group) {
867 $users = $group->getUserMembers();
868 foreach ($users as $id) {
869 if (!array_key_exists($id, $ni)) {
870 $user = User::staticGet('id', $id);
871 if (!$user->hasBlocked($profile)) {
872 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
878 $recipients = $this->saveReplies();
880 foreach ($recipients as $recipient) {
882 if (!array_key_exists($recipient, $ni)) {
883 $recipientUser = User::staticGet('id', $recipient);
884 if (!empty($recipientUser)) {
885 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
890 Notice_inbox::bulkInsert($this->id, $this->created, $ni);
895 function getSubscribedUsers()
899 if(common_config('db','quote_identifiers'))
900 $user_table = '"user"';
901 else $user_table = 'user';
905 'FROM '. $user_table .' JOIN subscription '.
906 'ON '. $user_table .'.id = subscription.subscriber ' .
907 'WHERE subscription.subscribed = %d ';
909 $user->query(sprintf($qry, $this->profile_id));
913 while ($user->fetch()) {
922 function saveGroups()
926 /* extract all !group */
927 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
928 strtolower($this->content),
934 $profile = $this->getProfile();
936 /* Add them to the database */
938 foreach (array_unique($match[1]) as $nickname) {
939 /* XXX: remote groups. */
940 $group = User_group::getForNickname($nickname);
946 // we automatically add a tag for every group name, too
948 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
949 'notice_id' => $this->id));
952 $this->saveTag($nickname);
955 if ($profile->isMember($group)) {
957 $result = $this->addToGroupInbox($group);
960 common_log_db_error($gi, 'INSERT', __FILE__);
963 $groups[] = clone($group);
970 function addToGroupInbox($group)
972 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
973 'notice_id' => $this->id));
977 $gi = new Group_inbox();
979 $gi->group_id = $group->id;
980 $gi->notice_id = $this->id;
981 $gi->created = $this->created;
983 return $gi->insert();
990 * @return array of integer profile IDs
992 function saveReplies()
994 // Alternative reply format
996 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
999 // extract all @messages
1000 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1004 if ($cnt || $tname) {
1005 // XXX: is there another way to make an array copy?
1006 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1009 $sender = Profile::staticGet($this->profile_id);
1013 // store replied only for first @ (what user/notice what the reply directed,
1014 // we assume first @ is it)
1016 for ($i=0; $i<count($names); $i++) {
1017 $nickname = $names[$i];
1018 $recipient = common_relative_profile($sender, $nickname, $this->created);
1019 if (empty($recipient)) {
1022 // Don't save replies from blocked profile to local user
1023 $recipient_user = User::staticGet('id', $recipient->id);
1024 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1027 $reply = new Reply();
1028 $reply->notice_id = $this->id;
1029 $reply->profile_id = $recipient->id;
1030 $id = $reply->insert();
1032 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1033 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1034 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1037 $replied[$recipient->id] = 1;
1041 // Hash format replies, too
1042 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1044 foreach ($match[1] as $tag) {
1045 $tagged = Profile_tag::getTagged($sender->id, $tag);
1046 foreach ($tagged as $t) {
1047 if (!$replied[$t->id]) {
1048 // Don't save replies from blocked profile to local user
1049 $t_user = User::staticGet('id', $t->id);
1050 if ($t_user && $t_user->hasBlocked($sender)) {
1053 $reply = new Reply();
1054 $reply->notice_id = $this->id;
1055 $reply->profile_id = $t->id;
1056 $id = $reply->insert();
1058 common_log_db_error($reply, 'INSERT', __FILE__);
1061 $replied[$recipient->id] = 1;
1068 $recipientIds = array_keys($replied);
1070 foreach ($recipientIds as $recipientId) {
1071 $user = User::staticGet('id', $recipientId);
1073 mail_notify_attn($user, $this);
1077 return $recipientIds;
1080 function asAtomEntry($namespace=false, $source=false)
1082 $profile = $this->getProfile();
1084 $xs = new XMLStringer(true);
1087 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1088 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1093 $xs->elementStart('entry', $attrs);
1096 $xs->elementStart('source');
1097 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1098 $xs->element('link', array('href' => $profile->profileurl));
1099 $user = User::staticGet('id', $profile->id);
1100 if (!empty($user)) {
1101 $atom_feed = common_local_url('ApiTimelineUser',
1102 array('format' => 'atom',
1103 'id' => $profile->nickname));
1104 $xs->element('link', array('rel' => 'self',
1105 'type' => 'application/atom+xml',
1106 'href' => $profile->profileurl));
1107 $xs->element('link', array('rel' => 'license',
1108 'href' => common_config('license', 'url')));
1111 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1114 $xs->elementStart('author');
1115 $xs->element('name', null, $profile->nickname);
1116 $xs->element('uri', null, $profile->profileurl);
1117 $xs->elementEnd('author');
1120 $xs->elementEnd('source');
1123 $xs->element('title', null, $this->content);
1124 $xs->element('summary', null, $this->content);
1126 $xs->element('link', array('rel' => 'alternate',
1127 'href' => $this->bestUrl()));
1129 $xs->element('id', null, $this->uri);
1131 $xs->element('published', null, common_date_w3dtf($this->created));
1132 $xs->element('updated', null, common_date_w3dtf($this->created));
1134 if ($this->reply_to) {
1135 $reply_notice = Notice::staticGet('id', $this->reply_to);
1136 if (!empty($reply_notice)) {
1137 $xs->element('link', array('rel' => 'related',
1138 'href' => $reply_notice->bestUrl()));
1139 $xs->element('thr:in-reply-to',
1140 array('ref' => $reply_notice->uri,
1141 'href' => $reply_notice->bestUrl()));
1145 $xs->element('content', array('type' => 'html'), $this->rendered);
1147 $tag = new Notice_tag();
1148 $tag->notice_id = $this->id;
1150 while ($tag->fetch()) {
1151 $xs->element('category', array('term' => $tag->tag));
1157 $attachments = $this->attachments();
1159 foreach($attachments as $attachment){
1160 $enclosure=$attachment->getEnclosure();
1162 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1163 if($enclosure->title){
1164 $attributes['title']=$enclosure->title;
1166 $xs->element('link', $attributes, null);
1171 if (!empty($this->lat) && !empty($this->lon)) {
1172 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1173 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1174 $xs->elementEnd('geo');
1177 $xs->elementEnd('entry');
1179 return $xs->getString();
1184 if (!empty($this->url)) {
1186 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1189 return common_local_url('shownotice',
1190 array('notice' => $this->id));
1194 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1196 $cache = common_memcache();
1198 if (empty($cache) ||
1199 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1201 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1202 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1206 $idkey = common_cache_key($cachekey);
1208 $idstr = $cache->get($idkey);
1210 if ($idstr !== false) {
1211 // Cache hit! Woohoo!
1212 $window = explode(',', $idstr);
1213 $ids = array_slice($window, $offset, $limit);
1217 $laststr = $cache->get($idkey.';last');
1219 if ($laststr !== false) {
1220 $window = explode(',', $laststr);
1221 $last_id = $window[0];
1222 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1223 $last_id, 0, null)));
1225 $new_window = array_merge($new_ids, $window);
1227 $new_windowstr = implode(',', $new_window);
1229 $result = $cache->set($idkey, $new_windowstr);
1230 $result = $cache->set($idkey . ';last', $new_windowstr);
1232 $ids = array_slice($new_window, $offset, $limit);
1237 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1240 $windowstr = implode(',', $window);
1242 $result = $cache->set($idkey, $windowstr);
1243 $result = $cache->set($idkey . ';last', $windowstr);
1245 $ids = array_slice($window, $offset, $limit);
1251 * Determine which notice, if any, a new notice is in reply to.
1253 * For conversation tracking, we try to see where this notice fits
1254 * in the tree. Rough algorithm is:
1256 * if (reply_to is set and valid) {
1258 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1259 * return ID of last notice by initial @name in content;
1262 * Note that all @nickname instances will still be used to save "reply" records,
1263 * so the notice shows up in the mentioned users' "replies" tab.
1265 * @param integer $reply_to ID passed in by Web or API
1266 * @param integer $profile_id ID of author
1267 * @param string $source Source tag, like 'web' or 'gwibber'
1268 * @param string $content Final notice content
1270 * @return integer ID of replied-to notice, or null for not a reply.
1273 static function getReplyTo($reply_to, $profile_id, $source, $content)
1275 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1277 // If $reply_to is specified, we check that it exists, and then
1278 // return it if it does
1280 if (!empty($reply_to)) {
1281 $reply_notice = Notice::staticGet('id', $reply_to);
1282 if (!empty($reply_notice)) {
1287 // If it's not a "low bandwidth" source (one where you can't set
1288 // a reply_to argument), we return. This is mostly web and API
1291 if (!in_array($source, $lb)) {
1295 // Is there an initial @ or T?
1297 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1298 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1299 $nickname = common_canonical_nickname($match[1]);
1304 // Figure out who that is.
1306 $sender = Profile::staticGet('id', $profile_id);
1307 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1309 if (empty($recipient)) {
1313 // Get their last notice
1315 $last = $recipient->getCurrentNotice();
1317 if (!empty($last)) {
1322 static function maxContent()
1324 $contentlimit = common_config('notice', 'contentlimit');
1325 // null => use global limit (distinct from 0!)
1326 if (is_null($contentlimit)) {
1327 $contentlimit = common_config('site', 'textlimit');
1329 return $contentlimit;
1332 static function contentTooLong($content)
1334 $contentlimit = self::maxContent();
1335 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1338 function getLocation()
1342 if (!empty($this->location_id) && !empty($this->location_ns)) {
1343 $location = Location::fromId($this->location_id, $this->location_ns);
1346 if (is_null($location)) { // no ID, or Location::fromId() failed
1347 if (!empty($this->lat) && !empty($this->lon)) {
1348 $location = Location::fromLatLon($this->lat, $this->lon);
1355 function repeat($repeater_id, $source)
1357 $author = Profile::staticGet('id', $this->profile_id);
1359 $content = sprintf(_('RT @%1$s %2$s'),
1363 $maxlen = common_config('site', 'textlimit');
1364 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1365 // Web interface and current Twitter API clients will
1366 // pull the original notice's text, but some older
1367 // clients and RSS/Atom feeds will see this trimmed text.
1369 // Unfortunately this is likely to lose tags or URLs
1370 // at the end of long notices.
1371 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1374 return self::saveNew($repeater_id, $content, $source,
1375 array('repeat_of' => $this->id));
1378 // These are supposed to be in chron order!
1380 function repeatStream($limit=100)
1382 $cache = common_memcache();
1384 if (empty($cache)) {
1385 $ids = $this->_repeatStreamDirect($limit);
1387 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1388 if ($idstr !== false) {
1389 $ids = explode(',', $idstr);
1391 $ids = $this->_repeatStreamDirect(100);
1392 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1395 // We do a max of 100, so slice down to limit
1396 $ids = array_slice($ids, 0, $limit);
1400 return Notice::getStreamByIds($ids);
1403 function _repeatStreamDirect($limit)
1405 $notice = new Notice();
1407 $notice->selectAdd(); // clears it
1408 $notice->selectAdd('id');
1410 $notice->repeat_of = $this->id;
1412 $notice->orderBy('created'); // NB: asc!
1414 if (!is_null($offset)) {
1415 $notice->limit($offset, $limit);
1420 if ($notice->find()) {
1421 while ($notice->fetch()) {
1422 $ids[] = $notice->id;
1432 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1436 if (!empty($location_id) && !empty($location_ns)) {
1438 $options['location_id'] = $location_id;
1439 $options['location_ns'] = $location_ns;
1441 $location = Location::fromId($location_id, $location_ns);
1443 if (!empty($location)) {
1444 $options['lat'] = $location->lat;
1445 $options['lon'] = $location->lon;
1448 } else if (!empty($lat) && !empty($lon)) {
1450 $options['lat'] = $lat;
1451 $options['lon'] = $lon;
1453 $location = Location::fromLatLon($lat, $lon);
1455 if (!empty($location)) {
1456 $options['location_id'] = $location->location_id;
1457 $options['location_ns'] = $location->location_ns;
1459 } else if (!empty($profile)) {
1461 if (isset($profile->lat) && isset($profile->lon)) {
1462 $options['lat'] = $profile->lat;
1463 $options['lon'] = $profile->lon;
1466 if (isset($profile->location_id) && isset($profile->location_ns)) {
1467 $options['location_id'] = $profile->location_id;
1468 $options['location_ns'] = $profile->location_ns;