3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
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.
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.
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/>.
21 * Basic client class for Yammer's OAuth/JSON API.
23 * Depends on Favorite plugin
25 * @package YammerImportPlugin
26 * @author Brion Vibber <brion@status.net>
32 function __construct(SNYammerClient $client)
34 $this->client = $client;
38 * Load or create an imported profile from Yammer data.
40 * @param object $item loaded JSON data for Yammer importer
43 function importUser($item)
45 $data = $this->prepUser($item);
46 $nickname = $data['options']['nickname'];
48 $profileId = $this->findImportedUser($data['orig_id']);
50 return Profile::getKV('id', $profileId);
52 $user = User::getKV('nickname', $nickname);
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'));
59 $user = User::register($data['options']);
60 $profile = $user->getProfile();
62 if ($data['avatar']) {
64 $this->saveAvatar($data['avatar'], $profile);
65 } catch (Exception $e) {
66 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
69 $this->recordImportedUser($data['orig_id'], $profile->id);
75 * Load or create an imported group from Yammer data.
77 * @param object $item loaded JSON data for Yammer importer
80 function importGroup($item)
82 $data = $this->prepGroup($item);
83 $nickname = $data['options']['nickname'];
85 $groupId = $this->findImportedGroup($data['orig_id']);
87 return User_group::getKV('id', $groupId);
89 $local = Local_group::getKV('nickname', $nickname);
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'));
96 $group = User_group::register($data['options']);
98 if ($data['avatar']) {
100 $this->saveAvatar($data['avatar'], $group);
101 } catch (Exception $e) {
102 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
105 $this->recordImportedGroup($data['orig_id'], $group->id);
110 private function savePropertiesOn($target, $options, $propList)
113 $orig = clone($target);
114 foreach ($propList as $prop) {
115 if (!empty($options[$prop]) && $target->$prop != $options[$prop]) {
116 $target->$prop = $options[$prop];
120 $target->update($orig);
124 * Load or create an imported notice from Yammer data.
126 * @param object $item loaded JSON data for Yammer importer
129 function importNotice($item)
131 $data = $this->prepNotice($item);
133 $noticeId = $this->findImportedNotice($data['orig_id']);
135 return Notice::getKV('id', $noticeId);
137 $notice = Notice::getKV('uri', $data['options']['uri']);
138 $content = $data['content'];
139 $user = User::getKV($data['profile']);
141 // Fetch file attachments and add the URLs...
143 foreach ($data['attachments'] as $url) {
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());
153 // Here's the meat! Actually save the dang ol' notice.
154 $notice = Notice::saveNew($user->id,
159 // Save "likes" as favorites...
160 foreach ($data['faves'] as $nickname) {
161 $user = User::getKV('nickname', $nickname);
163 Fave::addNew($user->getProfile(), $notice);
167 // And finally attach the upload records...
168 foreach ($uploads as $upload) {
169 $upload->attachToNotice($notice);
171 $this->recordImportedNotice($data['orig_id'], $notice->id);
177 * Pull relevant info out of a Yammer data record for a user import.
182 function prepUser($item)
184 if ($item['type'] != 'user') {
185 // TRANS: Exception thrown when a non-user item type is used, but expected.
186 throw new Exception(_m('Wrong item type sent to Yammer user import processing.'));
189 $origId = $item['id'];
190 $origUrl = $item['url'];
192 // @fixme check username rules?
194 $options['nickname'] = $item['name'];
195 $options['fullname'] = trim($item['full_name']);
197 // Avatar... this will be the "_small" variant.
198 // Remove that (pre-extension) suffix to get the orig-size image.
199 $avatar = $item['mugshot_url'];
201 // The following info is only available in full data, not in the reference version.
203 // There can be extensive contact info, but for now we'll only pull the primary email.
204 if (isset($item['contact'])) {
205 foreach ($item['contact']['email_addresses'] as $addr) {
206 if ($addr['type'] == 'primary') {
207 $options['email'] = $addr['address'];
208 $options['email_confirmed'] = true;
214 // There can be multiple external URLs; for now pull the first one as home page.
215 if (isset($item['external_urls'])) {
216 foreach ($item['external_urls'] as $url) {
217 if (common_valid_http_url($url)) {
218 $options['homepage'] = $url;
224 // Combine a few bits into the bio...
226 if (!empty($item['job_title'])) {
227 $bio[] = $item['job_title'];
229 if (!empty($item['summary'])) {
230 $bio[] = $item['summary'];
232 if (!empty($item['expertise'])) {
233 // TRANS: Used as a prefix for the Yammer expertise field contents.
234 $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
236 $options['bio'] = implode("\n\n", $bio);
238 // Pull raw location string, may be lookupable
239 if (!empty($item['location'])) {
240 $options['location'] = $item['location'];
243 // Timezone is in format like 'Pacific Time (US & Canada)'
244 // We need to convert that to a zone id. :P
245 // @fixme timezone not yet supported at registration time :)
246 if (!empty($item['timezone'])) {
247 $tz = $this->timezone($item['timezone']);
249 $options['timezone'] = $tz;
253 return array('orig_id' => $origId,
254 'orig_url' => $origUrl,
256 'options' => $options);
261 * Pull relevant info out of a Yammer data record for a group import.
266 function prepGroup($item)
268 if ($item['type'] != 'group') {
269 // TRANS: Exception thrown when a non-group item type is used, but expected.
270 throw new Exception(_m('Wrong item type sent to Yammer group import processing.'));
273 $origId = $item['id'];
274 $origUrl = $item['url'];
276 $privacy = $item['privacy']; // Warning! only public groups in SN so far
278 $options['nickname'] = $item['name'];
279 $options['fullname'] = $item['full_name'];
280 $options['description'] = $item['description'];
281 $options['created'] = $this->timestamp($item['created_at']);
283 $avatar = $item['mugshot_url']; // as with user profiles...
285 $options['mainpage'] = common_local_url('showgroup',
286 array('nickname' => $options['nickname']));
288 // Set some default vals or User_group::register will whine
289 $options['homepage'] = '';
290 $options['location'] = '';
291 $options['aliases'] = array();
292 // @todo FIXME: What about admin user for the group?
294 $options['local'] = true;
295 return array('orig_id' => $origId,
296 'orig_url' => $origUrl,
297 'options' => $options,
298 'avatar' => $avatar);
302 * Pull relevant info out of a Yammer data record for a notice import.
307 function prepNotice($item)
309 if (isset($item['type']) && $item['type'] != 'message') {
310 // TRANS: Exception thrown when a non-message item type is used, but expected.
311 throw new Exception(_m('Wrong item type sent to Yammer message import processing.'));
314 $origId = $item['id'];
315 $origUrl = $item['url'];
317 $profile = $this->findImportedUser($item['sender_id']);
318 $content = $item['body']['plain'];
322 if ($item['replied_to_id']) {
323 $replyTo = $this->findImportedNotice($item['replied_to_id']);
325 $options['reply_to'] = $replyTo;
328 $options['created'] = $this->timestamp($item['created_at']);
330 if (!empty($item['group_id'])) {
331 $groupId = $this->findImportedGroup($item['group_id']);
333 $options['groups'] = array($groupId);
335 // @fixme if we see a group link inline, don't add this?
336 $group = User_group::getKV('id', $groupId);
338 $content .= ' !' . $group->nickname;
344 foreach ($item['liked_by']['names'] as $liker) {
345 // "permalink" is the username. wtf?
346 $faves[] = $liker['permalink'];
349 $attachments = array();
350 foreach ($item['attachments'] as $attach) {
351 if ($attach['type'] == 'image' || $attach['type'] == 'file') {
352 $attachments[] = $attach[$attach['type']]['url'];
354 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
358 return array('orig_id' => $origId,
359 'orig_url' => $origUrl,
360 'profile' => $profile,
361 'content' => $content,
363 'options' => $options,
365 'attachments' => $attachments);
368 private function findImportedUser($origId)
370 $map = Yammer_user::getKV('id', $origId);
371 return $map ? $map->user_id : null;
374 private function findImportedGroup($origId)
376 $map = Yammer_group::getKV('id', $origId);
377 return $map ? $map->group_id : null;
380 private function findImportedNotice($origId)
382 $map = Yammer_notice::getKV('id', $origId);
383 return $map ? $map->notice_id : null;
386 private function recordImportedUser($origId, $userId)
388 Yammer_user::record($origId, $userId);
391 private function recordImportedGroup($origId, $groupId)
393 Yammer_group::record($origId, $groupId);
396 private function recordImportedNotice($origId, $noticeId)
398 Yammer_notice::record($origId, $noticeId);
402 * Normalize timestamp format.
406 private function timestamp($ts)
408 return common_sql_date(strtotime($ts));
411 private function timezone($tz)
414 $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
415 'Eastern Time (US & Canada)' => 'America/New_York');
416 if (array_key_exists($tz, $known)) {
424 * Download and update given avatar image
427 * @param mixed $dest either a Profile or User_group object
428 * @throws Exception in various failure cases
430 private function saveAvatar($url, $dest)
432 // Yammer API data mostly gives us the small variant.
433 // Try hitting the source image if we can!
434 // @fixme no guarantee of this URL scheme I think.
435 $url = preg_replace('/_small(\..*?)$/', '$1', $url);
437 if (!common_valid_http_url($url)) {
438 // TRANS: Server exception thrown when an avatar URL is invalid.
439 // TRANS: %s is the invalid avatar URL.
440 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
443 // @fixme this should be better encapsulated
444 // ripped from oauthstore.php (for old OMB client)
445 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
447 if (!copy($url, $temp_filename)) {
448 // TRANS: Server exception thrown when an avatar could not be fetched.
449 // TRANS: %s is the failed avatar URL.
450 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
454 // @fixme should we be using different ids?
455 $imagefile = new ImageFile($id, $temp_filename);
456 $filename = Avatar::filename($id,
457 image_type_to_extension($imagefile->type),
460 rename($temp_filename, Avatar::path($filename));
461 } catch (Exception $e) {
462 unlink($temp_filename);
465 // @fixme hardcoded chmod is lame, but seems to be necessary to
466 // keep from accidentally saving images from command-line (queues)
467 // that can't be read from web server, which causes hard-to-notice
468 // problems later on:
470 // http://status.net/open-source/issues/2663
471 chmod(Avatar::path($filename), 0644);
473 $dest->setOriginal($filename);
477 * Fetch an attachment from Yammer and save it into our system.
478 * Unlike avatars, the attachment URLs are guarded by authentication,
479 * so we need to run the HTTP hit through our OAuth API client.
485 * @throws Exception on low-level network or HTTP error
487 private function saveAttachment($url, User $user)
489 // Fetch the attachment...
490 // WARNING: file must fit in memory here :(
491 $body = $this->client->fetchUrl($url);
493 // Save to a temporary file and shove it into our file-attachment space...
495 fwrite($temp, $body);
497 $upload = MediaFile::fromFilehandle($temp, $user->getProfile());
500 } catch (Exception $e) {