]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/scripts/update_ostatus_profiles.php
XSS vulnerability when remote-subscribing
[quix0rs-gnu-social.git] / plugins / OStatus / scripts / update_ostatus_profiles.php
1 #!/usr/bin/env php
2 <?php
3 /*
4  * StatusNet - a distributed open-source microblogging tool
5  * Copyright (C) 2011, StatusNet, Inc.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
22
23 $shortoptions = 'u:af';
24 $longoptions = array('uri=', 'all', 'force');
25
26 $helptext = <<<UPDATE_OSTATUS_PROFILES
27 update_ostatus_profiles.php [options]
28 Refetch / update OStatus profile info and avatars. Useful if you
29 do something like accidentally delete your avatars directory when
30 you have no backup.
31
32     -u --uri OStatus profile URI to update
33     -a --all update all
34
35     -f --force  Force update (despite identical avatar URLs etc.)
36
37 UPDATE_OSTATUS_PROFILES;
38
39 require_once INSTALLDIR . '/scripts/commandline.inc';
40
41 /*
42  * Hacky class to remove some checks and get public access to
43  * protected mentods
44  */
45 class LooseOstatusProfile extends Ostatus_profile
46 {
47     /**
48      * Look up and if necessary create an Ostatus_profile for the remote entity
49      * with the given profile page URL. This should never return null -- you
50      * will either get an object or an exception will be thrown.
51      *
52      * @param string $profile_url
53      * @return Ostatus_profile
54      * @throws Exception on various error conditions
55      * @throws OStatusShadowException if this reference would obscure a local user/group
56      */
57     public static function updateProfileURL($profile_url, $hints=array())
58     {
59         $oprofile = null;
60
61         $hints['profileurl'] = $profile_url;
62
63         // Fetch the URL
64         // XXX: HTTP caching
65
66         $client = new HTTPClient();
67         $client->setHeader('Accept', 'text/html,application/xhtml+xml');
68         $response = $client->get($profile_url);
69
70         if (!$response->isOk()) {
71             // TRANS: Exception. %s is a profile URL.
72             throw new Exception(sprintf(_('Could not reach profile page %s.'),$profile_url));
73         }
74
75         // Check if we have a non-canonical URL
76
77         $finalUrl = $response->getUrl();
78
79         if ($finalUrl != $profile_url) {
80             $hints['profileurl'] = $finalUrl;
81         }
82
83         // Try to get some hCard data
84
85         $body = $response->getBody();
86
87         $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
88
89         if (!empty($hcardHints)) {
90             $hints = array_merge($hints, $hcardHints);
91         }
92
93         // Check if they've got an LRDD header
94
95         $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
96         try {
97             $xrd = new XML_XRD();
98             $xrd->loadFile($lrdd);
99             $xrdHints = DiscoveryHints::fromXRD($xrd);
100             $hints = array_merge($hints, $xrdHints);
101         } catch (Exception $e) {
102             // No hints available from XRD
103         }
104
105         // If discovery found a feedurl (probably from LRDD), use it.
106
107         if (array_key_exists('feedurl', $hints)) {
108             return self::ensureFeedURL($hints['feedurl'], $hints);
109         }
110
111         // Get the feed URL from HTML
112
113         $discover = new FeedDiscovery();
114
115         $feedurl = $discover->discoverFromHTML($finalUrl, $body);
116
117         if (!empty($feedurl)) {
118             $hints['feedurl'] = $feedurl;
119             return self::ensureFeedURL($feedurl, $hints);
120         }
121
122         // TRANS: Exception. %s is a URL.
123         throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
124     }
125
126     /**
127      * Look up, and if necessary create, an Ostatus_profile for the remote
128      * entity with the given webfinger address.
129      * This should never return null -- you will either get an object or
130      * an exception will be thrown.
131      *
132      * @param string $addr webfinger address
133      * @return Ostatus_profile
134      * @throws Exception on error conditions
135      * @throws OStatusShadowException if this reference would obscure a local user/group
136      */
137     public static function updateWebfinger($addr)
138     {
139         $disco = new Discovery();
140
141         try {
142             $xrd = $disco->lookup($addr);
143         } catch (Exception $e) {
144             // Save negative cache entry so we don't waste time looking it up again.
145             // @fixme distinguish temporary failures?
146             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
147             // TRANS: Exception.
148             throw new Exception(_m('Not a valid webfinger address.'));
149         }
150
151         $hints = array('webfinger' => $addr);
152
153         try {
154             $dHints = DiscoveryHints::fromXRD($xrd);
155             $hints = array_merge($hints, $xrdHints);
156         } catch (Exception $e) {
157             // No hints available from XRD
158         }
159
160         // If there's an Hcard, let's grab its info
161         if (array_key_exists('hcard', $hints)) {
162             if (!array_key_exists('profileurl', $hints) ||
163                 $hints['hcard'] != $hints['profileurl']) {
164                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
165                 $hints = array_merge($hcardHints, $hints);
166             }
167         }
168
169         // If we got a feed URL, try that
170         if (array_key_exists('feedurl', $hints)) {
171             try {
172                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
173                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
174                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
175                 return $oprofile;
176             } catch (Exception $e) {
177                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
178                 // keep looking
179             }
180         }
181
182         // If we got a profile page, try that!
183         if (array_key_exists('profileurl', $hints)) {
184             try {
185                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
186                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
187                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
188                 return $oprofile;
189             } catch (OStatusShadowException $e) {
190                 // We've ended up with a remote reference to a local user or group.
191                 // @fixme ideally we should be able to say who it was so we can
192                 // go back and refer to it the regular way
193                 throw $e;
194             } catch (Exception $e) {
195                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
196                 // keep looking
197                 //
198                 // @fixme this means an error discovering from profile page
199                 // may give us a corrupt entry using the webfinger URI, which
200                 // will obscure the correct page-keyed profile later on.
201             }
202         }
203         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
204     }
205 }
206
207 function pullOstatusProfile($uri) {
208
209     $oprofile = null;
210     $validate = new Validate();
211
212     if ($validate->email($uri)) {
213         $oprofile = LooseOstatusProfile::updateWebfinger($uri);
214     } else if ($validate->uri($uri)) {
215         $oprofile = LooseOstatusProfile::updateProfileURL($uri);
216     } else {
217         print "Sorry, we could not reach the address: $uri\n";
218         return false;
219     }
220
221    return $oprofile;
222 }
223
224 $quiet = have_option('q', 'quiet');
225
226 $lop = new LooseOstatusProfile();
227
228 if (have_option('u', 'uri')) {
229     $lop->uri = get_option_value('u', 'uri');
230 } else if (!have_option('a', 'all')) {
231     show_help();
232     exit(1);
233 }
234
235 $forceUpdates = have_option('f', 'force');
236
237 $cnt = $lop->find();
238
239 if (!empty($cnt)) {
240     if (!$quiet) { echo "Found {$cnt} OStatus profiles:\n"; }
241 } else {
242     if (have_option('u', 'uri')) {
243         if (!$quiet) { echo "Couldn't find an existing OStatus profile with that URI.\n"; }
244     } else {
245         if (!$quiet) { echo "Couldn't find any existing OStatus profiles.\n"; }
246     }
247     exit(0);
248 }
249
250 while($lop->fetch()) {
251     if (!$quiet) { echo "Updating OStatus profile '{$lop->uri}' ... "; }
252     try {
253         $oprofile = pullOstatusProfile($lop->uri);
254
255         if (!empty($oprofile)) {
256             $orig = clone($lop);
257             $lop->avatar = $oprofile->avatar;
258             $lop->update($orig);
259             $lop->updateAvatar($oprofile->avatar, $forceUpdates);
260             if (!$quiet) { print "Done.\n"; }
261         }
262     } catch (Exception $e) {
263         if (!$quiet) { print $e->getMessage() . "\n"; }
264         common_log(LOG_WARNING, $e->getMessage(), __FILE__);
265         // continue on error
266     }
267 }
268
269 if (!$quiet) { echo "OK.\n"; }