]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
4169f1a1c7505621671b6570322f717676efd65a
[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  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
34  */
35
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
37     exit(1);
38 }
39
40 /**
41  * Table Definition for notice
42  */
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
44
45 /* We keep 200 notices, the max number of notices available per API request,
46  * in the memcached cache. */
47
48 define('NOTICE_CACHE_WINDOW', 200);
49
50 define('MAX_BOXCARS', 128);
51
52 class Notice extends Memcached_DataObject
53 {
54     ###START_AUTOCODE
55     /* the code below is auto generated do not remove the above tag */
56
57     public $__table = 'notice';                          // table name
58     public $id;                              // int(4)  primary_key not_null
59     public $profile_id;                      // int(4)  multiple_key not_null
60     public $uri;                             // varchar(255)  unique_key
61     public $content;                         // text
62     public $rendered;                        // text
63     public $url;                             // varchar(255)
64     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
65     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
66     public $reply_to;                        // int(4)
67     public $is_local;                        // int(4)
68     public $source;                          // varchar(32)
69     public $conversation;                    // int(4)
70     public $lat;                             // decimal(10,7)
71     public $lon;                             // decimal(10,7)
72     public $location_id;                     // int(4)
73     public $location_ns;                     // int(4)
74     public $repeat_of;                       // int(4)
75
76     /* Static get */
77     function staticGet($k,$v=NULL)
78     {
79         return Memcached_DataObject::staticGet('Notice',$k,$v);
80     }
81
82     /* the code above is auto generated do not remove the tag below */
83     ###END_AUTOCODE
84
85     /* Notice types */
86     const LOCAL_PUBLIC    =  1;
87     const REMOTE_OMB      =  0;
88     const LOCAL_NONPUBLIC = -1;
89     const GATEWAY         = -2;
90
91     function getProfile()
92     {
93         $profile = Profile::staticGet('id', $this->profile_id);
94
95         if (empty($profile)) {
96             // TRANS: Server exception thrown when a user profile for a notice cannot be found.
97             // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
98             throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
99         }
100
101         return $profile;
102     }
103
104     function delete()
105     {
106         // For auditing purposes, save a record that the notice
107         // was deleted.
108
109         // @fixme we have some cases where things get re-run and so the
110         // insert fails.
111         $deleted = Deleted_notice::staticGet('id', $this->id);
112         if (!$deleted) {
113             $deleted = new Deleted_notice();
114
115             $deleted->id         = $this->id;
116             $deleted->profile_id = $this->profile_id;
117             $deleted->uri        = $this->uri;
118             $deleted->created    = $this->created;
119             $deleted->deleted    = common_sql_now();
120
121             $deleted->insert();
122         }
123
124         if (Event::handle('NoticeDeleteRelated', array($this))) {
125
126             // Clear related records
127
128             $this->clearReplies();
129             $this->clearRepeats();
130             $this->clearFaves();
131             $this->clearTags();
132             $this->clearGroupInboxes();
133
134             // NOTE: we don't clear inboxes
135             // NOTE: we don't clear queue items
136         }
137
138         $result = parent::delete();
139
140         $this->blowOnDelete();
141         return $result;
142     }
143
144     /**
145      * Extract #hashtags from this notice's content and save them to the database.
146      */
147     function saveTags()
148     {
149         /* extract all #hastags */
150         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
151         if (!$count) {
152             return true;
153         }
154
155         /* Add them to the database */
156         return $this->saveKnownTags($match[1]);
157     }
158
159     /**
160      * Record the given set of hash tags in the db for this notice.
161      * Given tag strings will be normalized and checked for dupes.
162      */
163     function saveKnownTags($hashtags)
164     {
165         //turn each into their canonical tag
166         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
167         for($i=0; $i<count($hashtags); $i++) {
168             /* elide characters we don't want in the tag */
169             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
170         }
171
172         foreach(array_unique($hashtags) as $hashtag) {
173             $this->saveTag($hashtag);
174             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
175         }
176         return true;
177     }
178
179     /**
180      * Record a single hash tag as associated with this notice.
181      * Tag format and uniqueness must be validated by caller.
182      */
183     function saveTag($hashtag)
184     {
185         $tag = new Notice_tag();
186         $tag->notice_id = $this->id;
187         $tag->tag = $hashtag;
188         $tag->created = $this->created;
189         $id = $tag->insert();
190
191         if (!$id) {
192             // TRANS: Server exception. %s are the error details.
193             throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
194                                               $last_error->message));
195             return;
196         }
197
198         // if it's saved, blow its cache
199         $tag->blowCache(false);
200     }
201
202     /**
203      * Save a new notice and push it out to subscribers' inboxes.
204      * Poster's permissions are checked before sending.
205      *
206      * @param int $profile_id Profile ID of the poster
207      * @param string $content source message text; links may be shortened
208      *                        per current user's preference
209      * @param string $source source key ('web', 'api', etc)
210      * @param array $options Associative array of optional properties:
211      *              string 'created' timestamp of notice; defaults to now
212      *              int 'is_local' source/gateway ID, one of:
213      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
214      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
215      *                                            hide from public timeline but show in
216      *                                            local "and friends" timelines
217      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
218      *                  Notice::GATEWAY         - From another non-OMB service;
219      *                                            will not appear in public views
220      *              float 'lat' decimal latitude for geolocation
221      *              float 'lon' decimal longitude for geolocation
222      *              int 'location_id' geoname identifier
223      *              int 'location_ns' geoname namespace to interpret location_id
224      *              int 'reply_to'; notice ID this is a reply to
225      *              int 'repeat_of'; notice ID this is a repeat of
226      *              string 'uri' unique ID for notice; defaults to local notice URL
227      *              string 'url' permalink to notice; defaults to local notice URL
228      *              string 'rendered' rendered HTML version of content
229      *              array 'replies' list of profile URIs for reply delivery in
230      *                              place of extracting @-replies from content.
231      *              array 'groups' list of group IDs to deliver to, in place of
232      *                              extracting ! tags from content
233      *              array 'tags' list of hashtag strings to save with the notice
234      *                           in place of extracting # tags from content
235      *              array 'urls' list of attached/referred URLs to save with the
236      *                           notice in place of extracting links from content
237      * @fixme tag override
238      *
239      * @return Notice
240      * @throws ClientException
241      */
242     static function saveNew($profile_id, $content, $source, $options=null) {
243         $defaults = array('uri' => null,
244                           'url' => null,
245                           'reply_to' => null,
246                           'repeat_of' => null);
247
248         if (!empty($options)) {
249             $options = $options + $defaults;
250             extract($options);
251         } else {
252             extract($defaults);
253         }
254
255         if (!isset($is_local)) {
256             $is_local = Notice::LOCAL_PUBLIC;
257         }
258
259         $profile = Profile::staticGet('id', $profile_id);
260         $user = User::staticGet('id', $profile_id);
261         if ($user) {
262             // Use the local user's shortening preferences, if applicable.
263             $final = $user->shortenLinks($content);
264         } else {
265             $final = common_shorten_links($content);
266         }
267
268         if (Notice::contentTooLong($final)) {
269             // TRANS: Client exception thrown if a notice contains too many characters.
270             throw new ClientException(_('Problem saving notice. Too long.'));
271         }
272
273         if (empty($profile)) {
274             // TRANS: Client exception thrown when trying to save a notice for an unknown user.
275             throw new ClientException(_('Problem saving notice. Unknown user.'));
276         }
277
278         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
279             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
280             // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
281             throw new ClientException(_('Too many notices too fast; take a breather '.
282                                         'and post again in a few minutes.'));
283         }
284
285         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
286             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
287             // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
288             throw new ClientException(_('Too many duplicate messages too quickly;'.
289                                         ' take a breather and post again in a few minutes.'));
290         }
291
292         if (!$profile->hasRight(Right::NEWNOTICE)) {
293             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
294
295             // TRANS: Client exception thrown when a user tries to post while being banned.
296             throw new ClientException(_('You are banned from posting notices on this site.'), 403);
297         }
298
299         $notice = new Notice();
300         $notice->profile_id = $profile_id;
301
302         $autosource = common_config('public', 'autosource');
303
304         # Sandboxed are non-false, but not 1, either
305
306         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
307             ($source && $autosource && in_array($source, $autosource))) {
308             $notice->is_local = Notice::LOCAL_NONPUBLIC;
309         } else {
310             $notice->is_local = $is_local;
311         }
312
313         if (!empty($created)) {
314             $notice->created = $created;
315         } else {
316             $notice->created = common_sql_now();
317         }
318
319         $notice->content = $final;
320
321         $notice->source = $source;
322         $notice->uri = $uri;
323         $notice->url = $url;
324
325         // Handle repeat case
326
327         if (isset($repeat_of)) {
328             $notice->repeat_of = $repeat_of;
329         } else {
330             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
331         }
332
333         if (!empty($notice->reply_to)) {
334             $reply = Notice::staticGet('id', $notice->reply_to);
335             $notice->conversation = $reply->conversation;
336         }
337
338         if (!empty($lat) && !empty($lon)) {
339             $notice->lat = $lat;
340             $notice->lon = $lon;
341         }
342
343         if (!empty($location_ns) && !empty($location_id)) {
344             $notice->location_id = $location_id;
345             $notice->location_ns = $location_ns;
346         }
347
348         if (!empty($rendered)) {
349             $notice->rendered = $rendered;
350         } else {
351             $notice->rendered = common_render_content($final, $notice);
352         }
353
354         if (Event::handle('StartNoticeSave', array(&$notice))) {
355
356             // XXX: some of these functions write to the DB
357
358             $id = $notice->insert();
359
360             if (!$id) {
361                 common_log_db_error($notice, 'INSERT', __FILE__);
362                 // TRANS: Server exception thrown when a notice cannot be saved.
363                 throw new ServerException(_('Problem saving notice.'));
364             }
365
366             // Update ID-dependent columns: URI, conversation
367
368             $orig = clone($notice);
369
370             $changed = false;
371
372             if (empty($uri)) {
373                 $notice->uri = common_notice_uri($notice);
374                 $changed = true;
375             }
376
377             // If it's not part of a conversation, it's
378             // the beginning of a new conversation.
379
380             if (empty($notice->conversation)) {
381                 $conv = Conversation::create();
382                 $notice->conversation = $conv->id;
383                 $changed = true;
384             }
385
386             if ($changed) {
387                 if (!$notice->update($orig)) {
388                     common_log_db_error($notice, 'UPDATE', __FILE__);
389                     // TRANS: Server exception thrown when a notice cannot be updated.
390                     throw new ServerException(_('Problem saving notice.'));
391                 }
392             }
393
394         }
395
396         # Clear the cache for subscribed users, so they'll update at next request
397         # XXX: someone clever could prepend instead of clearing the cache
398
399         $notice->blowOnInsert();
400
401         // Save per-notice metadata...
402
403         if (isset($replies)) {
404             $notice->saveKnownReplies($replies);
405         } else {
406             $notice->saveReplies();
407         }
408
409         if (isset($tags)) {
410             $notice->saveKnownTags($tags);
411         } else {
412             $notice->saveTags();
413         }
414
415         // Note: groups may save tags, so must be run after tags are saved
416         // to avoid errors on duplicates.
417         if (isset($groups)) {
418             $notice->saveKnownGroups($groups);
419         } else {
420             $notice->saveGroups();
421         }
422
423         if (isset($urls)) {
424             $notice->saveKnownUrls($urls);
425         } else {
426             $notice->saveUrls();
427         }
428
429         // Prepare inbox delivery, may be queued to background.
430         $notice->distribute();
431
432         return $notice;
433     }
434
435     function blowOnInsert($conversation = false)
436     {
437         self::blow('profile:notice_ids:%d', $this->profile_id);
438         self::blow('public');
439
440         // XXX: Before we were blowing the casche only if the notice id
441         // was not the root of the conversation.  What to do now?
442
443         self::blow('notice:conversation_ids:%d', $this->conversation);
444
445         if (!empty($this->repeat_of)) {
446             self::blow('notice:repeats:%d', $this->repeat_of);
447         }
448
449         $original = Notice::staticGet('id', $this->repeat_of);
450
451         if (!empty($original)) {
452             $originalUser = User::staticGet('id', $original->profile_id);
453             if (!empty($originalUser)) {
454                 self::blow('user:repeats_of_me:%d', $originalUser->id);
455             }
456         }
457
458         $profile = Profile::staticGet($this->profile_id);
459         if (!empty($profile)) {
460             $profile->blowNoticeCount();
461         }
462     }
463
464     /**
465      * Clear cache entries related to this notice at delete time.
466      * Necessary to avoid breaking paging on public, profile timelines.
467      */
468     function blowOnDelete()
469     {
470         $this->blowOnInsert();
471
472         self::blow('profile:notice_ids:%d;last', $this->profile_id);
473         self::blow('public;last');
474     }
475
476     /** save all urls in the notice to the db
477      *
478      * follow redirects and save all available file information
479      * (mimetype, date, size, oembed, etc.)
480      *
481      * @return void
482      */
483     function saveUrls() {
484         if (common_config('attachments', 'process_links')) {
485             common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
486         }
487     }
488
489     /**
490      * Save the given URLs as related links/attachments to the db
491      *
492      * follow redirects and save all available file information
493      * (mimetype, date, size, oembed, etc.)
494      *
495      * @return void
496      */
497     function saveKnownUrls($urls)
498     {
499         if (common_config('attachments', 'process_links')) {
500             // @fixme validation?
501             foreach (array_unique($urls) as $url) {
502                 File::processNew($url, $this->id);
503             }
504         }
505     }
506
507     /**
508      * @private callback
509      */
510     function saveUrl($url, $notice_id) {
511         File::processNew($url, $notice_id);
512     }
513
514     static function checkDupes($profile_id, $content) {
515         $profile = Profile::staticGet($profile_id);
516         if (empty($profile)) {
517             return false;
518         }
519         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
520         if (!empty($notice)) {
521             $last = 0;
522             while ($notice->fetch()) {
523                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
524                     return true;
525                 } else if ($notice->content == $content) {
526                     return false;
527                 }
528             }
529         }
530         # If we get here, oldest item in cache window is not
531         # old enough for dupe limit; do direct check against DB
532         $notice = new Notice();
533         $notice->profile_id = $profile_id;
534         $notice->content = $content;
535         $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
536         $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
537
538         $cnt = $notice->count();
539         return ($cnt == 0);
540     }
541
542     static function checkEditThrottle($profile_id) {
543         $profile = Profile::staticGet($profile_id);
544         if (empty($profile)) {
545             return false;
546         }
547         # Get the Nth notice
548         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
549         if ($notice && $notice->fetch()) {
550             # If the Nth notice was posted less than timespan seconds ago
551             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
552                 # Then we throttle
553                 return false;
554             }
555         }
556         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
557         return true;
558     }
559
560     function getUploadedAttachment() {
561         $post = clone $this;
562         $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"';
563         $post->query($query);
564         $post->fetch();
565         if (empty($post->up) || empty($post->i)) {
566             $ret = false;
567         } else {
568             $ret = array($post->up, $post->i);
569         }
570         $post->free();
571         return $ret;
572     }
573
574     function hasAttachments() {
575         $post = clone $this;
576         $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);
577         $post->query($query);
578         $post->fetch();
579         $n_attachments = intval($post->n_attachments);
580         $post->free();
581         return $n_attachments;
582     }
583
584     function attachments() {
585         // XXX: cache this
586         $att = array();
587         $f2p = new File_to_post;
588         $f2p->post_id = $this->id;
589         if ($f2p->find()) {
590             while ($f2p->fetch()) {
591                 $f = File::staticGet($f2p->file_id);
592                 if ($f) {
593                     $att[] = clone($f);
594                 }
595             }
596         }
597         return $att;
598     }
599
600     function getStreamByIds($ids)
601     {
602         $cache = common_memcache();
603
604         if (!empty($cache)) {
605             $notices = array();
606             foreach ($ids as $id) {
607                 $n = Notice::staticGet('id', $id);
608                 if (!empty($n)) {
609                     $notices[] = $n;
610                 }
611             }
612             return new ArrayWrapper($notices);
613         } else {
614             $notice = new Notice();
615             if (empty($ids)) {
616                 //if no IDs requested, just return the notice object
617                 return $notice;
618             }
619             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
620
621             $notice->find();
622
623             $temp = array();
624
625             while ($notice->fetch()) {
626                 $temp[$notice->id] = clone($notice);
627             }
628
629             $wrapped = array();
630
631             foreach ($ids as $id) {
632                 if (array_key_exists($id, $temp)) {
633                     $wrapped[] = $temp[$id];
634                 }
635             }
636
637             return new ArrayWrapper($wrapped);
638         }
639     }
640
641     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
642     {
643         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
644                               array(),
645                               'public',
646                               $offset, $limit, $since_id, $max_id);
647         return Notice::getStreamByIds($ids);
648     }
649
650     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
651     {
652         $notice = new Notice();
653
654         $notice->selectAdd(); // clears it
655         $notice->selectAdd('id');
656
657         $notice->orderBy('id DESC');
658
659         if (!is_null($offset)) {
660             $notice->limit($offset, $limit);
661         }
662
663         if (common_config('public', 'localonly')) {
664             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
665         } else {
666             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
667             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
668             $notice->whereAdd('is_local !='. Notice::GATEWAY);
669         }
670
671         if ($since_id != 0) {
672             $notice->whereAdd('id > ' . $since_id);
673         }
674
675         if ($max_id != 0) {
676             $notice->whereAdd('id <= ' . $max_id);
677         }
678
679         $ids = array();
680
681         if ($notice->find()) {
682             while ($notice->fetch()) {
683                 $ids[] = $notice->id;
684             }
685         }
686
687         $notice->free();
688         $notice = NULL;
689
690         return $ids;
691     }
692
693     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
694     {
695         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
696                               array($id),
697                               'notice:conversation_ids:'.$id,
698                               $offset, $limit, $since_id, $max_id);
699
700         return Notice::getStreamByIds($ids);
701     }
702
703     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
704     {
705         $notice = new Notice();
706
707         $notice->selectAdd(); // clears it
708         $notice->selectAdd('id');
709
710         $notice->conversation = $id;
711
712         $notice->orderBy('id DESC');
713
714         if (!is_null($offset)) {
715             $notice->limit($offset, $limit);
716         }
717
718         if ($since_id != 0) {
719             $notice->whereAdd('id > ' . $since_id);
720         }
721
722         if ($max_id != 0) {
723             $notice->whereAdd('id <= ' . $max_id);
724         }
725
726         $ids = array();
727
728         if ($notice->find()) {
729             while ($notice->fetch()) {
730                 $ids[] = $notice->id;
731             }
732         }
733
734         $notice->free();
735         $notice = NULL;
736
737         return $ids;
738     }
739
740     /**
741      * Is this notice part of an active conversation?
742      *
743      * @return boolean true if other messages exist in the same
744      *                 conversation, false if this is the only one
745      */
746     function hasConversation()
747     {
748         if (!empty($this->conversation)) {
749             $conversation = Notice::conversationStream(
750                 $this->conversation,
751                 1,
752                 1
753             );
754
755             if ($conversation->N > 0) {
756                 return true;
757             }
758         }
759         return false;
760     }
761
762     /**
763      * Pull up a full list of local recipients who will be getting
764      * this notice in their inbox. Results will be cached, so don't
765      * change the input data wily-nilly!
766      *
767      * @param array $groups optional list of Group objects;
768      *              if left empty, will be loaded from group_inbox records
769      * @param array $recipient optional list of reply profile ids
770      *              if left empty, will be loaded from reply records
771      * @return array associating recipient user IDs with an inbox source constant
772      */
773     function whoGets($groups=null, $recipients=null)
774     {
775         $c = self::memcache();
776
777         if (!empty($c)) {
778             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
779             if ($ni !== false) {
780                 return $ni;
781             }
782         }
783
784         if (is_null($groups)) {
785             $groups = $this->getGroups();
786         }
787
788         if (is_null($recipients)) {
789             $recipients = $this->getReplies();
790         }
791
792         $users = $this->getSubscribedUsers();
793
794         // FIXME: kind of ignoring 'transitional'...
795         // we'll probably stop supporting inboxless mode
796         // in 0.9.x
797
798         $ni = array();
799
800         foreach ($users as $id) {
801             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
802         }
803
804         foreach ($groups as $group) {
805             $users = $group->getUserMembers();
806             foreach ($users as $id) {
807                 if (!array_key_exists($id, $ni)) {
808                     $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
809                 }
810             }
811         }
812
813         foreach ($recipients as $recipient) {
814             if (!array_key_exists($recipient, $ni)) {
815                 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
816             }
817         }
818
819         // Exclude any deleted, non-local, or blocking recipients.
820         $profile = $this->getProfile();
821         foreach ($ni as $id => $source) {
822             $user = User::staticGet('id', $id);
823             if (empty($user) || $user->hasBlocked($profile)) {
824                 unset($ni[$id]);
825             }
826         }
827
828         if (!empty($c)) {
829             // XXX: pack this data better
830             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
831         }
832
833         return $ni;
834     }
835
836     /**
837      * Adds this notice to the inboxes of each local user who should receive
838      * it, based on author subscriptions, group memberships, and @-replies.
839      *
840      * Warning: running a second time currently will make items appear
841      * multiple times in users' inboxes.
842      *
843      * @fixme make more robust against errors
844      * @fixme break up massive deliveries to smaller background tasks
845      *
846      * @param array $groups optional list of Group objects;
847      *              if left empty, will be loaded from group_inbox records
848      * @param array $recipient optional list of reply profile ids
849      *              if left empty, will be loaded from reply records
850      */
851     function addToInboxes($groups=null, $recipients=null)
852     {
853         $ni = $this->whoGets($groups, $recipients);
854
855         $ids = array_keys($ni);
856
857         // We remove the author (if they're a local user),
858         // since we'll have already done this in distribute()
859
860         $i = array_search($this->profile_id, $ids);
861
862         if ($i !== false) {
863             unset($ids[$i]);
864         }
865
866         // Bulk insert
867
868         Inbox::bulkInsert($this->id, $ids);
869
870         return;
871     }
872
873     function getSubscribedUsers()
874     {
875         $user = new User();
876
877         if(common_config('db','quote_identifiers'))
878           $user_table = '"user"';
879         else $user_table = 'user';
880
881         $qry =
882           'SELECT id ' .
883           'FROM '. $user_table .' JOIN subscription '.
884           'ON '. $user_table .'.id = subscription.subscriber ' .
885           'WHERE subscription.subscribed = %d ';
886
887         $user->query(sprintf($qry, $this->profile_id));
888
889         $ids = array();
890
891         while ($user->fetch()) {
892             $ids[] = $user->id;
893         }
894
895         $user->free();
896
897         return $ids;
898     }
899
900     /**
901      * Record this notice to the given group inboxes for delivery.
902      * Overrides the regular parsing of !group markup.
903      *
904      * @param string $group_ids
905      * @fixme might prefer URIs as identifiers, as for replies?
906      *        best with generalizations on user_group to support
907      *        remote groups better.
908      */
909     function saveKnownGroups($group_ids)
910     {
911         if (!is_array($group_ids)) {
912             // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
913             throw new ServerException(_('Bad type provided to saveKnownGroups.'));
914         }
915
916         $groups = array();
917         foreach (array_unique($group_ids) as $id) {
918             $group = User_group::staticGet('id', $id);
919             if ($group) {
920                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
921                 $result = $this->addToGroupInbox($group);
922                 if (!$result) {
923                     common_log_db_error($gi, 'INSERT', __FILE__);
924                 }
925
926                 // @fixme should we save the tags here or not?
927                 $groups[] = clone($group);
928             } else {
929                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
930             }
931         }
932
933         return $groups;
934     }
935
936     /**
937      * Parse !group delivery and record targets into group_inbox.
938      * @return array of Group objects
939      */
940     function saveGroups()
941     {
942         // Don't save groups for repeats
943
944         if (!empty($this->repeat_of)) {
945             return array();
946         }
947
948         $groups = array();
949
950         /* extract all !group */
951         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
952                                 strtolower($this->content),
953                                 $match);
954         if (!$count) {
955             return $groups;
956         }
957
958         $profile = $this->getProfile();
959
960         /* Add them to the database */
961
962         foreach (array_unique($match[1]) as $nickname) {
963             /* XXX: remote groups. */
964             $group = User_group::getForNickname($nickname, $profile);
965
966             if (empty($group)) {
967                 continue;
968             }
969
970             // we automatically add a tag for every group name, too
971
972             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
973                                              'notice_id' => $this->id));
974
975             if (is_null($tag)) {
976                 $this->saveTag($nickname);
977             }
978
979             if ($profile->isMember($group)) {
980
981                 $result = $this->addToGroupInbox($group);
982
983                 if (!$result) {
984                     common_log_db_error($gi, 'INSERT', __FILE__);
985                 }
986
987                 $groups[] = clone($group);
988             }
989         }
990
991         return $groups;
992     }
993
994     function addToGroupInbox($group)
995     {
996         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
997                                          'notice_id' => $this->id));
998
999         if (empty($gi)) {
1000
1001             $gi = new Group_inbox();
1002
1003             $gi->group_id  = $group->id;
1004             $gi->notice_id = $this->id;
1005             $gi->created   = $this->created;
1006
1007             $result = $gi->insert();
1008
1009             if (!$result) {
1010                 common_log_db_error($gi, 'INSERT', __FILE__);
1011                 // TRANS: Server exception thrown when an update for a group inbox fails.
1012                 throw new ServerException(_('Problem saving group inbox.'));
1013             }
1014
1015             self::blow('user_group:notice_ids:%d', $gi->group_id);
1016         }
1017
1018         return true;
1019     }
1020
1021     /**
1022      * Save reply records indicating that this notice needs to be
1023      * delivered to the local users with the given URIs.
1024      *
1025      * Since this is expected to be used when saving foreign-sourced
1026      * messages, we won't deliver to any remote targets as that's the
1027      * source service's responsibility.
1028      *
1029      * Mail notifications etc will be handled later.
1030      *
1031      * @param array of unique identifier URIs for recipients
1032      */
1033     function saveKnownReplies($uris)
1034     {
1035         if (empty($uris)) {
1036             return;
1037         }
1038
1039         $sender = Profile::staticGet($this->profile_id);
1040
1041         foreach (array_unique($uris) as $uri) {
1042
1043             $profile = Profile::fromURI($uri);
1044
1045             if (empty($profile)) {
1046                 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1047                 continue;
1048             }
1049
1050             if ($profile->hasBlocked($sender)) {
1051                 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1052                 continue;
1053             }
1054
1055             $reply = new Reply();
1056
1057             $reply->notice_id  = $this->id;
1058             $reply->profile_id = $profile->id;
1059
1060             common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1061
1062             $id = $reply->insert();
1063         }
1064
1065         return;
1066     }
1067
1068     /**
1069      * Pull @-replies from this message's content in StatusNet markup format
1070      * and save reply records indicating that this message needs to be
1071      * delivered to those users.
1072      *
1073      * Mail notifications to local profiles will be sent later.
1074      *
1075      * @return array of integer profile IDs
1076      */
1077
1078     function saveReplies()
1079     {
1080         // Don't save reply data for repeats
1081
1082         if (!empty($this->repeat_of)) {
1083             return array();
1084         }
1085
1086         $sender = Profile::staticGet($this->profile_id);
1087
1088         // @todo ideally this parser information would only
1089         // be calculated once.
1090
1091         $mentions = common_find_mentions($this->content, $this);
1092
1093         $replied = array();
1094
1095         // store replied only for first @ (what user/notice what the reply directed,
1096         // we assume first @ is it)
1097
1098         foreach ($mentions as $mention) {
1099
1100             foreach ($mention['mentioned'] as $mentioned) {
1101
1102                 // skip if they're already covered
1103
1104                 if (!empty($replied[$mentioned->id])) {
1105                     continue;
1106                 }
1107
1108                 // Don't save replies from blocked profile to local user
1109
1110                 $mentioned_user = User::staticGet('id', $mentioned->id);
1111                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1112                     continue;
1113                 }
1114
1115                 $reply = new Reply();
1116
1117                 $reply->notice_id  = $this->id;
1118                 $reply->profile_id = $mentioned->id;
1119
1120                 $id = $reply->insert();
1121
1122                 if (!$id) {
1123                     common_log_db_error($reply, 'INSERT', __FILE__);
1124                     // TRANS: Server exception thrown when a reply cannot be saved.
1125                     // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1126                     throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1127                 } else {
1128                     $replied[$mentioned->id] = 1;
1129                     self::blow('reply:stream:%d', $mentioned->id);
1130                 }
1131             }
1132         }
1133
1134         $recipientIds = array_keys($replied);
1135
1136         return $recipientIds;
1137     }
1138
1139     /**
1140      * Pull the complete list of @-reply targets for this notice.
1141      *
1142      * @return array of integer profile ids
1143      */
1144     function getReplies()
1145     {
1146         // XXX: cache me
1147
1148         $ids = array();
1149
1150         $reply = new Reply();
1151         $reply->selectAdd();
1152         $reply->selectAdd('profile_id');
1153         $reply->notice_id = $this->id;
1154
1155         if ($reply->find()) {
1156             while($reply->fetch()) {
1157                 $ids[] = $reply->profile_id;
1158             }
1159         }
1160
1161         $reply->free();
1162
1163         return $ids;
1164     }
1165
1166     /**
1167      * Send e-mail notifications to local @-reply targets.
1168      *
1169      * Replies must already have been saved; this is expected to be run
1170      * from the distrib queue handler.
1171      */
1172     function sendReplyNotifications()
1173     {
1174         // Don't send reply notifications for repeats
1175
1176         if (!empty($this->repeat_of)) {
1177             return array();
1178         }
1179
1180         $recipientIds = $this->getReplies();
1181
1182         foreach ($recipientIds as $recipientId) {
1183             $user = User::staticGet('id', $recipientId);
1184             if (!empty($user)) {
1185                 mail_notify_attn($user, $this);
1186             }
1187         }
1188     }
1189
1190     /**
1191      * Pull list of groups this notice needs to be delivered to,
1192      * as previously recorded by saveGroups() or saveKnownGroups().
1193      *
1194      * @return array of Group objects
1195      */
1196     function getGroups()
1197     {
1198         // Don't save groups for repeats
1199
1200         if (!empty($this->repeat_of)) {
1201             return array();
1202         }
1203
1204         // XXX: cache me
1205
1206         $groups = array();
1207
1208         $gi = new Group_inbox();
1209
1210         $gi->selectAdd();
1211         $gi->selectAdd('group_id');
1212
1213         $gi->notice_id = $this->id;
1214
1215         if ($gi->find()) {
1216             while ($gi->fetch()) {
1217                 $group = User_group::staticGet('id', $gi->group_id);
1218                 if ($group) {
1219                     $groups[] = $group;
1220                 }
1221             }
1222         }
1223
1224         $gi->free();
1225
1226         return $groups;
1227     }
1228
1229     function asActivity()
1230     {
1231         $profile = $this->getProfile();
1232
1233         $act = new Activity();
1234
1235         $act->actor     = ActivityObject::fromProfile($profile);
1236         $act->verb      = ActivityVerb::POST;
1237         $act->objects[] = ActivityObject::fromNotice($this);
1238
1239         $act->time    = strtotime($this->created);
1240         $act->link    = $this->bestUrl();
1241
1242         $act->content = common_xml_safe_str($this->rendered);
1243         $act->id      = $this->uri;
1244         $act->title   = common_xml_safe_str($this->content);
1245
1246         $ctx = new ActivityContext();
1247
1248         if (!empty($this->reply_to)) {
1249             $reply = Notice::staticGet('id', $this->reply_to);
1250             if (!empty($reply)) {
1251                 $ctx->replyToID  = $reply->uri;
1252                 $ctx->replyToUrl = $reply->bestUrl();
1253             }
1254         }
1255
1256         $ctx->location = $this->getLocation();
1257
1258         $conv = null;
1259
1260         if (!empty($this->conversation)) {
1261             $conv = Conversation::staticGet('id', $this->conversation);
1262             if (!empty($conv)) {
1263                 $ctx->conversation = $conv->uri;
1264             }
1265         }
1266
1267         $reply_ids = $this->getReplies();
1268
1269         foreach ($reply_ids as $id) {
1270             $profile = Profile::staticGet('id', $id);
1271             if (!empty($profile)) {
1272                 $ctx->attention[] = $profile->getUri();
1273             }
1274         }
1275
1276         $groups = $this->getGroups();
1277
1278         foreach ($groups as $group) {
1279             $ctx->attention[] = $group->uri;
1280         }
1281
1282         $act->context = $ctx;
1283
1284         return $act;
1285     }
1286
1287     // This has gotten way too long. Needs to be sliced up into functional bits
1288     // or ideally exported to a utility class.
1289
1290     function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1291     {
1292         $profile = $this->getProfile();
1293
1294         $xs = new XMLStringer(true);
1295
1296         if ($namespace) {
1297             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1298                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1299                            'xmlns:georss' => 'http://www.georss.org/georss',
1300                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1301                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
1302                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1303                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1304                            'xmlns:statusnet' => 'http://status.net/schema/api/1/');
1305         } else {
1306             $attrs = array();
1307         }
1308
1309         if (Event::handle('StartActivityStart', array(&$this, &$xs, &$attrs))) {
1310             $xs->elementStart('entry', $attrs);
1311             Event::handle('EndActivityStart', array(&$this, &$xs, &$attrs));
1312         }
1313
1314         if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
1315             if ($source) {
1316                 $atom_feed = $profile->getAtomFeed();
1317
1318                 if (!empty($atom_feed)) {
1319                     $xs->elementStart('source');
1320
1321                     // XXX: we should store the actual feed ID
1322
1323                     $xs->element('id', null, $atom_feed);
1324
1325                     // XXX: we should store the actual feed title
1326
1327                     $xs->element('title', null, $profile->getBestName());
1328
1329                     $xs->element('link', array('rel' => 'alternate',
1330                                                'type' => 'text/html',
1331                                                'href' => $profile->profileurl));
1332
1333                     $xs->element('link', array('rel' => 'self',
1334                                                'type' => 'application/atom+xml',
1335                                                'href' => $atom_feed));
1336
1337                     $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1338
1339                     $notice = $profile->getCurrentNotice();
1340
1341                     if (!empty($notice)) {
1342                         $xs->element('updated', null, self::utcDate($notice->created));
1343                     }
1344
1345                     $user = User::staticGet('id', $profile->id);
1346
1347                     if (!empty($user)) {
1348                         $xs->element('link', array('rel' => 'license',
1349                                                    'href' => common_config('license', 'url')));
1350                     }
1351
1352                     $xs->elementEnd('source');
1353                 }
1354             }
1355             Event::handle('EndActivitySource', array(&$this, &$xs));
1356         }
1357
1358         $title = common_xml_safe_str($this->content);
1359
1360         if (Event::handle('StartActivityTitle', array(&$this, &$xs, &$title))) {
1361             $xs->element('title', null, $title);
1362             Event::handle('EndActivityTitle', array($this, &$xs, $title));
1363         }
1364
1365         $atomAuthor = '';
1366
1367         if ($author) {
1368             $atomAuthor = $profile->asAtomAuthor($cur);
1369         }
1370
1371         if (Event::handle('StartActivityAuthor', array(&$this, &$xs, &$atomAuthor))) {
1372             if (!empty($atomAuthor)) {
1373                 $xs->raw($atomAuthor);
1374                 Event::handle('EndActivityAuthor', array(&$this, &$xs, &$atomAuthor));
1375             }
1376         }
1377
1378         $actor = '';
1379
1380         if ($author) {
1381             $actor = $profile->asActivityActor();
1382         }
1383
1384         if (Event::handle('StartActivityActor', array(&$this, &$xs, &$actor))) {
1385             if (!empty($actor)) {
1386                 $xs->raw($actor);
1387                 Event::handle('EndActivityActor', array(&$this, &$xs, &$actor));
1388             }
1389         }
1390
1391         $url = $this->bestUrl();
1392
1393         if (Event::handle('StartActivityLink', array(&$this, &$xs, &$url))) {
1394             $xs->element('link', array('rel' => 'alternate',
1395                                        'type' => 'text/html',
1396                                        'href' => $url));
1397             Event::handle('EndActivityLink', array(&$this, &$xs, $url));
1398         }
1399
1400         $id = $this->uri;
1401
1402         if (Event::handle('StartActivityId', array(&$this, &$xs, &$id))) {
1403             $xs->element('id', null, $id);
1404             Event::handle('EndActivityId', array(&$this, &$xs, $id));
1405         }
1406
1407         $published = self::utcDate($this->created);
1408
1409         if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
1410             $xs->element('published', null, $published);
1411             Event::handle('EndActivityPublished', array(&$this, &$xs, $published));
1412         }
1413
1414         $updated = $published; // XXX: notices are usually immutable
1415
1416         if (Event::handle('StartActivityUpdated', array(&$this, &$xs, &$updated))) {
1417             $xs->element('updated', null, $updated);
1418             Event::handle('EndActivityUpdated', array(&$this, &$xs, $updated));
1419         }
1420
1421         $content = common_xml_safe_str($this->rendered);
1422
1423         if (Event::handle('StartActivityContent', array(&$this, &$xs, &$content))) {
1424             $xs->element('content', array('type' => 'html'), $content);
1425             Event::handle('EndActivityContent', array(&$this, &$xs, $content));
1426         }
1427
1428         // Most of our notices represent POSTing a NOTE. This is the default verb
1429         // for activity streams, so we normally just leave it out.
1430
1431         $verb = ActivityVerb::POST;
1432
1433         if (Event::handle('StartActivityVerb', array(&$this, &$xs, &$verb))) {
1434             $xs->element('activity:verb', null, $verb);
1435             Event::handle('EndActivityVerb', array(&$this, &$xs, $verb));
1436         }
1437
1438         // We use the default behavior for activity streams: if there's no activity:object,
1439         // then treat the entry itself as the object. Here, you can set the type of that object,
1440         // which is normally a NOTE.
1441
1442         $type = ActivityObject::NOTE;
1443
1444         if (Event::handle('StartActivityDefaultObjectType', array(&$this, &$xs, &$type))) {
1445             $xs->element('activity:object-type', null, $type);
1446             Event::handle('EndActivityDefaultObjectType', array(&$this, &$xs, $type));
1447         }
1448
1449         // Since we usually use the entry itself as an object, we don't have an explicit
1450         // object. Some extensions may want to add them (for photo, event, music, etc.).
1451
1452         $objects = array();
1453
1454         if (Event::handle('StartActivityObjects', array(&$this, &$xs, &$objects))) {
1455             foreach ($objects as $object) {
1456                 $xs->raw($object->asString());
1457             }
1458             Event::handle('EndActivityObjects', array(&$this, &$xs, $objects));
1459         }
1460
1461         $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
1462
1463         $ns = $this->getSource();
1464
1465         if (!empty($ns)) {
1466             $noticeInfoAttr['source'] =  $ns->code;
1467             if (!empty($ns->url)) {
1468                 $noticeInfoAttr['source_link'] = $ns->url;
1469                 if (!empty($ns->name)) {
1470                     $noticeInfoAttr['source'] =  '<a href="'
1471                       . htmlspecialchars($ns->url)
1472                         . '" rel="nofollow">'
1473                       . htmlspecialchars($ns->name)
1474                         . '</a>';
1475                 }
1476             }
1477         }
1478
1479         if (!empty($cur)) {
1480             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1481             $profile = $cur->getProfile();
1482             $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
1483         }
1484
1485         if (!empty($this->repeat_of)) {
1486             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1487         }
1488
1489         if (Event::handle('StartActivityNoticeInfo', array(&$this, &$xs, &$noticeInfoAttr))) {
1490             $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1491             Event::handle('EndActivityNoticeInfo', array(&$this, &$xs, $noticeInfoAttr));
1492         }
1493
1494         $replyNotice = null;
1495
1496         if ($this->reply_to) {
1497             $replyNotice = Notice::staticGet('id', $this->reply_to);
1498         }
1499
1500         if (Event::handle('StartActivityInReplyTo', array(&$this, &$xs, &$replyNotice))) {
1501             if (!empty($replyNotice)) {
1502                 $xs->element('link', array('rel' => 'related',
1503                                            'href' => $replyNotice->bestUrl()));
1504                 $xs->element('thr:in-reply-to',
1505                              array('ref' => $replyNotice->uri,
1506                                    'href' => $replyNotice->bestUrl()));
1507                 Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
1508             }
1509         }
1510
1511         $conv = null;
1512
1513         if (!empty($this->conversation)) {
1514             $conv = Conversation::staticGet('id', $this->conversation);
1515         }
1516
1517         if (Event::handle('StartActivityConversation', array(&$this, &$xs, &$conv))) {
1518             if (!empty($conv)) {
1519                 $xs->element('link', array('rel' => 'ostatus:conversation',
1520                                            'href' => $conv->uri));
1521             }
1522             Event::handle('EndActivityConversation', array(&$this, &$xs, $conv));
1523         }
1524
1525         $replyProfiles = array();
1526
1527         $reply_ids = $this->getReplies();
1528
1529         foreach ($reply_ids as $id) {
1530             $profile = Profile::staticGet('id', $id);
1531             if (!empty($profile)) {
1532                 $replyProfiles[] = $profile;
1533             }
1534         }
1535
1536         if (Event::handle('StartActivityAttentionProfiles', array(&$this, &$xs, &$replyProfiles))) {
1537             foreach ($replyProfiles as $profile) {
1538                 $xs->element('link', array('rel' => 'ostatus:attention',
1539                                            'href' => $profile->getUri()));
1540                 $xs->element('link', array('rel' => 'mentioned',
1541                                            'href' => $profile->getUri()));
1542             }
1543             Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
1544         }
1545
1546         $groups = $this->getGroups();
1547
1548         if (Event::handle('StartActivityAttentionGroups', array(&$this, &$xs, &$groups))) {
1549             foreach ($groups as $group) {
1550                 $xs->element('link', array('rel' => 'ostatus:attention',
1551                                            'href' => $group->permalink()));
1552                 $xs->element('link', array('rel' => 'mentioned',
1553                                            'href' => $group->permalink()));
1554             }
1555             Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
1556         }
1557
1558         $repeat = null;
1559
1560         if (!empty($this->repeat_of)) {
1561             $repeat = Notice::staticGet('id', $this->repeat_of);
1562         }
1563
1564         if (Event::handle('StartActivityForward', array(&$this, &$xs, &$repeat))) {
1565             if (!empty($repeat)) {
1566                 $xs->element('ostatus:forward',
1567                              array('ref' => $repeat->uri,
1568                                    'href' => $repeat->bestUrl()));
1569             }
1570
1571             Event::handle('EndActivityForward', array(&$this, &$xs, $repeat));
1572         }
1573
1574         $tags = $this->getTags();
1575
1576         if (Event::handle('StartActivityCategories', array(&$this, &$xs, &$tags))) {
1577             foreach ($tags as $tag) {
1578                 $xs->element('category', array('term' => $tag));
1579             }
1580             Event::handle('EndActivityCategories', array(&$this, &$xs, $tags));
1581         }
1582
1583         // Enclosures
1584
1585         $enclosures = array();
1586
1587         $attachments = $this->attachments();
1588
1589         foreach ($attachments as $attachment) {
1590             $enclosure = $attachment->getEnclosure();
1591             if ($enclosure) {
1592                 $enclosures[] = $enclosure;
1593             }
1594         }
1595
1596         if (Event::handle('StartActivityEnclosures', array(&$this, &$xs, &$enclosures))) {
1597             foreach ($enclosures as $enclosure) {
1598                 $attributes = array('rel' => 'enclosure',
1599                                     'href' => $enclosure->url,
1600                                     'type' => $enclosure->mimetype,
1601                                     'length' => $enclosure->size);
1602
1603                 if ($enclosure->title) {
1604                     $attributes['title'] = $enclosure->title;
1605                 }
1606
1607                 $xs->element('link', $attributes, null);
1608             }
1609             Event::handle('EndActivityEnclosures', array(&$this, &$xs, $enclosures));
1610         }
1611
1612         $lat = $this->lat;
1613         $lon = $this->lon;
1614
1615         if (Event::handle('StartActivityGeo', array(&$this, &$xs, &$lat, &$lon))) {
1616             if (!empty($lat) && !empty($lon)) {
1617                 $xs->element('georss:point', null, $lat . ' ' . $lon);
1618             }
1619             Event::handle('EndActivityGeo', array(&$this, &$xs, $lat, $lon));
1620         }
1621
1622         // @fixme check this logic
1623
1624         if ($this->isLocal()) {
1625
1626             $selfUrl = common_local_url('ApiStatusesShow', array('id' => $this->id,
1627                                                                  'format' => 'atom'));
1628
1629             if (Event::handle('StartActivityRelSelf', array(&$this, &$xs, &$selfUrl))) {
1630                 $xs->element('link', array('rel' => 'self',
1631                                            'type' => 'application/atom+xml',
1632                                            'href' => $selfUrl));
1633                 Event::handle('EndActivityRelSelf', array(&$this, &$xs, $selfUrl));
1634             }
1635
1636             if (!empty($cur) && $cur->id == $this->profile_id) {
1637
1638                 // note: $selfUrl may have been changed by a plugin
1639                 $relEditUrl = common_local_url('ApiStatusesShow', array('id' => $this->id,
1640                                                                         'format' => 'atom'));
1641
1642                 if (Event::handle('StartActivityRelEdit', array(&$this, &$xs, &$relEditUrl))) {
1643                     $xs->element('link', array('rel' => 'edit',
1644                                                'type' => 'application/atom+xml',
1645                                                'href' => $relEditUrl));
1646                     Event::handle('EndActivityRelEdit', array(&$this, &$xs, $relEditUrl));
1647                 }
1648             }
1649         }
1650
1651         if (Event::handle('StartActivityEnd', array(&$this, &$xs))) {
1652             $xs->elementEnd('entry');
1653             Event::handle('EndActivityEnd', array(&$this, &$xs));
1654         }
1655
1656         return $xs->getString();
1657     }
1658
1659     /**
1660      * Returns an XML string fragment with a reference to a notice as an
1661      * Activity Streams noun object with the given element type.
1662      *
1663      * Assumes that 'activity' namespace has been previously defined.
1664      *
1665      * @param string $element one of 'subject', 'object', 'target'
1666      * @return string
1667      */
1668     function asActivityNoun($element)
1669     {
1670         $noun = ActivityObject::fromNotice($this);
1671         return $noun->asString('activity:' . $element);
1672     }
1673
1674     function bestUrl()
1675     {
1676         if (!empty($this->url)) {
1677             return $this->url;
1678         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1679             return $this->uri;
1680         } else {
1681             return common_local_url('shownotice',
1682                                     array('notice' => $this->id));
1683         }
1684     }
1685
1686     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1687     {
1688         $cache = common_memcache();
1689
1690         if (empty($cache) ||
1691             $since_id != 0 || $max_id != 0 ||
1692             is_null($limit) ||
1693             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1694             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1695                                                                       $max_id)));
1696         }
1697
1698         $idkey = common_cache_key($cachekey);
1699
1700         $idstr = $cache->get($idkey);
1701
1702         if ($idstr !== false) {
1703             // Cache hit! Woohoo!
1704             $window = explode(',', $idstr);
1705             $ids = array_slice($window, $offset, $limit);
1706             return $ids;
1707         }
1708
1709         $laststr = $cache->get($idkey.';last');
1710
1711         if ($laststr !== false) {
1712             $window = explode(',', $laststr);
1713             $last_id = $window[0];
1714             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1715                                                                           $last_id, 0, null)));
1716
1717             $new_window = array_merge($new_ids, $window);
1718
1719             $new_windowstr = implode(',', $new_window);
1720
1721             $result = $cache->set($idkey, $new_windowstr);
1722             $result = $cache->set($idkey . ';last', $new_windowstr);
1723
1724             $ids = array_slice($new_window, $offset, $limit);
1725
1726             return $ids;
1727         }
1728
1729         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1730                                                                      0, 0, null)));
1731
1732         $windowstr = implode(',', $window);
1733
1734         $result = $cache->set($idkey, $windowstr);
1735         $result = $cache->set($idkey . ';last', $windowstr);
1736
1737         $ids = array_slice($window, $offset, $limit);
1738
1739         return $ids;
1740     }
1741
1742     /**
1743      * Determine which notice, if any, a new notice is in reply to.
1744      *
1745      * For conversation tracking, we try to see where this notice fits
1746      * in the tree. Rough algorithm is:
1747      *
1748      * if (reply_to is set and valid) {
1749      *     return reply_to;
1750      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1751      *     return ID of last notice by initial @name in content;
1752      * }
1753      *
1754      * Note that all @nickname instances will still be used to save "reply" records,
1755      * so the notice shows up in the mentioned users' "replies" tab.
1756      *
1757      * @param integer $reply_to   ID passed in by Web or API
1758      * @param integer $profile_id ID of author
1759      * @param string  $source     Source tag, like 'web' or 'gwibber'
1760      * @param string  $content    Final notice content
1761      *
1762      * @return integer ID of replied-to notice, or null for not a reply.
1763      */
1764
1765     static function getReplyTo($reply_to, $profile_id, $source, $content)
1766     {
1767         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1768
1769         // If $reply_to is specified, we check that it exists, and then
1770         // return it if it does
1771
1772         if (!empty($reply_to)) {
1773             $reply_notice = Notice::staticGet('id', $reply_to);
1774             if (!empty($reply_notice)) {
1775                 return $reply_to;
1776             }
1777         }
1778
1779         // If it's not a "low bandwidth" source (one where you can't set
1780         // a reply_to argument), we return. This is mostly web and API
1781         // clients.
1782
1783         if (!in_array($source, $lb)) {
1784             return null;
1785         }
1786
1787         // Is there an initial @ or T?
1788
1789         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1790             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1791             $nickname = common_canonical_nickname($match[1]);
1792         } else {
1793             return null;
1794         }
1795
1796         // Figure out who that is.
1797
1798         $sender = Profile::staticGet('id', $profile_id);
1799         if (empty($sender)) {
1800             return null;
1801         }
1802
1803         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1804
1805         if (empty($recipient)) {
1806             return null;
1807         }
1808
1809         // Get their last notice
1810
1811         $last = $recipient->getCurrentNotice();
1812
1813         if (!empty($last)) {
1814             return $last->id;
1815         }
1816     }
1817
1818     static function maxContent()
1819     {
1820         $contentlimit = common_config('notice', 'contentlimit');
1821         // null => use global limit (distinct from 0!)
1822         if (is_null($contentlimit)) {
1823             $contentlimit = common_config('site', 'textlimit');
1824         }
1825         return $contentlimit;
1826     }
1827
1828     static function contentTooLong($content)
1829     {
1830         $contentlimit = self::maxContent();
1831         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1832     }
1833
1834     function getLocation()
1835     {
1836         $location = null;
1837
1838         if (!empty($this->location_id) && !empty($this->location_ns)) {
1839             $location = Location::fromId($this->location_id, $this->location_ns);
1840         }
1841
1842         if (is_null($location)) { // no ID, or Location::fromId() failed
1843             if (!empty($this->lat) && !empty($this->lon)) {
1844                 $location = Location::fromLatLon($this->lat, $this->lon);
1845             }
1846         }
1847
1848         return $location;
1849     }
1850
1851     function repeat($repeater_id, $source)
1852     {
1853         $author = Profile::staticGet('id', $this->profile_id);
1854
1855         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1856         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1857         $content = sprintf(_('RT @%1$s %2$s'),
1858                            $author->nickname,
1859                            $this->content);
1860
1861         $maxlen = common_config('site', 'textlimit');
1862         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1863             // Web interface and current Twitter API clients will
1864             // pull the original notice's text, but some older
1865             // clients and RSS/Atom feeds will see this trimmed text.
1866             //
1867             // Unfortunately this is likely to lose tags or URLs
1868             // at the end of long notices.
1869             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1870         }
1871
1872         return self::saveNew($repeater_id, $content, $source,
1873                              array('repeat_of' => $this->id));
1874     }
1875
1876     // These are supposed to be in chron order!
1877
1878     function repeatStream($limit=100)
1879     {
1880         $cache = common_memcache();
1881
1882         if (empty($cache)) {
1883             $ids = $this->_repeatStreamDirect($limit);
1884         } else {
1885             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1886             if ($idstr !== false) {
1887                 $ids = explode(',', $idstr);
1888             } else {
1889                 $ids = $this->_repeatStreamDirect(100);
1890                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1891             }
1892             if ($limit < 100) {
1893                 // We do a max of 100, so slice down to limit
1894                 $ids = array_slice($ids, 0, $limit);
1895             }
1896         }
1897
1898         return Notice::getStreamByIds($ids);
1899     }
1900
1901     function _repeatStreamDirect($limit)
1902     {
1903         $notice = new Notice();
1904
1905         $notice->selectAdd(); // clears it
1906         $notice->selectAdd('id');
1907
1908         $notice->repeat_of = $this->id;
1909
1910         $notice->orderBy('created'); // NB: asc!
1911
1912         if (!is_null($offset)) {
1913             $notice->limit($offset, $limit);
1914         }
1915
1916         $ids = array();
1917
1918         if ($notice->find()) {
1919             while ($notice->fetch()) {
1920                 $ids[] = $notice->id;
1921             }
1922         }
1923
1924         $notice->free();
1925         $notice = NULL;
1926
1927         return $ids;
1928     }
1929
1930     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1931     {
1932         $options = array();
1933
1934         if (!empty($location_id) && !empty($location_ns)) {
1935             $options['location_id'] = $location_id;
1936             $options['location_ns'] = $location_ns;
1937
1938             $location = Location::fromId($location_id, $location_ns);
1939
1940             if (!empty($location)) {
1941                 $options['lat'] = $location->lat;
1942                 $options['lon'] = $location->lon;
1943             }
1944
1945         } else if (!empty($lat) && !empty($lon)) {
1946             $options['lat'] = $lat;
1947             $options['lon'] = $lon;
1948
1949             $location = Location::fromLatLon($lat, $lon);
1950
1951             if (!empty($location)) {
1952                 $options['location_id'] = $location->location_id;
1953                 $options['location_ns'] = $location->location_ns;
1954             }
1955         } else if (!empty($profile)) {
1956             if (isset($profile->lat) && isset($profile->lon)) {
1957                 $options['lat'] = $profile->lat;
1958                 $options['lon'] = $profile->lon;
1959             }
1960
1961             if (isset($profile->location_id) && isset($profile->location_ns)) {
1962                 $options['location_id'] = $profile->location_id;
1963                 $options['location_ns'] = $profile->location_ns;
1964             }
1965         }
1966
1967         return $options;
1968     }
1969
1970     function clearReplies()
1971     {
1972         $replyNotice = new Notice();
1973         $replyNotice->reply_to = $this->id;
1974
1975         //Null any notices that are replies to this notice
1976
1977         if ($replyNotice->find()) {
1978             while ($replyNotice->fetch()) {
1979                 $orig = clone($replyNotice);
1980                 $replyNotice->reply_to = null;
1981                 $replyNotice->update($orig);
1982             }
1983         }
1984
1985         // Reply records
1986
1987         $reply = new Reply();
1988         $reply->notice_id = $this->id;
1989
1990         if ($reply->find()) {
1991             while($reply->fetch()) {
1992                 self::blow('reply:stream:%d', $reply->profile_id);
1993                 $reply->delete();
1994             }
1995         }
1996
1997         $reply->free();
1998     }
1999
2000     function clearRepeats()
2001     {
2002         $repeatNotice = new Notice();
2003         $repeatNotice->repeat_of = $this->id;
2004
2005         //Null any notices that are repeats of this notice
2006
2007         if ($repeatNotice->find()) {
2008             while ($repeatNotice->fetch()) {
2009                 $orig = clone($repeatNotice);
2010                 $repeatNotice->repeat_of = null;
2011                 $repeatNotice->update($orig);
2012             }
2013         }
2014     }
2015
2016     function clearFaves()
2017     {
2018         $fave = new Fave();
2019         $fave->notice_id = $this->id;
2020
2021         if ($fave->find()) {
2022             while ($fave->fetch()) {
2023                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2024                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2025                 self::blow('fave:ids_by_user:%d', $fave->user_id);
2026                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2027                 $fave->delete();
2028             }
2029         }
2030
2031         $fave->free();
2032     }
2033
2034     function clearTags()
2035     {
2036         $tag = new Notice_tag();
2037         $tag->notice_id = $this->id;
2038
2039         if ($tag->find()) {
2040             while ($tag->fetch()) {
2041                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
2042                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
2043                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
2044                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
2045                 $tag->delete();
2046             }
2047         }
2048
2049         $tag->free();
2050     }
2051
2052     function clearGroupInboxes()
2053     {
2054         $gi = new Group_inbox();
2055
2056         $gi->notice_id = $this->id;
2057
2058         if ($gi->find()) {
2059             while ($gi->fetch()) {
2060                 self::blow('user_group:notice_ids:%d', $gi->group_id);
2061                 $gi->delete();
2062             }
2063         }
2064
2065         $gi->free();
2066     }
2067
2068     function distribute()
2069     {
2070         // We always insert for the author so they don't
2071         // have to wait
2072         Event::handle('StartNoticeDistribute', array($this));
2073
2074         $user = User::staticGet('id', $this->profile_id);
2075         if (!empty($user)) {
2076             Inbox::insertNotice($user->id, $this->id);
2077         }
2078
2079         if (common_config('queue', 'inboxes')) {
2080             // If there's a failure, we want to _force_
2081             // distribution at this point.
2082             try {
2083                 $qm = QueueManager::get();
2084                 $qm->enqueue($this, 'distrib');
2085             } catch (Exception $e) {
2086                 // If the exception isn't transient, this
2087                 // may throw more exceptions as DQH does
2088                 // its own enqueueing. So, we ignore them!
2089                 try {
2090                     $handler = new DistribQueueHandler();
2091                     $handler->handle($this);
2092                 } catch (Exception $e) {
2093                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2094                 }
2095                 // Re-throw so somebody smarter can handle it.
2096                 throw $e;
2097             }
2098         } else {
2099             $handler = new DistribQueueHandler();
2100             $handler->handle($this);
2101         }
2102     }
2103
2104     function insert()
2105     {
2106         $result = parent::insert();
2107
2108         if ($result) {
2109             // Profile::hasRepeated() abuses pkeyGet(), so we
2110             // have to clear manually
2111             if (!empty($this->repeat_of)) {
2112                 $c = self::memcache();
2113                 if (!empty($c)) {
2114                     $ck = self::multicacheKey('Notice',
2115                                               array('profile_id' => $this->profile_id,
2116                                                     'repeat_of' => $this->repeat_of));
2117                     $c->delete($ck);
2118                 }
2119             }
2120         }
2121
2122         return $result;
2123     }
2124
2125     /**
2126      * Get the source of the notice
2127      *
2128      * @return Notice_source $ns A notice source object. 'code' is the only attribute
2129      *                           guaranteed to be populated.
2130      */
2131     function getSource()
2132     {
2133         $ns = new Notice_source();
2134         if (!empty($this->source)) {
2135             switch ($this->source) {
2136             case 'web':
2137             case 'xmpp':
2138             case 'mail':
2139             case 'omb':
2140             case 'system':
2141             case 'api':
2142                 $ns->code = $this->source;
2143                 break;
2144             default:
2145                 $ns = Notice_source::staticGet($this->source);
2146                 if (!$ns) {
2147                     $ns = new Notice_source();
2148                     $ns->code = $this->source;
2149                     $app = Oauth_application::staticGet('name', $this->source);
2150                     if ($app) {
2151                         $ns->name = $app->name;
2152                         $ns->url  = $app->source_url;
2153                     }
2154                 }
2155                 break;
2156             }
2157         }
2158         return $ns;
2159     }
2160
2161     /**
2162      * Determine whether the notice was locally created
2163      *
2164      * @return boolean locality
2165      */
2166
2167     public function isLocal()
2168     {
2169         return ($this->is_local == Notice::LOCAL_PUBLIC ||
2170                 $this->is_local == Notice::LOCAL_NONPUBLIC);
2171     }
2172
2173     public function getTags()
2174     {
2175         $tags = array();
2176         $tag = new Notice_tag();
2177         $tag->notice_id = $this->id;
2178         if ($tag->find()) {
2179             while ($tag->fetch()) {
2180                 $tags[] = $tag->tag;
2181             }
2182         }
2183         $tag->free();
2184         return $tags;
2185     }
2186
2187     static private function utcDate($dt)
2188     {
2189         $dateStr = date('d F Y H:i:s', strtotime($dt));
2190         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2191         return $d->format(DATE_W3C);
2192     }
2193 }