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