]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/scripts/update_ostatus_profiles.php
bca136bbbce3a27285b99276df20f8ecaf604ff2
[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      * Download and update given avatar image
48      *
49      * @param string $url
50      * @throws Exception in various failure cases
51      */
52     public function updateAvatar($url)
53     {
54         if (!common_valid_http_url($url)) {
55             // TRANS: Server exception. %s is a URL.
56             throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
57         }
58
59         if ($this->isGroup()) {
60             $self = $this->localGroup();
61         } else {
62             $self = $this->localProfile();
63         }
64         if (!$self) {
65             throw new ServerException(sprintf(
66                 // TRANS: Server exception. %s is a URI.
67                 _m('Tried to update avatar for unsaved remote profile %s.'),
68                 $this->uri));
69         }
70
71         // @fixme this should be better encapsulated
72         // ripped from oauthstore.php (for old OMB client)
73         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
74         try {
75             if (!copy($url, $temp_filename)) {
76                 // TRANS: Server exception. %s is a URL.
77                 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
78             }
79
80             if ($this->isGroup()) {
81                 $id = $this->group_id;
82             } else {
83                 $id = $this->profile_id;
84             }
85             // @fixme should we be using different ids?
86             $imagefile = new ImageFile($id, $temp_filename);
87             $filename = Avatar::filename($id,
88                                          image_type_to_extension($imagefile->type),
89                                          null,
90                                          common_timestamp());
91             rename($temp_filename, Avatar::path($filename));
92         } catch (Exception $e) {
93             unlink($temp_filename);
94             throw $e;
95         }
96         // @fixme hardcoded chmod is lame, but seems to be necessary to
97         // keep from accidentally saving images from command-line (queues)
98         // that can't be read from web server, which causes hard-to-notice
99         // problems later on:
100         //
101         // http://status.net/open-source/issues/2663
102         chmod(Avatar::path($filename), 0644);
103
104         $self->setOriginal($filename);
105
106         $orig = clone($this);
107         $this->avatar = $url;
108         $this->update($orig);
109     }
110
111     /**
112      * Look up and if necessary create an Ostatus_profile for the remote entity
113      * with the given profile page URL. This should never return null -- you
114      * will either get an object or an exception will be thrown.
115      *
116      * @param string $profile_url
117      * @return Ostatus_profile
118      * @throws Exception on various error conditions
119      * @throws OStatusShadowException if this reference would obscure a local user/group
120      */
121     public static function updateProfileURL($profile_url, $hints=array())
122     {
123         $oprofile = null;
124
125         $hints['profileurl'] = $profile_url;
126
127         // Fetch the URL
128         // XXX: HTTP caching
129
130         $client = new HTTPClient();
131         $client->setHeader('Accept', 'text/html,application/xhtml+xml');
132         $response = $client->get($profile_url);
133
134         if (!$response->isOk()) {
135             // TRANS: Exception. %s is a profile URL.
136             throw new Exception(sprintf(_('Could not reach profile page %s.'),$profile_url));
137         }
138
139         // Check if we have a non-canonical URL
140
141         $finalUrl = $response->getUrl();
142
143         if ($finalUrl != $profile_url) {
144             $hints['profileurl'] = $finalUrl;
145         }
146
147         // Try to get some hCard data
148
149         $body = $response->getBody();
150
151         $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
152
153         if (!empty($hcardHints)) {
154             $hints = array_merge($hints, $hcardHints);
155         }
156
157         // Check if they've got an LRDD header
158
159         $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
160
161         if (!empty($lrdd)) {
162
163             $xrd = Discovery::fetchXrd($lrdd);
164             $xrdHints = DiscoveryHints::fromXRD($xrd);
165
166             $hints = array_merge($hints, $xrdHints);
167         }
168
169         // If discovery found a feedurl (probably from LRDD), use it.
170
171         if (array_key_exists('feedurl', $hints)) {
172             return self::ensureFeedURL($hints['feedurl'], $hints);
173         }
174
175         // Get the feed URL from HTML
176
177         $discover = new FeedDiscovery();
178
179         $feedurl = $discover->discoverFromHTML($finalUrl, $body);
180
181         if (!empty($feedurl)) {
182             $hints['feedurl'] = $feedurl;
183             return self::ensureFeedURL($feedurl, $hints);
184         }
185
186         // TRANS: Exception. %s is a URL.
187         throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
188     }
189
190     /**
191      * Look up, and if necessary create, an Ostatus_profile for the remote
192      * entity with the given webfinger address.
193      * This should never return null -- you will either get an object or
194      * an exception will be thrown.
195      *
196      * @param string $addr webfinger address
197      * @return Ostatus_profile
198      * @throws Exception on error conditions
199      * @throws OStatusShadowException if this reference would obscure a local user/group
200      */
201     public static function updateWebfinger($addr)
202     {
203         $disco = new Discovery();
204
205         try {
206             $xrd = $disco->lookup($addr);
207         } catch (Exception $e) {
208             // Save negative cache entry so we don't waste time looking it up again.
209             // @fixme distinguish temporary failures?
210             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
211             // TRANS: Exception.
212             throw new Exception(_m('Not a valid webfinger address.'));
213         }
214
215         $hints = array('webfinger' => $addr);
216
217         $dhints = DiscoveryHints::fromXRD($xrd);
218
219         $hints = array_merge($hints, $dhints);
220
221         // If there's an Hcard, let's grab its info
222         if (array_key_exists('hcard', $hints)) {
223             if (!array_key_exists('profileurl', $hints) ||
224                 $hints['hcard'] != $hints['profileurl']) {
225                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
226                 $hints = array_merge($hcardHints, $hints);
227             }
228         }
229
230         // If we got a feed URL, try that
231         if (array_key_exists('feedurl', $hints)) {
232             try {
233                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
234                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
235                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
236                 return $oprofile;
237             } catch (Exception $e) {
238                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
239                 // keep looking
240             }
241         }
242
243         // If we got a profile page, try that!
244         if (array_key_exists('profileurl', $hints)) {
245             try {
246                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
247                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
248                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
249                 return $oprofile;
250             } catch (OStatusShadowException $e) {
251                 // We've ended up with a remote reference to a local user or group.
252                 // @fixme ideally we should be able to say who it was so we can
253                 // go back and refer to it the regular way
254                 throw $e;
255             } catch (Exception $e) {
256                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
257                 // keep looking
258                 //
259                 // @fixme this means an error discovering from profile page
260                 // may give us a corrupt entry using the webfinger URI, which
261                 // will obscure the correct page-keyed profile later on.
262             }
263         }
264         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
265     }
266 }
267
268 function pullOstatusProfile($uri) {
269
270     $oprofile = null;
271
272     if (Validate::email($uri)) {
273         $oprofile = LooseOstatusProfile::updateWebfinger($uri);
274     } else if (Validate::uri($uri)) {
275         $oprofile = LooseOstatusProfile::updateProfileURL($uri);
276     } else {
277         print "Sorry, we could not reach the address: $uri\n";
278         return false;
279     }
280
281    return $oprofile;
282 }
283
284 $quiet = have_option('q', 'quiet');
285
286 $lop = new LooseOstatusProfile();
287
288 if (have_option('u', 'uri')) {
289     $lop->uri = get_option_value('u', 'uri');
290 } else if (!have_option('a', 'all')) {
291     show_help();
292     exit(1);
293 }
294
295 $cnt = $lop->find();
296
297 if (!empty($cnt)) {
298     if (!$quiet) { echo "Found {$cnt} OStatus profiles:\n"; }
299 } else {
300     if (have_option('u', 'uri')) {
301         if (!$quiet) { echo "Couldn't find an existing OStatus profile with that URI.\n"; }
302     } else {
303         if (!$quiet) { echo "Couldn't find any existing OStatus profiles.\n"; }
304     }
305     exit(0);
306 }
307
308 while($lop->fetch()) {
309     if (!$quiet) { echo "Updating OStatus profile '{$lop->uri}' ... "; }
310     try {
311         $oprofile = pullOstatusProfile($lop->uri);
312
313         if (!empty($oprofile)) {
314             $orig = clone($lop);
315             $lop->avatar = $oprofile->avatar;
316             $lop->update($orig);
317             $lop->updateAvatar($oprofile->avatar);
318             if (!$quiet) { print "Done.\n"; }
319         }
320     } catch (Exception $e) {
321         if (!$quiet) { print $e->getMessage() . "\n"; }
322         common_log(LOG_WARN, $e->getMessage(), __FILE__);
323         // continue on error
324     }
325 }
326
327 if (!$quiet) { echo "OK.\n"; }