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 $content = $data['content'];
136 $user = User::staticGet($data['profile']);
138 // Fetch file attachments and add the URLs...
140 foreach ($data['attachments'] as $url) {
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());
150 // Here's the meat! Actually save the dang ol' notice.
151 $notice = Notice::saveNew($user->id,
156 // Save "likes" as favorites...
157 foreach ($data['faves'] as $nickname) {
158 $user = User::staticGet('nickname', $nickname);
160 Fave::addNew($user->getProfile(), $notice);
164 // And finally attach the upload records...
165 foreach ($uploads as $upload) {
166 $upload->attachToNotice($notice);
168 $this->recordImportedNotice($data['orig_id'], $notice->id);
174 * Pull relevant info out of a Yammer data record for a user import.
179 function prepUser($item)
181 if ($item['type'] != 'user') {
182 throw new Exception('Wrong item type sent to Yammer user import processing.');
185 $origId = $item['id'];
186 $origUrl = $item['url'];
188 // @fixme check username rules?
190 $options['nickname'] = $item['name'];
191 $options['fullname'] = trim($item['full_name']);
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'];
197 // The following info is only available in full data, not in the reference version.
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;
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;
220 // Combine a few bits into the bio...
222 if (!empty($item['job_title'])) {
223 $bio[] = $item['job_title'];
225 if (!empty($item['summary'])) {
226 $bio[] = $item['summary'];
228 if (!empty($item['expertise'])) {
229 $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
231 $options['bio'] = implode("\n\n", $bio);
233 // Pull raw location string, may be lookupable
234 if (!empty($item['location'])) {
235 $options['location'] = $item['location'];
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']);
244 $options['timezone'] = $tz;
248 return array('orig_id' => $origId,
249 'orig_url' => $origUrl,
251 'options' => $options);
256 * Pull relevant info out of a Yammer data record for a group import.
261 function prepGroup($item)
263 if ($item['type'] != 'group') {
264 throw new Exception('Wrong item type sent to Yammer group import processing.');
267 $origId = $item['id'];
268 $origUrl = $item['url'];
270 $privacy = $item['privacy']; // Warning! only public groups in SN so far
272 $options['nickname'] = $item['name'];
273 $options['fullname'] = $item['full_name'];
274 $options['description'] = $item['description'];
275 $options['created'] = $this->timestamp($item['created_at']);
277 $avatar = $item['mugshot_url']; // as with user profiles...
280 $options['mainpage'] = common_local_url('showgroup',
281 array('nickname' => $options['nickname']));
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?
289 $options['local'] = true;
290 return array('orig_id' => $origId,
291 'orig_url' => $origUrl,
292 'options' => $options,
293 'avatar' => $avatar);
297 * Pull relevant info out of a Yammer data record for a notice import.
302 function prepNotice($item)
304 if (isset($item['type']) && $item['type'] != 'message') {
305 throw new Exception('Wrong item type sent to Yammer message import processing.');
308 $origId = $item['id'];
309 $origUrl = $item['url'];
311 $profile = $this->findImportedUser($item['sender_id']);
312 $content = $item['body']['plain'];
316 if ($item['replied_to_id']) {
317 $replyTo = $this->findImportedNotice($item['replied_to_id']);
319 $options['reply_to'] = $replyTo;
322 $options['created'] = $this->timestamp($item['created_at']);
324 if (!empty($item['group_id'])) {
325 $groupId = $this->findImportedGroup($item['group_id']);
327 $options['groups'] = array($groupId);
329 // @fixme if we see a group link inline, don't add this?
330 $group = User_group::staticGet('id', $groupId);
332 $content .= ' !' . $group->nickname;
338 foreach ($item['liked_by']['names'] as $liker) {
339 // "permalink" is the username. wtf?
340 $faves[] = $liker['permalink'];
343 $attachments = array();
344 foreach ($item['attachments'] as $attach) {
345 if ($attach['type'] == 'image' || $attach['type'] == 'file') {
346 $attachments[] = $attach[$attach['type']]['url'];
348 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
352 return array('orig_id' => $origId,
353 'orig_url' => $origUrl,
354 'profile' => $profile,
355 'content' => $content,
357 'options' => $options,
359 'attachments' => $attachments);
362 private function findImportedUser($origId)
364 $map = Yammer_user::staticGet('id', $origId);
365 return $map ? $map->user_id : null;
368 private function findImportedGroup($origId)
370 $map = Yammer_group::staticGet('id', $origId);
371 return $map ? $map->group_id : null;
374 private function findImportedNotice($origId)
376 $map = Yammer_notice::staticGet('id', $origId);
377 return $map ? $map->notice_id : null;
380 private function recordImportedUser($origId, $userId)
382 Yammer_user::record($origId, $userId);
385 private function recordImportedGroup($origId, $groupId)
387 Yammer_group::record($origId, $groupId);
390 private function recordImportedNotice($origId, $noticeId)
392 Yammer_notice::record($origId, $noticeId);
396 * Normalize timestamp format.
400 private function timestamp($ts)
402 return common_sql_date(strtotime($ts));
405 private function timezone($tz)
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)) {
418 * Download and update given avatar image
421 * @param mixed $dest either a Profile or User_group object
422 * @throws Exception in various failure cases
424 private function saveAvatar($url, $dest)
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);
431 if (!common_valid_http_url($url)) {
432 throw new ServerException(sprintf(_m("Invalid avatar URL %s."), $url));
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));
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),
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:
455 // http://status.net/open-source/issues/2663
456 chmod(Avatar::path($filename), 0644);
458 $dest->setOriginal($filename);
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.
470 * @throws Exception on low-level network or HTTP error
472 private function saveAttachment($url, User $user)
474 // Fetch the attachment...
475 // WARNING: file must fit in memory here :(
476 $body = $this->client->fetchUrl($url);
478 // Save to a temporary file and shove it into our file-attachment space...
480 fwrite($temp, $body);
482 $upload = MediaFile::fromFileHandle($temp, $user);
485 } catch (Exception $e) {