]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/scripts/update_ostatus_profiles.php
Merge branch 'master' of gitorious.org:social/mainline into social-master
[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.php';
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(common_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 to %s.'), $url, $temp_filename));
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, array $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         try {
161             $xrd = new XML_XRD();
162             $xrd->loadFile($lrdd);
163             $xrdHints = DiscoveryHints::fromXRD($xrd);
164             $hints = array_merge($hints, $xrdHints);
165         } catch (Exception $e) {
166             // No hints available from XRD
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         try {
218             $dHints = DiscoveryHints::fromXRD($xrd);
219             $hints = array_merge($hints, $xrdHints);
220         } catch (Exception $e) {
221             // No hints available from XRD
222         }
223
224         // If there's an Hcard, let's grab its info
225         if (array_key_exists('hcard', $hints)) {
226             if (!array_key_exists('profileurl', $hints) ||
227                 $hints['hcard'] != $hints['profileurl']) {
228                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
229                 $hints = array_merge($hcardHints, $hints);
230             }
231         }
232
233         // If we got a feed URL, try that
234         if (array_key_exists('feedurl', $hints)) {
235             try {
236                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
237                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
238                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
239                 return $oprofile;
240             } catch (Exception $e) {
241                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
242                 // keep looking
243             }
244         }
245
246         // If we got a profile page, try that!
247         if (array_key_exists('profileurl', $hints)) {
248             try {
249                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
250                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
251                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
252                 return $oprofile;
253             } catch (OStatusShadowException $e) {
254                 // We've ended up with a remote reference to a local user or group.
255                 // @fixme ideally we should be able to say who it was so we can
256                 // go back and refer to it the regular way
257                 throw $e;
258             } catch (Exception $e) {
259                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
260                 // keep looking
261                 //
262                 // @fixme this means an error discovering from profile page
263                 // may give us a corrupt entry using the webfinger URI, which
264                 // will obscure the correct page-keyed profile later on.
265             }
266         }
267         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
268     }
269 }
270
271 function pullOstatusProfile($uri) {
272
273     $oprofile = null;
274
275     if (Validate::email($uri)) {
276         $oprofile = LooseOstatusProfile::updateWebfinger($uri);
277     } else if (Validate::uri($uri)) {
278         $oprofile = LooseOstatusProfile::updateProfileURL($uri);
279     } else {
280         print "Sorry, we could not reach the address: $uri\n";
281         return false;
282     }
283
284    return $oprofile;
285 }
286
287 $quiet = have_option('q', 'quiet');
288
289 $lop = new LooseOstatusProfile();
290
291 if (have_option('u', 'uri')) {
292     $lop->uri = get_option_value('u', 'uri');
293 } else if (!have_option('a', 'all')) {
294     show_help();
295     exit(1);
296 }
297
298 $cnt = $lop->find();
299
300 if (!empty($cnt)) {
301     if (!$quiet) { echo "Found {$cnt} OStatus profiles:\n"; }
302 } else {
303     if (have_option('u', 'uri')) {
304         if (!$quiet) { echo "Couldn't find an existing OStatus profile with that URI.\n"; }
305     } else {
306         if (!$quiet) { echo "Couldn't find any existing OStatus profiles.\n"; }
307     }
308     exit(0);
309 }
310
311 while($lop->fetch()) {
312     if (!$quiet) { echo "Updating OStatus profile '{$lop->uri}' ... "; }
313     try {
314         $oprofile = pullOstatusProfile($lop->uri);
315
316         if (!empty($oprofile)) {
317             $orig = clone($lop);
318             $lop->avatar = $oprofile->avatar;
319             $lop->update($orig);
320             $lop->updateAvatar($oprofile->avatar);
321             if (!$quiet) { print "Done.\n"; }
322         }
323     } catch (Exception $e) {
324         if (!$quiet) { print $e->getMessage() . "\n"; }
325         common_log(LOG_WARNING, $e->getMessage(), __FILE__);
326         // continue on error
327     }
328 }
329
330 if (!$quiet) { echo "OK.\n"; }