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; // tinyint(1)
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));
178 static function saveNew($profile_id, $content, $source, $options=null) {
180 if (!empty($options)) {
182 if (!isset($reply_to)) {
187 if (empty($is_local)) {
188 $is_local = Notice::LOCAL_PUBLIC;
191 $profile = Profile::staticGet($profile_id);
193 $final = common_shorten_links($content);
195 if (Notice::contentTooLong($final)) {
196 throw new ClientException(_('Problem saving notice. Too long.'));
199 if (empty($profile)) {
200 throw new ClientException(_('Problem saving notice. Unknown user.'));
203 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
204 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
205 throw new ClientException(_('Too many notices too fast; take a breather '.
206 'and post again in a few minutes.'));
209 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
210 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
211 throw new ClientException(_('Too many duplicate messages too quickly;'.
212 ' take a breather and post again in a few minutes.'));
215 if (!$profile->hasRight(Right::NEWNOTICE)) {
216 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
217 throw new ClientException(_('You are banned from posting notices on this site.'));
220 $notice = new Notice();
221 $notice->profile_id = $profile_id;
223 $autosource = common_config('public', 'autosource');
225 # Sandboxed are non-false, but not 1, either
227 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
228 ($source && $autosource && in_array($source, $autosource))) {
229 $notice->is_local = Notice::LOCAL_NONPUBLIC;
231 $notice->is_local = $is_local;
234 if (!empty($created)) {
235 $notice->created = $created;
237 $notice->created = common_sql_now();
240 $notice->content = $final;
241 $notice->rendered = common_render_content($final, $notice);
242 $notice->source = $source;
245 // Handle repeat case
247 if (isset($repeat_of)) {
248 $notice->repeat_of = $repeat_of;
249 $notice->reply_to = $repeat_of;
251 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
254 if (!empty($notice->reply_to)) {
255 $reply = Notice::staticGet('id', $notice->reply_to);
256 $notice->conversation = $reply->conversation;
259 if (!empty($lat) && !empty($lon)) {
262 $notice->location_id = $location_id;
263 $notice->location_ns = $location_ns;
264 } else if (!empty($location_ns) && !empty($location_id)) {
265 $location = Location::fromId($location_id, $location_ns);
266 if (!empty($location)) {
267 $notice->lat = $location->lat;
268 $notice->lon = $location->lon;
269 $notice->location_id = $location_id;
270 $notice->location_ns = $location_ns;
273 $notice->lat = $profile->lat;
274 $notice->lon = $profile->lon;
275 $notice->location_id = $profile->location_id;
276 $notice->location_ns = $profile->location_ns;
279 if (Event::handle('StartNoticeSave', array(&$notice))) {
281 // XXX: some of these functions write to the DB
283 $notice->query('BEGIN');
285 $id = $notice->insert();
288 common_log_db_error($notice, 'INSERT', __FILE__);
289 throw new ServerException(_('Problem saving notice.'));
292 // Update ID-dependent columns: URI, conversation
294 $orig = clone($notice);
299 $notice->uri = common_notice_uri($notice);
303 // If it's not part of a conversation, it's
304 // the beginning of a new conversation.
306 if (empty($notice->conversation)) {
307 $notice->conversation = $notice->id;
312 if (!$notice->update($orig)) {
313 common_log_db_error($notice, 'UPDATE', __FILE__);
314 throw new ServerException(_('Problem saving notice.'));
318 // XXX: do we need to change this for remote users?
322 $notice->addToInboxes();
326 $notice->query('COMMIT');
328 Event::handle('EndNoticeSave', array($notice));
331 # Clear the cache for subscribed users, so they'll update at next request
332 # XXX: someone clever could prepend instead of clearing the cache
334 $notice->blowCaches();
339 /** save all urls in the notice to the db
341 * follow redirects and save all available file information
342 * (mimetype, date, size, oembed, etc.)
346 function saveUrls() {
347 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
350 function saveUrl($data) {
351 list($url, $notice_id) = $data;
352 File::processNew($url, $notice_id);
355 static function checkDupes($profile_id, $content) {
356 $profile = Profile::staticGet($profile_id);
357 if (empty($profile)) {
360 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
361 if (!empty($notice)) {
363 while ($notice->fetch()) {
364 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
366 } else if ($notice->content == $content) {
371 # If we get here, oldest item in cache window is not
372 # old enough for dupe limit; do direct check against DB
373 $notice = new Notice();
374 $notice->profile_id = $profile_id;
375 $notice->content = $content;
376 if (common_config('db','type') == 'pgsql')
377 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
379 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
381 $cnt = $notice->count();
385 static function checkEditThrottle($profile_id) {
386 $profile = Profile::staticGet($profile_id);
387 if (empty($profile)) {
391 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
392 if ($notice && $notice->fetch()) {
393 # If the Nth notice was posted less than timespan seconds ago
394 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
399 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
403 function getUploadedAttachment() {
405 $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"';
406 $post->query($query);
408 if (empty($post->up) || empty($post->i)) {
411 $ret = array($post->up, $post->i);
417 function hasAttachments() {
419 $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);
420 $post->query($query);
422 $n_attachments = intval($post->n_attachments);
424 return $n_attachments;
427 function attachments() {
430 $f2p = new File_to_post;
431 $f2p->post_id = $this->id;
433 while ($f2p->fetch()) {
434 $f = File::staticGet($f2p->file_id);
441 function blowCaches($blowLast=false)
443 $this->blowSubsCache($blowLast);
444 $this->blowNoticeCache($blowLast);
445 $this->blowRepliesCache($blowLast);
446 $this->blowPublicCache($blowLast);
447 $this->blowTagCache($blowLast);
448 $this->blowGroupCache($blowLast);
449 $this->blowConversationCache($blowLast);
450 $this->blowRepeatCache();
451 $profile = Profile::staticGet($this->profile_id);
452 $profile->blowNoticeCount();
455 function blowRepeatCache()
457 if (!empty($this->repeat_of)) {
458 $cache = common_memcache();
459 if (!empty($cache)) {
460 // XXX: only blow if <100 in cache
461 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
462 $result = $cache->delete($ck);
464 $user = User::staticGet('id', $this->profile_id);
467 $uk = common_cache_key('user:repeated_by_me:'.$user->id);
473 $original = Notice::staticGet('id', $this->repeat_of);
475 if (!empty($original)) {
476 $originalUser = User::staticGet('id', $original->profile_id);
477 if (!empty($originalUser)) {
478 $ouk = common_cache_key('user:repeats_of_me:'.$originalUser->id);
479 $cache->delete($ouk);
480 $originalUser->free();
481 unset($originalUser);
487 $ni = new Notice_inbox();
489 $ni->notice_id = $this->id;
492 while ($ni->fetch()) {
493 $tmk = common_cache_key('user:repeated_to_me:'.$ni->user_id);
494 $cache->delete($tmk);
504 function blowConversationCache($blowLast=false)
506 $cache = common_memcache();
508 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
511 $cache->delete($ck.';last');
516 function blowGroupCache($blowLast=false)
518 $cache = common_memcache();
520 $group_inbox = new Group_inbox();
521 $group_inbox->notice_id = $this->id;
522 if ($group_inbox->find()) {
523 while ($group_inbox->fetch()) {
524 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
526 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
528 $member = new Group_member();
529 $member->group_id = $group_inbox->group_id;
530 if ($member->find()) {
531 while ($member->fetch()) {
532 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
534 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
540 $group_inbox->free();
545 function blowTagCache($blowLast=false)
547 $cache = common_memcache();
549 $tag = new Notice_tag();
550 $tag->notice_id = $this->id;
552 while ($tag->fetch()) {
553 $tag->blowCache($blowLast);
554 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
558 $cache->delete($ck . ';last');
567 function blowSubsCache($blowLast=false)
569 $cache = common_memcache();
573 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
574 $user->query('SELECT id ' .
576 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
577 'WHERE subscription.subscribed = ' . $this->profile_id);
579 while ($user->fetch()) {
580 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
581 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
583 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
584 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
592 function blowNoticeCache($blowLast=false)
594 if ($this->is_local) {
595 $cache = common_memcache();
596 if (!empty($cache)) {
597 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
599 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
605 function blowRepliesCache($blowLast=false)
607 $cache = common_memcache();
609 $reply = new Reply();
610 $reply->notice_id = $this->id;
611 if ($reply->find()) {
612 while ($reply->fetch()) {
613 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
615 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
624 function blowPublicCache($blowLast=false)
626 if ($this->is_local == Notice::LOCAL_PUBLIC) {
627 $cache = common_memcache();
629 $cache->delete(common_cache_key('public'));
631 $cache->delete(common_cache_key('public').';last');
637 function blowFavesCache($blowLast=false)
639 $cache = common_memcache();
642 $fave->notice_id = $this->id;
644 while ($fave->fetch()) {
645 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
646 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
648 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
649 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
658 function getStreamByIds($ids)
660 $cache = common_memcache();
662 if (!empty($cache)) {
664 foreach ($ids as $id) {
665 $n = Notice::staticGet('id', $id);
670 return new ArrayWrapper($notices);
672 $notice = new Notice();
674 //if no IDs requested, just return the notice object
677 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
683 while ($notice->fetch()) {
684 $temp[$notice->id] = clone($notice);
689 foreach ($ids as $id) {
690 if (array_key_exists($id, $temp)) {
691 $wrapped[] = $temp[$id];
695 return new ArrayWrapper($wrapped);
699 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
701 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
704 $offset, $limit, $since_id, $max_id, $since);
706 return Notice::getStreamByIds($ids);
709 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
711 $notice = new Notice();
713 $notice->selectAdd(); // clears it
714 $notice->selectAdd('id');
716 $notice->orderBy('id DESC');
718 if (!is_null($offset)) {
719 $notice->limit($offset, $limit);
722 if (common_config('public', 'localonly')) {
723 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
725 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
726 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
727 $notice->whereAdd('is_local !='. Notice::GATEWAY);
730 if ($since_id != 0) {
731 $notice->whereAdd('id > ' . $since_id);
735 $notice->whereAdd('id <= ' . $max_id);
738 if (!is_null($since)) {
739 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
744 if ($notice->find()) {
745 while ($notice->fetch()) {
746 $ids[] = $notice->id;
756 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
758 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
760 'notice:conversation_ids:'.$id,
761 $offset, $limit, $since_id, $max_id, $since);
763 return Notice::getStreamByIds($ids);
766 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
768 $notice = new Notice();
770 $notice->selectAdd(); // clears it
771 $notice->selectAdd('id');
773 $notice->conversation = $id;
775 $notice->orderBy('id DESC');
777 if (!is_null($offset)) {
778 $notice->limit($offset, $limit);
781 if ($since_id != 0) {
782 $notice->whereAdd('id > ' . $since_id);
786 $notice->whereAdd('id <= ' . $max_id);
789 if (!is_null($since)) {
790 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
795 if ($notice->find()) {
796 while ($notice->fetch()) {
797 $ids[] = $notice->id;
807 function addToInboxes()
809 // XXX: loads constants
811 $inbox = new Notice_inbox();
813 $users = $this->getSubscribedUsers();
815 // FIXME: kind of ignoring 'transitional'...
816 // we'll probably stop supporting inboxless mode
821 foreach ($users as $id) {
822 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
825 $groups = $this->saveGroups();
826 $profile = $this->getProfile();
828 foreach ($groups as $group) {
829 $users = $group->getUserMembers();
830 foreach ($users as $id) {
831 if (!array_key_exists($id, $ni)) {
832 $user = User::staticGet('id', $id);
833 if (!$user->hasBlocked($profile)) {
834 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
840 $recipients = $this->saveReplies();
842 foreach ($recipients as $recipient) {
844 if (!array_key_exists($recipient, $ni)) {
845 $recipientUser = User::staticGet('id', $recipient);
846 if (!empty($recipientUser)) {
847 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
852 Notice_inbox::bulkInsert($this->id, $this->created, $ni);
857 function getSubscribedUsers()
861 if(common_config('db','quote_identifiers'))
862 $user_table = '"user"';
863 else $user_table = 'user';
867 'FROM '. $user_table .' JOIN subscription '.
868 'ON '. $user_table .'.id = subscription.subscriber ' .
869 'WHERE subscription.subscribed = %d ';
871 $user->query(sprintf($qry, $this->profile_id));
875 while ($user->fetch()) {
884 function saveGroups()
888 /* extract all !group */
889 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
890 strtolower($this->content),
896 $profile = $this->getProfile();
898 /* Add them to the database */
900 foreach (array_unique($match[1]) as $nickname) {
901 /* XXX: remote groups. */
902 $group = User_group::getForNickname($nickname);
908 // we automatically add a tag for every group name, too
910 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
911 'notice_id' => $this->id));
914 $this->saveTag($nickname);
917 if ($profile->isMember($group)) {
919 $result = $this->addToGroupInbox($group);
922 common_log_db_error($gi, 'INSERT', __FILE__);
925 $groups[] = clone($group);
932 function addToGroupInbox($group)
934 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
935 'notice_id' => $this->id));
939 $gi = new Group_inbox();
941 $gi->group_id = $group->id;
942 $gi->notice_id = $this->id;
943 $gi->created = $this->created;
945 return $gi->insert();
951 function saveReplies()
953 // Alternative reply format
955 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
958 // extract all @messages
959 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
963 if ($cnt || $tname) {
964 // XXX: is there another way to make an array copy?
965 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
968 $sender = Profile::staticGet($this->profile_id);
972 // store replied only for first @ (what user/notice what the reply directed,
973 // we assume first @ is it)
975 for ($i=0; $i<count($names); $i++) {
976 $nickname = $names[$i];
977 $recipient = common_relative_profile($sender, $nickname, $this->created);
978 if (empty($recipient)) {
981 // Don't save replies from blocked profile to local user
982 $recipient_user = User::staticGet('id', $recipient->id);
983 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
986 $reply = new Reply();
987 $reply->notice_id = $this->id;
988 $reply->profile_id = $recipient->id;
989 $id = $reply->insert();
991 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
992 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
993 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
996 $replied[$recipient->id] = 1;
1000 // Hash format replies, too
1001 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1003 foreach ($match[1] as $tag) {
1004 $tagged = Profile_tag::getTagged($sender->id, $tag);
1005 foreach ($tagged as $t) {
1006 if (!$replied[$t->id]) {
1007 // Don't save replies from blocked profile to local user
1008 $t_user = User::staticGet('id', $t->id);
1009 if ($t_user && $t_user->hasBlocked($sender)) {
1012 $reply = new Reply();
1013 $reply->notice_id = $this->id;
1014 $reply->profile_id = $t->id;
1015 $id = $reply->insert();
1017 common_log_db_error($reply, 'INSERT', __FILE__);
1020 $replied[$recipient->id] = 1;
1027 $recipientIds = array_keys($replied);
1029 foreach ($recipientIds as $recipient) {
1030 $user = User::staticGet('id', $recipient);
1032 mail_notify_attn($user, $this);
1036 return $recipientIds;
1039 function asAtomEntry($namespace=false, $source=false)
1041 $profile = $this->getProfile();
1043 $xs = new XMLStringer(true);
1046 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1047 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1052 $xs->elementStart('entry', $attrs);
1055 $xs->elementStart('source');
1056 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1057 $xs->element('link', array('href' => $profile->profileurl));
1058 $user = User::staticGet('id', $profile->id);
1059 if (!empty($user)) {
1060 $atom_feed = common_local_url('ApiTimelineUser',
1061 array('format' => 'atom',
1062 'id' => $profile->nickname));
1063 $xs->element('link', array('rel' => 'self',
1064 'type' => 'application/atom+xml',
1065 'href' => $profile->profileurl));
1066 $xs->element('link', array('rel' => 'license',
1067 'href' => common_config('license', 'url')));
1070 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1073 $xs->elementStart('author');
1074 $xs->element('name', null, $profile->nickname);
1075 $xs->element('uri', null, $profile->profileurl);
1076 $xs->elementEnd('author');
1079 $xs->elementEnd('source');
1082 $xs->element('title', null, $this->content);
1083 $xs->element('summary', null, $this->content);
1085 $xs->element('link', array('rel' => 'alternate',
1086 'href' => $this->bestUrl()));
1088 $xs->element('id', null, $this->uri);
1090 $xs->element('published', null, common_date_w3dtf($this->created));
1091 $xs->element('updated', null, common_date_w3dtf($this->modified));
1093 if ($this->reply_to) {
1094 $reply_notice = Notice::staticGet('id', $this->reply_to);
1095 if (!empty($reply_notice)) {
1096 $xs->element('link', array('rel' => 'related',
1097 'href' => $reply_notice->bestUrl()));
1098 $xs->element('thr:in-reply-to',
1099 array('ref' => $reply_notice->uri,
1100 'href' => $reply_notice->bestUrl()));
1104 $xs->element('content', array('type' => 'html'), $this->rendered);
1106 $tag = new Notice_tag();
1107 $tag->notice_id = $this->id;
1109 while ($tag->fetch()) {
1110 $xs->element('category', array('term' => $tag->tag));
1116 $attachments = $this->attachments();
1118 foreach($attachments as $attachment){
1119 $enclosure=$attachment->getEnclosure();
1121 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1122 if($enclosure->title){
1123 $attributes['title']=$enclosure->title;
1125 $xs->element('link', $attributes, null);
1130 if (!empty($this->lat) && !empty($this->lon)) {
1131 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1132 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1133 $xs->elementEnd('geo');
1136 $xs->elementEnd('entry');
1138 return $xs->getString();
1143 if (!empty($this->url)) {
1145 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1148 return common_local_url('shownotice',
1149 array('notice' => $this->id));
1153 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1155 $cache = common_memcache();
1157 if (empty($cache) ||
1158 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1160 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1161 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1165 $idkey = common_cache_key($cachekey);
1167 $idstr = $cache->get($idkey);
1169 if (!empty($idstr)) {
1170 // Cache hit! Woohoo!
1171 $window = explode(',', $idstr);
1172 $ids = array_slice($window, $offset, $limit);
1176 $laststr = $cache->get($idkey.';last');
1178 if (!empty($laststr)) {
1179 $window = explode(',', $laststr);
1180 $last_id = $window[0];
1181 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1182 $last_id, 0, null)));
1184 $new_window = array_merge($new_ids, $window);
1186 $new_windowstr = implode(',', $new_window);
1188 $result = $cache->set($idkey, $new_windowstr);
1189 $result = $cache->set($idkey . ';last', $new_windowstr);
1191 $ids = array_slice($new_window, $offset, $limit);
1196 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1199 $windowstr = implode(',', $window);
1201 $result = $cache->set($idkey, $windowstr);
1202 $result = $cache->set($idkey . ';last', $windowstr);
1204 $ids = array_slice($window, $offset, $limit);
1210 * Determine which notice, if any, a new notice is in reply to.
1212 * For conversation tracking, we try to see where this notice fits
1213 * in the tree. Rough algorithm is:
1215 * if (reply_to is set and valid) {
1217 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1218 * return ID of last notice by initial @name in content;
1221 * Note that all @nickname instances will still be used to save "reply" records,
1222 * so the notice shows up in the mentioned users' "replies" tab.
1224 * @param integer $reply_to ID passed in by Web or API
1225 * @param integer $profile_id ID of author
1226 * @param string $source Source tag, like 'web' or 'gwibber'
1227 * @param string $content Final notice content
1229 * @return integer ID of replied-to notice, or null for not a reply.
1232 static function getReplyTo($reply_to, $profile_id, $source, $content)
1234 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1236 // If $reply_to is specified, we check that it exists, and then
1237 // return it if it does
1239 if (!empty($reply_to)) {
1240 $reply_notice = Notice::staticGet('id', $reply_to);
1241 if (!empty($reply_notice)) {
1246 // If it's not a "low bandwidth" source (one where you can't set
1247 // a reply_to argument), we return. This is mostly web and API
1250 if (!in_array($source, $lb)) {
1254 // Is there an initial @ or T?
1256 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1257 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1258 $nickname = common_canonical_nickname($match[1]);
1263 // Figure out who that is.
1265 $sender = Profile::staticGet('id', $profile_id);
1266 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1268 if (empty($recipient)) {
1272 // Get their last notice
1274 $last = $recipient->getCurrentNotice();
1276 if (!empty($last)) {
1281 static function maxContent()
1283 $contentlimit = common_config('notice', 'contentlimit');
1284 // null => use global limit (distinct from 0!)
1285 if (is_null($contentlimit)) {
1286 $contentlimit = common_config('site', 'textlimit');
1288 return $contentlimit;
1291 static function contentTooLong($content)
1293 $contentlimit = self::maxContent();
1294 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1297 function getLocation()
1301 if (!empty($this->location_id) && !empty($this->location_ns)) {
1302 $location = Location::fromId($this->location_id, $this->location_ns);
1305 if (is_null($location)) { // no ID, or Location::fromId() failed
1306 if (!empty($this->lat) && !empty($this->lon)) {
1307 $location = Location::fromLatLon($this->lat, $this->lon);
1314 function repeat($repeater_id, $source)
1316 $author = Profile::staticGet('id', $this->profile_id);
1318 // FIXME: truncate on long repeats...?
1320 $content = sprintf(_('RT @%1$s %2$s'),
1324 return self::saveNew($repeater_id, $content, $source,
1325 array('repeat_of' => $this->id));
1328 // These are supposed to be in chron order!
1330 function repeatStream($limit=100)
1332 $cache = common_memcache();
1334 if (empty($cache)) {
1335 $ids = $this->_repeatStreamDirect($limit);
1337 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1338 if (!empty($idstr)) {
1339 $ids = explode(',', $idstr);
1341 $ids = $this->_repeatStreamDirect(100);
1342 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1345 // We do a max of 100, so slice down to limit
1346 $ids = array_slice($ids, 0, $limit);
1350 return Notice::getStreamByIds($ids);
1353 function _repeatStreamDirect($limit)
1355 $notice = new Notice();
1357 $notice->selectAdd(); // clears it
1358 $notice->selectAdd('id');
1360 $notice->repeat_of = $this->id;
1362 $notice->orderBy('created'); // NB: asc!
1364 if (!is_null($offset)) {
1365 $notice->limit($offset, $limit);
1370 if ($notice->find()) {
1371 while ($notice->fetch()) {
1372 $ids[] = $notice->id;