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