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