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