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