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