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 throw new Exception('Wrong item type sent to Yammer user import processing.');
186 $origId = $item['id'];
187 $origUrl = $item['url'];
189 // @fixme check username rules?
191 $options['nickname'] = $item['name'];
192 $options['fullname'] = trim($item['full_name']);
194 // Avatar... this will be the "_small" variant.
195 // Remove that (pre-extension) suffix to get the orig-size image.
196 $avatar = $item['mugshot_url'];
198 // The following info is only available in full data, not in the reference version.
200 // There can be extensive contact info, but for now we'll only pull the primary email.
201 if (isset($item['contact'])) {
202 foreach ($item['contact']['email_addresses'] as $addr) {
203 if ($addr['type'] == 'primary') {
204 $options['email'] = $addr['address'];
205 $options['email_confirmed'] = true;
211 // There can be multiple external URLs; for now pull the first one as home page.
212 if (isset($item['external_urls'])) {
213 foreach ($item['external_urls'] as $url) {
214 if (common_valid_http_url($url)) {
215 $options['homepage'] = $url;
221 // Combine a few bits into the bio...
223 if (!empty($item['job_title'])) {
224 $bio[] = $item['job_title'];
226 if (!empty($item['summary'])) {
227 $bio[] = $item['summary'];
229 if (!empty($item['expertise'])) {
230 $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
232 $options['bio'] = implode("\n\n", $bio);
234 // Pull raw location string, may be lookupable
235 if (!empty($item['location'])) {
236 $options['location'] = $item['location'];
239 // Timezone is in format like 'Pacific Time (US & Canada)'
240 // We need to convert that to a zone id. :P
241 // @fixme timezone not yet supported at registration time :)
242 if (!empty($item['timezone'])) {
243 $tz = $this->timezone($item['timezone']);
245 $options['timezone'] = $tz;
249 return array('orig_id' => $origId,
250 'orig_url' => $origUrl,
252 'options' => $options);
257 * Pull relevant info out of a Yammer data record for a group import.
262 function prepGroup($item)
264 if ($item['type'] != 'group') {
265 throw new Exception('Wrong item type sent to Yammer group import processing.');
268 $origId = $item['id'];
269 $origUrl = $item['url'];
271 $privacy = $item['privacy']; // Warning! only public groups in SN so far
273 $options['nickname'] = $item['name'];
274 $options['fullname'] = $item['full_name'];
275 $options['description'] = $item['description'];
276 $options['created'] = $this->timestamp($item['created_at']);
278 $avatar = $item['mugshot_url']; // as with user profiles...
281 $options['mainpage'] = common_local_url('showgroup',
282 array('nickname' => $options['nickname']));
284 // Set some default vals or User_group::register will whine
285 $options['homepage'] = '';
286 $options['location'] = '';
287 $options['aliases'] = array();
288 // @fixme what about admin user for the group?
290 $options['local'] = true;
291 return array('orig_id' => $origId,
292 'orig_url' => $origUrl,
293 'options' => $options,
294 'avatar' => $avatar);
298 * Pull relevant info out of a Yammer data record for a notice import.
303 function prepNotice($item)
305 if (isset($item['type']) && $item['type'] != 'message') {
306 throw new Exception('Wrong item type sent to Yammer message import processing.');
309 $origId = $item['id'];
310 $origUrl = $item['url'];
312 $profile = $this->findImportedUser($item['sender_id']);
313 $content = $item['body']['plain'];
317 if ($item['replied_to_id']) {
318 $replyTo = $this->findImportedNotice($item['replied_to_id']);
320 $options['reply_to'] = $replyTo;
323 $options['created'] = $this->timestamp($item['created_at']);
325 if (!empty($item['group_id'])) {
326 $groupId = $this->findImportedGroup($item['group_id']);
328 $options['groups'] = array($groupId);
330 // @fixme if we see a group link inline, don't add this?
331 $group = User_group::staticGet('id', $groupId);
333 $content .= ' !' . $group->nickname;
339 foreach ($item['liked_by']['names'] as $liker) {
340 // "permalink" is the username. wtf?
341 $faves[] = $liker['permalink'];
344 $attachments = array();
345 foreach ($item['attachments'] as $attach) {
346 if ($attach['type'] == 'image' || $attach['type'] == 'file') {
347 $attachments[] = $attach[$attach['type']]['url'];
349 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
353 return array('orig_id' => $origId,
354 'orig_url' => $origUrl,
355 'profile' => $profile,
356 'content' => $content,
358 'options' => $options,
360 'attachments' => $attachments);
363 private function findImportedUser($origId)
365 $map = Yammer_user::staticGet('id', $origId);
366 return $map ? $map->user_id : null;
369 private function findImportedGroup($origId)
371 $map = Yammer_group::staticGet('id', $origId);
372 return $map ? $map->group_id : null;
375 private function findImportedNotice($origId)
377 $map = Yammer_notice::staticGet('id', $origId);
378 return $map ? $map->notice_id : null;
381 private function recordImportedUser($origId, $userId)
383 Yammer_user::record($origId, $userId);
386 private function recordImportedGroup($origId, $groupId)
388 Yammer_group::record($origId, $groupId);
391 private function recordImportedNotice($origId, $noticeId)
393 Yammer_notice::record($origId, $noticeId);
397 * Normalize timestamp format.
401 private function timestamp($ts)
403 return common_sql_date(strtotime($ts));
406 private function timezone($tz)
409 $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
410 'Eastern Time (US & Canada)' => 'America/New_York');
411 if (array_key_exists($tz, $known)) {
419 * Download and update given avatar image
422 * @param mixed $dest either a Profile or User_group object
423 * @throws Exception in various failure cases
425 private function saveAvatar($url, $dest)
427 // Yammer API data mostly gives us the small variant.
428 // Try hitting the source image if we can!
429 // @fixme no guarantee of this URL scheme I think.
430 $url = preg_replace('/_small(\..*?)$/', '$1', $url);
432 if (!common_valid_http_url($url)) {
433 throw new ServerException(sprintf(_m("Invalid avatar URL %s."), $url));
436 // @fixme this should be better encapsulated
437 // ripped from oauthstore.php (for old OMB client)
438 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
439 if (!copy($url, $temp_filename)) {
440 throw new ServerException(sprintf(_m("Unable to fetch avatar from %s."), $url));
444 // @fixme should we be using different ids?
445 $imagefile = new ImageFile($id, $temp_filename);
446 $filename = Avatar::filename($id,
447 image_type_to_extension($imagefile->type),
450 rename($temp_filename, Avatar::path($filename));
451 // @fixme hardcoded chmod is lame, but seems to be necessary to
452 // keep from accidentally saving images from command-line (queues)
453 // that can't be read from web server, which causes hard-to-notice
454 // problems later on:
456 // http://status.net/open-source/issues/2663
457 chmod(Avatar::path($filename), 0644);
459 $dest->setOriginal($filename);
463 * Fetch an attachment from Yammer and save it into our system.
464 * Unlike avatars, the attachment URLs are guarded by authentication,
465 * so we need to run the HTTP hit through our OAuth API client.
471 * @throws Exception on low-level network or HTTP error
473 private function saveAttachment($url, User $user)
475 // Fetch the attachment...
476 // WARNING: file must fit in memory here :(
477 $body = $this->client->fetchUrl($url);
479 // Save to a temporary file and shove it into our file-attachment space...
481 fwrite($temp, $body);
483 $upload = MediaFile::fromFileHandle($temp, $user);
486 } catch (Exception $e) {