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