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