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