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);
45 $profileId = $this->findImportedUser($data['orig_id']);
47 return Profile::staticGet('id', $profileId);
49 $user = User::register($data['options']);
50 $profile = $user->getProfile();
51 if ($data['avatar']) {
53 $this->saveAvatar($data['avatar'], $profile);
54 } catch (Exception $e) {
55 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
58 $this->recordImportedUser($data['orig_id'], $profile->id);
64 * Load or create an imported group from Yammer data.
66 * @param object $item loaded JSON data for Yammer importer
69 function importGroup($item)
71 $data = $this->prepGroup($item);
73 $groupId = $this->findImportedGroup($data['orig_id']);
75 return User_group::staticGet('id', $groupId);
77 $group = User_group::register($data['options']);
78 if ($data['avatar']) {
80 $this->saveAvatar($data['avatar'], $group);
81 } catch (Exception $e) {
82 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
85 $this->recordImportedGroup($data['orig_id'], $group->id);
91 * Load or create an imported notice from Yammer data.
93 * @param object $item loaded JSON data for Yammer importer
96 function importNotice($item)
98 $data = $this->prepNotice($item);
100 $noticeId = $this->findImportedNotice($data['orig_id']);
102 return Notice::staticGet('id', $noticeId);
104 $content = $data['content'];
105 $user = User::staticGet($data['profile']);
107 // Fetch file attachments and add the URLs...
109 foreach ($data['attachments'] as $url) {
111 $upload = $this->saveAttachment($url, $user);
112 $content .= ' ' . $upload->shortUrl();
113 $uploads[] = $upload;
114 } catch (Exception $e) {
115 common_log(LOG_ERR, "Error importing Yammer attachment: " . $e->getMessage());
119 // Here's the meat! Actually save the dang ol' notice.
120 $notice = Notice::saveNew($user->id,
125 // Save "likes" as favorites...
126 foreach ($data['faves'] as $nickname) {
127 $user = User::staticGet('nickname', $nickname);
129 Fave::addNew($user->getProfile(), $notice);
133 // And finally attach the upload records...
134 foreach ($uploads as $upload) {
135 $upload->attachToNotice($notice);
137 $this->recordImportedNotice($data['orig_id'], $notice->id);
143 * Pull relevant info out of a Yammer data record for a user import.
148 function prepUser($item)
150 if ($item['type'] != 'user') {
151 throw new Exception('Wrong item type sent to Yammer user import processing.');
154 $origId = $item['id'];
155 $origUrl = $item['url'];
157 // @fixme check username rules?
159 $options['nickname'] = $item['name'];
160 $options['fullname'] = trim($item['full_name']);
162 // Avatar... this will be the "_small" variant.
163 // Remove that (pre-extension) suffix to get the orig-size image.
164 $avatar = $item['mugshot_url'];
166 // The following info is only available in full data, not in the reference version.
168 // There can be extensive contact info, but for now we'll only pull the primary email.
169 if (isset($item['contact'])) {
170 foreach ($item['contact']['email_addresses'] as $addr) {
171 if ($addr['type'] == 'primary') {
172 $options['email'] = $addr['address'];
173 $options['email_confirmed'] = true;
179 // There can be multiple external URLs; for now pull the first one as home page.
180 if (isset($item['external_urls'])) {
181 foreach ($item['external_urls'] as $url) {
182 if (common_valid_http_url($url)) {
183 $options['homepage'] = $url;
189 // Combine a few bits into the bio...
191 if (!empty($item['job_title'])) {
192 $bio[] = $item['job_title'];
194 if (!empty($item['summary'])) {
195 $bio[] = $item['summary'];
197 if (!empty($item['expertise'])) {
198 $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
200 $options['bio'] = implode("\n\n", $bio);
202 // Pull raw location string, may be lookupable
203 if (!empty($item['location'])) {
204 $options['location'] = $item['location'];
207 // Timezone is in format like 'Pacific Time (US & Canada)'
208 // We need to convert that to a zone id. :P
209 // @fixme timezone not yet supported at registration time :)
210 if (!empty($item['timezone'])) {
211 $tz = $this->timezone($item['timezone']);
213 $options['timezone'] = $tz;
217 return array('orig_id' => $origId,
218 'orig_url' => $origUrl,
220 'options' => $options);
225 * Pull relevant info out of a Yammer data record for a group import.
230 function prepGroup($item)
232 if ($item['type'] != 'group') {
233 throw new Exception('Wrong item type sent to Yammer group import processing.');
236 $origId = $item['id'];
237 $origUrl = $item['url'];
239 $privacy = $item['privacy']; // Warning! only public groups in SN so far
241 $options['nickname'] = $item['name'];
242 $options['fullname'] = $item['full_name'];
243 $options['description'] = $item['description'];
244 $options['created'] = $this->timestamp($item['created_at']);
246 $avatar = $item['mugshot_url']; // as with user profiles...
249 $options['mainpage'] = common_local_url('showgroup',
250 array('nickname' => $options['nickname']));
252 // @fixme what about admin user for the group?
253 // bio? homepage etc? aliases?
255 $options['local'] = true;
256 return array('orig_id' => $origId,
257 'orig_url' => $origUrl,
258 'options' => $options,
259 'avatar' => $avatar);
263 * Pull relevant info out of a Yammer data record for a notice import.
268 function prepNotice($item)
270 if (isset($item['type']) && $item['type'] != 'message') {
271 throw new Exception('Wrong item type sent to Yammer message import processing.');
274 $origId = $item['id'];
275 $origUrl = $item['url'];
277 $profile = $this->findImportedUser($item['sender_id']);
278 $content = $item['body']['plain'];
282 if ($item['replied_to_id']) {
283 $replyTo = $this->findImportedNotice($item['replied_to_id']);
285 $options['reply_to'] = $replyTo;
288 $options['created'] = $this->timestamp($item['created_at']);
290 if ($item['group_id']) {
291 $groupId = $this->findImportedGroup($item['group_id']);
293 $options['groups'] = array($groupId);
295 // @fixme if we see a group link inline, don't add this?
296 $group = User_group::staticGet('id', $groupId);
298 $content .= ' !' . $group->nickname;
304 foreach ($item['liked_by']['names'] as $liker) {
305 // "permalink" is the username. wtf?
306 $faves[] = $liker['permalink'];
309 $attachments = array();
310 foreach ($item['attachments'] as $attach) {
311 if ($attach['type'] == 'image' || $attach['type'] == 'file') {
312 $attachments[] = $attach[$attach['type']]['url'];
314 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
318 return array('orig_id' => $origId,
319 'orig_url' => $origUrl,
320 'profile' => $profile,
321 'content' => $content,
323 'options' => $options,
325 'attachments' => $attachments);
328 private function findImportedUser($origId)
330 $map = Yammer_user::staticGet('id', $origId);
331 return $map ? $map->user_id : null;
334 private function findImportedGroup($origId)
336 $map = Yammer_group::staticGet('id', $origId);
337 return $map ? $map->group_id : null;
340 private function findImportedNotice($origId)
342 $map = Yammer_notice::staticGet('id', $origId);
343 return $map ? $map->notice_id : null;
346 private function recordImportedUser($origId, $userId)
348 Yammer_user::record($origId, $userId);
351 private function recordImportedGroup($origId, $groupId)
353 Yammer_group::record($origId, $groupId);
356 private function recordImportedNotice($origId, $noticeId)
358 Yammer_notice::record($origId, $noticeId);
362 * Normalize timestamp format.
366 private function timestamp($ts)
368 return common_sql_date(strtotime($ts));
371 private function timezone($tz)
374 $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
375 'Eastern Time (US & Canada)' => 'America/New_York');
376 if (array_key_exists($tz, $known)) {
384 * Download and update given avatar image
387 * @param mixed $dest either a Profile or User_group object
388 * @throws Exception in various failure cases
390 private function saveAvatar($url, $dest)
392 // Yammer API data mostly gives us the small variant.
393 // Try hitting the source image if we can!
394 // @fixme no guarantee of this URL scheme I think.
395 $url = preg_replace('/_small(\..*?)$/', '$1', $url);
397 if (!common_valid_http_url($url)) {
398 throw new ServerException(sprintf(_m("Invalid avatar URL %s."), $url));
401 // @fixme this should be better encapsulated
402 // ripped from oauthstore.php (for old OMB client)
403 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
404 if (!copy($url, $temp_filename)) {
405 throw new ServerException(sprintf(_m("Unable to fetch avatar from %s."), $url));
409 // @fixme should we be using different ids?
410 $imagefile = new ImageFile($id, $temp_filename);
411 $filename = Avatar::filename($id,
412 image_type_to_extension($imagefile->type),
415 rename($temp_filename, Avatar::path($filename));
416 // @fixme hardcoded chmod is lame, but seems to be necessary to
417 // keep from accidentally saving images from command-line (queues)
418 // that can't be read from web server, which causes hard-to-notice
419 // problems later on:
421 // http://status.net/open-source/issues/2663
422 chmod(Avatar::path($filename), 0644);
424 $dest->setOriginal($filename);
428 * Fetch an attachment from Yammer and save it into our system.
429 * Unlike avatars, the attachment URLs are guarded by authentication,
430 * so we need to run the HTTP hit through our OAuth API client.
436 * @throws Exception on low-level network or HTTP error
438 private function saveAttachment($url, User $user)
440 // Fetch the attachment...
441 // WARNING: file must fit in memory here :(
442 $body = $this->client->fetchUrl($url);
444 // Save to a temporary file and shove it into our file-attachment space...
446 fwrite($temp, $body);
448 $upload = MediaFile::fromFileHandle($temp, $user);
451 } catch (Exception $e) {