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 * @package YammerImportPlugin
24 * @author Brion Vibber <brion@status.net>
30 function __construct(SN_YammerClient $client)
32 $this->client = $client;
36 * Load or create an imported profile from Yammer data.
38 * @param object $item loaded JSON data for Yammer importer
41 function importUser($item)
43 $data = $this->prepUser($item);
44 $nickname = $data['options']['nickname'];
46 $profileId = $this->findImportedUser($data['orig_id']);
48 return Profile::staticGet('id', $profileId);
50 $user = User::staticGet('nickname', $nickname);
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'));
57 $user = User::register($data['options']);
58 $profile = $user->getProfile();
60 if ($data['avatar']) {
62 $this->saveAvatar($data['avatar'], $profile);
63 } catch (Exception $e) {
64 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
67 $this->recordImportedUser($data['orig_id'], $profile->id);
73 * Load or create an imported group from Yammer data.
75 * @param object $item loaded JSON data for Yammer importer
78 function importGroup($item)
80 $data = $this->prepGroup($item);
81 $nickname = $data['options']['nickname'];
83 $groupId = $this->findImportedGroup($data['orig_id']);
85 return User_group::staticGet('id', $groupId);
87 $local = Local_group::staticGet('nickname', $nickname);
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'));
94 $group = User_group::register($data['options']);
96 if ($data['avatar']) {
98 $this->saveAvatar($data['avatar'], $group);
99 } catch (Exception $e) {
100 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
103 $this->recordImportedGroup($data['orig_id'], $group->id);
108 private function savePropertiesOn($target, $options, $propList)
111 $orig = clone($target);
112 foreach ($propList as $prop) {
113 if (!empty($options[$prop]) && $target->$prop != $options[$prop]) {
114 $target->$prop = $options[$prop];
118 $target->update($orig);
122 * Load or create an imported notice from Yammer data.
124 * @param object $item loaded JSON data for Yammer importer
127 function importNotice($item)
129 $data = $this->prepNotice($item);
131 $noticeId = $this->findImportedNotice($data['orig_id']);
133 return Notice::staticGet('id', $noticeId);
135 $notice = Notice::staticGet('uri', $data['options']['uri']);
136 $content = $data['content'];
137 $user = User::staticGet($data['profile']);
139 // Fetch file attachments and add the URLs...
141 foreach ($data['attachments'] as $url) {
143 $upload = $this->saveAttachment($url, $user);
144 $content .= ' ' . $upload->shortUrl();
145 $uploads[] = $upload;
146 } catch (Exception $e) {
147 common_log(LOG_ERR, "Error importing Yammer attachment: " . $e->getMessage());
151 // Here's the meat! Actually save the dang ol' notice.
152 $notice = Notice::saveNew($user->id,
157 // Save "likes" as favorites...
158 foreach ($data['faves'] as $nickname) {
159 $user = User::staticGet('nickname', $nickname);
161 Fave::addNew($user->getProfile(), $notice);
165 // And finally attach the upload records...
166 foreach ($uploads as $upload) {
167 $upload->attachToNotice($notice);
169 $this->recordImportedNotice($data['orig_id'], $notice->id);
175 * Pull relevant info out of a Yammer data record for a user import.
180 function prepUser($item)
182 if ($item['type'] != 'user') {
183 // TRANS: Exception thrown when a non-user item type is used, but expected.
184 throw new Exception(_m('Wrong item type sent to Yammer user import processing.'));
187 $origId = $item['id'];
188 $origUrl = $item['url'];
190 // @fixme check username rules?
192 $options['nickname'] = $item['name'];
193 $options['fullname'] = trim($item['full_name']);
195 // Avatar... this will be the "_small" variant.
196 // Remove that (pre-extension) suffix to get the orig-size image.
197 $avatar = $item['mugshot_url'];
199 // The following info is only available in full data, not in the reference version.
201 // There can be extensive contact info, but for now we'll only pull the primary email.
202 if (isset($item['contact'])) {
203 foreach ($item['contact']['email_addresses'] as $addr) {
204 if ($addr['type'] == 'primary') {
205 $options['email'] = $addr['address'];
206 $options['email_confirmed'] = true;
212 // There can be multiple external URLs; for now pull the first one as home page.
213 if (isset($item['external_urls'])) {
214 foreach ($item['external_urls'] as $url) {
215 if (common_valid_http_url($url)) {
216 $options['homepage'] = $url;
222 // Combine a few bits into the bio...
224 if (!empty($item['job_title'])) {
225 $bio[] = $item['job_title'];
227 if (!empty($item['summary'])) {
228 $bio[] = $item['summary'];
230 if (!empty($item['expertise'])) {
231 // TRANS: Used as a prefix for the Yammer expertise field contents.
232 $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
234 $options['bio'] = implode("\n\n", $bio);
236 // Pull raw location string, may be lookupable
237 if (!empty($item['location'])) {
238 $options['location'] = $item['location'];
241 // Timezone is in format like 'Pacific Time (US & Canada)'
242 // We need to convert that to a zone id. :P
243 // @fixme timezone not yet supported at registration time :)
244 if (!empty($item['timezone'])) {
245 $tz = $this->timezone($item['timezone']);
247 $options['timezone'] = $tz;
251 return array('orig_id' => $origId,
252 'orig_url' => $origUrl,
254 'options' => $options);
259 * Pull relevant info out of a Yammer data record for a group import.
264 function prepGroup($item)
266 if ($item['type'] != 'group') {
267 // TRANS: Exception thrown when a non-group item type is used, but expected.
268 throw new Exception(_m('Wrong item type sent to Yammer group import processing.'));
271 $origId = $item['id'];
272 $origUrl = $item['url'];
274 $privacy = $item['privacy']; // Warning! only public groups in SN so far
276 $options['nickname'] = $item['name'];
277 $options['fullname'] = $item['full_name'];
278 $options['description'] = $item['description'];
279 $options['created'] = $this->timestamp($item['created_at']);
281 $avatar = $item['mugshot_url']; // as with user profiles...
283 $options['mainpage'] = common_local_url('showgroup',
284 array('nickname' => $options['nickname']));
286 // Set some default vals or User_group::register will whine
287 $options['homepage'] = '';
288 $options['location'] = '';
289 $options['aliases'] = array();
290 // @todo FIXME: What about admin user for the group?
292 $options['local'] = true;
293 return array('orig_id' => $origId,
294 'orig_url' => $origUrl,
295 'options' => $options,
296 'avatar' => $avatar);
300 * Pull relevant info out of a Yammer data record for a notice import.
305 function prepNotice($item)
307 if (isset($item['type']) && $item['type'] != 'message') {
308 // TRANS: Exception thrown when a non-message item type is used, but expected.
309 throw new Exception(_m('Wrong item type sent to Yammer message import processing.'));
312 $origId = $item['id'];
313 $origUrl = $item['url'];
315 $profile = $this->findImportedUser($item['sender_id']);
316 $content = $item['body']['plain'];
320 if ($item['replied_to_id']) {
321 $replyTo = $this->findImportedNotice($item['replied_to_id']);
323 $options['reply_to'] = $replyTo;
326 $options['created'] = $this->timestamp($item['created_at']);
328 if (!empty($item['group_id'])) {
329 $groupId = $this->findImportedGroup($item['group_id']);
331 $options['groups'] = array($groupId);
333 // @fixme if we see a group link inline, don't add this?
334 $group = User_group::staticGet('id', $groupId);
336 $content .= ' !' . $group->nickname;
342 foreach ($item['liked_by']['names'] as $liker) {
343 // "permalink" is the username. wtf?
344 $faves[] = $liker['permalink'];
347 $attachments = array();
348 foreach ($item['attachments'] as $attach) {
349 if ($attach['type'] == 'image' || $attach['type'] == 'file') {
350 $attachments[] = $attach[$attach['type']]['url'];
352 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
356 return array('orig_id' => $origId,
357 'orig_url' => $origUrl,
358 'profile' => $profile,
359 'content' => $content,
361 'options' => $options,
363 'attachments' => $attachments);
366 private function findImportedUser($origId)
368 $map = Yammer_user::staticGet('id', $origId);
369 return $map ? $map->user_id : null;
372 private function findImportedGroup($origId)
374 $map = Yammer_group::staticGet('id', $origId);
375 return $map ? $map->group_id : null;
378 private function findImportedNotice($origId)
380 $map = Yammer_notice::staticGet('id', $origId);
381 return $map ? $map->notice_id : null;
384 private function recordImportedUser($origId, $userId)
386 Yammer_user::record($origId, $userId);
389 private function recordImportedGroup($origId, $groupId)
391 Yammer_group::record($origId, $groupId);
394 private function recordImportedNotice($origId, $noticeId)
396 Yammer_notice::record($origId, $noticeId);
400 * Normalize timestamp format.
404 private function timestamp($ts)
406 return common_sql_date(strtotime($ts));
409 private function timezone($tz)
412 $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
413 'Eastern Time (US & Canada)' => 'America/New_York');
414 if (array_key_exists($tz, $known)) {
422 * Download and update given avatar image
425 * @param mixed $dest either a Profile or User_group object
426 * @throws Exception in various failure cases
428 private function saveAvatar($url, $dest)
430 // Yammer API data mostly gives us the small variant.
431 // Try hitting the source image if we can!
432 // @fixme no guarantee of this URL scheme I think.
433 $url = preg_replace('/_small(\..*?)$/', '$1', $url);
435 if (!common_valid_http_url($url)) {
436 // TRANS: Server exception thrown when an avatar URL is invalid.
437 // TRANS: %s is the invalid avatar URL.
438 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
441 // @fixme this should be better encapsulated
442 // ripped from oauthstore.php (for old OMB client)
443 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
445 if (!copy($url, $temp_filename)) {
446 // TRANS: Server exception thrown when an avatar could not be fetched.
447 // TRANS: %s is the failed avatar URL.
448 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
452 // @fixme should we be using different ids?
453 $imagefile = new ImageFile($id, $temp_filename);
454 $filename = Avatar::filename($id,
455 image_type_to_extension($imagefile->type),
458 rename($temp_filename, Avatar::path($filename));
459 } catch (Exception $e) {
460 unlink($temp_filename);
463 // @fixme hardcoded chmod is lame, but seems to be necessary to
464 // keep from accidentally saving images from command-line (queues)
465 // that can't be read from web server, which causes hard-to-notice
466 // problems later on:
468 // http://status.net/open-source/issues/2663
469 chmod(Avatar::path($filename), 0644);
471 $dest->setOriginal($filename);
475 * Fetch an attachment from Yammer and save it into our system.
476 * Unlike avatars, the attachment URLs are guarded by authentication,
477 * so we need to run the HTTP hit through our OAuth API client.
483 * @throws Exception on low-level network or HTTP error
485 private function saveAttachment($url, User $user)
487 // Fetch the attachment...
488 // WARNING: file must fit in memory here :(
489 $body = $this->client->fetchUrl($url);
491 // Save to a temporary file and shove it into our file-attachment space...
493 fwrite($temp, $body);
495 $upload = MediaFile::fromFileHandle($temp, $user);
498 } catch (Exception $e) {