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