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