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