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