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