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