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