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