]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  *
19  * @category Notices
20  * @package  StatusNet
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/
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
36     exit(1);
37 }
38
39 /**
40  * Table Definition for notice
41  */
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
43
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45  * in the memcached cache. */
46
47 define('NOTICE_CACHE_WINDOW', 61);
48
49 define('MAX_BOXCARS', 128);
50
51 class Notice extends Memcached_DataObject
52 {
53     ###START_AUTOCODE
54     /* the code below is auto generated do not remove the above tag */
55
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)
74
75     /* Static get */
76     function staticGet($k,$v=NULL)
77     {
78         return Memcached_DataObject::staticGet('Notice',$k,$v);
79     }
80
81     /* the code above is auto generated do not remove the tag below */
82     ###END_AUTOCODE
83
84     /* Notice types */
85     const LOCAL_PUBLIC    =  1;
86     const REMOTE_OMB      =  0;
87     const LOCAL_NONPUBLIC = -1;
88     const GATEWAY         = -2;
89
90     function getProfile()
91     {
92         return Profile::staticGet('id', $this->profile_id);
93     }
94
95     function delete()
96     {
97         // For auditing purposes, save a record that the notice
98         // was deleted.
99
100         $deleted = new Deleted_notice();
101
102         $deleted->id         = $this->id;
103         $deleted->profile_id = $this->profile_id;
104         $deleted->uri        = $this->uri;
105         $deleted->created    = $this->created;
106         $deleted->deleted    = common_sql_now();
107
108         $deleted->insert();
109
110         // Clear related records
111
112         $this->clearReplies();
113         $this->clearRepeats();
114         $this->clearFaves();
115         $this->clearTags();
116         $this->clearGroupInboxes();
117
118         // NOTE: we don't clear inboxes
119         // NOTE: we don't clear queue items
120
121         $result = parent::delete();
122     }
123
124     function saveTags()
125     {
126         /* extract all #hastags */
127         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
128         if (!$count) {
129             return true;
130         }
131
132         //turn each into their canonical tag
133         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
134         $hashtags = array();
135         for($i=0; $i<count($match[1]); $i++) {
136             $hashtags[] = common_canonical_tag($match[1][$i]);
137         }
138
139         /* Add them to the database */
140         foreach(array_unique($hashtags) as $hashtag) {
141             /* elide characters we don't want in the tag */
142             $this->saveTag($hashtag);
143             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
144         }
145         return true;
146     }
147
148     function saveTag($hashtag)
149     {
150         $tag = new Notice_tag();
151         $tag->notice_id = $this->id;
152         $tag->tag = $hashtag;
153         $tag->created = $this->created;
154         $id = $tag->insert();
155
156         if (!$id) {
157             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
158                                               $last_error->message));
159             return;
160         }
161
162         // if it's saved, blow its cache
163         $tag->blowCache(false);
164     }
165
166     /**
167      * Save a new notice and push it out to subscribers' inboxes.
168      * Poster's permissions are checked before sending.
169      *
170      * @param int $profile_id Profile ID of the poster
171      * @param string $content source message text; links may be shortened
172      *                        per current user's preference
173      * @param string $source source key ('web', 'api', etc)
174      * @param array $options Associative array of optional properties:
175      *              string 'created' timestamp of notice; defaults to now
176      *              int 'is_local' source/gateway ID, one of:
177      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
178      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
179      *                                            hide from public timeline but show in
180      *                                            local "and friends" timelines
181      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
182      *                  Notice::GATEWAY         - From another non-OMB service;
183      *                                            will not appear in public views
184      *              float 'lat' decimal latitude for geolocation
185      *              float 'lon' decimal longitude for geolocation
186      *              int 'location_id' geoname identifier
187      *              int 'location_ns' geoname namespace to interpret location_id
188      *              int 'reply_to'; notice ID this is a reply to
189      *              int 'repeat_of'; notice ID this is a repeat of
190      *              string 'uri' permalink to notice; defaults to local notice URL
191      *
192      * @return Notice
193      * @throws ClientException
194      */
195     static function saveNew($profile_id, $content, $source, $options=null) {
196         $defaults = array('uri' => null,
197                           'url' => null,
198                           'reply_to' => null,
199                           'repeat_of' => null);
200
201         if (!empty($options)) {
202             $options = $options + $defaults;
203             extract($options);
204         }
205
206         if (!isset($is_local)) {
207             $is_local = Notice::LOCAL_PUBLIC;
208         }
209
210         $profile = Profile::staticGet($profile_id);
211
212         $final = common_shorten_links($content);
213
214         if (Notice::contentTooLong($final)) {
215             throw new ClientException(_('Problem saving notice. Too long.'));
216         }
217
218         if (empty($profile)) {
219             throw new ClientException(_('Problem saving notice. Unknown user.'));
220         }
221
222         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
223             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
224             throw new ClientException(_('Too many notices too fast; take a breather '.
225                                         'and post again in a few minutes.'));
226         }
227
228         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
229             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
230             throw new ClientException(_('Too many duplicate messages too quickly;'.
231                                         ' take a breather and post again in a few minutes.'));
232         }
233
234         if (!$profile->hasRight(Right::NEWNOTICE)) {
235             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
236             throw new ClientException(_('You are banned from posting notices on this site.'));
237         }
238
239         $notice = new Notice();
240         $notice->profile_id = $profile_id;
241
242         $autosource = common_config('public', 'autosource');
243
244         # Sandboxed are non-false, but not 1, either
245
246         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
247             ($source && $autosource && in_array($source, $autosource))) {
248             $notice->is_local = Notice::LOCAL_NONPUBLIC;
249         } else {
250             $notice->is_local = $is_local;
251         }
252
253         if (!empty($created)) {
254             $notice->created = $created;
255         } else {
256             $notice->created = common_sql_now();
257         }
258
259         $notice->content = $final;
260
261         if (!empty($rendered)) {
262             $notice->rendered = $rendered;
263         } else {
264             $notice->rendered = common_render_content($final, $notice);
265         }
266
267         $notice->source = $source;
268         $notice->uri = $uri;
269         $notice->url = $url;
270
271         // Handle repeat case
272
273         if (isset($repeat_of)) {
274             $notice->repeat_of = $repeat_of;
275         } else {
276             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
277         }
278
279         if (!empty($notice->reply_to)) {
280             $reply = Notice::staticGet('id', $notice->reply_to);
281             $notice->conversation = $reply->conversation;
282         }
283
284         if (!empty($lat) && !empty($lon)) {
285             $notice->lat = $lat;
286             $notice->lon = $lon;
287         }
288
289         if (!empty($location_ns) && !empty($location_id)) {
290             $notice->location_id = $location_id;
291             $notice->location_ns = $location_ns;
292         }
293
294         if (Event::handle('StartNoticeSave', array(&$notice))) {
295
296             // XXX: some of these functions write to the DB
297
298             $id = $notice->insert();
299
300             if (!$id) {
301                 common_log_db_error($notice, 'INSERT', __FILE__);
302                 throw new ServerException(_('Problem saving notice.'));
303             }
304
305             // Update ID-dependent columns: URI, conversation
306
307             $orig = clone($notice);
308
309             $changed = false;
310
311             if (empty($uri)) {
312                 $notice->uri = common_notice_uri($notice);
313                 $changed = true;
314             }
315
316             // If it's not part of a conversation, it's
317             // the beginning of a new conversation.
318
319             if (empty($notice->conversation)) {
320                 $conv = Conversation::create();
321                 $notice->conversation = $conv->id;
322                 $changed = true;
323             }
324
325             if ($changed) {
326                 if (!$notice->update($orig)) {
327                     common_log_db_error($notice, 'UPDATE', __FILE__);
328                     throw new ServerException(_('Problem saving notice.'));
329                 }
330             }
331
332         }
333
334         # Clear the cache for subscribed users, so they'll update at next request
335         # XXX: someone clever could prepend instead of clearing the cache
336
337         $notice->blowOnInsert();
338
339         if (isset($replies)) {
340             $notice->saveKnownReplies($replies);
341         } else {
342             $notice->saveReplies();
343         }
344
345         $notice->distribute();
346
347         return $notice;
348     }
349
350     function blowOnInsert($conversation = false)
351     {
352         self::blow('profile:notice_ids:%d', $this->profile_id);
353         self::blow('public');
354
355         // XXX: Before we were blowing the casche only if the notice id
356         // was not the root of the conversation.  What to do now?
357
358         self::blow('notice:conversation_ids:%d', $this->conversation);
359
360         if (!empty($this->repeat_of)) {
361             self::blow('notice:repeats:%d', $this->repeat_of);
362         }
363
364         $original = Notice::staticGet('id', $this->repeat_of);
365
366         if (!empty($original)) {
367             $originalUser = User::staticGet('id', $original->profile_id);
368             if (!empty($originalUser)) {
369                 self::blow('user:repeats_of_me:%d', $originalUser->id);
370             }
371         }
372
373         $profile = Profile::staticGet($this->profile_id);
374         $profile->blowNoticeCount();
375     }
376
377     /** save all urls in the notice to the db
378      *
379      * follow redirects and save all available file information
380      * (mimetype, date, size, oembed, etc.)
381      *
382      * @return void
383      */
384     function saveUrls() {
385         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
386     }
387
388     function saveUrl($data) {
389         list($url, $notice_id) = $data;
390         File::processNew($url, $notice_id);
391     }
392
393     static function checkDupes($profile_id, $content) {
394         $profile = Profile::staticGet($profile_id);
395         if (empty($profile)) {
396             return false;
397         }
398         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
399         if (!empty($notice)) {
400             $last = 0;
401             while ($notice->fetch()) {
402                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
403                     return true;
404                 } else if ($notice->content == $content) {
405                     return false;
406                 }
407             }
408         }
409         # If we get here, oldest item in cache window is not
410         # old enough for dupe limit; do direct check against DB
411         $notice = new Notice();
412         $notice->profile_id = $profile_id;
413         $notice->content = $content;
414         if (common_config('db','type') == 'pgsql')
415           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
416         else
417           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
418
419         $cnt = $notice->count();
420         return ($cnt == 0);
421     }
422
423     static function checkEditThrottle($profile_id) {
424         $profile = Profile::staticGet($profile_id);
425         if (empty($profile)) {
426             return false;
427         }
428         # Get the Nth notice
429         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
430         if ($notice && $notice->fetch()) {
431             # If the Nth notice was posted less than timespan seconds ago
432             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
433                 # Then we throttle
434                 return false;
435             }
436         }
437         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
438         return true;
439     }
440
441     function getUploadedAttachment() {
442         $post = clone $this;
443         $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"';
444         $post->query($query);
445         $post->fetch();
446         if (empty($post->up) || empty($post->i)) {
447             $ret = false;
448         } else {
449             $ret = array($post->up, $post->i);
450         }
451         $post->free();
452         return $ret;
453     }
454
455     function hasAttachments() {
456         $post = clone $this;
457         $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);
458         $post->query($query);
459         $post->fetch();
460         $n_attachments = intval($post->n_attachments);
461         $post->free();
462         return $n_attachments;
463     }
464
465     function attachments() {
466         // XXX: cache this
467         $att = array();
468         $f2p = new File_to_post;
469         $f2p->post_id = $this->id;
470         if ($f2p->find()) {
471             while ($f2p->fetch()) {
472                 $f = File::staticGet($f2p->file_id);
473                 $att[] = clone($f);
474             }
475         }
476         return $att;
477     }
478
479     function getStreamByIds($ids)
480     {
481         $cache = common_memcache();
482
483         if (!empty($cache)) {
484             $notices = array();
485             foreach ($ids as $id) {
486                 $n = Notice::staticGet('id', $id);
487                 if (!empty($n)) {
488                     $notices[] = $n;
489                 }
490             }
491             return new ArrayWrapper($notices);
492         } else {
493             $notice = new Notice();
494             if (empty($ids)) {
495                 //if no IDs requested, just return the notice object
496                 return $notice;
497             }
498             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
499
500             $notice->find();
501
502             $temp = array();
503
504             while ($notice->fetch()) {
505                 $temp[$notice->id] = clone($notice);
506             }
507
508             $wrapped = array();
509
510             foreach ($ids as $id) {
511                 if (array_key_exists($id, $temp)) {
512                     $wrapped[] = $temp[$id];
513                 }
514             }
515
516             return new ArrayWrapper($wrapped);
517         }
518     }
519
520     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
521     {
522         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
523                               array(),
524                               'public',
525                               $offset, $limit, $since_id, $max_id, $since);
526
527         return Notice::getStreamByIds($ids);
528     }
529
530     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
531     {
532         $notice = new Notice();
533
534         $notice->selectAdd(); // clears it
535         $notice->selectAdd('id');
536
537         $notice->orderBy('id DESC');
538
539         if (!is_null($offset)) {
540             $notice->limit($offset, $limit);
541         }
542
543         if (common_config('public', 'localonly')) {
544             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
545         } else {
546             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
547             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
548             $notice->whereAdd('is_local !='. Notice::GATEWAY);
549         }
550
551         if ($since_id != 0) {
552             $notice->whereAdd('id > ' . $since_id);
553         }
554
555         if ($max_id != 0) {
556             $notice->whereAdd('id <= ' . $max_id);
557         }
558
559         if (!is_null($since)) {
560             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
561         }
562
563         $ids = array();
564
565         if ($notice->find()) {
566             while ($notice->fetch()) {
567                 $ids[] = $notice->id;
568             }
569         }
570
571         $notice->free();
572         $notice = NULL;
573
574         return $ids;
575     }
576
577     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
578     {
579         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
580                               array($id),
581                               'notice:conversation_ids:'.$id,
582                               $offset, $limit, $since_id, $max_id, $since);
583
584         return Notice::getStreamByIds($ids);
585     }
586
587     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
588     {
589         $notice = new Notice();
590
591         $notice->selectAdd(); // clears it
592         $notice->selectAdd('id');
593
594         $notice->conversation = $id;
595
596         $notice->orderBy('id DESC');
597
598         if (!is_null($offset)) {
599             $notice->limit($offset, $limit);
600         }
601
602         if ($since_id != 0) {
603             $notice->whereAdd('id > ' . $since_id);
604         }
605
606         if ($max_id != 0) {
607             $notice->whereAdd('id <= ' . $max_id);
608         }
609
610         if (!is_null($since)) {
611             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
612         }
613
614         $ids = array();
615
616         if ($notice->find()) {
617             while ($notice->fetch()) {
618                 $ids[] = $notice->id;
619             }
620         }
621
622         $notice->free();
623         $notice = NULL;
624
625         return $ids;
626     }
627
628     /**
629      * @param $groups array of Group *objects*
630      * @param $recipients array of profile *ids*
631      */
632     function whoGets($groups=null, $recipients=null)
633     {
634         $c = self::memcache();
635
636         if (!empty($c)) {
637             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
638             if ($ni !== false) {
639                 return $ni;
640             }
641         }
642
643         if (is_null($groups)) {
644             $groups = $this->getGroups();
645         }
646
647         if (is_null($recipients)) {
648             $recipients = $this->getReplies();
649         }
650
651         $users = $this->getSubscribedUsers();
652
653         // FIXME: kind of ignoring 'transitional'...
654         // we'll probably stop supporting inboxless mode
655         // in 0.9.x
656
657         $ni = array();
658
659         foreach ($users as $id) {
660             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
661         }
662
663         $profile = $this->getProfile();
664
665         foreach ($groups as $group) {
666             $users = $group->getUserMembers();
667             foreach ($users as $id) {
668                 if (!array_key_exists($id, $ni)) {
669                     $user = User::staticGet('id', $id);
670                     if (!$user->hasBlocked($profile)) {
671                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
672                     }
673                 }
674             }
675         }
676
677         foreach ($recipients as $recipient) {
678
679             if (!array_key_exists($recipient, $ni)) {
680                 $recipientUser = User::staticGet('id', $recipient);
681                 if (!empty($recipientUser)) {
682                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
683                 }
684             }
685         }
686
687         if (!empty($c)) {
688             // XXX: pack this data better
689             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
690         }
691
692         return $ni;
693     }
694
695     function addToInboxes($groups, $recipients)
696     {
697         $ni = $this->whoGets($groups, $recipients);
698
699         $ids = array_keys($ni);
700
701         // We remove the author (if they're a local user),
702         // since we'll have already done this in distribute()
703
704         $i = array_search($this->profile_id, $ids);
705
706         if ($i !== false) {
707             unset($ids[$i]);
708         }
709
710         // Bulk insert
711
712         Inbox::bulkInsert($this->id, $ids);
713
714         return;
715     }
716
717     function getSubscribedUsers()
718     {
719         $user = new User();
720
721         if(common_config('db','quote_identifiers'))
722           $user_table = '"user"';
723         else $user_table = 'user';
724
725         $qry =
726           'SELECT id ' .
727           'FROM '. $user_table .' JOIN subscription '.
728           'ON '. $user_table .'.id = subscription.subscriber ' .
729           'WHERE subscription.subscribed = %d ';
730
731         $user->query(sprintf($qry, $this->profile_id));
732
733         $ids = array();
734
735         while ($user->fetch()) {
736             $ids[] = $user->id;
737         }
738
739         $user->free();
740
741         return $ids;
742     }
743
744     /**
745      * @return array of Group objects
746      */
747     function saveGroups()
748     {
749         // Don't save groups for repeats
750
751         if (!empty($this->repeat_of)) {
752             return array();
753         }
754
755         $groups = array();
756
757         /* extract all !group */
758         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
759                                 strtolower($this->content),
760                                 $match);
761         if (!$count) {
762             return $groups;
763         }
764
765         $profile = $this->getProfile();
766
767         /* Add them to the database */
768
769         foreach (array_unique($match[1]) as $nickname) {
770             /* XXX: remote groups. */
771             $group = User_group::getForNickname($nickname);
772
773             if (empty($group)) {
774                 continue;
775             }
776
777             // we automatically add a tag for every group name, too
778
779             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
780                                              'notice_id' => $this->id));
781
782             if (is_null($tag)) {
783                 $this->saveTag($nickname);
784             }
785
786             if ($profile->isMember($group)) {
787
788                 $result = $this->addToGroupInbox($group);
789
790                 if (!$result) {
791                     common_log_db_error($gi, 'INSERT', __FILE__);
792                 }
793
794                 $groups[] = clone($group);
795             }
796         }
797
798         return $groups;
799     }
800
801     function addToGroupInbox($group)
802     {
803         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
804                                          'notice_id' => $this->id));
805
806         if (empty($gi)) {
807
808             $gi = new Group_inbox();
809
810             $gi->group_id  = $group->id;
811             $gi->notice_id = $this->id;
812             $gi->created   = $this->created;
813
814             $result = $gi->insert();
815
816             if (!$result) {
817                 common_log_db_error($gi, 'INSERT', __FILE__);
818                 throw new ServerException(_('Problem saving group inbox.'));
819             }
820
821             self::blow('user_group:notice_ids:%d', $gi->group_id);
822         }
823
824         return true;
825     }
826
827     function saveKnownReplies($uris)
828     {
829         foreach ($uris as $uri) {
830
831             $user = User::staticGet('uri', $uri);
832
833             if (!empty($user)) {
834
835                 $reply = new Reply();
836
837                 $reply->notice_id  = $this->id;
838                 $reply->profile_id = $user->id;
839
840                 $id = $reply->insert();
841             }
842         }
843
844         return;
845     }
846
847     /**
848      * @return array of integer profile IDs
849      */
850
851     function saveReplies()
852     {
853         // Don't save reply data for repeats
854
855         if (!empty($this->repeat_of)) {
856             return array();
857         }
858
859         $sender = Profile::staticGet($this->profile_id);
860
861         $mentions = common_find_mentions($this->profile_id, $this->content);
862
863         $replied = array();
864
865         // store replied only for first @ (what user/notice what the reply directed,
866         // we assume first @ is it)
867
868         foreach ($mentions as $mention) {
869
870             foreach ($mention['mentioned'] as $mentioned) {
871
872                 // skip if they're already covered
873
874                 if (!empty($replied[$mentioned->id])) {
875                     continue;
876                 }
877
878                 // Don't save replies from blocked profile to local user
879
880                 $mentioned_user = User::staticGet('id', $mentioned->id);
881                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
882                     continue;
883                 }
884
885                 $reply = new Reply();
886
887                 $reply->notice_id  = $this->id;
888                 $reply->profile_id = $mentioned->id;
889
890                 $id = $reply->insert();
891
892                 if (!$id) {
893                     common_log_db_error($reply, 'INSERT', __FILE__);
894                     throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
895                 } else {
896                     $replied[$mentioned->id] = 1;
897                 }
898             }
899         }
900
901         $recipientIds = array_keys($replied);
902
903         foreach ($recipientIds as $recipientId) {
904             $user = User::staticGet('id', $recipientId);
905             if (!empty($user)) {
906                 self::blow('reply:stream:%d', $reply->profile_id);
907                 mail_notify_attn($user, $this);
908             }
909         }
910
911         return $recipientIds;
912     }
913
914     function getReplies()
915     {
916         // XXX: cache me
917
918         $ids = array();
919
920         $reply = new Reply();
921         $reply->selectAdd();
922         $reply->selectAdd('profile_id');
923         $reply->notice_id = $this->id;
924
925         if ($reply->find()) {
926             while($reply->fetch()) {
927                 $ids[] = $reply->profile_id;
928             }
929         }
930
931         $reply->free();
932
933         return $ids;
934     }
935
936     /**
937      * Same calculation as saveGroups but without the saving
938      * @fixme merge the functions
939      * @return array of Group_inbox objects
940      */
941     function getGroups()
942     {
943         // Don't save groups for repeats
944
945         if (!empty($this->repeat_of)) {
946             return array();
947         }
948
949         // XXX: cache me
950
951         $groups = array();
952
953         $gi = new Group_inbox();
954
955         $gi->selectAdd();
956         $gi->selectAdd('group_id');
957
958         $gi->notice_id = $this->id;
959
960         if ($gi->find()) {
961             while ($gi->fetch()) {
962                 $groups[] = clone($gi);
963             }
964         }
965
966         $gi->free();
967
968         return $groups;
969     }
970
971     function asAtomEntry($namespace=false, $source=false)
972     {
973         $profile = $this->getProfile();
974
975         $xs = new XMLStringer(true);
976
977         if ($namespace) {
978             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
979                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
980                            'xmlns:georss' => 'http://www.georss.org/georss',
981                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
982                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
983         } else {
984             $attrs = array();
985         }
986
987         $xs->elementStart('entry', $attrs);
988
989         if ($source) {
990             $xs->elementStart('source');
991             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
992             $xs->element('link', array('href' => $profile->profileurl));
993             $user = User::staticGet('id', $profile->id);
994             if (!empty($user)) {
995                 $atom_feed = common_local_url('ApiTimelineUser',
996                                               array('format' => 'atom',
997                                                     'id' => $profile->nickname));
998                 $xs->element('link', array('rel' => 'self',
999                                            'type' => 'application/atom+xml',
1000                                            'href' => $profile->profileurl));
1001                 $xs->element('link', array('rel' => 'license',
1002                                            'href' => common_config('license', 'url')));
1003             }
1004
1005             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1006         }
1007
1008         if ($source) {
1009             $xs->elementEnd('source');
1010         }
1011
1012         $xs->element('title', null, $this->content);
1013         $xs->element('summary', null, $this->content);
1014
1015         $xs->raw($profile->asAtomAuthor());
1016         $xs->raw($profile->asActivityActor());
1017
1018         $xs->element('link', array('rel' => 'alternate',
1019                                    'type' => 'text/html',
1020                                    'href' => $this->bestUrl()));
1021
1022         $xs->element('id', null, $this->uri);
1023
1024         $xs->element('published', null, common_date_w3dtf($this->created));
1025         $xs->element('updated', null, common_date_w3dtf($this->created));
1026
1027         if ($this->reply_to) {
1028             $reply_notice = Notice::staticGet('id', $this->reply_to);
1029             if (!empty($reply_notice)) {
1030                 $xs->element('link', array('rel' => 'related',
1031                                            'href' => $reply_notice->bestUrl()));
1032                 $xs->element('thr:in-reply-to',
1033                              array('ref' => $reply_notice->uri,
1034                                    'href' => $reply_notice->bestUrl()));
1035             }
1036         }
1037
1038         if (!empty($this->conversation)) {
1039
1040             $conv = Conversation::staticGet('id', $this->conversation);
1041
1042             if (!empty($conv)) {
1043                 $xs->element(
1044                     'link', array(
1045                         'rel' => 'ostatus:conversation',
1046                         'href' => $conv->uri
1047                     )
1048                 );
1049             }
1050         }
1051
1052         $reply_ids = $this->getReplies();
1053
1054         foreach ($reply_ids as $id) {
1055             $profile = Profile::staticGet('id', $id);
1056            if (!empty($profile)) {
1057                 $xs->element(
1058                     'link', array(
1059                         'rel' => 'ostatus:attention',
1060                         'href' => $profile->getUri()
1061                     )
1062                 );
1063             }
1064         }
1065
1066         if (!empty($this->repeat_of)) {
1067             $repeat = Notice::staticGet('id', $this->repeat_of);
1068             if (!empty($repeat)) {
1069                 $xs->element(
1070                     'ostatus:forward',
1071                      array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1072                 );
1073             }
1074         }
1075
1076         $xs->element('content', array('type' => 'html'), $this->rendered);
1077
1078         $tag = new Notice_tag();
1079         $tag->notice_id = $this->id;
1080         if ($tag->find()) {
1081             while ($tag->fetch()) {
1082                 $xs->element('category', array('term' => $tag->tag));
1083             }
1084         }
1085         $tag->free();
1086
1087         # Enclosures
1088         $attachments = $this->attachments();
1089         if($attachments){
1090             foreach($attachments as $attachment){
1091                 $enclosure=$attachment->getEnclosure();
1092                 if ($enclosure) {
1093                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1094                     if($enclosure->title){
1095                         $attributes['title']=$enclosure->title;
1096                     }
1097                     $xs->element('link', $attributes, null);
1098                 }
1099             }
1100         }
1101
1102         if (!empty($this->lat) && !empty($this->lon)) {
1103             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1104         }
1105
1106         $xs->elementEnd('entry');
1107
1108         return $xs->getString();
1109     }
1110
1111     /**
1112      * Returns an XML string fragment with a reference to a notice as an
1113      * Activity Streams noun object with the given element type.
1114      *
1115      * Assumes that 'activity' namespace has been previously defined.
1116      *
1117      * @param string $element one of 'subject', 'object', 'target'
1118      * @return string
1119      */
1120     function asActivityNoun($element)
1121     {
1122         $xs = new XMLStringer(true);
1123
1124         $xs->elementStart('activity:' . $element);
1125         $xs->element('activity:object-type',
1126                      null,
1127                      'http://activitystrea.ms/schema/1.0/note');
1128         $xs->element('id',
1129                      null,
1130                      $this->uri);
1131         $xs->element('content',
1132                      array('type' => 'text/html'),
1133                      $this->rendered);
1134         $xs->element('link',
1135                      array('type' => 'text/html',
1136                            'rel'  => 'alternate',
1137                            'href' => $this->bestUrl()));
1138         $xs->elementEnd('activity:' . $element);
1139
1140         return $xs->getString();
1141     }
1142
1143     function bestUrl()
1144     {
1145         if (!empty($this->url)) {
1146             return $this->url;
1147         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1148             return $this->uri;
1149         } else {
1150             return common_local_url('shownotice',
1151                                     array('notice' => $this->id));
1152         }
1153     }
1154
1155     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1156     {
1157         $cache = common_memcache();
1158
1159         if (empty($cache) ||
1160             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1161             is_null($limit) ||
1162             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1163             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1164                                                                       $max_id, $since)));
1165         }
1166
1167         $idkey = common_cache_key($cachekey);
1168
1169         $idstr = $cache->get($idkey);
1170
1171         if ($idstr !== false) {
1172             // Cache hit! Woohoo!
1173             $window = explode(',', $idstr);
1174             $ids = array_slice($window, $offset, $limit);
1175             return $ids;
1176         }
1177
1178         $laststr = $cache->get($idkey.';last');
1179
1180         if ($laststr !== false) {
1181             $window = explode(',', $laststr);
1182             $last_id = $window[0];
1183             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1184                                                                           $last_id, 0, null)));
1185
1186             $new_window = array_merge($new_ids, $window);
1187
1188             $new_windowstr = implode(',', $new_window);
1189
1190             $result = $cache->set($idkey, $new_windowstr);
1191             $result = $cache->set($idkey . ';last', $new_windowstr);
1192
1193             $ids = array_slice($new_window, $offset, $limit);
1194
1195             return $ids;
1196         }
1197
1198         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1199                                                                      0, 0, null)));
1200
1201         $windowstr = implode(',', $window);
1202
1203         $result = $cache->set($idkey, $windowstr);
1204         $result = $cache->set($idkey . ';last', $windowstr);
1205
1206         $ids = array_slice($window, $offset, $limit);
1207
1208         return $ids;
1209     }
1210
1211     /**
1212      * Determine which notice, if any, a new notice is in reply to.
1213      *
1214      * For conversation tracking, we try to see where this notice fits
1215      * in the tree. Rough algorithm is:
1216      *
1217      * if (reply_to is set and valid) {
1218      *     return reply_to;
1219      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1220      *     return ID of last notice by initial @name in content;
1221      * }
1222      *
1223      * Note that all @nickname instances will still be used to save "reply" records,
1224      * so the notice shows up in the mentioned users' "replies" tab.
1225      *
1226      * @param integer $reply_to   ID passed in by Web or API
1227      * @param integer $profile_id ID of author
1228      * @param string  $source     Source tag, like 'web' or 'gwibber'
1229      * @param string  $content    Final notice content
1230      *
1231      * @return integer ID of replied-to notice, or null for not a reply.
1232      */
1233
1234     static function getReplyTo($reply_to, $profile_id, $source, $content)
1235     {
1236         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1237
1238         // If $reply_to is specified, we check that it exists, and then
1239         // return it if it does
1240
1241         if (!empty($reply_to)) {
1242             $reply_notice = Notice::staticGet('id', $reply_to);
1243             if (!empty($reply_notice)) {
1244                 return $reply_to;
1245             }
1246         }
1247
1248         // If it's not a "low bandwidth" source (one where you can't set
1249         // a reply_to argument), we return. This is mostly web and API
1250         // clients.
1251
1252         if (!in_array($source, $lb)) {
1253             return null;
1254         }
1255
1256         // Is there an initial @ or T?
1257
1258         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1259             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1260             $nickname = common_canonical_nickname($match[1]);
1261         } else {
1262             return null;
1263         }
1264
1265         // Figure out who that is.
1266
1267         $sender = Profile::staticGet('id', $profile_id);
1268         if (empty($sender)) {
1269             return null;
1270         }
1271
1272         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1273
1274         if (empty($recipient)) {
1275             return null;
1276         }
1277
1278         // Get their last notice
1279
1280         $last = $recipient->getCurrentNotice();
1281
1282         if (!empty($last)) {
1283             return $last->id;
1284         }
1285     }
1286
1287     static function maxContent()
1288     {
1289         $contentlimit = common_config('notice', 'contentlimit');
1290         // null => use global limit (distinct from 0!)
1291         if (is_null($contentlimit)) {
1292             $contentlimit = common_config('site', 'textlimit');
1293         }
1294         return $contentlimit;
1295     }
1296
1297     static function contentTooLong($content)
1298     {
1299         $contentlimit = self::maxContent();
1300         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1301     }
1302
1303     function getLocation()
1304     {
1305         $location = null;
1306
1307         if (!empty($this->location_id) && !empty($this->location_ns)) {
1308             $location = Location::fromId($this->location_id, $this->location_ns);
1309         }
1310
1311         if (is_null($location)) { // no ID, or Location::fromId() failed
1312             if (!empty($this->lat) && !empty($this->lon)) {
1313                 $location = Location::fromLatLon($this->lat, $this->lon);
1314             }
1315         }
1316
1317         return $location;
1318     }
1319
1320     function repeat($repeater_id, $source)
1321     {
1322         $author = Profile::staticGet('id', $this->profile_id);
1323
1324         $content = sprintf(_('RT @%1$s %2$s'),
1325                            $author->nickname,
1326                            $this->content);
1327
1328         $maxlen = common_config('site', 'textlimit');
1329         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1330             // Web interface and current Twitter API clients will
1331             // pull the original notice's text, but some older
1332             // clients and RSS/Atom feeds will see this trimmed text.
1333             //
1334             // Unfortunately this is likely to lose tags or URLs
1335             // at the end of long notices.
1336             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1337         }
1338
1339         return self::saveNew($repeater_id, $content, $source,
1340                              array('repeat_of' => $this->id));
1341     }
1342
1343     // These are supposed to be in chron order!
1344
1345     function repeatStream($limit=100)
1346     {
1347         $cache = common_memcache();
1348
1349         if (empty($cache)) {
1350             $ids = $this->_repeatStreamDirect($limit);
1351         } else {
1352             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1353             if ($idstr !== false) {
1354                 $ids = explode(',', $idstr);
1355             } else {
1356                 $ids = $this->_repeatStreamDirect(100);
1357                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1358             }
1359             if ($limit < 100) {
1360                 // We do a max of 100, so slice down to limit
1361                 $ids = array_slice($ids, 0, $limit);
1362             }
1363         }
1364
1365         return Notice::getStreamByIds($ids);
1366     }
1367
1368     function _repeatStreamDirect($limit)
1369     {
1370         $notice = new Notice();
1371
1372         $notice->selectAdd(); // clears it
1373         $notice->selectAdd('id');
1374
1375         $notice->repeat_of = $this->id;
1376
1377         $notice->orderBy('created'); // NB: asc!
1378
1379         if (!is_null($offset)) {
1380             $notice->limit($offset, $limit);
1381         }
1382
1383         $ids = array();
1384
1385         if ($notice->find()) {
1386             while ($notice->fetch()) {
1387                 $ids[] = $notice->id;
1388             }
1389         }
1390
1391         $notice->free();
1392         $notice = NULL;
1393
1394         return $ids;
1395     }
1396
1397     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1398     {
1399         $options = array();
1400
1401         if (!empty($location_id) && !empty($location_ns)) {
1402
1403             $options['location_id'] = $location_id;
1404             $options['location_ns'] = $location_ns;
1405
1406             $location = Location::fromId($location_id, $location_ns);
1407
1408             if (!empty($location)) {
1409                 $options['lat'] = $location->lat;
1410                 $options['lon'] = $location->lon;
1411             }
1412
1413         } else if (!empty($lat) && !empty($lon)) {
1414
1415             $options['lat'] = $lat;
1416             $options['lon'] = $lon;
1417
1418             $location = Location::fromLatLon($lat, $lon);
1419
1420             if (!empty($location)) {
1421                 $options['location_id'] = $location->location_id;
1422                 $options['location_ns'] = $location->location_ns;
1423             }
1424         } else if (!empty($profile)) {
1425
1426             if (isset($profile->lat) && isset($profile->lon)) {
1427                 $options['lat'] = $profile->lat;
1428                 $options['lon'] = $profile->lon;
1429             }
1430
1431             if (isset($profile->location_id) && isset($profile->location_ns)) {
1432                 $options['location_id'] = $profile->location_id;
1433                 $options['location_ns'] = $profile->location_ns;
1434             }
1435         }
1436
1437         return $options;
1438     }
1439
1440     function clearReplies()
1441     {
1442         $replyNotice = new Notice();
1443         $replyNotice->reply_to = $this->id;
1444
1445         //Null any notices that are replies to this notice
1446
1447         if ($replyNotice->find()) {
1448             while ($replyNotice->fetch()) {
1449                 $orig = clone($replyNotice);
1450                 $replyNotice->reply_to = null;
1451                 $replyNotice->update($orig);
1452             }
1453         }
1454
1455         // Reply records
1456
1457         $reply = new Reply();
1458         $reply->notice_id = $this->id;
1459
1460         if ($reply->find()) {
1461             while($reply->fetch()) {
1462                 self::blow('reply:stream:%d', $reply->profile_id);
1463                 $reply->delete();
1464             }
1465         }
1466
1467         $reply->free();
1468     }
1469
1470     function clearRepeats()
1471     {
1472         $repeatNotice = new Notice();
1473         $repeatNotice->repeat_of = $this->id;
1474
1475         //Null any notices that are repeats of this notice
1476
1477         if ($repeatNotice->find()) {
1478             while ($repeatNotice->fetch()) {
1479                 $orig = clone($repeatNotice);
1480                 $repeatNotice->repeat_of = null;
1481                 $repeatNotice->update($orig);
1482             }
1483         }
1484     }
1485
1486     function clearFaves()
1487     {
1488         $fave = new Fave();
1489         $fave->notice_id = $this->id;
1490
1491         if ($fave->find()) {
1492             while ($fave->fetch()) {
1493                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1494                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1495                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1496                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1497                 $fave->delete();
1498             }
1499         }
1500
1501         $fave->free();
1502     }
1503
1504     function clearTags()
1505     {
1506         $tag = new Notice_tag();
1507         $tag->notice_id = $this->id;
1508
1509         if ($tag->find()) {
1510             while ($tag->fetch()) {
1511                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1512                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1513                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1514                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1515                 $tag->delete();
1516             }
1517         }
1518
1519         $tag->free();
1520     }
1521
1522     function clearGroupInboxes()
1523     {
1524         $gi = new Group_inbox();
1525
1526         $gi->notice_id = $this->id;
1527
1528         if ($gi->find()) {
1529             while ($gi->fetch()) {
1530                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1531                 $gi->delete();
1532             }
1533         }
1534
1535         $gi->free();
1536     }
1537
1538     function distribute()
1539     {
1540         // We always insert for the author so they don't
1541         // have to wait
1542
1543         $user = User::staticGet('id', $this->profile_id);
1544         if (!empty($user)) {
1545             Inbox::insertNotice($user->id, $this->id);
1546         }
1547
1548         if (common_config('queue', 'inboxes')) {
1549             // If there's a failure, we want to _force_
1550             // distribution at this point.
1551             try {
1552                 $qm = QueueManager::get();
1553                 $qm->enqueue($this, 'distrib');
1554             } catch (Exception $e) {
1555                 // If the exception isn't transient, this
1556                 // may throw more exceptions as DQH does
1557                 // its own enqueueing. So, we ignore them!
1558                 try {
1559                     $handler = new DistribQueueHandler();
1560                     $handler->handle($this);
1561                 } catch (Exception $e) {
1562                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1563                 }
1564                 // Re-throw so somebody smarter can handle it.
1565                 throw $e;
1566             }
1567         } else {
1568             $handler = new DistribQueueHandler();
1569             $handler->handle($this);
1570         }
1571     }
1572
1573     function insert()
1574     {
1575         $result = parent::insert();
1576
1577         if ($result) {
1578             // Profile::hasRepeated() abuses pkeyGet(), so we
1579             // have to clear manually
1580             if (!empty($this->repeat_of)) {
1581                 $c = self::memcache();
1582                 if (!empty($c)) {
1583                     $ck = self::multicacheKey('Notice',
1584                                               array('profile_id' => $this->profile_id,
1585                                                     'repeat_of' => $this->repeat_of));
1586                     $c->delete($ck);
1587                 }
1588             }
1589         }
1590
1591         return $result;
1592     }
1593 }