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