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