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