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