]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/scripts/update_ostatus_profiles.php
Loose_Ostatusprofile::updateAvatar was identical to Ostatus_profile
[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:a';
24 $longoptions = array('uri=', 'all');
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
36 UPDATE_OSTATUS_PROFILES;
37
38 require_once INSTALLDIR . '/scripts/commandline.inc';
39
40 /*
41  * Hacky class to remove some checks and get public access to
42  * protected mentods
43  */
44 class LooseOstatusProfile extends Ostatus_profile
45 {
46     /**
47      * Look up and if necessary create an Ostatus_profile for the remote entity
48      * with the given profile page URL. This should never return null -- you
49      * will either get an object or an exception will be thrown.
50      *
51      * @param string $profile_url
52      * @return Ostatus_profile
53      * @throws Exception on various error conditions
54      * @throws OStatusShadowException if this reference would obscure a local user/group
55      */
56     public static function updateProfileURL($profile_url, $hints=array())
57     {
58         $oprofile = null;
59
60         $hints['profileurl'] = $profile_url;
61
62         // Fetch the URL
63         // XXX: HTTP caching
64
65         $client = new HTTPClient();
66         $client->setHeader('Accept', 'text/html,application/xhtml+xml');
67         $response = $client->get($profile_url);
68
69         if (!$response->isOk()) {
70             // TRANS: Exception. %s is a profile URL.
71             throw new Exception(sprintf(_('Could not reach profile page %s.'),$profile_url));
72         }
73
74         // Check if we have a non-canonical URL
75
76         $finalUrl = $response->getUrl();
77
78         if ($finalUrl != $profile_url) {
79             $hints['profileurl'] = $finalUrl;
80         }
81
82         // Try to get some hCard data
83
84         $body = $response->getBody();
85
86         $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
87
88         if (!empty($hcardHints)) {
89             $hints = array_merge($hints, $hcardHints);
90         }
91
92         // Check if they've got an LRDD header
93
94         $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
95         try {
96             $xrd = new XML_XRD();
97             $xrd->loadFile($lrdd);
98             $xrdHints = DiscoveryHints::fromXRD($xrd);
99             $hints = array_merge($hints, $xrdHints);
100         } catch (Exception $e) {
101             // No hints available from XRD
102         }
103
104         // If discovery found a feedurl (probably from LRDD), use it.
105
106         if (array_key_exists('feedurl', $hints)) {
107             return self::ensureFeedURL($hints['feedurl'], $hints);
108         }
109
110         // Get the feed URL from HTML
111
112         $discover = new FeedDiscovery();
113
114         $feedurl = $discover->discoverFromHTML($finalUrl, $body);
115
116         if (!empty($feedurl)) {
117             $hints['feedurl'] = $feedurl;
118             return self::ensureFeedURL($feedurl, $hints);
119         }
120
121         // TRANS: Exception. %s is a URL.
122         throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
123     }
124
125     /**
126      * Look up, and if necessary create, an Ostatus_profile for the remote
127      * entity with the given webfinger address.
128      * This should never return null -- you will either get an object or
129      * an exception will be thrown.
130      *
131      * @param string $addr webfinger address
132      * @return Ostatus_profile
133      * @throws Exception on error conditions
134      * @throws OStatusShadowException if this reference would obscure a local user/group
135      */
136     public static function updateWebfinger($addr)
137     {
138         $disco = new Discovery();
139
140         try {
141             $xrd = $disco->lookup($addr);
142         } catch (Exception $e) {
143             // Save negative cache entry so we don't waste time looking it up again.
144             // @fixme distinguish temporary failures?
145             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
146             // TRANS: Exception.
147             throw new Exception(_m('Not a valid webfinger address.'));
148         }
149
150         $hints = array('webfinger' => $addr);
151
152         try {
153             $dHints = DiscoveryHints::fromXRD($xrd);
154             $hints = array_merge($hints, $xrdHints);
155         } catch (Exception $e) {
156             // No hints available from XRD
157         }
158
159         // If there's an Hcard, let's grab its info
160         if (array_key_exists('hcard', $hints)) {
161             if (!array_key_exists('profileurl', $hints) ||
162                 $hints['hcard'] != $hints['profileurl']) {
163                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
164                 $hints = array_merge($hcardHints, $hints);
165             }
166         }
167
168         // If we got a feed URL, try that
169         if (array_key_exists('feedurl', $hints)) {
170             try {
171                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
172                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
173                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
174                 return $oprofile;
175             } catch (Exception $e) {
176                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
177                 // keep looking
178             }
179         }
180
181         // If we got a profile page, try that!
182         if (array_key_exists('profileurl', $hints)) {
183             try {
184                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
185                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
186                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
187                 return $oprofile;
188             } catch (OStatusShadowException $e) {
189                 // We've ended up with a remote reference to a local user or group.
190                 // @fixme ideally we should be able to say who it was so we can
191                 // go back and refer to it the regular way
192                 throw $e;
193             } catch (Exception $e) {
194                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
195                 // keep looking
196                 //
197                 // @fixme this means an error discovering from profile page
198                 // may give us a corrupt entry using the webfinger URI, which
199                 // will obscure the correct page-keyed profile later on.
200             }
201         }
202         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
203     }
204 }
205
206 function pullOstatusProfile($uri) {
207
208     $oprofile = null;
209
210     if (Validate::email($uri)) {
211         $oprofile = LooseOstatusProfile::updateWebfinger($uri);
212     } else if (Validate::uri($uri)) {
213         $oprofile = LooseOstatusProfile::updateProfileURL($uri);
214     } else {
215         print "Sorry, we could not reach the address: $uri\n";
216         return false;
217     }
218
219    return $oprofile;
220 }
221
222 $quiet = have_option('q', 'quiet');
223
224 $lop = new LooseOstatusProfile();
225
226 if (have_option('u', 'uri')) {
227     $lop->uri = get_option_value('u', 'uri');
228 } else if (!have_option('a', 'all')) {
229     show_help();
230     exit(1);
231 }
232
233 $cnt = $lop->find();
234
235 if (!empty($cnt)) {
236     if (!$quiet) { echo "Found {$cnt} OStatus profiles:\n"; }
237 } else {
238     if (have_option('u', 'uri')) {
239         if (!$quiet) { echo "Couldn't find an existing OStatus profile with that URI.\n"; }
240     } else {
241         if (!$quiet) { echo "Couldn't find any existing OStatus profiles.\n"; }
242     }
243     exit(0);
244 }
245
246 while($lop->fetch()) {
247     if (!$quiet) { echo "Updating OStatus profile '{$lop->uri}' ... "; }
248     try {
249         $oprofile = pullOstatusProfile($lop->uri);
250
251         if (!empty($oprofile)) {
252             $orig = clone($lop);
253             $lop->avatar = $oprofile->avatar;
254             $lop->update($orig);
255             $lop->updateAvatar($oprofile->avatar);
256             if (!$quiet) { print "Done.\n"; }
257         }
258     } catch (Exception $e) {
259         if (!$quiet) { print $e->getMessage() . "\n"; }
260         common_log(LOG_WARNING, $e->getMessage(), __FILE__);
261         // continue on error
262     }
263 }
264
265 if (!$quiet) { echo "OK.\n"; }