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