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>
29 protected $users=array();
30 protected $groups=array();
31 protected $notices=array();
33 function __construct(SN_YammerClient $client)
35 $this->client = $client;
39 * Load or create an imported profile from Yammer data.
41 * @param object $item loaded JSON data for Yammer importer
44 function importUser($item)
46 $data = $this->prepUser($item);
48 $profileId = $this->findImportedUser($data['orig_id']);
50 return Profile::staticGet('id', $profileId);
52 $user = User::register($data['options']);
53 $profile = $user->getProfile();
54 if ($data['avatar']) {
56 $this->saveAvatar($data['avatar'], $profile);
57 } catch (Exception $e) {
58 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
61 $this->recordImportedUser($data['orig_id'], $profile->id);
67 * Load or create an imported group from Yammer data.
69 * @param object $item loaded JSON data for Yammer importer
72 function importGroup($item)
74 $data = $this->prepGroup($item);
76 $groupId = $this->findImportedGroup($data['orig_id']);
78 return User_group::staticGet('id', $groupId);
80 $group = User_group::register($data['options']);
81 if ($data['avatar']) {
83 $this->saveAvatar($data['avatar'], $group);
84 } catch (Exception $e) {
85 common_log(LOG_ERR, "Error importing Yammer avatar: " . $e->getMessage());
88 $this->recordImportedGroup($data['orig_id'], $group->id);
94 * Load or create an imported notice from Yammer data.
96 * @param object $item loaded JSON data for Yammer importer
99 function importNotice($item)
101 $data = $this->prepNotice($item);
103 $noticeId = $this->findImportedNotice($data['orig_id']);
105 return Notice::staticGet('id', $noticeId);
107 $content = $data['content'];
108 $user = User::staticGet($data['profile']);
110 // Fetch file attachments and add the URLs...
112 foreach ($data['attachments'] as $url) {
114 $upload = $this->saveAttachment($url, $user);
115 $content .= ' ' . $upload->shortUrl();
116 $uploads[] = $upload;
117 } catch (Exception $e) {
118 common_log(LOG_ERR, "Error importing Yammer attachment: " . $e->getMessage());
122 // Here's the meat! Actually save the dang ol' notice.
123 $notice = Notice::saveNew($user->id,
128 // Save "likes" as favorites...
129 foreach ($data['faves'] as $nickname) {
130 $user = User::staticGet('nickname', $nickname);
132 Fave::addNew($user->getProfile(), $notice);
136 // And finally attach the upload records...
137 foreach ($uploads as $upload) {
138 $upload->attachToNotice($notice);
140 $this->recordImportedNotice($data['orig_id'], $notice->id);
146 * Pull relevant info out of a Yammer data record for a user import.
151 function prepUser($item)
153 if ($item['type'] != 'user') {
154 throw new Exception('Wrong item type sent to Yammer user import processing.');
157 $origId = $item['id'];
158 $origUrl = $item['url'];
160 // @fixme check username rules?
162 $options['nickname'] = $item['name'];
163 $options['fullname'] = trim($item['full_name']);
165 // Avatar... this will be the "_small" variant.
166 // Remove that (pre-extension) suffix to get the orig-size image.
167 $avatar = $item['mugshot_url'];
169 // The following info is only available in full data, not in the reference version.
171 // There can be extensive contact info, but for now we'll only pull the primary email.
172 if (isset($item['contact'])) {
173 foreach ($item['contact']['email_addresses'] as $addr) {
174 if ($addr['type'] == 'primary') {
175 $options['email'] = $addr['address'];
176 $options['email_confirmed'] = true;
182 // There can be multiple external URLs; for now pull the first one as home page.
183 if (isset($item['external_urls'])) {
184 foreach ($item['external_urls'] as $url) {
185 if (common_valid_http_url($url)) {
186 $options['homepage'] = $url;
192 // Combine a few bits into the bio...
194 if (!empty($item['job_title'])) {
195 $bio[] = $item['job_title'];
197 if (!empty($item['summary'])) {
198 $bio[] = $item['summary'];
200 if (!empty($item['expertise'])) {
201 $bio[] = _m('Expertise:') . ' ' . $item['expertise'];
203 $options['bio'] = implode("\n\n", $bio);
205 // Pull raw location string, may be lookupable
206 if (!empty($item['location'])) {
207 $options['location'] = $item['location'];
210 // Timezone is in format like 'Pacific Time (US & Canada)'
211 // We need to convert that to a zone id. :P
212 // @fixme timezone not yet supported at registration time :)
213 if (!empty($item['timezone'])) {
214 $tz = $this->timezone($item['timezone']);
216 $options['timezone'] = $tz;
220 return array('orig_id' => $origId,
221 'orig_url' => $origUrl,
223 'options' => $options);
228 * Pull relevant info out of a Yammer data record for a group import.
233 function prepGroup($item)
235 if ($item['type'] != 'group') {
236 throw new Exception('Wrong item type sent to Yammer group import processing.');
239 $origId = $item['id'];
240 $origUrl = $item['url'];
242 $privacy = $item['privacy']; // Warning! only public groups in SN so far
244 $options['nickname'] = $item['name'];
245 $options['fullname'] = $item['full_name'];
246 $options['description'] = $item['description'];
247 $options['created'] = $this->timestamp($item['created_at']);
249 $avatar = $item['mugshot_url']; // as with user profiles...
252 $options['mainpage'] = common_local_url('showgroup',
253 array('nickname' => $options['nickname']));
255 // @fixme what about admin user for the group?
256 // bio? homepage etc? aliases?
258 $options['local'] = true;
259 return array('orig_id' => $origId,
260 'orig_url' => $origUrl,
261 'options' => $options,
262 'avatar' => $avatar);
266 * Pull relevant info out of a Yammer data record for a notice import.
271 function prepNotice($item)
273 if (isset($item['type']) && $item['type'] != 'message') {
274 throw new Exception('Wrong item type sent to Yammer message import processing.');
277 $origId = $item['id'];
278 $origUrl = $item['url'];
280 $profile = $this->findImportedUser($item['sender_id']);
281 $content = $item['body']['plain'];
285 if ($item['replied_to_id']) {
286 $replyTo = $this->findImportedNotice($item['replied_to_id']);
288 $options['reply_to'] = $replyTo;
291 $options['created'] = $this->timestamp($item['created_at']);
293 if ($item['group_id']) {
294 $groupId = $this->findImportedGroup($item['group_id']);
296 $options['groups'] = array($groupId);
298 // @fixme if we see a group link inline, don't add this?
299 $group = User_group::staticGet('id', $groupId);
301 $content .= ' !' . $group->nickname;
307 foreach ($item['liked_by']['names'] as $liker) {
308 // "permalink" is the username. wtf?
309 $faves[] = $liker['permalink'];
312 $attachments = array();
313 foreach ($item['attachments'] as $attach) {
314 if ($attach['type'] == 'image' || $attach['type'] == 'file') {
315 $attachments[] = $attach[$attach['type']]['url'];
317 common_log(LOG_WARNING, "Unrecognized Yammer attachment type: " . $attach['type']);
321 return array('orig_id' => $origId,
322 'orig_url' => $origUrl,
323 'profile' => $profile,
324 'content' => $content,
326 'options' => $options,
328 'attachments' => $attachments);
331 private function findImportedUser($origId)
333 if (isset($this->users[$origId])) {
334 return $this->users[$origId];
340 private function findImportedGroup($origId)
342 if (isset($this->groups[$origId])) {
343 return $this->groups[$origId];
349 private function findImportedNotice($origId)
351 if (isset($this->notices[$origId])) {
352 return $this->notices[$origId];
358 private function recordImportedUser($origId, $userId)
360 $this->users[$origId] = $userId;
363 private function recordImportedGroup($origId, $groupId)
365 $this->groups[$origId] = $groupId;
368 private function recordImportedNotice($origId, $noticeId)
370 $this->notices[$origId] = $noticeId;
374 * Normalize timestamp format.
378 private function timestamp($ts)
380 return common_sql_date(strtotime($ts));
383 private function timezone($tz)
386 $known = array('Pacific Time (US & Canada)' => 'America/Los_Angeles',
387 'Eastern Time (US & Canada)' => 'America/New_York');
388 if (array_key_exists($known, $tz)) {
396 * Download and update given avatar image
399 * @param mixed $dest either a Profile or User_group object
400 * @throws Exception in various failure cases
402 private function saveAvatar($url, $dest)
404 // Yammer API data mostly gives us the small variant.
405 // Try hitting the source image if we can!
406 // @fixme no guarantee of this URL scheme I think.
407 $url = preg_replace('/_small(\..*?)$/', '$1', $url);
409 if (!common_valid_http_url($url)) {
410 throw new ServerException(sprintf(_m("Invalid avatar URL %s."), $url));
413 // @fixme this should be better encapsulated
414 // ripped from oauthstore.php (for old OMB client)
415 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
416 if (!copy($url, $temp_filename)) {
417 throw new ServerException(sprintf(_m("Unable to fetch avatar from %s."), $url));
421 // @fixme should we be using different ids?
422 $imagefile = new ImageFile($id, $temp_filename);
423 $filename = Avatar::filename($id,
424 image_type_to_extension($imagefile->type),
427 rename($temp_filename, Avatar::path($filename));
428 // @fixme hardcoded chmod is lame, but seems to be necessary to
429 // keep from accidentally saving images from command-line (queues)
430 // that can't be read from web server, which causes hard-to-notice
431 // problems later on:
433 // http://status.net/open-source/issues/2663
434 chmod(Avatar::path($filename), 0644);
436 $dest->setOriginal($filename);
440 * Fetch an attachment from Yammer and save it into our system.
441 * Unlike avatars, the attachment URLs are guarded by authentication,
442 * so we need to run the HTTP hit through our OAuth API client.
448 * @throws Exception on low-level network or HTTP error
450 private function saveAttachment($url, User $user)
452 // Fetch the attachment...
453 // WARNING: file must fit in memory here :(
454 $body = $this->client->fetchUrl($url);
456 // Save to a temporary file and shove it into our file-attachment space...
458 fwrite($temp, $body);
460 $upload = MediaFile::fromFileHandle($temp, $user);
463 } catch (Exception $e) {