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