]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/YammerImport/lib/yammerimporter.php
Clean up remote avatar temporary files if we fail before saving them into avatars...
[quix0rs-gnu-social.git] / plugins / YammerImport / lib / yammerimporter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, 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
20 /**
21  * Basic client class for Yammer's OAuth/JSON API.
22  *
23  * @package YammerImportPlugin
24  * @author Brion Vibber <brion@status.net>
25  */
26 class YammerImporter
27 {
28     protected $client;
29
30     function __construct(SN_YammerClient $client)
31     {
32         $this->client = $client;
33     }
34
35     /**
36      * Load or create an imported profile from Yammer data.
37      * 
38      * @param object $item loaded JSON data for Yammer importer
39      * @return Profile
40      */
41     function importUser($item)
42     {
43         $data = $this->prepUser($item);
44         $nickname = $data['options']['nickname'];
45
46         $profileId = $this->findImportedUser($data['orig_id']);
47         if ($profileId) {
48             return Profile::staticGet('id', $profileId);
49         } else {
50             $user = User::staticGet('nickname', $nickname);
51             if ($user) {
52                 common_log(LOG_WARN, "Copying Yammer profile info onto existing user $nickname");
53                 $profile = $user->getProfile();
54                 $this->savePropertiesOn($profile, $data['options'],
55                         array('fullname', 'homepage', 'bio', 'location'));
56             } else {
57                 $user = User::register($data['options']);
58                 $profile = $user->getProfile();
59             }
60             if ($data['avatar']) {
61                 try {
62                     $this->saveAvatar($data['avatar'], $profile);
63                 } catch (Exception $e) {
64                     common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
65                 }
66             }
67             $this->recordImportedUser($data['orig_id'], $profile->id);
68             return $profile;
69         }
70     }
71
72     /**
73      * Load or create an imported group from Yammer data.
74      *
75      * @param object $item loaded JSON data for Yammer importer
76      * @return User_group
77      */
78     function importGroup($item)
79     {
80         $data = $this->prepGroup($item);
81         $nickname = $data['options']['nickname'];
82
83         $groupId = $this->findImportedGroup($data['orig_id']);
84         if ($groupId) {
85             return User_group::staticGet('id', $groupId);
86         } else {
87             $local = Local_group::staticGet('nickname', $nickname);
88             if ($local) {
89                 common_log(LOG_WARN, "Copying Yammer group info onto existing group $nickname");
90                 $group = User_group::staticGet('id', $local->group_id);
91                 $this->savePropertiesOn($group, $data['options'],
92                         array('fullname', 'description'));
93             } else {
94                 $group = User_group::register($data['options']);
95             }
96             if ($data['avatar']) {
97                 try {
98                     $this->saveAvatar($data['avatar'], $group);
99                 } catch (Exception $e) {
100                     common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
101                 }
102             }
103             $this->recordImportedGroup($data['orig_id'], $group->id);
104             return $group;
105         }
106     }
107
108     private function savePropertiesOn($target, $options, $propList)
109     {
110         $changed = 0;
111         $orig = clone($target);
112         foreach ($propList as $prop) {
113             if (!empty($options[$prop]) && $target->$prop != $options[$prop]) {
114                 $target->$prop = $options[$prop];
115                 $changed++;
116             }
117         }
118         $target->update($orig);
119     }
120
121     /**
122      * Load or create an imported notice from Yammer data.
123      *
124      * @param object $item loaded JSON data for Yammer importer
125      * @return Notice
126      */
127     function importNotice($item)
128     {
129         $data = $this->prepNotice($item);
130
131         $noticeId = $this->findImportedNotice($data['orig_id']);
132         if ($noticeId) {
133             return Notice::staticGet('id', $noticeId);
134         } else {
135             $notice = Notice::staticGet('uri', $data['options']['uri']);
136             $content = $data['content'];
137             $user = User::staticGet($data['profile']);
138
139             // Fetch file attachments and add the URLs...
140             $uploads = array();
141             foreach ($data['attachments'] as $url) {
142                 try {
143                     $upload = $this->saveAttachment($url, $user);
144                     $content .= ' ' . $upload->shortUrl();
145                     $uploads[] = $upload;
146                 } catch (Exception $e) {
147                     common_log(LOG_ERR, "Error importing Yammer attachment: " . $e->getMessage());
148                 }
149             }
150
151             // Here's the meat! Actually save the dang ol' notice.
152             $notice = Notice::saveNew($user->id,
153                                       $content,
154                                       $data['source'],
155                                       $data['options']);
156
157             // Save "likes" as favorites...
158             foreach ($data['faves'] as $nickname) {
159                 $user = User::staticGet('nickname', $nickname);
160                 if ($user) {
161                     Fave::addNew($user->getProfile(), $notice);
162                 }
163             }
164
165             // And finally attach the upload records...
166             foreach ($uploads as $upload) {
167                 $upload->attachToNotice($notice);
168             }
169             $this->recordImportedNotice($data['orig_id'], $notice->id);
170             return $notice;
171         }
172     }
173
174     /**
175      * Pull relevant info out of a Yammer data record for a user import.
176      *
177      * @param array $item
178      * @return array
179      */
180     function prepUser($item)
181     {
182         if ($item['type'] != 'user') {
183             throw new Exception('Wrong item type sent to Yammer user import processing.');
184         }
185
186         $origId = $item['id'];
187         $origUrl = $item['url'];
188
189         // @fixme check username rules?
190
191         $options['nickname'] = $item['name'];
192         $options['fullname'] = trim($item['full_name']);
193
194         // Avatar... this will be the "_small" variant.
195         // Remove that (pre-extension) suffix to get the orig-size image.
196         $avatar = $item['mugshot_url'];
197
198         // The following info is only available in full data, not in the reference version.
199
200         // There can be extensive contact info, but for now we'll only pull the primary email.
201         if (isset($item['contact'])) {
202             foreach ($item['contact']['email_addresses'] as $addr) {
203                 if ($addr['type'] == 'primary') {
204                     $options['email'] = $addr['address'];
205                     $options['email_confirmed'] = true;
206                     break;
207                 }
208             }
209         }
210
211         // There can be multiple external URLs; for now pull the first one as home page.
212         if (isset($item['external_urls'])) {
213             foreach ($item['external_urls'] as $url) {
214                 if (common_valid_http_url($url)) {
215                     $options['homepage'] = $url;
216                     break;
217                 }
218             }
219         }
220
221         // Combine a few bits into the bio...
222         $bio = array();
223         if (!empty($item['job_title'])) {
224             $bio[] = $item['job_title'];
225         }
226         if (!empty($item['summary'])) {
227             $bio[] = $item['summary'];
228         }
229         if (!empty($item['expertise'])) {
230             $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
231         }
232         $options['bio'] = implode("\n\n", $bio);
233
234         // Pull raw location string, may be lookupable
235         if (!empty($item['location'])) {
236             $options['location'] = $item['location'];
237         }
238
239         // Timezone is in format like 'Pacific Time (US & Canada)'
240         // We need to convert that to a zone id. :P
241         // @fixme timezone not yet supported at registration time :)
242         if (!empty($item['timezone'])) {
243             $tz = $this->timezone($item['timezone']);
244             if ($tz) {
245                 $options['timezone'] = $tz;
246             }
247         }
248
249         return array('orig_id' => $origId,
250                      'orig_url' => $origUrl,
251                      'avatar' => $avatar,
252                      'options' => $options);
253
254     }
255
256     /**
257      * Pull relevant info out of a Yammer data record for a group import.
258      *
259      * @param array $item
260      * @return array
261      */
262     function prepGroup($item)
263     {
264         if ($item['type'] != 'group') {
265             throw new Exception('Wrong item type sent to Yammer group import processing.');
266         }
267
268         $origId = $item['id'];
269         $origUrl = $item['url'];
270
271         $privacy = $item['privacy']; // Warning! only public groups in SN so far
272
273         $options['nickname'] = $item['name'];
274         $options['fullname'] = $item['full_name'];
275         $options['description'] = $item['description'];
276         $options['created'] = $this->timestamp($item['created_at']);
277
278         $avatar = $item['mugshot_url']; // as with user profiles...
279
280
281         $options['mainpage'] = common_local_url('showgroup',
282                                    array('nickname' => $options['nickname']));
283
284         // Set some default vals or User_group::register will whine
285         $options['homepage'] = '';
286         $options['location'] = '';
287         $options['aliases'] = array();
288         // @fixme what about admin user for the group?
289
290         $options['local'] = true;
291         return array('orig_id' => $origId,
292                      'orig_url' => $origUrl,
293                      'options' => $options,
294                      'avatar' => $avatar);
295     }
296
297     /**
298      * Pull relevant info out of a Yammer data record for a notice import.
299      *
300      * @param array $item
301      * @return array
302      */
303     function prepNotice($item)
304     {
305         if (isset($item['type']) && $item['type'] != 'message') {
306             throw new Exception('Wrong item type sent to Yammer message import processing.');
307         }
308
309         $origId = $item['id'];
310         $origUrl = $item['url'];
311
312         $profile = $this->findImportedUser($item['sender_id']);
313         $content = $item['body']['plain'];
314         $source = 'yammer';
315         $options = array();
316
317         if ($item['replied_to_id']) {
318             $replyTo = $this->findImportedNotice($item['replied_to_id']);
319             if ($replyTo) {
320                 $options['reply_to'] = $replyTo;
321             }
322         }
323         $options['created'] = $this->timestamp($item['created_at']);
324
325         if (!empty($item['group_id'])) {
326             $groupId = $this->findImportedGroup($item['group_id']);
327             if ($groupId) {
328                 $options['groups'] = array($groupId);
329
330                 // @fixme if we see a group link inline, don't add this?
331                 $group = User_group::staticGet('id', $groupId);
332                 if ($group) {
333                     $content .= ' !' . $group->nickname;
334                 }
335             }
336         }
337
338         $faves = array();
339         foreach ($item['liked_by']['names'] as $liker) {
340             // "permalink" is the username. wtf?
341             $faves[] = $liker['permalink'];
342         }
343
344         $attachments = array();
345         foreach ($item['attachments'] as $attach) {
346             if ($attach['type'] == 'image' || $attach['type'] == 'file') {
347                 $attachments[] = $attach[$attach['type']]['url'];
348             } else {
349                 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
350             }
351         }
352
353         return array('orig_id' => $origId,
354                      'orig_url' => $origUrl,
355                      'profile' => $profile,
356                      'content' => $content,
357                      'source' => $source,
358                      'options' => $options,
359                      'faves' => $faves,
360                      'attachments' => $attachments);
361     }
362
363     private function findImportedUser($origId)
364     {
365         $map = Yammer_user::staticGet('id', $origId);
366         return $map ? $map->user_id : null;
367     }
368
369     private function findImportedGroup($origId)
370     {
371         $map = Yammer_group::staticGet('id', $origId);
372         return $map ? $map->group_id : null;
373     }
374
375     private function findImportedNotice($origId)
376     {
377         $map = Yammer_notice::staticGet('id', $origId);
378         return $map ? $map->notice_id : null;
379     }
380
381     private function recordImportedUser($origId, $userId)
382     {
383         Yammer_user::record($origId, $userId);
384     }
385
386     private function recordImportedGroup($origId, $groupId)
387     {
388         Yammer_group::record($origId, $groupId);
389     }
390
391     private function recordImportedNotice($origId, $noticeId)
392     {
393         Yammer_notice::record($origId, $noticeId);
394     }
395
396     /**
397      * Normalize timestamp format.
398      * @param string $ts
399      * @return string
400      */
401     private function timestamp($ts)
402     {
403         return common_sql_date(strtotime($ts));
404     }
405
406     private function timezone($tz)
407     {
408         // Blaaaaaarf!
409         $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
410                        'Eastern Time (US & Canada)' => 'America/New_York');
411         if (array_key_exists($tz, $known)) {
412             return $known[$tz];
413         } else {
414             return false;
415         }
416     }
417
418     /**
419      * Download and update given avatar image
420      *
421      * @param string $url
422      * @param mixed $dest either a Profile or User_group object
423      * @throws Exception in various failure cases
424      */
425     private function saveAvatar($url, $dest)
426     {
427         // Yammer API data mostly gives us the small variant.
428         // Try hitting the source image if we can!
429         // @fixme no guarantee of this URL scheme I think.
430         $url = preg_replace('/_small(\..*?)$/', '$1', $url);
431
432         if (!common_valid_http_url($url)) {
433             throw new ServerException(sprintf(_m("Invalid avatar URL %s."), $url));
434         }
435
436         // @fixme this should be better encapsulated
437         // ripped from oauthstore.php (for old OMB client)
438         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
439         try {
440             if (!copy($url, $temp_filename)) {
441                 throw new ServerException(sprintf(_m("Unable to fetch avatar from %s."), $url));
442             }
443
444             $id = $dest->id;
445             // @fixme should we be using different ids?
446             $imagefile = new ImageFile($id, $temp_filename);
447             $filename = Avatar::filename($id,
448                                          image_type_to_extension($imagefile->type),
449                                          null,
450                                          common_timestamp());
451             rename($temp_filename, Avatar::path($filename));
452         } catch (Exception $e) {
453             unlink($temp_filename);
454             throw $e;
455         }
456         // @fixme hardcoded chmod is lame, but seems to be necessary to
457         // keep from accidentally saving images from command-line (queues)
458         // that can't be read from web server, which causes hard-to-notice
459         // problems later on:
460         //
461         // http://status.net/open-source/issues/2663
462         chmod(Avatar::path($filename), 0644);
463
464         $dest->setOriginal($filename);
465     }
466
467     /**
468      * Fetch an attachment from Yammer and save it into our system.
469      * Unlike avatars, the attachment URLs are guarded by authentication,
470      * so we need to run the HTTP hit through our OAuth API client.
471      *
472      * @param string $url
473      * @param User $user
474      * @return MediaFile
475      *
476      * @throws Exception on low-level network or HTTP error
477      */
478     private function saveAttachment($url, User $user)
479     {
480         // Fetch the attachment...
481         // WARNING: file must fit in memory here :(
482         $body = $this->client->fetchUrl($url);
483
484         // Save to a temporary file and shove it into our file-attachment space...
485         $temp = tmpfile();
486         fwrite($temp, $body);
487         try {
488             $upload = MediaFile::fromFileHandle($temp, $user);
489             fclose($temp);
490             return $upload;
491         } catch (Exception $e) {
492             fclose($temp);
493             throw $e;
494         }
495     }
496 }