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