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',
130 foreach ($related as $cls) {
132 $inst->notice_id = $this->id;
135 $result = parent::delete();
136 $this->query('COMMIT');
141 /* extract all #hastags */
142 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
147 //turn each into their canonical tag
148 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
150 for($i=0; $i<count($match[1]); $i++) {
151 $hashtags[] = common_canonical_tag($match[1][$i]);
154 /* Add them to the database */
155 foreach(array_unique($hashtags) as $hashtag) {
156 /* elide characters we don't want in the tag */
157 $this->saveTag($hashtag);
162 function saveTag($hashtag)
164 $tag = new Notice_tag();
165 $tag->notice_id = $this->id;
166 $tag->tag = $hashtag;
167 $tag->created = $this->created;
168 $id = $tag->insert();
171 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
172 $last_error->message));
178 * Save a new notice and push it out to subscribers' inboxes.
179 * Poster's permissions are checked before sending.
181 * @param int $profile_id Profile ID of the poster
182 * @param string $content source message text; links may be shortened
183 * per current user's preference
184 * @param string $source source key ('web', 'api', etc)
185 * @param array $options Associative array of optional properties:
186 * string 'created' timestamp of notice; defaults to now
187 * int 'is_local' source/gateway ID, one of:
188 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
189 * Notice::REMOTE_OMB - Sent from a remote OMB service;
190 * hide from public timeline but show in
191 * local "and friends" timelines
192 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
193 * Notice::GATEWAY - From another non-OMB service;
194 * will not appear in public views
195 * float 'lat' decimal latitude for geolocation
196 * float 'lon' decimal longitude for geolocation
197 * int 'location_id' geoname identifier
198 * int 'location_ns' geoname namespace to interpret location_id
199 * int 'reply_to'; notice ID this is a reply to
200 * int 'repeat_of'; notice ID this is a repeat of
201 * string 'uri' permalink to notice; defaults to local notice URL
204 * @throws ClientException
206 static function saveNew($profile_id, $content, $source, $options=null) {
207 $defaults = array('uri' => null,
209 'repeat_of' => null);
211 if (!empty($options)) {
212 $options = $options + $defaults;
216 if (!isset($is_local)) {
217 $is_local = Notice::LOCAL_PUBLIC;
220 $profile = Profile::staticGet($profile_id);
222 $final = common_shorten_links($content);
224 if (Notice::contentTooLong($final)) {
225 throw new ClientException(_('Problem saving notice. Too long.'));
228 if (empty($profile)) {
229 throw new ClientException(_('Problem saving notice. Unknown user.'));
232 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
233 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
234 throw new ClientException(_('Too many notices too fast; take a breather '.
235 'and post again in a few minutes.'));
238 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
239 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
240 throw new ClientException(_('Too many duplicate messages too quickly;'.
241 ' take a breather and post again in a few minutes.'));
244 if (!$profile->hasRight(Right::NEWNOTICE)) {
245 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
246 throw new ClientException(_('You are banned from posting notices on this site.'));
249 $notice = new Notice();
250 $notice->profile_id = $profile_id;
252 $autosource = common_config('public', 'autosource');
254 # Sandboxed are non-false, but not 1, either
256 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
257 ($source && $autosource && in_array($source, $autosource))) {
258 $notice->is_local = Notice::LOCAL_NONPUBLIC;
260 $notice->is_local = $is_local;
263 if (!empty($created)) {
264 $notice->created = $created;
266 $notice->created = common_sql_now();
269 $notice->content = $final;
270 $notice->rendered = common_render_content($final, $notice);
271 $notice->source = $source;
274 // Handle repeat case
276 if (isset($repeat_of)) {
277 $notice->repeat_of = $repeat_of;
278 $notice->reply_to = $repeat_of;
280 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
283 if (!empty($notice->reply_to)) {
284 $reply = Notice::staticGet('id', $notice->reply_to);
285 $notice->conversation = $reply->conversation;
288 if (!empty($lat) && !empty($lon)) {
293 if (!empty($location_ns) && !empty($location_id)) {
294 $notice->location_id = $location_id;
295 $notice->location_ns = $location_ns;
298 if (Event::handle('StartNoticeSave', array(&$notice))) {
300 // XXX: some of these functions write to the DB
302 $id = $notice->insert();
305 common_log_db_error($notice, 'INSERT', __FILE__);
306 throw new ServerException(_('Problem saving notice.'));
309 // Update ID-dependent columns: URI, conversation
311 $orig = clone($notice);
316 $notice->uri = common_notice_uri($notice);
320 // If it's not part of a conversation, it's
321 // the beginning of a new conversation.
323 if (empty($notice->conversation)) {
324 $notice->conversation = $notice->id;
329 if (!$notice->update($orig)) {
330 common_log_db_error($notice, 'UPDATE', __FILE__);
331 throw new ServerException(_('Problem saving notice.'));
335 // XXX: do we need to change this for remote users?
339 $notice->addToInboxes();
343 Event::handle('EndNoticeSave', array($notice));
346 # Clear the cache for subscribed users, so they'll update at next request
347 # XXX: someone clever could prepend instead of clearing the cache
349 $notice->blowCaches();
354 /** save all urls in the notice to the db
356 * follow redirects and save all available file information
357 * (mimetype, date, size, oembed, etc.)
361 function saveUrls() {
362 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
365 function saveUrl($data) {
366 list($url, $notice_id) = $data;
367 File::processNew($url, $notice_id);
370 static function checkDupes($profile_id, $content) {
371 $profile = Profile::staticGet($profile_id);
372 if (empty($profile)) {
375 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
376 if (!empty($notice)) {
378 while ($notice->fetch()) {
379 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
381 } else if ($notice->content == $content) {
386 # If we get here, oldest item in cache window is not
387 # old enough for dupe limit; do direct check against DB
388 $notice = new Notice();
389 $notice->profile_id = $profile_id;
390 $notice->content = $content;
391 if (common_config('db','type') == 'pgsql')
392 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
394 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
396 $cnt = $notice->count();
400 static function checkEditThrottle($profile_id) {
401 $profile = Profile::staticGet($profile_id);
402 if (empty($profile)) {
406 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
407 if ($notice && $notice->fetch()) {
408 # If the Nth notice was posted less than timespan seconds ago
409 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
414 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
418 function getUploadedAttachment() {
420 $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"';
421 $post->query($query);
423 if (empty($post->up) || empty($post->i)) {
426 $ret = array($post->up, $post->i);
432 function hasAttachments() {
434 $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);
435 $post->query($query);
437 $n_attachments = intval($post->n_attachments);
439 return $n_attachments;
442 function attachments() {
445 $f2p = new File_to_post;
446 $f2p->post_id = $this->id;
448 while ($f2p->fetch()) {
449 $f = File::staticGet($f2p->file_id);
456 function blowCaches($blowLast=false)
458 $this->blowSubsCache($blowLast);
459 $this->blowNoticeCache($blowLast);
460 $this->blowRepliesCache($blowLast);
461 $this->blowPublicCache($blowLast);
462 $this->blowTagCache($blowLast);
463 $this->blowGroupCache($blowLast);
464 $this->blowConversationCache($blowLast);
465 $this->blowRepeatCache();
466 $profile = Profile::staticGet($this->profile_id);
467 $profile->blowNoticeCount();
470 function blowRepeatCache()
472 if (!empty($this->repeat_of)) {
473 $cache = common_memcache();
474 if (!empty($cache)) {
475 // XXX: only blow if <100 in cache
476 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
477 $result = $cache->delete($ck);
479 $user = User::staticGet('id', $this->profile_id);
482 $uk = common_cache_key('user:repeated_by_me:'.$user->id);
488 $original = Notice::staticGet('id', $this->repeat_of);
490 if (!empty($original)) {
491 $originalUser = User::staticGet('id', $original->profile_id);
492 if (!empty($originalUser)) {
493 $ouk = common_cache_key('user:repeats_of_me:'.$originalUser->id);
494 $cache->delete($ouk);
495 $originalUser->free();
496 unset($originalUser);
508 function blowConversationCache($blowLast=false)
510 $cache = common_memcache();
512 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
515 $cache->delete($ck.';last');
520 function blowGroupCache($blowLast=false)
522 $cache = common_memcache();
524 $group_inbox = new Group_inbox();
525 $group_inbox->notice_id = $this->id;
526 if ($group_inbox->find()) {
527 while ($group_inbox->fetch()) {
528 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
530 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
532 $member = new Group_member();
533 $member->group_id = $group_inbox->group_id;
534 if ($member->find()) {
535 while ($member->fetch()) {
536 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
537 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id));
538 if (empty($this->repeat_of)) {
539 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id));
540 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id));
543 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
544 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id . ';last'));
545 if (empty($this->repeat_of)) {
546 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id . ';last'));
547 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id . ';last'));
554 $group_inbox->free();
559 function blowTagCache($blowLast=false)
561 $cache = common_memcache();
563 $tag = new Notice_tag();
564 $tag->notice_id = $this->id;
566 while ($tag->fetch()) {
567 $tag->blowCache($blowLast);
568 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
572 $cache->delete($ck . ';last');
581 function blowSubsCache($blowLast=false)
583 $cache = common_memcache();
587 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
588 $user->query('SELECT id ' .
590 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
591 'WHERE subscription.subscribed = ' . $this->profile_id);
593 while ($user->fetch()) {
594 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
595 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
596 if (empty($this->repeat_of)) {
597 $cache->delete(common_cache_key('user:friends_timeline:'.$user->id));
598 $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id));
601 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
602 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
603 if (empty($this->repeat_of)) {
604 $cache->delete(common_cache_key('user:friends_timeline:'.$user->id.';last'));
605 $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id.';last'));
614 function blowNoticeCache($blowLast=false)
616 if ($this->is_local) {
617 $cache = common_memcache();
618 if (!empty($cache)) {
619 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
621 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
627 function blowRepliesCache($blowLast=false)
629 $cache = common_memcache();
631 $reply = new Reply();
632 $reply->notice_id = $this->id;
633 if ($reply->find()) {
634 while ($reply->fetch()) {
635 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
637 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
646 function blowPublicCache($blowLast=false)
648 if ($this->is_local == Notice::LOCAL_PUBLIC) {
649 $cache = common_memcache();
651 $cache->delete(common_cache_key('public'));
653 $cache->delete(common_cache_key('public').';last');
659 function blowFavesCache($blowLast=false)
661 $cache = common_memcache();
664 $fave->notice_id = $this->id;
666 while ($fave->fetch()) {
667 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
668 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
670 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
671 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
680 function getStreamByIds($ids)
682 $cache = common_memcache();
684 if (!empty($cache)) {
686 foreach ($ids as $id) {
687 $n = Notice::staticGet('id', $id);
692 return new ArrayWrapper($notices);
694 $notice = new Notice();
696 //if no IDs requested, just return the notice object
699 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
705 while ($notice->fetch()) {
706 $temp[$notice->id] = clone($notice);
711 foreach ($ids as $id) {
712 if (array_key_exists($id, $temp)) {
713 $wrapped[] = $temp[$id];
717 return new ArrayWrapper($wrapped);
721 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
723 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
726 $offset, $limit, $since_id, $max_id, $since);
728 return Notice::getStreamByIds($ids);
731 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
733 $notice = new Notice();
735 $notice->selectAdd(); // clears it
736 $notice->selectAdd('id');
738 $notice->orderBy('id DESC');
740 if (!is_null($offset)) {
741 $notice->limit($offset, $limit);
744 if (common_config('public', 'localonly')) {
745 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
747 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
748 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
749 $notice->whereAdd('is_local !='. Notice::GATEWAY);
752 if ($since_id != 0) {
753 $notice->whereAdd('id > ' . $since_id);
757 $notice->whereAdd('id <= ' . $max_id);
760 if (!is_null($since)) {
761 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
766 if ($notice->find()) {
767 while ($notice->fetch()) {
768 $ids[] = $notice->id;
778 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
780 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
782 'notice:conversation_ids:'.$id,
783 $offset, $limit, $since_id, $max_id, $since);
785 return Notice::getStreamByIds($ids);
788 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
790 $notice = new Notice();
792 $notice->selectAdd(); // clears it
793 $notice->selectAdd('id');
795 $notice->conversation = $id;
797 $notice->orderBy('id DESC');
799 if (!is_null($offset)) {
800 $notice->limit($offset, $limit);
803 if ($since_id != 0) {
804 $notice->whereAdd('id > ' . $since_id);
808 $notice->whereAdd('id <= ' . $max_id);
811 if (!is_null($since)) {
812 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
817 if ($notice->find()) {
818 while ($notice->fetch()) {
819 $ids[] = $notice->id;
831 $c = self::memcache();
834 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
840 $users = $this->getSubscribedUsers();
842 // FIXME: kind of ignoring 'transitional'...
843 // we'll probably stop supporting inboxless mode
848 foreach ($users as $id) {
849 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
852 $groups = $this->saveGroups();
853 $profile = $this->getProfile();
855 foreach ($groups as $group) {
856 $users = $group->getUserMembers();
857 foreach ($users as $id) {
858 if (!array_key_exists($id, $ni)) {
859 $user = User::staticGet('id', $id);
860 if (!$user->hasBlocked($profile)) {
861 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
867 $recipients = $this->saveReplies();
869 foreach ($recipients as $recipient) {
871 if (!array_key_exists($recipient, $ni)) {
872 $recipientUser = User::staticGet('id', $recipient);
873 if (!empty($recipientUser)) {
874 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
880 // XXX: pack this data better
881 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
887 function addToInboxes()
889 $ni = $this->whoGets();
891 Inbox::bulkInsert($this->id, array_keys($ni));
896 function getSubscribedUsers()
900 if(common_config('db','quote_identifiers'))
901 $user_table = '"user"';
902 else $user_table = 'user';
906 'FROM '. $user_table .' JOIN subscription '.
907 'ON '. $user_table .'.id = subscription.subscriber ' .
908 'WHERE subscription.subscribed = %d ';
910 $user->query(sprintf($qry, $this->profile_id));
914 while ($user->fetch()) {
923 function saveGroups()
927 /* extract all !group */
928 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
929 strtolower($this->content),
935 $profile = $this->getProfile();
937 /* Add them to the database */
939 foreach (array_unique($match[1]) as $nickname) {
940 /* XXX: remote groups. */
941 $group = User_group::getForNickname($nickname);
947 // we automatically add a tag for every group name, too
949 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
950 'notice_id' => $this->id));
953 $this->saveTag($nickname);
956 if ($profile->isMember($group)) {
958 $result = $this->addToGroupInbox($group);
961 common_log_db_error($gi, 'INSERT', __FILE__);
964 $groups[] = clone($group);
971 function addToGroupInbox($group)
973 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
974 'notice_id' => $this->id));
978 $gi = new Group_inbox();
980 $gi->group_id = $group->id;
981 $gi->notice_id = $this->id;
982 $gi->created = $this->created;
984 return $gi->insert();
991 * @return array of integer profile IDs
993 function saveReplies()
995 // Alternative reply format
997 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1000 // extract all @messages
1001 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1005 if ($cnt || $tname) {
1006 // XXX: is there another way to make an array copy?
1007 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1010 $sender = Profile::staticGet($this->profile_id);
1014 // store replied only for first @ (what user/notice what the reply directed,
1015 // we assume first @ is it)
1017 for ($i=0; $i<count($names); $i++) {
1018 $nickname = $names[$i];
1019 $recipient = common_relative_profile($sender, $nickname, $this->created);
1020 if (empty($recipient)) {
1023 // Don't save replies from blocked profile to local user
1024 $recipient_user = User::staticGet('id', $recipient->id);
1025 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1028 $reply = new Reply();
1029 $reply->notice_id = $this->id;
1030 $reply->profile_id = $recipient->id;
1031 $id = $reply->insert();
1033 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1034 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1035 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1038 $replied[$recipient->id] = 1;
1042 // Hash format replies, too
1043 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1045 foreach ($match[1] as $tag) {
1046 $tagged = Profile_tag::getTagged($sender->id, $tag);
1047 foreach ($tagged as $t) {
1048 if (!$replied[$t->id]) {
1049 // Don't save replies from blocked profile to local user
1050 $t_user = User::staticGet('id', $t->id);
1051 if ($t_user && $t_user->hasBlocked($sender)) {
1054 $reply = new Reply();
1055 $reply->notice_id = $this->id;
1056 $reply->profile_id = $t->id;
1057 $id = $reply->insert();
1059 common_log_db_error($reply, 'INSERT', __FILE__);
1062 $replied[$recipient->id] = 1;
1069 $recipientIds = array_keys($replied);
1071 foreach ($recipientIds as $recipientId) {
1072 $user = User::staticGet('id', $recipientId);
1074 mail_notify_attn($user, $this);
1078 return $recipientIds;
1081 function asAtomEntry($namespace=false, $source=false)
1083 $profile = $this->getProfile();
1085 $xs = new XMLStringer(true);
1088 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1089 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1094 $xs->elementStart('entry', $attrs);
1097 $xs->elementStart('source');
1098 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1099 $xs->element('link', array('href' => $profile->profileurl));
1100 $user = User::staticGet('id', $profile->id);
1101 if (!empty($user)) {
1102 $atom_feed = common_local_url('ApiTimelineUser',
1103 array('format' => 'atom',
1104 'id' => $profile->nickname));
1105 $xs->element('link', array('rel' => 'self',
1106 'type' => 'application/atom+xml',
1107 'href' => $profile->profileurl));
1108 $xs->element('link', array('rel' => 'license',
1109 'href' => common_config('license', 'url')));
1112 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1115 $xs->elementStart('author');
1116 $xs->element('name', null, $profile->nickname);
1117 $xs->element('uri', null, $profile->profileurl);
1118 $xs->elementEnd('author');
1121 $xs->elementEnd('source');
1124 $xs->element('title', null, $this->content);
1125 $xs->element('summary', null, $this->content);
1127 $xs->element('link', array('rel' => 'alternate',
1128 'href' => $this->bestUrl()));
1130 $xs->element('id', null, $this->uri);
1132 $xs->element('published', null, common_date_w3dtf($this->created));
1133 $xs->element('updated', null, common_date_w3dtf($this->created));
1135 if ($this->reply_to) {
1136 $reply_notice = Notice::staticGet('id', $this->reply_to);
1137 if (!empty($reply_notice)) {
1138 $xs->element('link', array('rel' => 'related',
1139 'href' => $reply_notice->bestUrl()));
1140 $xs->element('thr:in-reply-to',
1141 array('ref' => $reply_notice->uri,
1142 'href' => $reply_notice->bestUrl()));
1146 $xs->element('content', array('type' => 'html'), $this->rendered);
1148 $tag = new Notice_tag();
1149 $tag->notice_id = $this->id;
1151 while ($tag->fetch()) {
1152 $xs->element('category', array('term' => $tag->tag));
1158 $attachments = $this->attachments();
1160 foreach($attachments as $attachment){
1161 $enclosure=$attachment->getEnclosure();
1163 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1164 if($enclosure->title){
1165 $attributes['title']=$enclosure->title;
1167 $xs->element('link', $attributes, null);
1172 if (!empty($this->lat) && !empty($this->lon)) {
1173 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1174 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1175 $xs->elementEnd('geo');
1178 $xs->elementEnd('entry');
1180 return $xs->getString();
1185 if (!empty($this->url)) {
1187 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1190 return common_local_url('shownotice',
1191 array('notice' => $this->id));
1195 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1197 $cache = common_memcache();
1199 if (empty($cache) ||
1200 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1202 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1203 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1207 $idkey = common_cache_key($cachekey);
1209 $idstr = $cache->get($idkey);
1211 if ($idstr !== false) {
1212 // Cache hit! Woohoo!
1213 $window = explode(',', $idstr);
1214 $ids = array_slice($window, $offset, $limit);
1218 $laststr = $cache->get($idkey.';last');
1220 if ($laststr !== false) {
1221 $window = explode(',', $laststr);
1222 $last_id = $window[0];
1223 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1224 $last_id, 0, null)));
1226 $new_window = array_merge($new_ids, $window);
1228 $new_windowstr = implode(',', $new_window);
1230 $result = $cache->set($idkey, $new_windowstr);
1231 $result = $cache->set($idkey . ';last', $new_windowstr);
1233 $ids = array_slice($new_window, $offset, $limit);
1238 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1241 $windowstr = implode(',', $window);
1243 $result = $cache->set($idkey, $windowstr);
1244 $result = $cache->set($idkey . ';last', $windowstr);
1246 $ids = array_slice($window, $offset, $limit);
1252 * Determine which notice, if any, a new notice is in reply to.
1254 * For conversation tracking, we try to see where this notice fits
1255 * in the tree. Rough algorithm is:
1257 * if (reply_to is set and valid) {
1259 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1260 * return ID of last notice by initial @name in content;
1263 * Note that all @nickname instances will still be used to save "reply" records,
1264 * so the notice shows up in the mentioned users' "replies" tab.
1266 * @param integer $reply_to ID passed in by Web or API
1267 * @param integer $profile_id ID of author
1268 * @param string $source Source tag, like 'web' or 'gwibber'
1269 * @param string $content Final notice content
1271 * @return integer ID of replied-to notice, or null for not a reply.
1274 static function getReplyTo($reply_to, $profile_id, $source, $content)
1276 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1278 // If $reply_to is specified, we check that it exists, and then
1279 // return it if it does
1281 if (!empty($reply_to)) {
1282 $reply_notice = Notice::staticGet('id', $reply_to);
1283 if (!empty($reply_notice)) {
1288 // If it's not a "low bandwidth" source (one where you can't set
1289 // a reply_to argument), we return. This is mostly web and API
1292 if (!in_array($source, $lb)) {
1296 // Is there an initial @ or T?
1298 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1299 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1300 $nickname = common_canonical_nickname($match[1]);
1305 // Figure out who that is.
1307 $sender = Profile::staticGet('id', $profile_id);
1308 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1310 if (empty($recipient)) {
1314 // Get their last notice
1316 $last = $recipient->getCurrentNotice();
1318 if (!empty($last)) {
1323 static function maxContent()
1325 $contentlimit = common_config('notice', 'contentlimit');
1326 // null => use global limit (distinct from 0!)
1327 if (is_null($contentlimit)) {
1328 $contentlimit = common_config('site', 'textlimit');
1330 return $contentlimit;
1333 static function contentTooLong($content)
1335 $contentlimit = self::maxContent();
1336 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1339 function getLocation()
1343 if (!empty($this->location_id) && !empty($this->location_ns)) {
1344 $location = Location::fromId($this->location_id, $this->location_ns);
1347 if (is_null($location)) { // no ID, or Location::fromId() failed
1348 if (!empty($this->lat) && !empty($this->lon)) {
1349 $location = Location::fromLatLon($this->lat, $this->lon);
1356 function repeat($repeater_id, $source)
1358 $author = Profile::staticGet('id', $this->profile_id);
1360 $content = sprintf(_('RT @%1$s %2$s'),
1364 $maxlen = common_config('site', 'textlimit');
1365 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1366 // Web interface and current Twitter API clients will
1367 // pull the original notice's text, but some older
1368 // clients and RSS/Atom feeds will see this trimmed text.
1370 // Unfortunately this is likely to lose tags or URLs
1371 // at the end of long notices.
1372 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1375 return self::saveNew($repeater_id, $content, $source,
1376 array('repeat_of' => $this->id));
1379 // These are supposed to be in chron order!
1381 function repeatStream($limit=100)
1383 $cache = common_memcache();
1385 if (empty($cache)) {
1386 $ids = $this->_repeatStreamDirect($limit);
1388 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1389 if ($idstr !== false) {
1390 $ids = explode(',', $idstr);
1392 $ids = $this->_repeatStreamDirect(100);
1393 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1396 // We do a max of 100, so slice down to limit
1397 $ids = array_slice($ids, 0, $limit);
1401 return Notice::getStreamByIds($ids);
1404 function _repeatStreamDirect($limit)
1406 $notice = new Notice();
1408 $notice->selectAdd(); // clears it
1409 $notice->selectAdd('id');
1411 $notice->repeat_of = $this->id;
1413 $notice->orderBy('created'); // NB: asc!
1415 if (!is_null($offset)) {
1416 $notice->limit($offset, $limit);
1421 if ($notice->find()) {
1422 while ($notice->fetch()) {
1423 $ids[] = $notice->id;
1433 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1437 if (!empty($location_id) && !empty($location_ns)) {
1439 $options['location_id'] = $location_id;
1440 $options['location_ns'] = $location_ns;
1442 $location = Location::fromId($location_id, $location_ns);
1444 if (!empty($location)) {
1445 $options['lat'] = $location->lat;
1446 $options['lon'] = $location->lon;
1449 } else if (!empty($lat) && !empty($lon)) {
1451 $options['lat'] = $lat;
1452 $options['lon'] = $lon;
1454 $location = Location::fromLatLon($lat, $lon);
1456 if (!empty($location)) {
1457 $options['location_id'] = $location->location_id;
1458 $options['location_ns'] = $location->location_ns;
1460 } else if (!empty($profile)) {
1462 if (isset($profile->lat) && isset($profile->lon)) {
1463 $options['lat'] = $profile->lat;
1464 $options['lon'] = $profile->lon;
1467 if (isset($profile->location_id) && isset($profile->location_ns)) {
1468 $options['location_id'] = $profile->location_id;
1469 $options['location_ns'] = $profile->location_ns;