]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/YammerImport/lib/yammerimporter.php
1542b5909d63d48b5890bf54038e7906f340c746
[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(SNYammerClient $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::getKV('id', $profileId);
49         } else {
50             $user = User::getKV('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::getKV('id', $groupId);
86         } else {
87             $local = Local_group::getKV('nickname', $nickname);
88             if ($local) {
89                 common_log(LOG_WARN, "Copying Yammer group info onto existing group $nickname");
90                 $group = User_group::getKV('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::getKV('id', $noticeId);
134         } else {
135             $notice = Notice::getKV('uri', $data['options']['uri']);
136             $content = $data['content'];
137             $user = User::getKV($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::getKV('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             // TRANS: Exception thrown when a non-user item type is used, but expected.
184             throw new Exception(_m('Wrong item type sent to Yammer user import processing.'));
185         }
186
187         $origId = $item['id'];
188         $origUrl = $item['url'];
189
190         // @fixme check username rules?
191
192         $options['nickname'] = $item['name'];
193         $options['fullname'] = trim($item['full_name']);
194
195         // Avatar... this will be the "_small" variant.
196         // Remove that (pre-extension) suffix to get the orig-size image.
197         $avatar = $item['mugshot_url'];
198
199         // The following info is only available in full data, not in the reference version.
200
201         // There can be extensive contact info, but for now we'll only pull the primary email.
202         if (isset($item['contact'])) {
203             foreach ($item['contact']['email_addresses'] as $addr) {
204                 if ($addr['type'] == 'primary') {
205                     $options['email'] = $addr['address'];
206                     $options['email_confirmed'] = true;
207                     break;
208                 }
209             }
210         }
211
212         // There can be multiple external URLs; for now pull the first one as home page.
213         if (isset($item['external_urls'])) {
214             foreach ($item['external_urls'] as $url) {
215                 if (common_valid_http_url($url)) {
216                     $options['homepage'] = $url;
217                     break;
218                 }
219             }
220         }
221
222         // Combine a few bits into the bio...
223         $bio = array();
224         if (!empty($item['job_title'])) {
225             $bio[] = $item['job_title'];
226         }
227         if (!empty($item['summary'])) {
228             $bio[] = $item['summary'];
229         }
230         if (!empty($item['expertise'])) {
231             // TRANS: Used as a prefix for the Yammer expertise field contents.
232             $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
233         }
234         $options['bio'] = implode("\n\n", $bio);
235
236         // Pull raw location string, may be lookupable
237         if (!empty($item['location'])) {
238             $options['location'] = $item['location'];
239         }
240
241         // Timezone is in format like 'Pacific Time (US & Canada)'
242         // We need to convert that to a zone id. :P
243         // @fixme timezone not yet supported at registration time :)
244         if (!empty($item['timezone'])) {
245             $tz = $this->timezone($item['timezone']);
246             if ($tz) {
247                 $options['timezone'] = $tz;
248             }
249         }
250
251         return array('orig_id' => $origId,
252                      'orig_url' => $origUrl,
253                      'avatar' => $avatar,
254                      'options' => $options);
255
256     }
257
258     /**
259      * Pull relevant info out of a Yammer data record for a group import.
260      *
261      * @param array $item
262      * @return array
263      */
264     function prepGroup($item)
265     {
266         if ($item['type'] != 'group') {
267             // TRANS: Exception thrown when a non-group item type is used, but expected.
268             throw new Exception(_m('Wrong item type sent to Yammer group import processing.'));
269         }
270
271         $origId = $item['id'];
272         $origUrl = $item['url'];
273
274         $privacy = $item['privacy']; // Warning! only public groups in SN so far
275
276         $options['nickname'] = $item['name'];
277         $options['fullname'] = $item['full_name'];
278         $options['description'] = $item['description'];
279         $options['created'] = $this->timestamp($item['created_at']);
280
281         $avatar = $item['mugshot_url']; // as with user profiles...
282
283         $options['mainpage'] = common_local_url('showgroup',
284                                    array('nickname' => $options['nickname']));
285
286         // Set some default vals or User_group::register will whine
287         $options['homepage'] = '';
288         $options['location'] = '';
289         $options['aliases'] = array();
290         // @todo FIXME: What about admin user for the group?
291
292         $options['local'] = true;
293         return array('orig_id' => $origId,
294                      'orig_url' => $origUrl,
295                      'options' => $options,
296                      'avatar' => $avatar);
297     }
298
299     /**
300      * Pull relevant info out of a Yammer data record for a notice import.
301      *
302      * @param array $item
303      * @return array
304      */
305     function prepNotice($item)
306     {
307         if (isset($item['type']) && $item['type'] != 'message') {
308             // TRANS: Exception thrown when a non-message item type is used, but expected.
309             throw new Exception(_m('Wrong item type sent to Yammer message import processing.'));
310         }
311
312         $origId = $item['id'];
313         $origUrl = $item['url'];
314
315         $profile = $this->findImportedUser($item['sender_id']);
316         $content = $item['body']['plain'];
317         $source = 'yammer';
318         $options = array();
319
320         if ($item['replied_to_id']) {
321             $replyTo = $this->findImportedNotice($item['replied_to_id']);
322             if ($replyTo) {
323                 $options['reply_to'] = $replyTo;
324             }
325         }
326         $options['created'] = $this->timestamp($item['created_at']);
327
328         if (!empty($item['group_id'])) {
329             $groupId = $this->findImportedGroup($item['group_id']);
330             if ($groupId) {
331                 $options['groups'] = array($groupId);
332
333                 // @fixme if we see a group link inline, don't add this?
334                 $group = User_group::getKV('id', $groupId);
335                 if ($group) {
336                     $content .= ' !' . $group->nickname;
337                 }
338             }
339         }
340
341         $faves = array();
342         foreach ($item['liked_by']['names'] as $liker) {
343             // "permalink" is the username. wtf?
344             $faves[] = $liker['permalink'];
345         }
346
347         $attachments = array();
348         foreach ($item['attachments'] as $attach) {
349             if ($attach['type'] == 'image' || $attach['type'] == 'file') {
350                 $attachments[] = $attach[$attach['type']]['url'];
351             } else {
352                 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
353             }
354         }
355
356         return array('orig_id' => $origId,
357                      'orig_url' => $origUrl,
358                      'profile' => $profile,
359                      'content' => $content,
360                      'source' => $source,
361                      'options' => $options,
362                      'faves' => $faves,
363                      'attachments' => $attachments);
364     }
365
366     private function findImportedUser($origId)
367     {
368         $map = Yammer_user::getKV('id', $origId);
369         return $map ? $map->user_id : null;
370     }
371
372     private function findImportedGroup($origId)
373     {
374         $map = Yammer_group::getKV('id', $origId);
375         return $map ? $map->group_id : null;
376     }
377
378     private function findImportedNotice($origId)
379     {
380         $map = Yammer_notice::getKV('id', $origId);
381         return $map ? $map->notice_id : null;
382     }
383
384     private function recordImportedUser($origId, $userId)
385     {
386         Yammer_user::record($origId, $userId);
387     }
388
389     private function recordImportedGroup($origId, $groupId)
390     {
391         Yammer_group::record($origId, $groupId);
392     }
393
394     private function recordImportedNotice($origId, $noticeId)
395     {
396         Yammer_notice::record($origId, $noticeId);
397     }
398
399     /**
400      * Normalize timestamp format.
401      * @param string $ts
402      * @return string
403      */
404     private function timestamp($ts)
405     {
406         return common_sql_date(strtotime($ts));
407     }
408
409     private function timezone($tz)
410     {
411         // Blaaaaaarf!
412         $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
413                        'Eastern Time (US & Canada)' => 'America/New_York');
414         if (array_key_exists($tz, $known)) {
415             return $known[$tz];
416         } else {
417             return false;
418         }
419     }
420
421     /**
422      * Download and update given avatar image
423      *
424      * @param string $url
425      * @param mixed $dest either a Profile or User_group object
426      * @throws Exception in various failure cases
427      */
428     private function saveAvatar($url, $dest)
429     {
430         // Yammer API data mostly gives us the small variant.
431         // Try hitting the source image if we can!
432         // @fixme no guarantee of this URL scheme I think.
433         $url = preg_replace('/_small(\..*?)$/', '$1', $url);
434
435         if (!common_valid_http_url($url)) {
436             // TRANS: Server exception thrown when an avatar URL is invalid.
437             // TRANS: %s is the invalid avatar URL.
438             throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
439         }
440
441         // @fixme this should be better encapsulated
442         // ripped from oauthstore.php (for old OMB client)
443         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
444         try {
445             if (!copy($url, $temp_filename)) {
446                 // TRANS: Server exception thrown when an avatar could not be fetched.
447                 // TRANS: %s is the failed avatar URL.
448                 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
449             }
450
451             $id = $dest->id;
452             // @fixme should we be using different ids?
453             $imagefile = new ImageFile($id, $temp_filename);
454             $filename = Avatar::filename($id,
455                                          image_type_to_extension($imagefile->type),
456                                          null,
457                                          common_timestamp());
458             rename($temp_filename, Avatar::path($filename));
459         } catch (Exception $e) {
460             unlink($temp_filename);
461             throw $e;
462         }
463         // @fixme hardcoded chmod is lame, but seems to be necessary to
464         // keep from accidentally saving images from command-line (queues)
465         // that can't be read from web server, which causes hard-to-notice
466         // problems later on:
467         //
468         // http://status.net/open-source/issues/2663
469         chmod(Avatar::path($filename), 0644);
470
471         $dest->setOriginal($filename);
472     }
473
474     /**
475      * Fetch an attachment from Yammer and save it into our system.
476      * Unlike avatars, the attachment URLs are guarded by authentication,
477      * so we need to run the HTTP hit through our OAuth API client.
478      *
479      * @param string $url
480      * @param User $user
481      * @return MediaFile
482      *
483      * @throws Exception on low-level network or HTTP error
484      */
485     private function saveAttachment($url, User $user)
486     {
487         // Fetch the attachment...
488         // WARNING: file must fit in memory here :(
489         $body = $this->client->fetchUrl($url);
490
491         // Save to a temporary file and shove it into our file-attachment space...
492         $temp = tmpfile();
493         fwrite($temp, $body);
494         try {
495             $upload = MediaFile::fromFileHandle($temp, $user);
496             fclose($temp);
497             return $upload;
498         } catch (Exception $e) {
499             fclose($temp);
500             throw $e;
501         }
502     }
503 }