replace all tabs with four spaces

The PEAR coding standards decree: no tabs, but indent by four spaces.
I've done a global search-and-replace on all tabs, replacing them by
four spaces. This is a huge change, but it will go a long way to
getting us towards phpcs-compliance. And that means better code
readability, and that means more participation.

darcs-hash:20081223191907-84dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz
This commit is contained in:
Evan Prodromou 2008-12-23 14:19:07 -05:00
parent 17ece0777b
commit edbc0c665c
273 changed files with 53858 additions and 25794 deletions

View File

@ -49,4 +49,14 @@ Evan Prodromou <evan@prodromou.name>**20081223173330]
[bring lib/noticelist.php into line with PEAR code standards [bring lib/noticelist.php into line with PEAR code standards
Evan Prodromou <evan@prodromou.name>**20081223190851] Evan Prodromou <evan@prodromou.name>**20081223190851]
[incorrect label on notice list file comment [incorrect label on notice list file comment
Evan Prodromou <evan@prodromou.name>**20081223191430] Evan Prodromou <evan@prodromou.name>**20081223191430]
[replace all tabs with four spaces
Evan Prodromou <evan@prodromou.name>**20081223191907
The PEAR coding standards decree: no tabs, but indent by four spaces.
I've done a global search-and-replace on all tabs, replacing them by
four spaces. This is a huge change, but it will go a long way to
getting us towards phpcs-compliance. And that means better code
readability, and that means more participation.
]

View File

@ -22,21 +22,21 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/omb.php'); require_once(INSTALLDIR.'/lib/omb.php');
class AccesstokenAction extends Action { class AccesstokenAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
try { try {
common_debug('getting request from env variables', __FILE__); common_debug('getting request from env variables', __FILE__);
common_remove_magic_from_request(); common_remove_magic_from_request();
$req = OAuthRequest::from_request(); $req = OAuthRequest::from_request();
common_debug('getting a server', __FILE__); common_debug('getting a server', __FILE__);
$server = omb_oauth_server(); $server = omb_oauth_server();
common_debug('fetching the access token', __FILE__); common_debug('fetching the access token', __FILE__);
$token = $server->fetch_access_token($req); $token = $server->fetch_access_token($req);
common_debug('got this token: "'.print_r($token,TRUE).'"', __FILE__); common_debug('got this token: "'.print_r($token,TRUE).'"', __FILE__);
common_debug('printing the access token', __FILE__); common_debug('printing the access token', __FILE__);
print $token; print $token;
} catch (OAuthException $e) { } catch (OAuthException $e) {
common_server_error($e->getMessage()); common_server_error($e->getMessage());
} }
} }
} }

View File

@ -23,71 +23,71 @@ require_once(INSTALLDIR.'/actions/showstream.php');
class AllAction extends StreamAction { class AllAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname = common_canonical_nickname($this->arg('nickname')); $nickname = common_canonical_nickname($this->arg('nickname'));
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
$this->client_error(_('No such user.')); $this->client_error(_('No such user.'));
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.')); common_server_error(_('User has no profile.'));
return; return;
} }
# Looks like we're good; show the header # Looks like we're good; show the header
common_show_header(sprintf(_("%s and friends"), $profile->nickname), common_show_header(sprintf(_("%s and friends"), $profile->nickname),
array($this, 'show_header'), $user, array($this, 'show_header'), $user,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_notices($user); $this->show_notices($user);
common_show_footer(); common_show_footer();
} }
function show_header($user) { function show_header($user) {
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('allrss', array('nickname' => 'href' => common_local_url('allrss', array('nickname' =>
$user->nickname)), $user->nickname)),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => sprintf(_('Feed for friends of %s'), $user->nickname))); 'title' => sprintf(_('Feed for friends of %s'), $user->nickname)));
} }
function show_top($user) { function show_top($user) {
$cur = common_current_user(); $cur = common_current_user();
if ($cur && $cur->id == $user->id) { if ($cur && $cur->id == $user->id) {
common_notice_form('all'); common_notice_form('all');
} }
$this->views_menu(); $this->views_menu();
$this->show_feeds_list(array(0=>array('href'=>common_local_url('allrss', array('nickname' => $user->nickname)), $this->show_feeds_list(array(0=>array('href'=>common_local_url('allrss', array('nickname' => $user->nickname)),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'allrss'))); 'item' => 'allrss')));
} }
function show_notices($user) { function show_notices($user) {
$page = $this->trimmed('page'); $page = $this->trimmed('page');
if (!$page) { if (!$page) {
$page = 1; $page = 1;
} }
$notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1);
$cnt = $this->show_notice_list($notice); $cnt = $this->show_notice_list($notice);
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'all', array('nickname' => $user->nickname)); $page, 'all', array('nickname' => $user->nickname));
} }
} }

View File

@ -25,53 +25,53 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class AllrssAction extends Rss10Action { class AllrssAction extends Rss10Action {
var $user = NULL; var $user = NULL;
function init() { function init() {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$this->user = User::staticGet('nickname', $nickname); $this->user = User::staticGet('nickname', $nickname);
if (!$this->user) { if (!$this->user) {
common_user_error(_('No such user.')); common_user_error(_('No such user.'));
return false; return false;
} else { } else {
return true; return true;
} }
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$user = $this->user; $user = $this->user;
$notice = $user->noticesWithFriends(0, $limit); $notice = $user->noticesWithFriends(0, $limit);
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
$user = $this->user; $user = $this->user;
$c = array('url' => common_local_url('allrss', $c = array('url' => common_local_url('allrss',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'title' => sprintf(_('%s and friends'), $user->nickname), 'title' => sprintf(_('%s and friends'), $user->nickname),
'link' => common_local_url('all', 'link' => common_local_url('all',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'description' => sprintf(_('Feed for friends of %s'), $user->nickname)); 'description' => sprintf(_('Feed for friends of %s'), $user->nickname));
return $c; return $c;
} }
function get_image() { function get_image() {
$user = $this->user; $user = $this->user;
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
return NULL; return NULL;
} }
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
return ($avatar) ? $avatar->url : NULL; return ($avatar) ? $avatar->url : NULL;
} }
} }

View File

@ -10,115 +10,115 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
class ApiAction extends Action { class ApiAction extends Action {
var $user; var $user;
var $content_type; var $content_type;
var $api_arg; var $api_arg;
var $api_method; var $api_method;
var $api_action; var $api_action;
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$this->api_action = $this->arg('apiaction'); $this->api_action = $this->arg('apiaction');
$method = $this->arg('method'); $method = $this->arg('method');
$argument = $this->arg('argument'); $argument = $this->arg('argument');
if (isset($argument)) { if (isset($argument)) {
$cmdext = explode('.', $argument); $cmdext = explode('.', $argument);
$this->api_arg = $cmdext[0]; $this->api_arg = $cmdext[0];
$this->api_method = $method; $this->api_method = $method;
$this->content_type = strtolower($cmdext[1]); $this->content_type = strtolower($cmdext[1]);
} else { } else {
# Requested format / content-type will be an extension on the method # Requested format / content-type will be an extension on the method
$cmdext = explode('.', $method); $cmdext = explode('.', $method);
$this->api_method = $cmdext[0]; $this->api_method = $cmdext[0];
$this->content_type = strtolower($cmdext[1]); $this->content_type = strtolower($cmdext[1]);
} }
if ($this->requires_auth()) { if ($this->requires_auth()) {
if (!isset($_SERVER['PHP_AUTH_USER'])) { if (!isset($_SERVER['PHP_AUTH_USER'])) {
# This header makes basic auth go # This header makes basic auth go
header('WWW-Authenticate: Basic realm="Laconica API"'); header('WWW-Authenticate: Basic realm="Laconica API"');
# If the user hits cancel -- bam! # If the user hits cancel -- bam!
$this->show_basic_auth_error(); $this->show_basic_auth_error();
} else { } else {
$nickname = $_SERVER['PHP_AUTH_USER']; $nickname = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW']; $password = $_SERVER['PHP_AUTH_PW'];
$user = common_check_user($nickname, $password); $user = common_check_user($nickname, $password);
if ($user) { if ($user) {
$this->user = $user; $this->user = $user;
$this->process_command(); $this->process_command();
} else { } else {
# basic authentication failed # basic authentication failed
$this->show_basic_auth_error(); $this->show_basic_auth_error();
} }
} }
} else { } else {
# Look for the user in the session # Look for the user in the session
if (common_logged_in()) { if (common_logged_in()) {
$this->user = common_current_user(); $this->user = common_current_user();
} }
$this->process_command(); $this->process_command();
} }
} }
function process_command() { function process_command() {
$action = "twitapi$this->api_action"; $action = "twitapi$this->api_action";
$actionfile = INSTALLDIR."/actions/$action.php"; $actionfile = INSTALLDIR."/actions/$action.php";
if (file_exists($actionfile)) { if (file_exists($actionfile)) {
require_once($actionfile); require_once($actionfile);
$action_class = ucfirst($action)."Action"; $action_class = ucfirst($action)."Action";
$action_obj = new $action_class(); $action_obj = new $action_class();
if (!$action_obj->prepare($this->args)) { if (!$action_obj->prepare($this->args)) {
return; return;
} }
if (method_exists($action_obj, $this->api_method)) { if (method_exists($action_obj, $this->api_method)) {
$apidata = array( 'content-type' => $this->content_type, $apidata = array( 'content-type' => $this->content_type,
'api_method' => $this->api_method, 'api_method' => $this->api_method,
'api_arg' => $this->api_arg, 'api_arg' => $this->api_arg,
'user' => $this->user); 'user' => $this->user);
call_user_func(array($action_obj, $this->api_method), $_REQUEST, $apidata); call_user_func(array($action_obj, $this->api_method), $_REQUEST, $apidata);
} else { } else {
common_user_error("API method not found!", $code=404); common_user_error("API method not found!", $code=404);
} }
} else { } else {
common_user_error("API method not found!", $code=404); common_user_error("API method not found!", $code=404);
} }
} }
# Whitelist of API methods that don't need authentication # Whitelist of API methods that don't need authentication
function requires_auth() { function requires_auth() {
static $noauth = array( 'statuses/public_timeline', static $noauth = array( 'statuses/public_timeline',
'statuses/show', 'statuses/show',
'users/show', 'users/show',
'help/test', 'help/test',
'help/downtime_schedule'); 'help/downtime_schedule');
static $bareauth = array('statuses/user_timeline', static $bareauth = array('statuses/user_timeline',
'statuses/friends', 'statuses/friends',
'statuses/followers', 'statuses/followers',
'favorites/favorites'); 'favorites/favorites');
# If the site is "private", all API methods need authentication # If the site is "private", all API methods need authentication
@ -126,71 +126,71 @@ class ApiAction extends Action {
return true; return true;
} }
$fullname = "$this->api_action/$this->api_method"; $fullname = "$this->api_action/$this->api_method";
if (in_array($fullname, $bareauth)) { if (in_array($fullname, $bareauth)) {
# bareauth: only needs auth if without an argument # bareauth: only needs auth if without an argument
if ($this->api_arg) { if ($this->api_arg) {
return false; return false;
} else { } else {
return true; return true;
} }
} else if (in_array($fullname, $noauth)) { } else if (in_array($fullname, $noauth)) {
# noauth: never needs auth # noauth: never needs auth
return false; return false;
} else { } else {
# everybody else needs auth # everybody else needs auth
return true; return true;
} }
} }
function show_basic_auth_error() { function show_basic_auth_error() {
header('HTTP/1.1 401 Unauthorized'); header('HTTP/1.1 401 Unauthorized');
$msg = 'Could not authenticate you.'; $msg = 'Could not authenticate you.';
if ($this->content_type == 'xml') { if ($this->content_type == 'xml') {
header('Content-Type: application/xml; charset=utf-8'); header('Content-Type: application/xml; charset=utf-8');
common_start_xml(); common_start_xml();
common_element_start('hash'); common_element_start('hash');
common_element('error', NULL, $msg); common_element('error', NULL, $msg);
common_element('request', NULL, $_SERVER['REQUEST_URI']); common_element('request', NULL, $_SERVER['REQUEST_URI']);
common_element_end('hash'); common_element_end('hash');
common_end_xml(); common_end_xml();
} else if ($this->content_type == 'json') { } else if ($this->content_type == 'json') {
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
$error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
print(json_encode($error_array)); print(json_encode($error_array));
} else { } else {
header('Content-type: text/plain'); header('Content-type: text/plain');
print "$msg\n"; print "$msg\n";
} }
} }
function is_readonly() { function is_readonly() {
# NOTE: before handle(), can't use $this->arg # NOTE: before handle(), can't use $this->arg
$apiaction = $_REQUEST['apiaction']; $apiaction = $_REQUEST['apiaction'];
$method = $_REQUEST['method']; $method = $_REQUEST['method'];
list($cmdtext, $fmt) = explode('.', $method); list($cmdtext, $fmt) = explode('.', $method);
static $write_methods = array( static $write_methods = array(
'account' => array('update_location', 'update_delivery_device', 'end_session'), 'account' => array('update_location', 'update_delivery_device', 'end_session'),
'blocks' => array('create', 'destroy'), 'blocks' => array('create', 'destroy'),
'direct_messages' => array('create', 'destroy'), 'direct_messages' => array('create', 'destroy'),
'favorites' => array('create', 'destroy'), 'favorites' => array('create', 'destroy'),
'friendships' => array('create', 'destroy'), 'friendships' => array('create', 'destroy'),
'help' => array(), 'help' => array(),
'notifications' => array('follow', 'leave'), 'notifications' => array('follow', 'leave'),
'statuses' => array('update', 'destroy'), 'statuses' => array('update', 'destroy'),
'users' => array() 'users' => array()
); );
if (array_key_exists($apiaction, $write_methods)) { if (array_key_exists($apiaction, $write_methods)) {
if (!in_array($cmdtext, $write_methods[$apiaction])) { if (!in_array($cmdtext, $write_methods[$apiaction])) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@ -24,45 +24,45 @@ class AvatarbynicknameAction extends Action {
parent::handle($args); parent::handle($args);
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
if (!$nickname) { if (!$nickname) {
$this->client_error(_('No nickname.')); $this->client_error(_('No nickname.'));
return; return;
} }
$size = $this->trimmed('size'); $size = $this->trimmed('size');
if (!$size) { if (!$size) {
$this->client_error(_('No size.')); $this->client_error(_('No size.'));
return; return;
} }
$size = strtolower($size); $size = strtolower($size);
if (!in_array($size, array('original', '96', '48', '24'))) { if (!in_array($size, array('original', '96', '48', '24'))) {
$this->client_error(_('Invalid size.')); $this->client_error(_('Invalid size.'));
return; return;
} }
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
$this->client_error(_('No such user.')); $this->client_error(_('No such user.'));
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
$this->client_error(_('User has no profile.')); $this->client_error(_('User has no profile.'));
return; return;
} }
if ($size == 'original') { if ($size == 'original') {
$avatar = $profile->getOriginal(); $avatar = $profile->getOriginal();
} else { } else {
$avatar = $profile->getAvatar($size+0); $avatar = $profile->getAvatar($size+0);
} }
if ($avatar) { if ($avatar) {
$url = $avatar->url; $url = $avatar->url;
} else { } else {
if ($size == 'original') { if ($size == 'original') {
$url = common_default_avatar(AVATAR_PROFILE_SIZE); $url = common_default_avatar(AVATAR_PROFILE_SIZE);
} else { } else {
$url = common_default_avatar($size+0); $url = common_default_avatar($size+0);
} }
} }
common_redirect($url, 302); common_redirect($url, 302);
} }
} }

View File

@ -32,12 +32,12 @@ class BlockAction extends Action {
return false; return false;
} }
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$id = $this->trimmed('blockto'); $id = $this->trimmed('blockto');
@ -75,7 +75,7 @@ class BlockAction extends Action {
$id = $this->profile->id; $id = $this->profile->id;
common_show_header(_('Block user')); common_show_header(_('Block user'));
common_element('p', NULL, common_element('p', NULL,
_('Are you sure you want to block this user? '. _('Are you sure you want to block this user? '.

View File

@ -43,44 +43,44 @@ class ConfirmaddressAction extends Action {
$this->client_error(_('That confirmation code is not for you!')); $this->client_error(_('That confirmation code is not for you!'));
return; return;
} }
$type = $confirm->address_type; $type = $confirm->address_type;
if (!in_array($type, array('email', 'jabber', 'sms'))) { if (!in_array($type, array('email', 'jabber', 'sms'))) {
$this->server_error(sprintf(_('Unrecognized address type %s'), $type)); $this->server_error(sprintf(_('Unrecognized address type %s'), $type));
return; return;
} }
if ($cur->$type == $confirm->address) { if ($cur->$type == $confirm->address) {
$this->client_error(_('That address has already been confirmed.')); $this->client_error(_('That address has already been confirmed.'));
return; return;
} }
$cur->query('BEGIN'); $cur->query('BEGIN');
$orig_user = clone($cur); $orig_user = clone($cur);
$cur->$type = $confirm->address; $cur->$type = $confirm->address;
if ($type == 'sms') { if ($type == 'sms') {
$cur->carrier = ($confirm->address_extra)+0; $cur->carrier = ($confirm->address_extra)+0;
$carrier = Sms_carrier::staticGet($cur->carrier); $carrier = Sms_carrier::staticGet($cur->carrier);
$cur->smsemail = $carrier->toEmailAddress($cur->sms); $cur->smsemail = $carrier->toEmailAddress($cur->sms);
} }
$result = $cur->updateKeys($orig_user); $result = $cur->updateKeys($orig_user);
if (!$result) { if (!$result) {
common_log_db_error($cur, 'UPDATE', __FILE__); common_log_db_error($cur, 'UPDATE', __FILE__);
$this->server_error(_('Couldn\'t update user.')); $this->server_error(_('Couldn\'t update user.'));
return; return;
} }
if ($type == 'email') { if ($type == 'email') {
$cur->emailChanged(); $cur->emailChanged();
} }
$result = $confirm->delete(); $result = $confirm->delete();
if (!$result) { if (!$result) {
common_log_db_error($confirm, 'DELETE', __FILE__); common_log_db_error($confirm, 'DELETE', __FILE__);
$this->server_error(_('Couldn\'t delete email confirmation.')); $this->server_error(_('Couldn\'t delete email confirmation.'));
return; return;
} }

View File

@ -22,80 +22,80 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/deleteaction.php'); require_once(INSTALLDIR.'/lib/deleteaction.php');
class DeletenoticeAction extends DeleteAction { class DeletenoticeAction extends DeleteAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
# XXX: Ajax! # XXX: Ajax!
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->delete_notice(); $this->delete_notice();
} else if ($_SERVER['REQUEST_METHOD'] == 'GET') { } else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$this->show_form(); $this->show_form();
} }
} }
function get_instructions() { function get_instructions() {
return _('You are about to permanently delete a notice. Once this is done, it cannot be undone.'); return _('You are about to permanently delete a notice. Once this is done, it cannot be undone.');
} }
function get_title() { function get_title() {
return _('Delete notice'); return _('Delete notice');
} }
function show_form($error=NULL) { function show_form($error=NULL) {
$user = common_current_user(); $user = common_current_user();
common_show_header($this->get_title(), array($this, 'show_header'), $error, common_show_header($this->get_title(), array($this, 'show_header'), $error,
array($this, 'show_top')); array($this, 'show_top'));
common_element_start('form', array('id' => 'notice_delete_form', common_element_start('form', array('id' => 'notice_delete_form',
'method' => 'post', 'method' => 'post',
'action' => common_local_url('deletenotice'))); 'action' => common_local_url('deletenotice')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_hidden('notice', $this->trimmed('notice')); common_hidden('notice', $this->trimmed('notice'));
common_element_start('p'); common_element_start('p');
common_element('span', array('id' => 'confirmation_text'), _('Are you sure you want to delete this notice?')); common_element('span', array('id' => 'confirmation_text'), _('Are you sure you want to delete this notice?'));
common_element('input', array('id' => 'submit_no', common_element('input', array('id' => 'submit_no',
'name' => 'submit', 'name' => 'submit',
'type' => 'submit', 'type' => 'submit',
'value' => _('No'))); 'value' => _('No')));
common_element('input', array('id' => 'submit_yes', common_element('input', array('id' => 'submit_yes',
'name' => 'submit', 'name' => 'submit',
'type' => 'submit', 'type' => 'submit',
'value' => _('Yes'))); 'value' => _('Yes')));
common_element_end('p'); common_element_end('p');
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function delete_notice() { function delete_notice() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$url = common_get_returnto(); $url = common_get_returnto();
$confirmed = $this->trimmed('submit'); $confirmed = $this->trimmed('submit');
if ($confirmed == _('Yes')) { if ($confirmed == _('Yes')) {
$user = common_current_user(); $user = common_current_user();
$notice_id = $this->trimmed('notice'); $notice_id = $this->trimmed('notice');
$notice = Notice::staticGet($notice_id); $notice = Notice::staticGet($notice_id);
$replies = new Reply; $replies = new Reply;
$replies->get('notice_id', $notice_id); $replies->get('notice_id', $notice_id);
common_dequeue_notice($notice); common_dequeue_notice($notice);
if (common_config('memcached', 'enabled')) { if (common_config('memcached', 'enabled')) {
$notice->blowSubsCache(); $notice->blowSubsCache();
} }
$replies->delete(); $replies->delete();
$notice->delete(); $notice->delete();
} else { } else {
if ($url) { if ($url) {
common_set_returnto(NULL); common_set_returnto(NULL);
} else { } else {
$url = common_local_url('public'); $url = common_local_url('public');
} }
} }
common_redirect($url); common_redirect($url);
} }
} }

View File

@ -32,101 +32,101 @@ class DeleteprofileAction extends Action {
} }
} }
function get_instructions() { function get_instructions() {
return _('Export and delete your user information.'); return _('Export and delete your user information.');
} }
function form_header($title, $msg=NULL, $success=false) { function form_header($title, $msg=NULL, $success=false) {
common_show_header($title, common_show_header($title,
NULL, NULL,
array($msg, $success), array($msg, $success),
array($this, 'show_top')); array($this, 'show_top'));
} }
function show_feeds_list($feeds) { function show_feeds_list($feeds) {
common_element_start('div', array('class' => 'feedsdel')); common_element_start('div', array('class' => 'feedsdel'));
common_element('p', null, 'Feeds:'); common_element('p', null, 'Feeds:');
common_element_start('ul', array('class' => 'xoxo')); common_element_start('ul', array('class' => 'xoxo'));
foreach ($feeds as $key => $value) { foreach ($feeds as $key => $value) {
$this->common_feed_item($feeds[$key]); $this->common_feed_item($feeds[$key]);
} }
common_element_end('ul'); common_element_end('ul');
common_element_end('div'); common_element_end('div');
} }
//TODO move to common.php (and retrace its origin) //TODO move to common.php (and retrace its origin)
function common_feed_item($feed) { function common_feed_item($feed) {
$user = common_current_user(); $user = common_current_user();
$nickname = $user->nickname; $nickname = $user->nickname;
switch($feed['item']) { switch($feed['item']) {
case 'notices': default: case 'notices': default:
$feed_classname = $feed['type']; $feed_classname = $feed['type'];
$feed_mimetype = "application/".$feed['type']."+xml"; $feed_mimetype = "application/".$feed['type']."+xml";
$feed_title = "$nickname's ".$feed['version']." notice feed"; $feed_title = "$nickname's ".$feed['version']." notice feed";
$feed['textContent'] = "RSS"; $feed['textContent'] = "RSS";
break; break;
case 'foaf': case 'foaf':
$feed_classname = "foaf"; $feed_classname = "foaf";
$feed_mimetype = "application/".$feed['type']."+xml"; $feed_mimetype = "application/".$feed['type']."+xml";
$feed_title = "$nickname's FOAF file"; $feed_title = "$nickname's FOAF file";
$feed['textContent'] = "FOAF"; $feed['textContent'] = "FOAF";
break; break;
} }
common_element_start('li'); common_element_start('li');
common_element('a', array('href' => $feed['href'], common_element('a', array('href' => $feed['href'],
'class' => $feed_classname, 'class' => $feed_classname,
'type' => $feed_mimetype, 'type' => $feed_mimetype,
'title' => $feed_title), 'title' => $feed_title),
$feed['textContent']); $feed['textContent']);
common_element_end('li'); common_element_end('li');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$this->form_header(_('Delete my account'), $msg, $success); $this->form_header(_('Delete my account'), $msg, $success);
common_element('h2', NULL, _('Delete my account confirmation')); common_element('h2', NULL, _('Delete my account confirmation'));
$this->show_confirm_delete_form(); $this->show_confirm_delete_form();
common_show_footer(); common_show_footer();
} }
function show_confirm_delete_form() { function show_confirm_delete_form() {
$user = common_current_user(); $user = common_current_user();
$notices = DB_DataObject::factory('notice'); $notices = DB_DataObject::factory('notice');
$notices->profile_id = $user->id; $notices->profile_id = $user->id;
$notice_count = (int) $notices->count(); $notice_count = (int) $notices->count();
common_element_start('form', array('method' => 'POST', common_element_start('form', array('method' => 'POST',
'id' => 'delete', 'id' => 'delete',
'action' => 'action' =>
common_local_url('deleteprofile'))); common_local_url('deleteprofile')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('p', null, "Last chance to copy your notices and contacts by saving the two links below before deleting your account. Be careful, this operation cannot be undone."); common_element('p', null, "Last chance to copy your notices and contacts by saving the two links below before deleting your account. Be careful, this operation cannot be undone.");
$this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)), $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'notices'), 'item' => 'notices'),
1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)),
'type' => 'rdf', 'type' => 'rdf',
'version' => 'FOAF', 'version' => 'FOAF',
'item' => 'foaf'))); 'item' => 'foaf')));
common_checkbox('confirmation', _('Check if you are sure you want to delete your account.')); common_checkbox('confirmation', _('Check if you are sure you want to delete your account.'));
common_submit('deleteaccount', _('Delete my account')); common_submit('deleteaccount', _('Delete my account'));
common_element_end('form'); common_element_end('form');
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('deleteaccount') && $this->arg('confirmation')) { if ($this->arg('deleteaccount') && $this->arg('confirmation')) {
$this->delete_account(); $this->delete_account();
@ -134,9 +134,9 @@ class DeleteprofileAction extends Action {
$this->show_form(); $this->show_form();
} }
function delete_account() { function delete_account() {
$user = common_current_user(); $user = common_current_user();
assert(!is_null($user)); # should already be checked assert(!is_null($user)); # should already be checked
// deleted later through the profile // deleted later through the profile
/* /*
@ -219,53 +219,53 @@ class DeleteprofileAction extends Action {
common_redirect(common_local_url('public')); common_redirect(common_local_url('public'));
} }
function show_top($arr) { function show_top($arr) {
$msg = $arr[0]; $msg = $arr[0];
$success = $arr[1]; $success = $arr[1];
if ($msg) { if ($msg) {
$this->message($msg, $success); $this->message($msg, $success);
} else { } else {
$inst = $this->get_instructions(); $inst = $this->get_instructions();
$output = common_markup_to_html($inst); $output = common_markup_to_html($inst);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
} }
$this->settings_menu(); $this->settings_menu();
} }
function settings_menu() { function settings_menu() {
# action => array('prompt', 'title') # action => array('prompt', 'title')
$menu = $menu =
array('profilesettings' => array('profilesettings' =>
array(_('Profile'), array(_('Profile'),
_('Change your profile settings')), _('Change your profile settings')),
'emailsettings' => 'emailsettings' =>
array(_('Email'), array(_('Email'),
_('Change email handling')), _('Change email handling')),
'openidsettings' => 'openidsettings' =>
array(_('OpenID'), array(_('OpenID'),
_('Add or remove OpenIDs')), _('Add or remove OpenIDs')),
'smssettings' => 'smssettings' =>
array(_('SMS'), array(_('SMS'),
_('Updates by SMS')), _('Updates by SMS')),
'imsettings' => 'imsettings' =>
array(_('IM'), array(_('IM'),
_('Updates by instant messenger (IM)')), _('Updates by instant messenger (IM)')),
'twittersettings' => 'twittersettings' =>
array(_('Twitter'), array(_('Twitter'),
_('Twitter integration options')), _('Twitter integration options')),
'othersettings' => 'othersettings' =>
array(_('Other'), array(_('Other'),
_('Other options'))); _('Other options')));
$action = $this->trimmed('action'); $action = $this->trimmed('action');
common_element_start('ul', array('id' => 'nav_views')); common_element_start('ul', array('id' => 'nav_views'));
foreach ($menu as $menuaction => $menudesc) { foreach ($menu as $menuaction => $menudesc) {
if ($menuaction == 'imsettings' && if ($menuaction == 'imsettings' &&
!common_config('xmpp', 'enabled')) { !common_config('xmpp', 'enabled')) {
continue; continue;
} }
common_menu_item(common_local_url($menuaction), common_menu_item(common_local_url($menuaction),
$menudesc[0], $menudesc[0],
$menudesc[1], $menudesc[1],

View File

@ -21,63 +21,63 @@ if (!defined('LACONICA')) { exit(1); }
class DisfavorAction extends Action { class DisfavorAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname))); common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname)));
return; return;
} }
$id = $this->trimmed('notice'); $id = $this->trimmed('notice');
$notice = Notice::staticGet($id); $notice = Notice::staticGet($id);
$token = $this->trimmed('token-'.$notice->id); $token = $this->trimmed('token-'.$notice->id);
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_("There was a problem with your session token. Try again, please.")); $this->client_error(_("There was a problem with your session token. Try again, please."));
return; return;
} }
$fave = new Fave(); $fave = new Fave();
$fave->user_id = $this->id; $fave->user_id = $this->id;
$fave->notice_id = $notice->id; $fave->notice_id = $notice->id;
if (!$fave->find(true)) { if (!$fave->find(true)) {
$this->client_error(_('This notice is not a favorite!')); $this->client_error(_('This notice is not a favorite!'));
return; return;
} }
$result = $fave->delete(); $result = $fave->delete();
if (!$result) { if (!$result) {
common_log_db_error($fave, 'DELETE', __FILE__); common_log_db_error($fave, 'DELETE', __FILE__);
$this->server_error(_('Could not delete favorite.')); $this->server_error(_('Could not delete favorite.'));
return; return;
} }
$user->blowFavesCache(); $user->blowFavesCache();
if ($this->boolean('ajax')) { if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Add to favorites')); common_element('title', null, _('Add to favorites'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
common_favor_form($notice); common_favor_form($notice);
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} else { } else {
common_redirect(common_local_url('showfavorites', common_redirect(common_local_url('showfavorites',
array('nickname' => $user->nickname))); array('nickname' => $user->nickname)));
} }
} }
} }

View File

@ -21,18 +21,18 @@ if (!defined('LACONICA')) { exit(1); }
class DocAction extends Action { class DocAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$title = $this->trimmed('title'); $title = $this->trimmed('title');
$filename = INSTALLDIR.'/doc/'.$title; $filename = INSTALLDIR.'/doc/'.$title;
if (!file_exists($filename)) { if (!file_exists($filename)) {
common_user_error(_('No such document.')); common_user_error(_('No such document.'));
return; return;
} }
$c = file_get_contents($filename); $c = file_get_contents($filename);
$output = common_markup_to_html($c); $output = common_markup_to_html($c);
common_show_header(_(ucfirst($title))); common_show_header(_(ucfirst($title)));
common_raw($output); common_raw($output);
common_show_footer(); common_show_footer();
} }
} }

View File

@ -23,308 +23,308 @@ require_once(INSTALLDIR.'/lib/settingsaction.php');
class EmailsettingsAction extends SettingsAction { class EmailsettingsAction extends SettingsAction {
function get_instructions() { function get_instructions() {
return _('Manage how you get email from %%site.name%%.'); return _('Manage how you get email from %%site.name%%.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$user = common_current_user(); $user = common_current_user();
$this->form_header(_('Email Settings'), $msg, $success); $this->form_header(_('Email Settings'), $msg, $success);
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'emailsettings', 'id' => 'emailsettings',
'action' => 'action' =>
common_local_url('emailsettings'))); common_local_url('emailsettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('h2', NULL, _('Address')); common_element('h2', NULL, _('Address'));
if ($user->email) { if ($user->email) {
common_element_start('p'); common_element_start('p');
common_element('span', 'address confirmed', $user->email); common_element('span', 'address confirmed', $user->email);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Current confirmed email address.')); _('Current confirmed email address.'));
common_hidden('email', $user->email); common_hidden('email', $user->email);
common_element_end('p'); common_element_end('p');
common_submit('remove', _('Remove')); common_submit('remove', _('Remove'));
} else { } else {
$confirm = $this->get_confirmation(); $confirm = $this->get_confirmation();
if ($confirm) { if ($confirm) {
common_element_start('p'); common_element_start('p');
common_element('span', 'address unconfirmed', $confirm->address); common_element('span', 'address unconfirmed', $confirm->address);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Awaiting confirmation on this address. Check your inbox (and spam box!) for a message with further instructions.')); _('Awaiting confirmation on this address. Check your inbox (and spam box!) for a message with further instructions.'));
common_hidden('email', $confirm->address); common_hidden('email', $confirm->address);
common_element_end('p'); common_element_end('p');
common_submit('cancel', _('Cancel')); common_submit('cancel', _('Cancel'));
} else { } else {
common_input('email', _('Email Address'), common_input('email', _('Email Address'),
($this->arg('email')) ? $this->arg('email') : NULL, ($this->arg('email')) ? $this->arg('email') : NULL,
_('Email address, like "UserName@example.org"')); _('Email address, like "UserName@example.org"'));
common_submit('add', _('Add')); common_submit('add', _('Add'));
} }
} }
if ($user->email) { if ($user->email) {
common_element('h2', NULL, _('Incoming email')); common_element('h2', NULL, _('Incoming email'));
if ($user->incomingemail) { if ($user->incomingemail) {
common_element_start('p'); common_element_start('p');
common_element('span', 'address', $user->incomingemail); common_element('span', 'address', $user->incomingemail);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Send email to this address to post new notices.')); _('Send email to this address to post new notices.'));
common_element_end('p'); common_element_end('p');
common_submit('removeincoming', _('Remove')); common_submit('removeincoming', _('Remove'));
} }
common_element_start('p'); common_element_start('p');
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Make a new email address for posting to; cancels the old one.')); _('Make a new email address for posting to; cancels the old one.'));
common_element_end('p'); common_element_end('p');
common_submit('newincoming', _('New')); common_submit('newincoming', _('New'));
} }
common_element('h2', NULL, _('Preferences')); common_element('h2', NULL, _('Preferences'));
common_checkbox('emailnotifysub', common_checkbox('emailnotifysub',
_('Send me notices of new subscriptions through email.'), _('Send me notices of new subscriptions through email.'),
$user->emailnotifysub); $user->emailnotifysub);
common_checkbox('emailnotifyfav', common_checkbox('emailnotifyfav',
_('Send me email when someone adds my notice as a favorite.'), _('Send me email when someone adds my notice as a favorite.'),
$user->emailnotifyfav); $user->emailnotifyfav);
common_checkbox('emailnotifymsg', common_checkbox('emailnotifymsg',
_('Send me email when someone sends me a private message.'), _('Send me email when someone sends me a private message.'),
$user->emailnotifymsg); $user->emailnotifymsg);
common_checkbox('emailnotifynudge', common_checkbox('emailnotifynudge',
_('Allow friends to nudge me and send me an email.'), _('Allow friends to nudge me and send me an email.'),
$user->emailnotifynudge); $user->emailnotifynudge);
common_checkbox('emailpost', common_checkbox('emailpost',
_('I want to post notices by email.'), _('I want to post notices by email.'),
$user->emailpost); $user->emailpost);
common_checkbox('emailmicroid', common_checkbox('emailmicroid',
_('Publish a MicroID for my email address.'), _('Publish a MicroID for my email address.'),
$user->emailmicroid); $user->emailmicroid);
common_submit('save', _('Save')); common_submit('save', _('Save'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function get_confirmation() { function get_confirmation() {
$user = common_current_user(); $user = common_current_user();
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->address_type = 'email'; $confirm->address_type = 'email';
if ($confirm->find(TRUE)) { if ($confirm->find(TRUE)) {
return $confirm; return $confirm;
} else { } else {
return NULL; return NULL;
} }
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('save')) { if ($this->arg('save')) {
$this->save_preferences(); $this->save_preferences();
} else if ($this->arg('add')) { } else if ($this->arg('add')) {
$this->add_address(); $this->add_address();
} else if ($this->arg('cancel')) { } else if ($this->arg('cancel')) {
$this->cancel_confirmation(); $this->cancel_confirmation();
} else if ($this->arg('remove')) { } else if ($this->arg('remove')) {
$this->remove_address(); $this->remove_address();
} else if ($this->arg('removeincoming')) { } else if ($this->arg('removeincoming')) {
$this->remove_incoming(); $this->remove_incoming();
} else if ($this->arg('newincoming')) { } else if ($this->arg('newincoming')) {
$this->new_incoming(); $this->new_incoming();
} else { } else {
$this->show_form(_('Unexpected form submission.')); $this->show_form(_('Unexpected form submission.'));
} }
} }
function save_preferences() { function save_preferences() {
$emailnotifysub = $this->boolean('emailnotifysub'); $emailnotifysub = $this->boolean('emailnotifysub');
$emailnotifyfav = $this->boolean('emailnotifyfav'); $emailnotifyfav = $this->boolean('emailnotifyfav');
$emailnotifymsg = $this->boolean('emailnotifymsg'); $emailnotifymsg = $this->boolean('emailnotifymsg');
$emailnotifynudge = $this->boolean('emailnotifynudge'); $emailnotifynudge = $this->boolean('emailnotifynudge');
$emailmicroid = $this->boolean('emailmicroid'); $emailmicroid = $this->boolean('emailmicroid');
$emailpost = $this->boolean('emailpost'); $emailpost = $this->boolean('emailpost');
$user = common_current_user(); $user = common_current_user();
assert(!is_null($user)); # should already be checked assert(!is_null($user)); # should already be checked
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->emailnotifysub = $emailnotifysub; $user->emailnotifysub = $emailnotifysub;
$user->emailnotifyfav = $emailnotifyfav; $user->emailnotifyfav = $emailnotifyfav;
$user->emailnotifymsg = $emailnotifymsg; $user->emailnotifymsg = $emailnotifymsg;
$user->emailnotifynudge = $emailnotifynudge; $user->emailnotifynudge = $emailnotifynudge;
$user->emailmicroid = $emailmicroid; $user->emailmicroid = $emailmicroid;
$user->emailpost = $emailpost; $user->emailpost = $emailpost;
$result = $user->update($original); $result = $user->update($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
$this->show_form(_('Preferences saved.'), true); $this->show_form(_('Preferences saved.'), true);
} }
function add_address() { function add_address() {
$user = common_current_user(); $user = common_current_user();
$email = $this->trimmed('email'); $email = $this->trimmed('email');
# Some validation # Some validation
if (!$email) { if (!$email) {
$this->show_form(_('No email address.')); $this->show_form(_('No email address.'));
return; return;
} }
$email = common_canonical_email($email); $email = common_canonical_email($email);
if (!$email) { if (!$email) {
$this->show_form(_('Cannot normalize that email address')); $this->show_form(_('Cannot normalize that email address'));
return; return;
} }
if (!Validate::email($email, true)) { if (!Validate::email($email, true)) {
$this->show_form(_('Not a valid email address')); $this->show_form(_('Not a valid email address'));
return; return;
} else if ($user->email == $email) { } else if ($user->email == $email) {
$this->show_form(_('That is already your email address.')); $this->show_form(_('That is already your email address.'));
return; return;
} else if ($this->email_exists($email)) { } else if ($this->email_exists($email)) {
$this->show_form(_('That email address already belongs to another user.')); $this->show_form(_('That email address already belongs to another user.'));
return; return;
} }
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->address = $email; $confirm->address = $email;
$confirm->address_type = 'email'; $confirm->address_type = 'email';
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->code = common_confirmation_code(64); $confirm->code = common_confirmation_code(64);
$result = $confirm->insert(); $result = $confirm->insert();
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($confirm, 'INSERT', __FILE__); common_log_db_error($confirm, 'INSERT', __FILE__);
common_server_error(_('Couldn\'t insert confirmation code.')); common_server_error(_('Couldn\'t insert confirmation code.'));
return; return;
} }
mail_confirm_address($user, $confirm->code, $user->nickname, $email); mail_confirm_address($user, $confirm->code, $user->nickname, $email);
$msg = _('A confirmation code was sent to the email address you added. Check your inbox (and spam box!) for the code and instructions on how to use it.'); $msg = _('A confirmation code was sent to the email address you added. Check your inbox (and spam box!) for the code and instructions on how to use it.');
$this->show_form($msg, TRUE); $this->show_form($msg, TRUE);
} }
function cancel_confirmation() { function cancel_confirmation() {
$email = $this->arg('email'); $email = $this->arg('email');
$confirm = $this->get_confirmation(); $confirm = $this->get_confirmation();
if (!$confirm) { if (!$confirm) {
$this->show_form(_('No pending confirmation to cancel.')); $this->show_form(_('No pending confirmation to cancel.'));
return; return;
} }
if ($confirm->address != $email) { if ($confirm->address != $email) {
$this->show_form(_('That is the wrong IM address.')); $this->show_form(_('That is the wrong IM address.'));
return; return;
} }
$result = $confirm->delete(); $result = $confirm->delete();
if (!$result) { if (!$result) {
common_log_db_error($confirm, 'DELETE', __FILE__); common_log_db_error($confirm, 'DELETE', __FILE__);
$this->server_error(_('Couldn\'t delete email confirmation.')); $this->server_error(_('Couldn\'t delete email confirmation.'));
return; return;
} }
$this->show_form(_('Confirmation cancelled.'), TRUE); $this->show_form(_('Confirmation cancelled.'), TRUE);
} }
function remove_address() { function remove_address() {
$user = common_current_user(); $user = common_current_user();
$email = $this->arg('email'); $email = $this->arg('email');
# Maybe an old tab open...? # Maybe an old tab open...?
if ($user->email != $email) { if ($user->email != $email) {
$this->show_form(_('That is not your email address.')); $this->show_form(_('That is not your email address.'));
return; return;
} }
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->email = NULL; $user->email = NULL;
$result = $user->updateKeys($original); $result = $user->updateKeys($original);
if (!$result) { if (!$result) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
$this->show_form(_('The address was removed.'), TRUE); $this->show_form(_('The address was removed.'), TRUE);
} }
function remove_incoming() { function remove_incoming() {
$user = common_current_user(); $user = common_current_user();
if (!$user->incomingemail) { if (!$user->incomingemail) {
$this->show_form(_('No incoming email address.')); $this->show_form(_('No incoming email address.'));
return; return;
} }
$orig = clone($user); $orig = clone($user);
$user->incomingemail = NULL; $user->incomingemail = NULL;
if (!$user->updateKeys($orig)) { if (!$user->updateKeys($orig)) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
$this->server_error(_("Couldn't update user record.")); $this->server_error(_("Couldn't update user record."));
} }
$this->show_form(_('Incoming email address removed.'), TRUE); $this->show_form(_('Incoming email address removed.'), TRUE);
} }
function new_incoming() { function new_incoming() {
$user = common_current_user(); $user = common_current_user();
$orig = clone($user); $orig = clone($user);
$user->incomingemail = mail_new_incoming_address(); $user->incomingemail = mail_new_incoming_address();
if (!$user->updateKeys($orig)) { if (!$user->updateKeys($orig)) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
$this->server_error(_("Couldn't update user record.")); $this->server_error(_("Couldn't update user record."));
} }
$this->show_form(_('New incoming email address added.'), TRUE); $this->show_form(_('New incoming email address added.'), TRUE);
} }
function email_exists($email) { function email_exists($email) {
$user = common_current_user(); $user = common_current_user();
$other = User::staticGet('email', $email); $other = User::staticGet('email', $email);
if (!$other) { if (!$other) {
return false; return false;
} else { } else {
return $other->id != $user->id; return $other->id != $user->id;
} }
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,110 +23,110 @@ require_once(INSTALLDIR.'/lib/facebookaction.php');
class FacebookhomeAction extends FacebookAction { class FacebookhomeAction extends FacebookAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$this->login(); $this->login();
} }
function login() { function login() {
$user = null; $user = null;
$facebook = $this->get_facebook(); $facebook = $this->get_facebook();
$fbuid = $facebook->require_login(); $fbuid = $facebook->require_login();
# check to see whether there's already a Facebook link for this user # check to see whether there's already a Facebook link for this user
$flink = Foreign_link::getByForeignID($fbuid, 2); // 2 == Facebook $flink = Foreign_link::getByForeignID($fbuid, 2); // 2 == Facebook
if ($flink) { if ($flink) {
$user = $flink->getUser(); $user = $flink->getUser();
$this->show_home($facebook, $fbuid, $user); $this->show_home($facebook, $fbuid, $user);
} else { } else {
# Make the user put in her Laconica creds # Make the user put in her Laconica creds
$nickname = common_canonical_nickname($this->trimmed('nickname')); $nickname = common_canonical_nickname($this->trimmed('nickname'));
$password = $this->arg('password'); $password = $this->arg('password');
if ($nickname) { if ($nickname) {
if (common_check_user($nickname, $password)) { if (common_check_user($nickname, $password)) {
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
echo '<fb:error message="Coudln\'t get user!" />'; echo '<fb:error message="Coudln\'t get user!" />';
$this->show_login_form(); $this->show_login_form();
} }
$flink = DB_DataObject::factory('foreign_link'); $flink = DB_DataObject::factory('foreign_link');
$flink->user_id = $user->id; $flink->user_id = $user->id;
$flink->foreign_id = $fbuid; $flink->foreign_id = $fbuid;
$flink->service = 2; # Facebook $flink->service = 2; # Facebook
$flink->created = common_sql_now(); $flink->created = common_sql_now();
# $this->set_flags($flink, $noticesync, $replysync, $friendsync); # $this->set_flags($flink, $noticesync, $replysync, $friendsync);
$flink_id = $flink->insert(); $flink_id = $flink->insert();
if ($flink_id) { if ($flink_id) {
echo '<fb:success message="You can now use the Identi.ca from Facebook!" />'; echo '<fb:success message="You can now use the Identi.ca from Facebook!" />';
} }
$this->show_home($facebook, $fbuid, $user); $this->show_home($facebook, $fbuid, $user);
return; return;
} else { } else {
echo '<fb:error message="Incorrect username or password." />'; echo '<fb:error message="Incorrect username or password." />';
} }
} }
$this->show_login_form(); $this->show_login_form();
} }
} }
function show_home($facebook, $fbuid, $user) { function show_home($facebook, $fbuid, $user) {
$this->show_header('Home'); $this->show_header('Home');
echo $this->show_notices($user); echo $this->show_notices($user);
$this->update_profile_box($facebook, $fbuid, $user); $this->update_profile_box($facebook, $fbuid, $user);
$this->show_footer(); $this->show_footer();
} }
function show_notices($user) { function show_notices($user) {
$page = $this->trimmed('page'); $page = $this->trimmed('page');
if (!$page) { if (!$page) {
$page = 1; $page = 1;
} }
$notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1);
echo '<ul id="notices">'; echo '<ul id="notices">';
$cnt = 0; $cnt = 0;
while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) { while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) {
$cnt++; $cnt++;
if ($cnt > NOTICES_PER_PAGE) { if ($cnt > NOTICES_PER_PAGE) {
break; break;
} }
echo $this->render_notice($notice); echo $this->render_notice($notice);
} }
echo '<ul>'; echo '<ul>';
$this->pagination($page > 1, $cnt > NOTICES_PER_PAGE, $this->pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'index.php', array('nickname' => $user->nickname)); $page, 'index.php', array('nickname' => $user->nickname));
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,24 +23,24 @@ require_once(INSTALLDIR.'/lib/facebookaction.php');
class FacebookinviteAction extends FacebookAction { class FacebookinviteAction extends FacebookAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$this->display(); $this->display();
} }
function display() { function display() {
$facebook = $this->get_facebook(); $facebook = $this->get_facebook();
$fbuid = $facebook->require_login(); $fbuid = $facebook->require_login();
$this->show_header('Invite'); $this->show_header('Invite');
echo '<h2>Coming soon...</h2>'; echo '<h2>Coming soon...</h2>';
$this->show_footer(); $this->show_footer();
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,43 +23,43 @@ require_once(INSTALLDIR.'/lib/facebookaction.php');
class FacebookremoveAction extends FacebookAction { class FacebookremoveAction extends FacebookAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$secret = common_config('facebook', 'secret'); $secret = common_config('facebook', 'secret');
$sig = ''; $sig = '';
ksort($_POST); ksort($_POST);
foreach ($_POST as $key => $val) { foreach ($_POST as $key => $val) {
if (substr($key, 0, 7) == 'fb_sig_') { if (substr($key, 0, 7) == 'fb_sig_') {
$sig .= substr($key, 7) . '=' . $val; $sig .= substr($key, 7) . '=' . $val;
} }
} }
$sig .= $secret; $sig .= $secret;
$verify = md5($sig); $verify = md5($sig);
if ($verify == $this->arg('fb_sig')) { if ($verify == $this->arg('fb_sig')) {
$flink = Foreign_link::getByForeignID($this->arg('fb_sig_user'), 2); $flink = Foreign_link::getByForeignID($this->arg('fb_sig_user'), 2);
common_debug("Removing foreign link to Facebook - local user ID: $flink->user_id, Facebook ID: $flink->foreign_id"); common_debug("Removing foreign link to Facebook - local user ID: $flink->user_id, Facebook ID: $flink->foreign_id");
$result = $flink->delete(); $result = $flink->delete();
if (!$result) { if (!$result) {
common_log_db_error($flink, 'DELETE', __FILE__); common_log_db_error($flink, 'DELETE', __FILE__);
common_server_error(_('Couldn\'t remove Facebook user.')); common_server_error(_('Couldn\'t remove Facebook user.'));
return; return;
} }
} else { } else {
# Someone bad tried to remove facebook link? # Someone bad tried to remove facebook link?
common_log(LOG_ERR, "Someone from $_SERVER[REMOTE_ADDR] " . common_log(LOG_ERR, "Someone from $_SERVER[REMOTE_ADDR] " .
'unsuccessfully tried to remove a foreign link to Facebook!'); 'unsuccessfully tried to remove a foreign link to Facebook!');
} }
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/facebookaction.php');
class FacebooksettingsAction extends FacebookAction { class FacebooksettingsAction extends FacebookAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$this->display(); $this->display();
} }
function display() { function display() {
$facebook = $this->get_facebook(); $facebook = $this->get_facebook();
$fbuid = $facebook->require_login(); $fbuid = $facebook->require_login();
$fbml = '<fb:if-section-not-added section="profile">' $fbml = '<fb:if-section-not-added section="profile">'
.'<h2>Add an Identi.ca box to your profile!</h2>' .'<h2>Add an Identi.ca box to your profile!</h2>'
.'<fb:add-section-button section="profile"/>' .'<fb:add-section-button section="profile"/>'
.'</fb:if-section-not-added>'; .'</fb:if-section-not-added>';
$this->show_header('Settings'); $this->show_header('Settings');
echo $fbml; echo $fbml;
$this->show_footer(); $this->show_footer();
} }
} }

View File

@ -23,72 +23,72 @@ require_once(INSTALLDIR.'/lib/mail.php');
class FavorAction extends Action { class FavorAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname))); common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname)));
return; return;
} }
$id = $this->trimmed('notice'); $id = $this->trimmed('notice');
$notice = Notice::staticGet($id); $notice = Notice::staticGet($id);
# CSRF protection # CSRF protection
$token = $this->trimmed('token-'.$notice->id); $token = $this->trimmed('token-'.$notice->id);
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_("There was a problem with your session token. Try again, please.")); $this->client_error(_("There was a problem with your session token. Try again, please."));
return; return;
} }
if ($user->hasFave($notice)) { if ($user->hasFave($notice)) {
$this->client_error(_('This notice is already a favorite!')); $this->client_error(_('This notice is already a favorite!'));
return; return;
} }
$fave = Fave::addNew($user, $notice); $fave = Fave::addNew($user, $notice);
if (!$fave) { if (!$fave) {
$this->server_error(_('Could not create favorite.')); $this->server_error(_('Could not create favorite.'));
return; return;
} }
$this->notify($fave, $notice, $user); $this->notify($fave, $notice, $user);
$user->blowFavesCache(); $user->blowFavesCache();
if ($this->boolean('ajax')) { if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Disfavor favorite')); common_element('title', null, _('Disfavor favorite'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
common_disfavor_form($notice); common_disfavor_form($notice);
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} else { } else {
common_redirect(common_local_url('showfavorites', common_redirect(common_local_url('showfavorites',
array('nickname' => $user->nickname))); array('nickname' => $user->nickname)));
} }
} }
function notify($fave, $notice, $user) { function notify($fave, $notice, $user) {
$other = User::staticGet('id', $notice->profile_id); $other = User::staticGet('id', $notice->profile_id);
if ($other && $other->id != $user->id) { if ($other && $other->id != $user->id) {
if ($other->email && $other->emailnotifyfav) { if ($other->email && $other->emailnotifyfav) {
mail_notify_fave($other, $user, $notice); mail_notify_fave($other, $user, $notice);
} }
# XXX: notify by IM # XXX: notify by IM
# XXX: notify by SMS # XXX: notify by SMS
} }
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,77 +23,77 @@ require_once(INSTALLDIR.'/lib/stream.php');
class FavoritedAction extends StreamAction { class FavoritedAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
common_show_header(_('Popular notices'), common_show_header(_('Popular notices'),
array($this, 'show_header'), NULL, array($this, 'show_header'), NULL,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_notices($page); $this->show_notices($page);
common_show_footer(); common_show_footer();
} }
function show_top() { function show_top() {
$instr = $this->get_instructions(); $instr = $this->get_instructions();
$output = common_markup_to_html($instr); $output = common_markup_to_html($instr);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
$this->public_views_menu(); $this->public_views_menu();
} }
function show_header() { function show_header() {
return; return;
} }
function get_instructions() { function get_instructions() {
return _('Showing recently popular notices'); return _('Showing recently popular notices');
} }
function show_notices($page) { function show_notices($page) {
$qry = 'SELECT notice.*, sum(exp(-(now() - fave.modified) / %s)) as weight ' . $qry = 'SELECT notice.*, sum(exp(-(now() - fave.modified) / %s)) as weight ' .
'FROM notice JOIN fave ON notice.id = fave.notice_id ' . 'FROM notice JOIN fave ON notice.id = fave.notice_id ' .
'GROUP BY fave.notice_id ' . 'GROUP BY fave.notice_id ' .
'ORDER BY weight DESC'; 'ORDER BY weight DESC';
$offset = ($page - 1) * NOTICES_PER_PAGE; $offset = ($page - 1) * NOTICES_PER_PAGE;
$limit = NOTICES_PER_PAGE + 1; $limit = NOTICES_PER_PAGE + 1;
if (common_config('db','type') == 'pgsql') { if (common_config('db','type') == 'pgsql') {
$qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
} else { } else {
$qry .= ' LIMIT ' . $offset . ', ' . $limit; $qry .= ' LIMIT ' . $offset . ', ' . $limit;
} }
# Figure out how to cache this query # Figure out how to cache this query
$notice = new Notice; $notice = new Notice;
$notice->query(sprintf($qry, common_config('popular', 'dropoff'))); $notice->query(sprintf($qry, common_config('popular', 'dropoff')));
common_element_start('ul', array('id' => 'notices')); common_element_start('ul', array('id' => 'notices'));
$cnt = 0; $cnt = 0;
while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) { while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) {
$cnt++; $cnt++;
if ($cnt > NOTICES_PER_PAGE) { if ($cnt > NOTICES_PER_PAGE) {
break; break;
} }
$item = new NoticeListItem($notice); $item = new NoticeListItem($notice);
$item->show(); $item->show();
} }
common_element_end('ul'); common_element_end('ul');
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'favorited'); $page, 'favorited');
} }
} }

View File

@ -25,49 +25,49 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class FavoritesrssAction extends Rss10Action { class FavoritesrssAction extends Rss10Action {
var $user = NULL; var $user = NULL;
function init() { function init() {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$this->user = User::staticGet('nickname', $nickname); $this->user = User::staticGet('nickname', $nickname);
if (!$this->user) { if (!$this->user) {
common_user_error(_('No such user.')); common_user_error(_('No such user.'));
return false; return false;
} else { } else {
return true; return true;
} }
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$user = $this->user; $user = $this->user;
$notice = $user->favoriteNotices(0, $limit); $notice = $user->favoriteNotices(0, $limit);
$notices = array(); $notices = array();
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
$user = $this->user; $user = $this->user;
$c = array('url' => common_local_url('favoritesrss', $c = array('url' => common_local_url('favoritesrss',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'title' => sprintf(_("%s favorite notices"), $user->nickname), 'title' => sprintf(_("%s favorite notices"), $user->nickname),
'link' => common_local_url('showfavorites', 'link' => common_local_url('showfavorites',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'description' => sprintf(_('Feed of favorite notices of %s'), $user->nickname)); 'description' => sprintf(_('Feed of favorite notices of %s'), $user->nickname));
return $c; return $c;
} }
function get_image() { function get_image() {
return NULL; return NULL;
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -24,79 +24,79 @@ require_once(INSTALLDIR.'/lib/profilelist.php');
class FeaturedAction extends StreamAction { class FeaturedAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
common_show_header(_('Featured users'), common_show_header(_('Featured users'),
array($this, 'show_header'), NULL, array($this, 'show_header'), NULL,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_notices($page); $this->show_notices($page);
common_show_footer(); common_show_footer();
} }
function show_top() { function show_top() {
$instr = $this->get_instructions(); $instr = $this->get_instructions();
$output = common_markup_to_html($instr); $output = common_markup_to_html($instr);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
$this->public_views_menu(); $this->public_views_menu();
} }
function show_header() { function show_header() {
} }
function get_instructions() { function get_instructions() {
return _('Featured users'); return _('Featured users');
} }
function show_notices($page) { function show_notices($page) {
// XXX: Note I'm doing it this two-stage way because a raw query // XXX: Note I'm doing it this two-stage way because a raw query
// with a JOIN was *not* working. --Zach // with a JOIN was *not* working. --Zach
$featured_nicks = common_config('nickname', 'featured'); $featured_nicks = common_config('nickname', 'featured');
if (count($featured_nicks) > 0) { if (count($featured_nicks) > 0) {
$quoted = array(); $quoted = array();
foreach ($featured_nicks as $nick) { foreach ($featured_nicks as $nick) {
$quoted[] = "'$nick'"; $quoted[] = "'$nick'";
} }
$user = new User; $user = new User;
$user->whereAdd(sprintf('nickname IN (%s)', implode(',', $quoted))); $user->whereAdd(sprintf('nickname IN (%s)', implode(',', $quoted)));
$user->limit(($page - 1) * PROFILES_PER_PAGE, PROFILES_PER_PAGE + 1); $user->limit(($page - 1) * PROFILES_PER_PAGE, PROFILES_PER_PAGE + 1);
$user->orderBy('user.nickname ASC'); $user->orderBy('user.nickname ASC');
$user->find(); $user->find();
$profile_ids = array(); $profile_ids = array();
while ($user->fetch()) { while ($user->fetch()) {
$profile_ids[] = $user->id; $profile_ids[] = $user->id;
} }
$profile = new Profile; $profile = new Profile;
$profile->whereAdd(sprintf('profile.id IN (%s)', implode(',', $profile_ids))); $profile->whereAdd(sprintf('profile.id IN (%s)', implode(',', $profile_ids)));
$profile->orderBy('nickname ASC'); $profile->orderBy('nickname ASC');
$cnt = $profile->find(); $cnt = $profile->find();
if ($cnt > 0) { if ($cnt > 0) {
$featured = new ProfileList($profile); $featured = new ProfileList($profile);
$featured->show_list(); $featured->show_list();
} }
$profile->free(); $profile->free();
common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, $page, 'featured'); common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, $page, 'featured');
} }
} }
} }

View File

@ -23,81 +23,81 @@ require_once(INSTALLDIR.'/lib/openid.php');
class FinishaddopenidAction extends Action { class FinishaddopenidAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
} else { } else {
$this->try_login(); $this->try_login();
} }
} }
function try_login() { function try_login() {
$consumer =& oid_consumer(); $consumer =& oid_consumer();
$response = $consumer->complete(common_local_url('finishaddopenid')); $response = $consumer->complete(common_local_url('finishaddopenid'));
if ($response->status == Auth_OpenID_CANCEL) { if ($response->status == Auth_OpenID_CANCEL) {
$this->message(_('OpenID authentication cancelled.')); $this->message(_('OpenID authentication cancelled.'));
return; return;
} else if ($response->status == Auth_OpenID_FAILURE) { } else if ($response->status == Auth_OpenID_FAILURE) {
// Authentication failed; display the error message. // Authentication failed; display the error message.
$this->message(sprintf(_('OpenID authentication failed: %s'), $response->message)); $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
} else if ($response->status == Auth_OpenID_SUCCESS) { } else if ($response->status == Auth_OpenID_SUCCESS) {
$display = $response->getDisplayIdentifier(); $display = $response->getDisplayIdentifier();
$canonical = ($response->endpoint && $response->endpoint->canonicalID) ? $canonical = ($response->endpoint && $response->endpoint->canonicalID) ?
$response->endpoint->canonicalID : $display; $response->endpoint->canonicalID : $display;
$sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
if ($sreg_resp) { if ($sreg_resp) {
$sreg = $sreg_resp->contents(); $sreg = $sreg_resp->contents();
} }
$cur =& common_current_user(); $cur =& common_current_user();
$other = oid_get_user($canonical); $other = oid_get_user($canonical);
if ($other) { if ($other) {
if ($other->id == $cur->id) { if ($other->id == $cur->id) {
$this->message(_('You already have this OpenID!')); $this->message(_('You already have this OpenID!'));
} else { } else {
$this->message(_('Someone else already has this OpenID.')); $this->message(_('Someone else already has this OpenID.'));
} }
return; return;
} }
# start a transaction # start a transaction
$cur->query('BEGIN'); $cur->query('BEGIN');
$result = oid_link_user($cur->id, $canonical, $display); $result = oid_link_user($cur->id, $canonical, $display);
if (!$result) { if (!$result) {
$this->message(_('Error connecting user.')); $this->message(_('Error connecting user.'));
return; return;
} }
if ($sreg) { if ($sreg) {
if (!oid_update_user($cur, $sreg)) { if (!oid_update_user($cur, $sreg)) {
$this->message(_('Error updating profile')); $this->message(_('Error updating profile'));
return; return;
} }
} }
# success! # success!
$cur->query('COMMIT'); $cur->query('COMMIT');
oid_set_last($display); oid_set_last($display);
common_redirect(common_local_url('openidsettings')); common_redirect(common_local_url('openidsettings'));
} }
} }
function message($msg) { function message($msg) {
common_show_header(_('OpenID Login')); common_show_header(_('OpenID Login'));
common_element('p', NULL, $msg); common_element('p', NULL, $msg);
common_show_footer(); common_show_footer();
} }
} }

View File

@ -23,43 +23,43 @@ require_once(INSTALLDIR.'/lib/openid.php');
class FinishimmediateAction extends Action { class FinishimmediateAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$consumer = oid_consumer(); $consumer = oid_consumer();
$response = $consumer->complete(common_local_url('finishimmediate')); $response = $consumer->complete(common_local_url('finishimmediate'));
if ($response->status == Auth_OpenID_SUCCESS) { if ($response->status == Auth_OpenID_SUCCESS) {
$display = $response->getDisplayIdentifier(); $display = $response->getDisplayIdentifier();
$canonical = ($response->endpoint->canonicalID) ? $canonical = ($response->endpoint->canonicalID) ?
$response->endpoint->canonicalID : $response->getDisplayIdentifier(); $response->endpoint->canonicalID : $response->getDisplayIdentifier();
$user = oid_get_user($canonical); $user = oid_get_user($canonical);
if ($user) { if ($user) {
oid_update_user($user, $sreg); oid_update_user($user, $sreg);
oid_set_last($display); # refresh for another year oid_set_last($display); # refresh for another year
common_set_user($user->nickname); common_set_user($user->nickname);
$this->go_backto(); $this->go_backto();
return; return;
} }
} }
# Failure! Clear openid so we don't try it again # Failure! Clear openid so we don't try it again
oid_clear_last(); oid_clear_last();
$this->go_backto(); $this->go_backto();
return; return;
} }
function go_backto() { function go_backto() {
common_ensure_session(); common_ensure_session();
$backto = $_SESSION['openid_immediate_backto']; $backto = $_SESSION['openid_immediate_backto'];
if (!$backto) { if (!$backto) {
# gar. Well, push them to the public page # gar. Well, push them to the public page
$backto = common_local_url('public'); $backto = common_local_url('public');
} }
common_redirect($backto); common_redirect($backto);
} }
} }

View File

@ -23,414 +23,414 @@ require_once(INSTALLDIR.'/lib/openid.php');
class FinishopenidloginAction extends Action { class FinishopenidloginAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_logged_in()) { if (common_logged_in()) {
common_user_error(_('Already logged in.')); common_user_error(_('Already logged in.'));
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('create')) { if ($this->arg('create')) {
if (!$this->boolean('license')) { if (!$this->boolean('license')) {
$this->show_form(_('You can\'t register if you don\'t agree to the license.'), $this->show_form(_('You can\'t register if you don\'t agree to the license.'),
$this->trimmed('newname')); $this->trimmed('newname'));
return; return;
} }
$this->create_new_user(); $this->create_new_user();
} else if ($this->arg('connect')) { } else if ($this->arg('connect')) {
$this->connect_user(); $this->connect_user();
} else { } else {
common_debug(print_r($this->args, true), __FILE__); common_debug(print_r($this->args, true), __FILE__);
$this->show_form(_('Something weird happened.'), $this->show_form(_('Something weird happened.'),
$this->trimmed('newname')); $this->trimmed('newname'));
} }
} else { } else {
$this->try_login(); $this->try_login();
} }
} }
function show_top($error=NULL) { function show_top($error=NULL) {
if ($error) { if ($error) {
common_element('div', array('class' => 'error'), $error); common_element('div', array('class' => 'error'), $error);
} else { } else {
global $config; global $config;
common_element('div', 'instructions', common_element('div', 'instructions',
sprintf(_('This is the first time you\'ve logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), $config['site']['name'])); sprintf(_('This is the first time you\'ve logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), $config['site']['name']));
} }
} }
function show_form($error=NULL, $username=NULL) { function show_form($error=NULL, $username=NULL) {
common_show_header(_('OpenID Account Setup'), NULL, $error, common_show_header(_('OpenID Account Setup'), NULL, $error,
array($this, 'show_top')); array($this, 'show_top'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'account_connect', 'id' => 'account_connect',
'action' => common_local_url('finishopenidlogin'))); 'action' => common_local_url('finishopenidlogin')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('h2', NULL, common_element('h2', NULL,
_('Create new account')); _('Create new account'));
common_element('p', NULL, common_element('p', NULL,
_('Create a new user with this nickname.')); _('Create a new user with this nickname.'));
common_input('newname', _('New nickname'), common_input('newname', _('New nickname'),
($username) ? $username : '', ($username) ? $username : '',
_('1-64 lowercase letters or numbers, no punctuation or spaces')); _('1-64 lowercase letters or numbers, no punctuation or spaces'));
common_element_start('p'); common_element_start('p');
common_element('input', array('type' => 'checkbox', common_element('input', array('type' => 'checkbox',
'id' => 'license', 'id' => 'license',
'name' => 'license', 'name' => 'license',
'value' => 'true')); 'value' => 'true'));
common_text(_('My text and files are available under ')); common_text(_('My text and files are available under '));
common_element('a', array(href => common_config('license', 'url')), common_element('a', array(href => common_config('license', 'url')),
common_config('license', 'title')); common_config('license', 'title'));
common_text(_(' except this private data: password, email address, IM address, phone number.')); common_text(_(' except this private data: password, email address, IM address, phone number.'));
common_element_end('p'); common_element_end('p');
common_submit('create', _('Create')); common_submit('create', _('Create'));
common_element('h2', NULL, common_element('h2', NULL,
_('Connect existing account')); _('Connect existing account'));
common_element('p', NULL, common_element('p', NULL,
_('If you already have an account, login with your username and password to connect it to your OpenID.')); _('If you already have an account, login with your username and password to connect it to your OpenID.'));
common_input('nickname', _('Existing nickname')); common_input('nickname', _('Existing nickname'));
common_password('password', _('Password')); common_password('password', _('Password'));
common_submit('connect', _('Connect')); common_submit('connect', _('Connect'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function try_login() { function try_login() {
$consumer = oid_consumer(); $consumer = oid_consumer();
$response = $consumer->complete(common_local_url('finishopenidlogin')); $response = $consumer->complete(common_local_url('finishopenidlogin'));
if ($response->status == Auth_OpenID_CANCEL) { if ($response->status == Auth_OpenID_CANCEL) {
$this->message(_('OpenID authentication cancelled.')); $this->message(_('OpenID authentication cancelled.'));
return; return;
} else if ($response->status == Auth_OpenID_FAILURE) { } else if ($response->status == Auth_OpenID_FAILURE) {
// Authentication failed; display the error message. // Authentication failed; display the error message.
$this->message(sprintf(_('OpenID authentication failed: %s'), $response->message)); $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message));
} else if ($response->status == Auth_OpenID_SUCCESS) { } else if ($response->status == Auth_OpenID_SUCCESS) {
// This means the authentication succeeded; extract the // This means the authentication succeeded; extract the
// identity URL and Simple Registration data (if it was // identity URL and Simple Registration data (if it was
// returned). // returned).
$display = $response->getDisplayIdentifier(); $display = $response->getDisplayIdentifier();
$canonical = ($response->endpoint->canonicalID) ? $canonical = ($response->endpoint->canonicalID) ?
$response->endpoint->canonicalID : $response->getDisplayIdentifier(); $response->endpoint->canonicalID : $response->getDisplayIdentifier();
$sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
if ($sreg_resp) { if ($sreg_resp) {
$sreg = $sreg_resp->contents(); $sreg = $sreg_resp->contents();
} }
$user = oid_get_user($canonical); $user = oid_get_user($canonical);
if ($user) { if ($user) {
oid_set_last($display); oid_set_last($display);
# XXX: commented out at @edd's request until better # XXX: commented out at @edd's request until better
# control over how data flows from OpenID provider. # control over how data flows from OpenID provider.
# oid_update_user($user, $sreg); # oid_update_user($user, $sreg);
common_set_user($user); common_set_user($user);
common_real_login(true); common_real_login(true);
if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
common_rememberme($user); common_rememberme($user);
} }
unset($_SESSION['openid_rememberme']); unset($_SESSION['openid_rememberme']);
$this->go_home($user->nickname); $this->go_home($user->nickname);
} else { } else {
$this->save_values($display, $canonical, $sreg); $this->save_values($display, $canonical, $sreg);
$this->show_form(NULL, $this->best_new_nickname($display, $sreg)); $this->show_form(NULL, $this->best_new_nickname($display, $sreg));
} }
} }
} }
function message($msg) { function message($msg) {
common_show_header(_('OpenID Login')); common_show_header(_('OpenID Login'));
common_element('p', NULL, $msg); common_element('p', NULL, $msg);
common_show_footer(); common_show_footer();
} }
function save_values($display, $canonical, $sreg) { function save_values($display, $canonical, $sreg) {
common_ensure_session(); common_ensure_session();
$_SESSION['openid_display'] = $display; $_SESSION['openid_display'] = $display;
$_SESSION['openid_canonical'] = $canonical; $_SESSION['openid_canonical'] = $canonical;
$_SESSION['openid_sreg'] = $sreg; $_SESSION['openid_sreg'] = $sreg;
} }
function get_saved_values() { function get_saved_values() {
return array($_SESSION['openid_display'], return array($_SESSION['openid_display'],
$_SESSION['openid_canonical'], $_SESSION['openid_canonical'],
$_SESSION['openid_sreg']); $_SESSION['openid_sreg']);
} }
function create_new_user() { function create_new_user() {
# FIXME: save invite code before redirect, and check here # FIXME: save invite code before redirect, and check here
if (common_config('site', 'closed') || common_config('site', 'inviteonly')) { if (common_config('site', 'closed') || common_config('site', 'inviteonly')) {
common_user_error(_('Registration not allowed.')); common_user_error(_('Registration not allowed.'));
return; return;
} }
$nickname = $this->trimmed('newname'); $nickname = $this->trimmed('newname');
if (!Validate::string($nickname, array('min_length' => 1, if (!Validate::string($nickname, array('min_length' => 1,
'max_length' => 64, 'max_length' => 64,
'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
$this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
return; return;
} }
if (!User::allowed_nickname($nickname)) { if (!User::allowed_nickname($nickname)) {
$this->show_form(_('Nickname not allowed.')); $this->show_form(_('Nickname not allowed.'));
return; return;
} }
if (User::staticGet('nickname', $nickname)) { if (User::staticGet('nickname', $nickname)) {
$this->show_form(_('Nickname already in use. Try another one.')); $this->show_form(_('Nickname already in use. Try another one.'));
return; return;
} }
list($display, $canonical, $sreg) = $this->get_saved_values(); list($display, $canonical, $sreg) = $this->get_saved_values();
if (!$display || !$canonical) { if (!$display || !$canonical) {
common_server_error(_('Stored OpenID not found.')); common_server_error(_('Stored OpenID not found.'));
return; return;
} }
# Possible race condition... let's be paranoid # Possible race condition... let's be paranoid
$other = oid_get_user($canonical); $other = oid_get_user($canonical);
if ($other) { if ($other) {
common_server_error(_('Creating new account for OpenID that already has a user.')); common_server_error(_('Creating new account for OpenID that already has a user.'));
return; return;
} }
if ($sreg['country']) { if ($sreg['country']) {
if ($sreg['postcode']) { if ($sreg['postcode']) {
# XXX: use postcode to get city and region # XXX: use postcode to get city and region
# XXX: also, store postcode somewhere -- it's valuable! # XXX: also, store postcode somewhere -- it's valuable!
$location = $sreg['postcode'] . ', ' . $sreg['country']; $location = $sreg['postcode'] . ', ' . $sreg['country'];
} else { } else {
$location = $sreg['country']; $location = $sreg['country'];
} }
} }
if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) { if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) {
$fullname = $sreg['fullname']; $fullname = $sreg['fullname'];
} }
if ($sreg['email'] && Validate::email($sreg['email'], true)) { if ($sreg['email'] && Validate::email($sreg['email'], true)) {
$email = $sreg['email']; $email = $sreg['email'];
} }
# XXX: add language # XXX: add language
# XXX: add timezone # XXX: add timezone
$user = User::register(array('nickname' => $nickname, $user = User::register(array('nickname' => $nickname,
'email' => $email, 'email' => $email,
'fullname' => $fullname, 'fullname' => $fullname,
'location' => $location)); 'location' => $location));
$result = oid_link_user($user->id, $canonical, $display); $result = oid_link_user($user->id, $canonical, $display);
oid_set_last($display); oid_set_last($display);
common_set_user($user); common_set_user($user);
common_real_login(true); common_real_login(true);
if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
common_rememberme($user); common_rememberme($user);
} }
unset($_SESSION['openid_rememberme']); unset($_SESSION['openid_rememberme']);
common_redirect(common_local_url('showstream', array('nickname' => $user->nickname))); common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)));
} }
function connect_user() { function connect_user() {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$password = $this->trimmed('password'); $password = $this->trimmed('password');
if (!common_check_user($nickname, $password)) { if (!common_check_user($nickname, $password)) {
$this->show_form(_('Invalid username or password.')); $this->show_form(_('Invalid username or password.'));
return; return;
} }
# They're legit! # They're legit!
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
list($display, $canonical, $sreg) = $this->get_saved_values(); list($display, $canonical, $sreg) = $this->get_saved_values();
if (!$display || !$canonical) { if (!$display || !$canonical) {
common_server_error(_('Stored OpenID not found.')); common_server_error(_('Stored OpenID not found.'));
return; return;
} }
$result = oid_link_user($user->id, $canonical, $display); $result = oid_link_user($user->id, $canonical, $display);
if (!$result) { if (!$result) {
common_server_error(_('Error connecting user to OpenID.')); common_server_error(_('Error connecting user to OpenID.'));
return; return;
} }
oid_update_user($user, $sreg); oid_update_user($user, $sreg);
oid_set_last($display); oid_set_last($display);
common_set_user($user); common_set_user($user);
common_real_login(true); common_real_login(true);
if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) {
common_rememberme($user); common_rememberme($user);
} }
unset($_SESSION['openid_rememberme']); unset($_SESSION['openid_rememberme']);
$this->go_home($user->nickname); $this->go_home($user->nickname);
} }
function go_home($nickname) { function go_home($nickname) {
$url = common_get_returnto(); $url = common_get_returnto();
if ($url) { if ($url) {
# We don't have to return to it again # We don't have to return to it again
common_set_returnto(NULL); common_set_returnto(NULL);
} else { } else {
$url = common_local_url('all', $url = common_local_url('all',
array('nickname' => array('nickname' =>
$nickname)); $nickname));
} }
common_redirect($url); common_redirect($url);
} }
function best_new_nickname($display, $sreg) { function best_new_nickname($display, $sreg) {
# Try the passed-in nickname # Try the passed-in nickname
if ($sreg['nickname']) { if ($sreg['nickname']) {
$nickname = $this->nicknamize($sreg['nickname']); $nickname = $this->nicknamize($sreg['nickname']);
if ($this->is_new_nickname($nickname)) { if ($this->is_new_nickname($nickname)) {
return $nickname; return $nickname;
} }
} }
# Try the full name # Try the full name
if ($sreg['fullname']) { if ($sreg['fullname']) {
$fullname = $this->nicknamize($sreg['fullname']); $fullname = $this->nicknamize($sreg['fullname']);
if ($this->is_new_nickname($fullname)) { if ($this->is_new_nickname($fullname)) {
return $fullname; return $fullname;
} }
} }
# Try the URL # Try the URL
$from_url = $this->openid_to_nickname($display); $from_url = $this->openid_to_nickname($display);
if ($from_url && $this->is_new_nickname($from_url)) { if ($from_url && $this->is_new_nickname($from_url)) {
return $from_url; return $from_url;
} }
# XXX: others? # XXX: others?
return NULL; return NULL;
} }
function is_new_nickname($str) { function is_new_nickname($str) {
if (!Validate::string($str, array('min_length' => 1, if (!Validate::string($str, array('min_length' => 1,
'max_length' => 64, 'max_length' => 64,
'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
return false; return false;
} }
if (!User::allowed_nickname($str)) { if (!User::allowed_nickname($str)) {
return false; return false;
} }
if (User::staticGet('nickname', $str)) { if (User::staticGet('nickname', $str)) {
return false; return false;
} }
return true; return true;
} }
function openid_to_nickname($openid) { function openid_to_nickname($openid) {
if (Auth_Yadis_identifierScheme($openid) == 'XRI') { if (Auth_Yadis_identifierScheme($openid) == 'XRI') {
return $this->xri_to_nickname($openid); return $this->xri_to_nickname($openid);
} else { } else {
return $this->url_to_nickname($openid); return $this->url_to_nickname($openid);
} }
} }
# We try to use an OpenID URL as a legal Laconica user name in this order # We try to use an OpenID URL as a legal Laconica user name in this order
# 1. Plain hostname, like http://evanp.myopenid.com/ # 1. Plain hostname, like http://evanp.myopenid.com/
# 2. One element in path, like http://profile.typekey.com/EvanProdromou/ # 2. One element in path, like http://profile.typekey.com/EvanProdromou/
# or http://getopenid.com/evanprodromou # or http://getopenid.com/evanprodromou
function url_to_nickname($openid) { function url_to_nickname($openid) {
static $bad = array('query', 'user', 'password', 'port', 'fragment'); static $bad = array('query', 'user', 'password', 'port', 'fragment');
$parts = parse_url($openid); $parts = parse_url($openid);
# If any of these parts exist, this won't work # If any of these parts exist, this won't work
foreach ($bad as $badpart) { foreach ($bad as $badpart) {
if (array_key_exists($badpart, $parts)) { if (array_key_exists($badpart, $parts)) {
return NULL; return NULL;
} }
} }
# We just have host and/or path # We just have host and/or path
# If it's just a host... # If it's just a host...
if (array_key_exists('host', $parts) && if (array_key_exists('host', $parts) &&
(!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0)) (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
{ {
$hostparts = explode('.', $parts['host']); $hostparts = explode('.', $parts['host']);
# Try to catch common idiom of nickname.service.tld # Try to catch common idiom of nickname.service.tld
if ((count($hostparts) > 2) && if ((count($hostparts) > 2) &&
(strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
(strcmp($hostparts[0], 'www') != 0)) (strcmp($hostparts[0], 'www') != 0))
{ {
return $this->nicknamize($hostparts[0]); return $this->nicknamize($hostparts[0]);
} else { } else {
# Do the whole hostname # Do the whole hostname
return $this->nicknamize($parts['host']); return $this->nicknamize($parts['host']);
} }
} else { } else {
if (array_key_exists('path', $parts)) { if (array_key_exists('path', $parts)) {
# Strip starting, ending slashes # Strip starting, ending slashes
$path = preg_replace('@/$@', '', $parts['path']); $path = preg_replace('@/$@', '', $parts['path']);
$path = preg_replace('@^/@', '', $path); $path = preg_replace('@^/@', '', $path);
if (strpos($path, '/') === false) { if (strpos($path, '/') === false) {
return $this->nicknamize($path); return $this->nicknamize($path);
} }
} }
} }
return NULL; return NULL;
} }
function xri_to_nickname($xri) { function xri_to_nickname($xri) {
$base = $this->xri_base($xri); $base = $this->xri_base($xri);
if (!$base) { if (!$base) {
return NULL; return NULL;
} else { } else {
# =evan.prodromou # =evan.prodromou
# or @gratis*evan.prodromou # or @gratis*evan.prodromou
$parts = explode('*', substr($base, 1)); $parts = explode('*', substr($base, 1));
return $this->nicknamize(array_pop($parts)); return $this->nicknamize(array_pop($parts));
} }
} }
function xri_base($xri) { function xri_base($xri) {
if (substr($xri, 0, 6) == 'xri://') { if (substr($xri, 0, 6) == 'xri://') {
return substr($xri, 6); return substr($xri, 6);
} else { } else {
return $xri; return $xri;
} }
} }
# Given a string, try to make it work as a nickname # Given a string, try to make it work as a nickname
function nicknamize($str) { function nicknamize($str) {
$str = preg_replace('/\W/', '', $str); $str = preg_replace('/\W/', '', $str);
return strtolower($str); return strtolower($str);
} }
} }

View File

@ -23,174 +23,174 @@ require_once(INSTALLDIR.'/lib/omb.php');
class FinishremotesubscribeAction extends Action { class FinishremotesubscribeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_logged_in()) { if (common_logged_in()) {
common_user_error(_('You can use the local subscription!')); common_user_error(_('You can use the local subscription!'));
return; return;
} }
$omb = $_SESSION['oauth_authorization_request']; $omb = $_SESSION['oauth_authorization_request'];
if (!$omb) { if (!$omb) {
common_user_error(_('Not expecting this response!')); common_user_error(_('Not expecting this response!'));
return; return;
} }
common_debug('stored request: '.print_r($omb,true), __FILE__); common_debug('stored request: '.print_r($omb,true), __FILE__);
common_remove_magic_from_request(); common_remove_magic_from_request();
$req = OAuthRequest::from_request(); $req = OAuthRequest::from_request();
$token = $req->get_parameter('oauth_token'); $token = $req->get_parameter('oauth_token');
# I think this is the success metric # I think this is the success metric
if ($token != $omb['token']) { if ($token != $omb['token']) {
common_user_error(_('Not authorized.')); common_user_error(_('Not authorized.'));
return; return;
} }
$version = $req->get_parameter('omb_version'); $version = $req->get_parameter('omb_version');
if ($version != OMB_VERSION_01) { if ($version != OMB_VERSION_01) {
common_user_error(_('Unknown version of OMB protocol.')); common_user_error(_('Unknown version of OMB protocol.'));
return; return;
} }
$nickname = $req->get_parameter('omb_listener_nickname'); $nickname = $req->get_parameter('omb_listener_nickname');
if (!$nickname) { if (!$nickname) {
common_user_error(_('No nickname provided by remote server.')); common_user_error(_('No nickname provided by remote server.'));
return; return;
} }
$profile_url = $req->get_parameter('omb_listener_profile'); $profile_url = $req->get_parameter('omb_listener_profile');
if (!$profile_url) { if (!$profile_url) {
common_user_error(_('No profile URL returned by server.')); common_user_error(_('No profile URL returned by server.'));
return; return;
} }
if (!Validate::uri($profile_url, array('allowed_schemes' => array('http', 'https')))) { if (!Validate::uri($profile_url, array('allowed_schemes' => array('http', 'https')))) {
common_user_error(_('Invalid profile URL returned by server.')); common_user_error(_('Invalid profile URL returned by server.'));
return; return;
} }
if ($profile_url == common_local_url('showstream', array('nickname' => $nickname))) { if ($profile_url == common_local_url('showstream', array('nickname' => $nickname))) {
common_user_error(_('You can use the local subscription!')); common_user_error(_('You can use the local subscription!'));
return; return;
} }
common_debug('listenee: "'.$omb['listenee'].'"', __FILE__); common_debug('listenee: "'.$omb['listenee'].'"', __FILE__);
$user = User::staticGet('nickname', $omb['listenee']); $user = User::staticGet('nickname', $omb['listenee']);
if (!$user) { if (!$user) {
common_user_error(_('User being listened to doesn\'t exist.')); common_user_error(_('User being listened to doesn\'t exist.'));
return; return;
} }
$other = User::staticGet('uri', $omb['listener']); $other = User::staticGet('uri', $omb['listener']);
if ($other) { if ($other) {
common_user_error(_('You can use the local subscription!')); common_user_error(_('You can use the local subscription!'));
return; return;
} }
$fullname = $req->get_parameter('omb_listener_fullname'); $fullname = $req->get_parameter('omb_listener_fullname');
$homepage = $req->get_parameter('omb_listener_homepage'); $homepage = $req->get_parameter('omb_listener_homepage');
$bio = $req->get_parameter('omb_listener_bio'); $bio = $req->get_parameter('omb_listener_bio');
$location = $req->get_parameter('omb_listener_location'); $location = $req->get_parameter('omb_listener_location');
$avatar_url = $req->get_parameter('omb_listener_avatar'); $avatar_url = $req->get_parameter('omb_listener_avatar');
list($newtok, $newsecret) = $this->access_token($omb); list($newtok, $newsecret) = $this->access_token($omb);
if (!$newtok || !$newsecret) { if (!$newtok || !$newsecret) {
common_user_error(_('Couldn\'t convert request tokens to access tokens.')); common_user_error(_('Couldn\'t convert request tokens to access tokens.'));
return; return;
} }
# XXX: possible attack point; subscribe and return someone else's profile URI # XXX: possible attack point; subscribe and return someone else's profile URI
$remote = Remote_profile::staticGet('uri', $omb['listener']); $remote = Remote_profile::staticGet('uri', $omb['listener']);
if ($remote) { if ($remote) {
$exists = true; $exists = true;
$profile = Profile::staticGet($remote->id); $profile = Profile::staticGet($remote->id);
$orig_remote = clone($remote); $orig_remote = clone($remote);
$orig_profile = clone($profile); $orig_profile = clone($profile);
# XXX: compare current postNotice and updateProfile URLs to the ones # XXX: compare current postNotice and updateProfile URLs to the ones
# stored in the DB to avoid (possibly...) above attack # stored in the DB to avoid (possibly...) above attack
} else { } else {
$exists = false; $exists = false;
$remote = new Remote_profile(); $remote = new Remote_profile();
$remote->uri = $omb['listener']; $remote->uri = $omb['listener'];
$profile = new Profile(); $profile = new Profile();
} }
$profile->nickname = $nickname; $profile->nickname = $nickname;
$profile->profileurl = $profile_url; $profile->profileurl = $profile_url;
if ($fullname) { if ($fullname) {
$profile->fullname = $fullname; $profile->fullname = $fullname;
} }
if ($homepage) { if ($homepage) {
$profile->homepage = $homepage; $profile->homepage = $homepage;
} }
if ($bio) { if ($bio) {
$profile->bio = $bio; $profile->bio = $bio;
} }
if ($location) { if ($location) {
$profile->location = $location; $profile->location = $location;
} }
if ($exists) { if ($exists) {
$profile->update($orig_profile); $profile->update($orig_profile);
} else { } else {
$profile->created = DB_DataObject_Cast::dateTime(); # current time $profile->created = DB_DataObject_Cast::dateTime(); # current time
$id = $profile->insert(); $id = $profile->insert();
if (!$id) { if (!$id) {
common_server_error(_('Error inserting new profile')); common_server_error(_('Error inserting new profile'));
return; return;
} }
$remote->id = $id; $remote->id = $id;
} }
if ($avatar_url) { if ($avatar_url) {
if (!$this->add_avatar($profile, $avatar_url)) { if (!$this->add_avatar($profile, $avatar_url)) {
common_server_error(_('Error inserting avatar')); common_server_error(_('Error inserting avatar'));
return; return;
} }
} }
$remote->postnoticeurl = $omb['post_notice_url']; $remote->postnoticeurl = $omb['post_notice_url'];
$remote->updateprofileurl = $omb['update_profile_url']; $remote->updateprofileurl = $omb['update_profile_url'];
if ($exists) { if ($exists) {
if (!$remote->update($orig_remote)) { if (!$remote->update($orig_remote)) {
common_server_error(_('Error updating remote profile')); common_server_error(_('Error updating remote profile'));
return; return;
} }
} else { } else {
$remote->created = DB_DataObject_Cast::dateTime(); # current time $remote->created = DB_DataObject_Cast::dateTime(); # current time
if (!$remote->insert()) { if (!$remote->insert()) {
common_server_error(_('Error inserting remote profile')); common_server_error(_('Error inserting remote profile'));
return; return;
} }
} }
if ($user->hasBlocked($profile)) { if ($user->hasBlocked($profile)) {
$this->client_error(_('That user has blocked you from subscribing.')); $this->client_error(_('That user has blocked you from subscribing.'));
return; return;
} }
$sub = new Subscription(); $sub = new Subscription();
$sub->subscriber = $remote->id; $sub->subscriber = $remote->id;
$sub->subscribed = $user->id; $sub->subscribed = $user->id;
$sub_exists = false; $sub_exists = false;
@ -202,8 +202,8 @@ class FinishremotesubscribeAction extends Action {
$sub->created = DB_DataObject_Cast::dateTime(); # current time $sub->created = DB_DataObject_Cast::dateTime(); # current time
} }
$sub->token = $newtok; $sub->token = $newtok;
$sub->secret = $newsecret; $sub->secret = $newsecret;
if ($sub_exists) { if ($sub_exists) {
$result = $sub->update($orig_sub); $result = $sub->update($orig_sub);
@ -211,78 +211,78 @@ class FinishremotesubscribeAction extends Action {
$result = $sub->insert(); $result = $sub->insert();
} }
if (!$result) { if (!$result) {
common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__); common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
common_user_error(_('Couldn\'t insert new subscription.')); common_user_error(_('Couldn\'t insert new subscription.'));
return; return;
} }
# Notify user, if necessary # Notify user, if necessary
mail_subscribe_notify_profile($user, $profile); mail_subscribe_notify_profile($user, $profile);
# Clear the data # Clear the data
unset($_SESSION['oauth_authorization_request']); unset($_SESSION['oauth_authorization_request']);
# If we show subscriptions in reverse chron order, this should # If we show subscriptions in reverse chron order, this should
# show up close to the top of the page # show up close to the top of the page
common_redirect(common_local_url('subscribers', array('nickname' => common_redirect(common_local_url('subscribers', array('nickname' =>
$user->nickname))); $user->nickname)));
} }
function add_avatar($profile, $url) { function add_avatar($profile, $url) {
$temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar'); $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
copy($url, $temp_filename); copy($url, $temp_filename);
return $profile->setOriginal($temp_filename); return $profile->setOriginal($temp_filename);
} }
function access_token($omb) { function access_token($omb) {
common_debug('starting request for access token', __FILE__); common_debug('starting request for access token', __FILE__);
$con = omb_oauth_consumer(); $con = omb_oauth_consumer();
$tok = new OAuthToken($omb['token'], $omb['secret']); $tok = new OAuthToken($omb['token'], $omb['secret']);
common_debug('using request token "'.$tok.'"', __FILE__); common_debug('using request token "'.$tok.'"', __FILE__);
$url = $omb['access_token_url']; $url = $omb['access_token_url'];
common_debug('using access token url "'.$url.'"', __FILE__); common_debug('using access token url "'.$url.'"', __FILE__);
# XXX: Is this the right thing to do? Strip off GET params and make them # XXX: Is this the right thing to do? Strip off GET params and make them
# POST params? Seems wrong to me. # POST params? Seems wrong to me.
$parsed = parse_url($url); $parsed = parse_url($url);
$params = array(); $params = array();
parse_str($parsed['query'], $params); parse_str($parsed['query'], $params);
$req = OAuthRequest::from_consumer_and_token($con, $tok, "POST", $url, $params); $req = OAuthRequest::from_consumer_and_token($con, $tok, "POST", $url, $params);
$req->set_parameter('omb_version', OMB_VERSION_01); $req->set_parameter('omb_version', OMB_VERSION_01);
# XXX: test to see if endpoint accepts this signature method # XXX: test to see if endpoint accepts this signature method
$req->sign_request(omb_hmac_sha1(), $con, $tok); $req->sign_request(omb_hmac_sha1(), $con, $tok);
# We re-use this tool's fetcher, since it's pretty good # We re-use this tool's fetcher, since it's pretty good
common_debug('posting to access token url "'.$req->get_normalized_http_url().'"', __FILE__); common_debug('posting to access token url "'.$req->get_normalized_http_url().'"', __FILE__);
common_debug('posting request data "'.$req->to_postdata().'"', __FILE__); common_debug('posting request data "'.$req->to_postdata().'"', __FILE__);
$fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
$result = $fetcher->post($req->get_normalized_http_url(), $result = $fetcher->post($req->get_normalized_http_url(),
$req->to_postdata(), $req->to_postdata(),
array('User-Agent' => 'Laconica/' . LACONICA_VERSION)); array('User-Agent' => 'Laconica/' . LACONICA_VERSION));
common_debug('got result: "'.print_r($result,TRUE).'"', __FILE__); common_debug('got result: "'.print_r($result,TRUE).'"', __FILE__);
if ($result->status != 200) { if ($result->status != 200) {
return NULL; return NULL;
} }
parse_str($result->body, $return); parse_str($result->body, $return);
return array($return['oauth_token'], $return['oauth_token_secret']); return array($return['oauth_token'], $return['oauth_token_secret']);
} }
} }

View File

@ -25,178 +25,178 @@ define('BOTH', 0);
class FoafAction extends Action { class FoafAction extends Action {
function is_readonly() { function is_readonly() {
return true; return true;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
common_user_error(_('No such user.'), 404); common_user_error(_('No such user.'), 404);
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.'), 500); common_server_error(_('User has no profile.'), 500);
return; return;
} }
header('Content-Type: application/rdf+xml'); header('Content-Type: application/rdf+xml');
common_start_xml(); common_start_xml();
common_element_start('rdf:RDF', array('xmlns:rdf' => common_element_start('rdf:RDF', array('xmlns:rdf' =>
'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'xmlns:rdfs' => 'xmlns:rdfs' =>
'http://www.w3.org/2000/01/rdf-schema#', 'http://www.w3.org/2000/01/rdf-schema#',
'xmlns:geo' => 'xmlns:geo' =>
'http://www.w3.org/2003/01/geo/wgs84_pos#', 'http://www.w3.org/2003/01/geo/wgs84_pos#',
'xmlns' => 'http://xmlns.com/foaf/0.1/')); 'xmlns' => 'http://xmlns.com/foaf/0.1/'));
# This is the document about the user # This is the document about the user
$this->show_ppd('', $user->uri); $this->show_ppd('', $user->uri);
# XXX: might not be a person # XXX: might not be a person
common_element_start('Person', array('rdf:about' => common_element_start('Person', array('rdf:about' =>
$user->uri)); $user->uri));
common_element('mbox_sha1sum', NULL, sha1('mailto:' . $user->email)); common_element('mbox_sha1sum', NULL, sha1('mailto:' . $user->email));
if ($profile->fullname) { if ($profile->fullname) {
common_element('name', NULL, $profile->fullname); common_element('name', NULL, $profile->fullname);
} }
if ($profile->homepage) { if ($profile->homepage) {
common_element('homepage', array('rdf:resource' => $profile->homepage)); common_element('homepage', array('rdf:resource' => $profile->homepage));
} }
if ($profile->bio) { if ($profile->bio) {
common_element('rdfs:comment', NULL, $profile->bio); common_element('rdfs:comment', NULL, $profile->bio);
} }
# XXX: more structured location data # XXX: more structured location data
if ($profile->location) { if ($profile->location) {
common_element_start('based_near'); common_element_start('based_near');
common_element_start('geo:SpatialThing'); common_element_start('geo:SpatialThing');
common_element('name', NULL, $profile->location); common_element('name', NULL, $profile->location);
common_element_end('geo:SpatialThing'); common_element_end('geo:SpatialThing');
common_element_end('based_near'); common_element_end('based_near');
} }
$this->show_microblogging_account($profile, common_root_url()); $this->show_microblogging_account($profile, common_root_url());
$avatar = $profile->getOriginalAvatar(); $avatar = $profile->getOriginalAvatar();
if ($avatar) { if ($avatar) {
common_element_start('img'); common_element_start('img');
common_element_start('Image', array('rdf:about' => $avatar->url)); common_element_start('Image', array('rdf:about' => $avatar->url));
foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) { foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
$scaled = $profile->getAvatar($size); $scaled = $profile->getAvatar($size);
if (!$scaled->original) { # sometimes the original has one of our scaled sizes if (!$scaled->original) { # sometimes the original has one of our scaled sizes
common_element_start('thumbnail'); common_element_start('thumbnail');
common_element('Image', array('rdf:about' => $scaled->url)); common_element('Image', array('rdf:about' => $scaled->url));
common_element_end('thumbnail'); common_element_end('thumbnail');
} }
} }
common_element_end('Image'); common_element_end('Image');
common_element_end('img'); common_element_end('img');
} }
# Get people user is subscribed to # Get people user is subscribed to
$person = array(); $person = array();
$sub = new Subscription(); $sub = new Subscription();
$sub->subscriber = $profile->id; $sub->subscriber = $profile->id;
$sub->whereAdd('subscriber != subscribed'); $sub->whereAdd('subscriber != subscribed');
if ($sub->find()) { if ($sub->find()) {
while ($sub->fetch()) { while ($sub->fetch()) {
if ($sub->token) { if ($sub->token) {
$other = Remote_profile::staticGet('id', $sub->subscribed); $other = Remote_profile::staticGet('id', $sub->subscribed);
} else { } else {
$other = User::staticGet('id', $sub->subscribed); $other = User::staticGet('id', $sub->subscribed);
} }
if (!$other) { if (!$other) {
common_debug('Got a bad subscription: '.print_r($sub,TRUE)); common_debug('Got a bad subscription: '.print_r($sub,TRUE));
continue; continue;
} }
common_element('knows', array('rdf:resource' => $other->uri)); common_element('knows', array('rdf:resource' => $other->uri));
$person[$other->uri] = array(LISTENEE, $other); $person[$other->uri] = array(LISTENEE, $other);
} }
} }
# Get people who subscribe to user # Get people who subscribe to user
$sub = new Subscription(); $sub = new Subscription();
$sub->subscribed = $profile->id; $sub->subscribed = $profile->id;
$sub->whereAdd('subscriber != subscribed'); $sub->whereAdd('subscriber != subscribed');
if ($sub->find()) { if ($sub->find()) {
while ($sub->fetch()) { while ($sub->fetch()) {
if ($sub->token) { if ($sub->token) {
$other = Remote_profile::staticGet('id', $sub->subscriber); $other = Remote_profile::staticGet('id', $sub->subscriber);
} else { } else {
$other = User::staticGet('id', $sub->subscriber); $other = User::staticGet('id', $sub->subscriber);
} }
if (!$other) { if (!$other) {
common_debug('Got a bad subscription: '.print_r($sub,TRUE)); common_debug('Got a bad subscription: '.print_r($sub,TRUE));
continue; continue;
} }
if (array_key_exists($other->uri, $person)) { if (array_key_exists($other->uri, $person)) {
$person[$other->uri][0] = BOTH; $person[$other->uri][0] = BOTH;
} else { } else {
$person[$other->uri] = array(LISTENER, $other); $person[$other->uri] = array(LISTENER, $other);
} }
} }
} }
common_element_end('Person'); common_element_end('Person');
foreach ($person as $uri => $p) { foreach ($person as $uri => $p) {
$foaf_url = NULL; $foaf_url = NULL;
if ($p[1] instanceof User) { if ($p[1] instanceof User) {
$foaf_url = common_local_url('foaf', array('nickname' => $p[1]->nickname)); $foaf_url = common_local_url('foaf', array('nickname' => $p[1]->nickname));
} }
$profile = Profile::staticGet($p[1]->id); $profile = Profile::staticGet($p[1]->id);
common_element_start('Person', array('rdf:about' => $uri)); common_element_start('Person', array('rdf:about' => $uri));
if ($p[0] == LISTENER || $p[0] == BOTH) { if ($p[0] == LISTENER || $p[0] == BOTH) {
common_element('knows', array('rdf:resource' => $user->uri)); common_element('knows', array('rdf:resource' => $user->uri));
} }
$this->show_microblogging_account($profile, ($p[1] instanceof User) ? $this->show_microblogging_account($profile, ($p[1] instanceof User) ?
common_root_url() : NULL); common_root_url() : NULL);
if ($foaf_url) { if ($foaf_url) {
common_element('rdfs:seeAlso', array('rdf:resource' => $foaf_url)); common_element('rdfs:seeAlso', array('rdf:resource' => $foaf_url));
} }
common_element_end('Person'); common_element_end('Person');
if ($foaf_url) { if ($foaf_url) {
$this->show_ppd($foaf_url, $uri); $this->show_ppd($foaf_url, $uri);
} }
} }
common_element_end('rdf:RDF'); common_element_end('rdf:RDF');
} }
function show_ppd($foaf_url, $person_uri) { function show_ppd($foaf_url, $person_uri) {
common_element_start('PersonalProfileDocument', array('rdf:about' => $foaf_url)); common_element_start('PersonalProfileDocument', array('rdf:about' => $foaf_url));
common_element('maker', array('rdf:resource' => $person_uri)); common_element('maker', array('rdf:resource' => $person_uri));
common_element('primaryTopic', array('rdf:resource' => $person_uri)); common_element('primaryTopic', array('rdf:resource' => $person_uri));
common_element_end('PersonalProfileDocument'); common_element_end('PersonalProfileDocument');
} }
function show_microblogging_account($profile, $service=NULL) { function show_microblogging_account($profile, $service=NULL) {
# Their account # Their account
common_element_start('holdsAccount'); common_element_start('holdsAccount');
common_element_start('OnlineAccount'); common_element_start('OnlineAccount');
if ($service) { if ($service) {
common_element('accountServiceHomepage', array('rdf:resource' => common_element('accountServiceHomepage', array('rdf:resource' =>
$service)); $service));
} }
common_element('accountName', NULL, $profile->nickname); common_element('accountName', NULL, $profile->nickname);
common_element('homepage', array('rdf:resource' => $profile->profileurl)); common_element('homepage', array('rdf:resource' => $profile->profileurl));
common_element_end('OnlineAccount'); common_element_end('OnlineAccount');
common_element_end('holdsAccount'); common_element_end('holdsAccount');
} }
} }

View File

@ -24,247 +24,247 @@ require_once(INSTALLDIR.'/lib/jabber.php');
class ImsettingsAction extends SettingsAction { class ImsettingsAction extends SettingsAction {
function get_instructions() { function get_instructions() {
return _('You can send and receive notices through Jabber/GTalk [instant messages](%%doc.im%%). Configure your address and settings below.'); return _('You can send and receive notices through Jabber/GTalk [instant messages](%%doc.im%%). Configure your address and settings below.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$user = common_current_user(); $user = common_current_user();
$this->form_header(_('IM Settings'), $msg, $success); $this->form_header(_('IM Settings'), $msg, $success);
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'imsettings', 'id' => 'imsettings',
'action' => 'action' =>
common_local_url('imsettings'))); common_local_url('imsettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('h2', NULL, _('Address')); common_element('h2', NULL, _('Address'));
if ($user->jabber) { if ($user->jabber) {
common_element_start('p'); common_element_start('p');
common_element('span', 'address confirmed', $user->jabber); common_element('span', 'address confirmed', $user->jabber);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Current confirmed Jabber/GTalk address.')); _('Current confirmed Jabber/GTalk address.'));
common_hidden('jabber', $user->jabber); common_hidden('jabber', $user->jabber);
common_element_end('p'); common_element_end('p');
common_submit('remove', _('Remove')); common_submit('remove', _('Remove'));
} else { } else {
$confirm = $this->get_confirmation(); $confirm = $this->get_confirmation();
if ($confirm) { if ($confirm) {
common_element_start('p'); common_element_start('p');
common_element('span', 'address unconfirmed', $confirm->address); common_element('span', 'address unconfirmed', $confirm->address);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
sprintf(_('Awaiting confirmation on this address. Check your Jabber/GTalk account for a message with further instructions. (Did you add %s to your buddy list?)'), jabber_daemon_address())); sprintf(_('Awaiting confirmation on this address. Check your Jabber/GTalk account for a message with further instructions. (Did you add %s to your buddy list?)'), jabber_daemon_address()));
common_hidden('jabber', $confirm->address); common_hidden('jabber', $confirm->address);
common_element_end('p'); common_element_end('p');
common_submit('cancel', _('Cancel')); common_submit('cancel', _('Cancel'));
} else { } else {
common_input('jabber', _('IM Address'), common_input('jabber', _('IM Address'),
($this->arg('jabber')) ? $this->arg('jabber') : NULL, ($this->arg('jabber')) ? $this->arg('jabber') : NULL,
sprintf(_('Jabber or GTalk address, like "UserName@example.org". First, make sure to add %s to your buddy list in your IM client or on GTalk.'), jabber_daemon_address())); sprintf(_('Jabber or GTalk address, like "UserName@example.org". First, make sure to add %s to your buddy list in your IM client or on GTalk.'), jabber_daemon_address()));
common_submit('add', _('Add')); common_submit('add', _('Add'));
} }
} }
common_element('h2', NULL, _('Preferences')); common_element('h2', NULL, _('Preferences'));
common_checkbox('jabbernotify', common_checkbox('jabbernotify',
_('Send me notices through Jabber/GTalk.'), _('Send me notices through Jabber/GTalk.'),
$user->jabbernotify); $user->jabbernotify);
common_checkbox('updatefrompresence', common_checkbox('updatefrompresence',
_('Post a notice when my Jabber/GTalk status changes.'), _('Post a notice when my Jabber/GTalk status changes.'),
$user->updatefrompresence); $user->updatefrompresence);
common_checkbox('jabberreplies', common_checkbox('jabberreplies',
_('Send me replies through Jabber/GTalk from people I\'m not subscribed to.'), _('Send me replies through Jabber/GTalk from people I\'m not subscribed to.'),
$user->jabberreplies); $user->jabberreplies);
common_checkbox('jabbermicroid', common_checkbox('jabbermicroid',
_('Publish a MicroID for my Jabber/GTalk address.'), _('Publish a MicroID for my Jabber/GTalk address.'),
$user->jabbermicroid); $user->jabbermicroid);
common_submit('save', _('Save')); common_submit('save', _('Save'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function get_confirmation() { function get_confirmation() {
$user = common_current_user(); $user = common_current_user();
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->address_type = 'jabber'; $confirm->address_type = 'jabber';
if ($confirm->find(TRUE)) { if ($confirm->find(TRUE)) {
return $confirm; return $confirm;
} else { } else {
return NULL; return NULL;
} }
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('save')) { if ($this->arg('save')) {
$this->save_preferences(); $this->save_preferences();
} else if ($this->arg('add')) { } else if ($this->arg('add')) {
$this->add_address(); $this->add_address();
} else if ($this->arg('cancel')) { } else if ($this->arg('cancel')) {
$this->cancel_confirmation(); $this->cancel_confirmation();
} else if ($this->arg('remove')) { } else if ($this->arg('remove')) {
$this->remove_address(); $this->remove_address();
} else { } else {
$this->show_form(_('Unexpected form submission.')); $this->show_form(_('Unexpected form submission.'));
} }
} }
function save_preferences() { function save_preferences() {
$jabbernotify = $this->boolean('jabbernotify'); $jabbernotify = $this->boolean('jabbernotify');
$updatefrompresence = $this->boolean('updatefrompresence'); $updatefrompresence = $this->boolean('updatefrompresence');
$jabberreplies = $this->boolean('jabberreplies'); $jabberreplies = $this->boolean('jabberreplies');
$jabbermicroid = $this->boolean('jabbermicroid'); $jabbermicroid = $this->boolean('jabbermicroid');
$user = common_current_user(); $user = common_current_user();
assert(!is_null($user)); # should already be checked assert(!is_null($user)); # should already be checked
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->jabbernotify = $jabbernotify; $user->jabbernotify = $jabbernotify;
$user->updatefrompresence = $updatefrompresence; $user->updatefrompresence = $updatefrompresence;
$user->jabberreplies = $jabberreplies; $user->jabberreplies = $jabberreplies;
$user->jabbermicroid = $jabbermicroid; $user->jabbermicroid = $jabbermicroid;
$result = $user->update($original); $result = $user->update($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
$this->show_form(_('Preferences saved.'), true); $this->show_form(_('Preferences saved.'), true);
} }
function add_address() { function add_address() {
$user = common_current_user(); $user = common_current_user();
$jabber = $this->trimmed('jabber'); $jabber = $this->trimmed('jabber');
# Some validation # Some validation
if (!$jabber) { if (!$jabber) {
$this->show_form(_('No Jabber ID.')); $this->show_form(_('No Jabber ID.'));
return; return;
} }
$jabber = jabber_normalize_jid($jabber); $jabber = jabber_normalize_jid($jabber);
if (!$jabber) { if (!$jabber) {
$this->show_form(_('Cannot normalize that Jabber ID')); $this->show_form(_('Cannot normalize that Jabber ID'));
return; return;
} }
if (!jabber_valid_base_jid($jabber)) { if (!jabber_valid_base_jid($jabber)) {
$this->show_form(_('Not a valid Jabber ID')); $this->show_form(_('Not a valid Jabber ID'));
return; return;
} else if ($user->jabber == $jabber) { } else if ($user->jabber == $jabber) {
$this->show_form(_('That is already your Jabber ID.')); $this->show_form(_('That is already your Jabber ID.'));
return; return;
} else if ($this->jabber_exists($jabber)) { } else if ($this->jabber_exists($jabber)) {
$this->show_form(_('Jabber ID already belongs to another user.')); $this->show_form(_('Jabber ID already belongs to another user.'));
return; return;
} }
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->address = $jabber; $confirm->address = $jabber;
$confirm->address_type = 'jabber'; $confirm->address_type = 'jabber';
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->code = common_confirmation_code(64); $confirm->code = common_confirmation_code(64);
$result = $confirm->insert(); $result = $confirm->insert();
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($confirm, 'INSERT', __FILE__); common_log_db_error($confirm, 'INSERT', __FILE__);
common_server_error(_('Couldn\'t insert confirmation code.')); common_server_error(_('Couldn\'t insert confirmation code.'));
return; return;
} }
if (!common_config('queue', 'enabled')) { if (!common_config('queue', 'enabled')) {
jabber_confirm_address($confirm->code, jabber_confirm_address($confirm->code,
$user->nickname, $user->nickname,
$jabber); $jabber);
} }
$msg = sprintf(_('A confirmation code was sent to the IM address you added. You must approve %s for sending messages to you.'), jabber_daemon_address()); $msg = sprintf(_('A confirmation code was sent to the IM address you added. You must approve %s for sending messages to you.'), jabber_daemon_address());
$this->show_form($msg, TRUE); $this->show_form($msg, TRUE);
} }
function cancel_confirmation() { function cancel_confirmation() {
$jabber = $this->arg('jabber'); $jabber = $this->arg('jabber');
$confirm = $this->get_confirmation(); $confirm = $this->get_confirmation();
if (!$confirm) { if (!$confirm) {
$this->show_form(_('No pending confirmation to cancel.')); $this->show_form(_('No pending confirmation to cancel.'));
return; return;
} }
if ($confirm->address != $jabber) { if ($confirm->address != $jabber) {
$this->show_form(_('That is the wrong IM address.')); $this->show_form(_('That is the wrong IM address.'));
return; return;
} }
$result = $confirm->delete(); $result = $confirm->delete();
if (!$result) { if (!$result) {
common_log_db_error($confirm, 'DELETE', __FILE__); common_log_db_error($confirm, 'DELETE', __FILE__);
$this->server_error(_('Couldn\'t delete email confirmation.')); $this->server_error(_('Couldn\'t delete email confirmation.'));
return; return;
} }
$this->show_form(_('Confirmation cancelled.'), TRUE); $this->show_form(_('Confirmation cancelled.'), TRUE);
} }
function remove_address() { function remove_address() {
$user = common_current_user(); $user = common_current_user();
$jabber = $this->arg('jabber'); $jabber = $this->arg('jabber');
# Maybe an old tab open...? # Maybe an old tab open...?
if ($user->jabber != $jabber) { if ($user->jabber != $jabber) {
$this->show_form(_('That is not your Jabber ID.')); $this->show_form(_('That is not your Jabber ID.'));
return; return;
} }
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->jabber = NULL; $user->jabber = NULL;
$result = $user->updateKeys($original); $result = $user->updateKeys($original);
if (!$result) { if (!$result) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
# XXX: unsubscribe to the old address # XXX: unsubscribe to the old address
$this->show_form(_('The address was removed.'), TRUE); $this->show_form(_('The address was removed.'), TRUE);
} }
function jabber_exists($jabber) { function jabber_exists($jabber) {
$user = common_current_user(); $user = common_current_user();
$other = User::staticGet('jabber', $jabber); $other = User::staticGet('jabber', $jabber);
if (!$other) { if (!$other) {
return false; return false;
} else { } else {
return $other->id != $user->id; return $other->id != $user->id;
} }
} }
} }

View File

@ -21,179 +21,179 @@ if (!defined('LACONICA')) { exit(1); }
class InviteAction extends Action { class InviteAction extends Action {
function is_readonly() { function is_readonly() {
return false; return false;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
$this->client_error(sprintf(_('You must be logged in to invite other users to use %s'), $this->client_error(sprintf(_('You must be logged in to invite other users to use %s'),
common_config('site', 'name'))); common_config('site', 'name')));
return; return;
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->send_invitations(); $this->send_invitations();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
function send_invitations() { function send_invitations() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
$profile = $user->getProfile(); $profile = $user->getProfile();
$bestname = $profile->getBestName(); $bestname = $profile->getBestName();
$sitename = common_config('site', 'name'); $sitename = common_config('site', 'name');
$personal = $this->trimmed('personal'); $personal = $this->trimmed('personal');
$addresses = explode("\n", $this->trimmed('addresses')); $addresses = explode("\n", $this->trimmed('addresses'));
foreach ($addresses as $email) { foreach ($addresses as $email) {
$email = trim($email); $email = trim($email);
if (!Validate::email($email, true)) { if (!Validate::email($email, true)) {
$this->show_form(sprintf(_('Invalid email address: %s'), $email)); $this->show_form(sprintf(_('Invalid email address: %s'), $email));
return; return;
} }
} }
$already = array(); $already = array();
$subbed = array(); $subbed = array();
foreach ($addresses as $email) { foreach ($addresses as $email) {
$email = common_canonical_email($email); $email = common_canonical_email($email);
$other = User::staticGet('email', $email); $other = User::staticGet('email', $email);
if ($other) { if ($other) {
if ($user->isSubscribed($other)) { if ($user->isSubscribed($other)) {
$already[] = $other; $already[] = $other;
} else { } else {
subs_subscribe_to($user, $other); subs_subscribe_to($user, $other);
$subbed[] = $other; $subbed[] = $other;
} }
} else { } else {
$sent[] = $email; $sent[] = $email;
$this->send_invitation($email, $user, $personal); $this->send_invitation($email, $user, $personal);
} }
} }
common_show_header(_('Invitation(s) sent')); common_show_header(_('Invitation(s) sent'));
if ($already) { if ($already) {
common_element('p', NULL, _('You are already subscribed to these users:')); common_element('p', NULL, _('You are already subscribed to these users:'));
common_element_start('ul'); common_element_start('ul');
foreach ($already as $other) { foreach ($already as $other) {
common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email)); common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email));
} }
common_element_end('ul'); common_element_end('ul');
} }
if ($subbed) { if ($subbed) {
common_element('p', NULL, _('These people are already users and you were automatically subscribed to them:')); common_element('p', NULL, _('These people are already users and you were automatically subscribed to them:'));
common_element_start('ul'); common_element_start('ul');
foreach ($subbed as $other) { foreach ($subbed as $other) {
common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email)); common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email));
} }
common_element_end('ul'); common_element_end('ul');
} }
if ($sent) { if ($sent) {
common_element('p', NULL, _('Invitation(s) sent to the following people:')); common_element('p', NULL, _('Invitation(s) sent to the following people:'));
common_element_start('ul'); common_element_start('ul');
foreach ($sent as $other) { foreach ($sent as $other) {
common_element('li', NULL, $other); common_element('li', NULL, $other);
} }
common_element_end('ul'); common_element_end('ul');
common_element('p', NULL, _('You will be notified when your invitees accept the invitation and register on the site. Thanks for growing the community!')); common_element('p', NULL, _('You will be notified when your invitees accept the invitation and register on the site. Thanks for growing the community!'));
} }
common_show_footer(); common_show_footer();
} }
function show_top($error=NULL) { function show_top($error=NULL) {
if ($error) { if ($error) {
common_element('p', 'error', $error); common_element('p', 'error', $error);
} else { } else {
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_element('p', NULL, common_element('p', NULL,
_('Use this form to invite your friends and colleagues to use this service.')); _('Use this form to invite your friends and colleagues to use this service.'));
common_element_end('div'); common_element_end('div');
} }
} }
function show_form($error=NULL) { function show_form($error=NULL) {
global $config; global $config;
common_show_header(_('Invite new users'), NULL, $error, array($this, 'show_top')); common_show_header(_('Invite new users'), NULL, $error, array($this, 'show_top'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'invite', 'id' => 'invite',
'action' => common_local_url('invite'))); 'action' => common_local_url('invite')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_textarea('addresses', _('Email addresses'), common_textarea('addresses', _('Email addresses'),
$this->trimmed('addresses'), $this->trimmed('addresses'),
_('Addresses of friends to invite (one per line)')); _('Addresses of friends to invite (one per line)'));
common_textarea('personal', _('Personal message'), common_textarea('personal', _('Personal message'),
$this->trimmed('personal'), $this->trimmed('personal'),
_('Optionally add a personal message to the invitation.')); _('Optionally add a personal message to the invitation.'));
common_submit('send', _('Send')); common_submit('send', _('Send'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function send_invitation($email, $user, $personal) { function send_invitation($email, $user, $personal) {
$profile = $user->getProfile(); $profile = $user->getProfile();
$bestname = $profile->getBestName(); $bestname = $profile->getBestName();
$sitename = common_config('site', 'name'); $sitename = common_config('site', 'name');
$invite = new Invitation(); $invite = new Invitation();
$invite->address = $email; $invite->address = $email;
$invite->address_type = 'email'; $invite->address_type = 'email';
$invite->code = common_confirmation_code(128); $invite->code = common_confirmation_code(128);
$invite->user_id = $user->id; $invite->user_id = $user->id;
$invite->created = common_sql_now(); $invite->created = common_sql_now();
if (!$invite->insert()) { if (!$invite->insert()) {
common_log_db_error($invite, 'INSERT', __FILE__); common_log_db_error($invite, 'INSERT', __FILE__);
return false; return false;
} }
$recipients = array($email); $recipients = array($email);
$headers['From'] = mail_notify_from(); $headers['From'] = mail_notify_from();
$headers['To'] = $email; $headers['To'] = $email;
$headers['Subject'] = sprintf(_('%1$s has invited you to join them on %2$s'), $bestname, $sitename); $headers['Subject'] = sprintf(_('%1$s has invited you to join them on %2$s'), $bestname, $sitename);
$body = sprintf(_("%1\$s has invited you to join them on %2\$s (%3\$s).\n\n". $body = sprintf(_("%1\$s has invited you to join them on %2\$s (%3\$s).\n\n".
"%2\$s is a micro-blogging service that lets you keep up-to-date with people you know and people who interest you.\n\n". "%2\$s is a micro-blogging service that lets you keep up-to-date with people you know and people who interest you.\n\n".
"You can also share news about yourself, your thoughts, or your life online with people who know about you. ". "You can also share news about yourself, your thoughts, or your life online with people who know about you. ".
"It's also great for meeting new people who share your interests.\n\n". "It's also great for meeting new people who share your interests.\n\n".
"%1\$s said:\n\n%4\$s\n\n". "%1\$s said:\n\n%4\$s\n\n".
"You can see %1\$s's profile page on %2\$s here:\n\n". "You can see %1\$s's profile page on %2\$s here:\n\n".
"%5\$s\n\n". "%5\$s\n\n".
"If you'd like to try the service, click on the link below to accept the invitation.\n\n". "If you'd like to try the service, click on the link below to accept the invitation.\n\n".
"%6\$s\n\n". "%6\$s\n\n".
"If not, you can ignore this message. Thanks for your patience and your time.\n\n". "If not, you can ignore this message. Thanks for your patience and your time.\n\n".
"Sincerely, %2\$s\n"), "Sincerely, %2\$s\n"),
$bestname, $bestname,
$sitename, $sitename,
common_root_url(), common_root_url(),
$personal, $personal,
common_local_url('showstream', array('nickname' => $user->nickname)), common_local_url('showstream', array('nickname' => $user->nickname)),
common_local_url('register', array('code' => $invite->code))); common_local_url('register', array('code' => $invite->code)));
mail_send($recipients, $headers, $body); mail_send($recipients, $headers, $body);
} }
} }

View File

@ -21,132 +21,132 @@ if (!defined('LACONICA')) { exit(1); }
class LoginAction extends Action { class LoginAction extends Action {
function is_readonly() { function is_readonly() {
return true; return true;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_is_real_login()) { if (common_is_real_login()) {
common_user_error(_('Already logged in.')); common_user_error(_('Already logged in.'));
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->check_login(); $this->check_login();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
function check_login() { function check_login() {
# XXX: login throttle # XXX: login throttle
# CSRF protection - token set in common_notice_form() # CSRF protection - token set in common_notice_form()
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$nickname = common_canonical_nickname($this->trimmed('nickname')); $nickname = common_canonical_nickname($this->trimmed('nickname'));
$password = $this->arg('password'); $password = $this->arg('password');
if (common_check_user($nickname, $password)) { if (common_check_user($nickname, $password)) {
# success! # success!
if (!common_set_user($nickname)) { if (!common_set_user($nickname)) {
common_server_error(_('Error setting user.')); common_server_error(_('Error setting user.'));
return; return;
} }
common_real_login(true); common_real_login(true);
if ($this->boolean('rememberme')) { if ($this->boolean('rememberme')) {
common_debug('Adding rememberme cookie for ' . $nickname); common_debug('Adding rememberme cookie for ' . $nickname);
common_rememberme(); common_rememberme();
} }
# success! # success!
$url = common_get_returnto(); $url = common_get_returnto();
if ($url) { if ($url) {
# We don't have to return to it again # We don't have to return to it again
common_set_returnto(NULL); common_set_returnto(NULL);
} else { } else {
$url = common_local_url('all', $url = common_local_url('all',
array('nickname' => array('nickname' =>
$nickname)); $nickname));
} }
common_redirect($url); common_redirect($url);
} else { } else {
$this->show_form(_('Incorrect username or password.')); $this->show_form(_('Incorrect username or password.'));
return; return;
} }
# success! # success!
if (!common_set_user($user)) { if (!common_set_user($user)) {
common_server_error(_('Error setting user.')); common_server_error(_('Error setting user.'));
return; return;
} }
common_real_login(true); common_real_login(true);
if ($this->boolean('rememberme')) { if ($this->boolean('rememberme')) {
common_debug('Adding rememberme cookie for ' . $nickname); common_debug('Adding rememberme cookie for ' . $nickname);
common_rememberme($user); common_rememberme($user);
} }
# success! # success!
$url = common_get_returnto(); $url = common_get_returnto();
if ($url) { if ($url) {
# We don't have to return to it again # We don't have to return to it again
common_set_returnto(NULL); common_set_returnto(NULL);
} else { } else {
$url = common_local_url('all', $url = common_local_url('all',
array('nickname' => array('nickname' =>
$nickname)); $nickname));
} }
common_redirect($url); common_redirect($url);
} }
function show_form($error=NULL) { function show_form($error=NULL) {
common_show_header(_('Login'), NULL, $error, array($this, 'show_top')); common_show_header(_('Login'), NULL, $error, array($this, 'show_top'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'login', 'id' => 'login',
'action' => common_local_url('login'))); 'action' => common_local_url('login')));
common_input('nickname', _('Nickname')); common_input('nickname', _('Nickname'));
common_password('password', _('Password')); common_password('password', _('Password'));
common_checkbox('rememberme', _('Remember me'), false, common_checkbox('rememberme', _('Remember me'), false,
_('Automatically login in the future; ' . _('Automatically login in the future; ' .
'not for shared computers!')); 'not for shared computers!'));
common_submit('submit', _('Login')); common_submit('submit', _('Login'));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element_end('form'); common_element_end('form');
common_element_start('p'); common_element_start('p');
common_element('a', array('href' => common_local_url('recoverpassword')), common_element('a', array('href' => common_local_url('recoverpassword')),
_('Lost or forgotten password?')); _('Lost or forgotten password?'));
common_element_end('p'); common_element_end('p');
common_show_footer(); common_show_footer();
} }
function get_instructions() { function get_instructions() {
if (common_logged_in() && if (common_logged_in() &&
!common_is_real_login() && !common_is_real_login() &&
common_get_returnto()) common_get_returnto())
{ {
# rememberme logins have to reauthenticate before # rememberme logins have to reauthenticate before
# changing any profile settings (cookie-stealing protection) # changing any profile settings (cookie-stealing protection)
return _('For security reasons, please re-enter your ' . return _('For security reasons, please re-enter your ' .
'user name and password ' . 'user name and password ' .
'before changing your settings.'); 'before changing your settings.');
} else { } else {
return _('Login with your username and password. ' . return _('Login with your username and password. ' .
'Don\'t have a username yet? ' . 'Don\'t have a username yet? ' .
'[Register](%%action.register%%) a new account, or ' . '[Register](%%action.register%%) a new account, or ' .
'try [OpenID](%%action.openidlogin%%). '); 'try [OpenID](%%action.openidlogin%%). ');
} }
} }
function show_top($error=NULL) { function show_top($error=NULL) {
if ($error) { if ($error) {
common_element('p', 'error', $error); common_element('p', 'error', $error);
} else { } else {
$instr = $this->get_instructions(); $instr = $this->get_instructions();
$output = common_markup_to_html($instr); $output = common_markup_to_html($instr);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
} }
} }
} }

View File

@ -22,20 +22,20 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/openid.php'); require_once(INSTALLDIR.'/lib/openid.php');
class LogoutAction extends Action { class LogoutAction extends Action {
function is_readonly() { function is_readonly() {
return true; return true;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
} else { } else {
common_set_user(NULL); common_set_user(NULL);
common_real_login(false); # not logged in common_real_login(false); # not logged in
common_forgetme(); # don't log back in! common_forgetme(); # don't log back in!
common_redirect(common_local_url('public')); common_redirect(common_local_url('public'));
} }
} }
} }

View File

@ -21,26 +21,26 @@ if (!defined('LACONICA')) { exit(1); }
class MicrosummaryAction extends Action { class MicrosummaryAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname = common_canonical_nickname($this->arg('nickname')); $nickname = common_canonical_nickname($this->arg('nickname'));
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
$this->client_error(_('No such user'), 404); $this->client_error(_('No such user'), 404);
return; return;
} }
$notice = $user->getCurrentNotice(); $notice = $user->getCurrentNotice();
if (!$notice) { if (!$notice) {
$this->client_error(_('No current status'), 404); $this->client_error(_('No current status'), 404);
} }
header('Content-Type: text/plain'); header('Content-Type: text/plain');
print $user->nickname . ': ' . $notice->content; print $user->nickname . ': ' . $notice->content;
} }
} }

View File

@ -20,116 +20,116 @@
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
class NewmessageAction extends Action { class NewmessageAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
$this->client_error(_('Not logged in.'), 403); $this->client_error(_('Not logged in.'), 403);
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->save_new_message(); $this->save_new_message();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
function save_new_message() { function save_new_message() {
$user = common_current_user(); $user = common_current_user();
assert($user); # XXX: maybe an error instead... assert($user); # XXX: maybe an error instead...
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$content = $this->trimmed('content'); $content = $this->trimmed('content');
$to = $this->trimmed('to'); $to = $this->trimmed('to');
if (!$content) { if (!$content) {
$this->show_form(_('No content!')); $this->show_form(_('No content!'));
return; return;
} else { } else {
$content_shortened = common_shorten_links($content); $content_shortened = common_shorten_links($content);
if (mb_strlen($content_shortened) > 140) { if (mb_strlen($content_shortened) > 140) {
common_debug("Content = '$content_shortened'", __FILE__); common_debug("Content = '$content_shortened'", __FILE__);
common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__); common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__);
$this->show_form(_('That\'s too long. Max message size is 140 chars.')); $this->show_form(_('That\'s too long. Max message size is 140 chars.'));
return; return;
} }
} }
$other = User::staticGet('id', $to); $other = User::staticGet('id', $to);
if (!$other) { if (!$other) {
$this->show_form(_('No recipient specified.')); $this->show_form(_('No recipient specified.'));
return; return;
} else if (!$user->mutuallySubscribed($other)) { } else if (!$user->mutuallySubscribed($other)) {
$this->client_error(_('You can\'t send a message to this user.'), 404); $this->client_error(_('You can\'t send a message to this user.'), 404);
return; return;
} else if ($user->id == $other->id) { } else if ($user->id == $other->id) {
$this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), 403); $this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), 403);
return; return;
} }
$message = Message::saveNew($user->id, $other->id, $content, 'web'); $message = Message::saveNew($user->id, $other->id, $content, 'web');
if (is_string($message)) { if (is_string($message)) {
$this->show_form($message); $this->show_form($message);
return; return;
} }
$this->notify($user, $other, $message); $this->notify($user, $other, $message);
$url = common_local_url('outbox', array('nickname' => $user->nickname)); $url = common_local_url('outbox', array('nickname' => $user->nickname));
common_redirect($url, 303); common_redirect($url, 303);
} }
function show_top($params) { function show_top($params) {
list($content, $user, $to) = $params; list($content, $user, $to) = $params;
assert(!is_null($user)); assert(!is_null($user));
common_message_form($content, $user, $to); common_message_form($content, $user, $to);
} }
function show_form($msg=NULL) { function show_form($msg=NULL) {
$content = $this->trimmed('content'); $content = $this->trimmed('content');
$user = common_current_user(); $user = common_current_user();
$to = $this->trimmed('to'); $to = $this->trimmed('to');
$other = User::staticGet('id', $to); $other = User::staticGet('id', $to);
if (!$other) { if (!$other) {
$this->client_error(_('No such user'), 404); $this->client_error(_('No such user'), 404);
return; return;
} }
if (!$user->mutuallySubscribed($other)) { if (!$user->mutuallySubscribed($other)) {
$this->client_error(_('You can\'t send a message to this user.'), 404); $this->client_error(_('You can\'t send a message to this user.'), 404);
return; return;
} }
common_show_header(_('New message'), NULL, common_show_header(_('New message'), NULL,
array($content, $user, $other), array($content, $user, $other),
array($this, 'show_top')); array($this, 'show_top'));
if ($msg) { if ($msg) {
common_element('p', array('id'=>'error'), $msg); common_element('p', array('id'=>'error'), $msg);
} }
common_show_footer(); common_show_footer();
} }
function notify($from, $to, $message) { function notify($from, $to, $message) {
mail_notify_message($message, $from, $to); mail_notify_message($message, $from, $to);
# XXX: Jabber, SMS notifications... probably queued # XXX: Jabber, SMS notifications... probably queued
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,132 +23,132 @@ require_once INSTALLDIR . '/lib/noticelist.php';
class NewnoticeAction extends Action { class NewnoticeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
# CSRF protection - token set in common_notice_form() # CSRF protection - token set in common_notice_form()
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$this->save_new_notice(); $this->save_new_notice();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
function save_new_notice() { function save_new_notice() {
$user = common_current_user(); $user = common_current_user();
assert($user); # XXX: maybe an error instead... assert($user); # XXX: maybe an error instead...
$content = $this->trimmed('status_textarea'); $content = $this->trimmed('status_textarea');
if (!$content) { if (!$content) {
$this->show_form(_('No content!')); $this->show_form(_('No content!'));
return; return;
} else { } else {
$content_shortened = common_shorten_links($content); $content_shortened = common_shorten_links($content);
if (mb_strlen($content_shortened) > 140) { if (mb_strlen($content_shortened) > 140) {
common_debug("Content = '$content_shortened'", __FILE__); common_debug("Content = '$content_shortened'", __FILE__);
common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__); common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__);
$this->show_form(_('That\'s too long. Max notice size is 140 chars.')); $this->show_form(_('That\'s too long. Max notice size is 140 chars.'));
return; return;
} }
} }
$inter = new CommandInterpreter(); $inter = new CommandInterpreter();
$cmd = $inter->handle_command($user, $content_shortened); $cmd = $inter->handle_command($user, $content_shortened);
if ($cmd) { if ($cmd) {
if ($this->boolean('ajax')) { if ($this->boolean('ajax')) {
$cmd->execute(new AjaxWebChannel()); $cmd->execute(new AjaxWebChannel());
} else { } else {
$cmd->execute(new WebChannel()); $cmd->execute(new WebChannel());
} }
return; return;
} }
$replyto = $this->trimmed('inreplyto'); $replyto = $this->trimmed('inreplyto');
$notice = Notice::saveNew($user->id, $content, 'web', 1, ($replyto == 'false') ? NULL : $replyto); $notice = Notice::saveNew($user->id, $content, 'web', 1, ($replyto == 'false') ? NULL : $replyto);
if (is_string($notice)) { if (is_string($notice)) {
$this->show_form($notice); $this->show_form($notice);
return; return;
} }
common_broadcast_notice($notice); common_broadcast_notice($notice);
if ($this->boolean('ajax')) { if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Notice posted')); common_element('title', null, _('Notice posted'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
$this->show_notice($notice); $this->show_notice($notice);
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} else { } else {
$returnto = $this->trimmed('returnto'); $returnto = $this->trimmed('returnto');
if ($returnto) { if ($returnto) {
$url = common_local_url($returnto, $url = common_local_url($returnto,
array('nickname' => $user->nickname)); array('nickname' => $user->nickname));
} else { } else {
$url = common_local_url('shownotice', $url = common_local_url('shownotice',
array('notice' => $notice->id)); array('notice' => $notice->id));
} }
common_redirect($url, 303); common_redirect($url, 303);
} }
} }
function ajax_error_msg($msg) { function ajax_error_msg($msg) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Ajax Error')); common_element('title', null, _('Ajax Error'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
common_element('p', array('id' => 'error'), $msg); common_element('p', array('id' => 'error'), $msg);
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} }
function show_top($content=NULL) { function show_top($content=NULL) {
common_notice_form(NULL, $content); common_notice_form(NULL, $content);
} }
function show_form($msg=NULL) { function show_form($msg=NULL) {
if ($msg && $this->boolean('ajax')) { if ($msg && $this->boolean('ajax')) {
$this->ajax_error_msg($msg); $this->ajax_error_msg($msg);
return; return;
} }
$content = $this->trimmed('status_textarea'); $content = $this->trimmed('status_textarea');
if (!$content) { if (!$content) {
$replyto = $this->trimmed('replyto'); $replyto = $this->trimmed('replyto');
$profile = Profile::staticGet('nickname', $replyto); $profile = Profile::staticGet('nickname', $replyto);
if ($profile) { if ($profile) {
$content = '@' . $profile->nickname . ' '; $content = '@' . $profile->nickname . ' ';
} }
} }
common_show_header(_('New notice'), NULL, $content, common_show_header(_('New notice'), NULL, $content,
array($this, 'show_top')); array($this, 'show_top'));
if ($msg) { if ($msg) {
common_element('p', array('id' => 'error'), $msg); common_element('p', array('id' => 'error'), $msg);
} }
common_show_footer(); common_show_footer();
} }
function show_notice($notice) { function show_notice($notice) {
$nli = new NoticeListItem($notice); $nli = new NoticeListItem($notice);
$nli->show(); $nli->show();
} }
} }

View File

@ -25,140 +25,140 @@ require_once(INSTALLDIR.'/lib/searchaction.php');
class NoticesearchAction extends SearchAction { class NoticesearchAction extends SearchAction {
function get_instructions() { function get_instructions() {
return _('Search for notices on %%site.name%% by their contents. Separate search terms by spaces; they must be 3 characters or more.'); return _('Search for notices on %%site.name%% by their contents. Separate search terms by spaces; they must be 3 characters or more.');
} }
function get_title() { function get_title() {
return _('Text search'); return _('Text search');
} }
function show_results($q, $page) { function show_results($q, $page) {
$notice = new Notice(); $notice = new Notice();
# lcase it for comparison # lcase it for comparison
$q = strtolower($q); $q = strtolower($q);
$search_engine = $notice->getSearchEngine('identica_notices'); $search_engine = $notice->getSearchEngine('identica_notices');
$search_engine->set_sort_mode('chron'); $search_engine->set_sort_mode('chron');
# Ask for an extra to see if there's more. # Ask for an extra to see if there's more.
$search_engine->limit((($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1); $search_engine->limit((($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1);
if (false === $search_engine->query($q)) { if (false === $search_engine->query($q)) {
$cnt = 0; $cnt = 0;
} }
else { else {
$cnt = $notice->find(); $cnt = $notice->find();
}
if ($cnt > 0) {
$terms = preg_split('/[\s,]+/', $q);
common_element_start('ul', array('id' => 'notices'));
for ($i = 0; $i < min($cnt, NOTICES_PER_PAGE); $i++) {
if ($notice->fetch()) {
$this->show_notice($notice, $terms);
} else {
// shouldn't happen!
break;
}
}
common_element_end('ul');
} else {
common_element('p', 'error', _('No results'));
} }
if ($cnt > 0) {
$terms = preg_split('/[\s,]+/', $q);
common_element_start('ul', array('id' => 'notices'));
for ($i = 0; $i < min($cnt, NOTICES_PER_PAGE); $i++) {
if ($notice->fetch()) {
$this->show_notice($notice, $terms);
} else {
// shouldn't happen!
break;
}
}
common_element_end('ul');
} else {
common_element('p', 'error', _('No results'));
}
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'noticesearch', array('q' => $q)); $page, 'noticesearch', array('q' => $q));
} }
function show_header($arr) { function show_header($arr) {
if ($arr) { if ($arr) {
$q = $arr[0]; $q = $arr[0];
} }
if ($q) { if ($q) {
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('noticesearchrss', 'href' => common_local_url('noticesearchrss',
array('q' => $q)), array('q' => $q)),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => _('Search Stream Feed'))); 'title' => _('Search Stream Feed')));
} }
} }
# XXX: refactor and combine with StreamAction::show_notice() # XXX: refactor and combine with StreamAction::show_notice()
function show_notice($notice, $terms) { function show_notice($notice, $terms) {
$profile = $notice->getProfile(); $profile = $notice->getProfile();
if (!$profile) { if (!$profile) {
common_log_db_error($notice, 'SELECT', __FILE__); common_log_db_error($notice, 'SELECT', __FILE__);
$this->server_error(_('Notice without matching profile')); $this->server_error(_('Notice without matching profile'));
return; return;
} }
# XXX: RDFa # XXX: RDFa
common_element_start('li', array('class' => 'notice_single', common_element_start('li', array('class' => 'notice_single',
'id' => 'notice-' . $notice->id)); 'id' => 'notice-' . $notice->id));
$avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
common_element_start('a', array('href' => $profile->profileurl)); common_element_start('a', array('href' => $profile->profileurl));
common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE),
'class' => 'avatar stream', 'class' => 'avatar stream',
'width' => AVATAR_STREAM_SIZE, 'width' => AVATAR_STREAM_SIZE,
'height' => AVATAR_STREAM_SIZE, 'height' => AVATAR_STREAM_SIZE,
'alt' => 'alt' =>
($profile->fullname) ? $profile->fullname : ($profile->fullname) ? $profile->fullname :
$profile->nickname)); $profile->nickname));
common_element_end('a'); common_element_end('a');
common_element('a', array('href' => $profile->profileurl, common_element('a', array('href' => $profile->profileurl,
'class' => 'nickname'), 'class' => 'nickname'),
$profile->nickname); $profile->nickname);
# FIXME: URL, image, video, audio # FIXME: URL, image, video, audio
common_element_start('p', array('class' => 'content')); common_element_start('p', array('class' => 'content'));
if ($notice->rendered) { if ($notice->rendered) {
common_raw($this->highlight($notice->rendered, $terms)); common_raw($this->highlight($notice->rendered, $terms));
} else { } else {
# XXX: may be some uncooked notices in the DB, # XXX: may be some uncooked notices in the DB,
# we cook them right now. This should probably disappear in future # we cook them right now. This should probably disappear in future
# versions (>> 0.4.x) # versions (>> 0.4.x)
common_raw($this->highlight(common_render_content($notice->content, $notice), $terms)); common_raw($this->highlight(common_render_content($notice->content, $notice), $terms));
} }
common_element_end('p'); common_element_end('p');
$noticeurl = common_local_url('shownotice', array('notice' => $notice->id)); $noticeurl = common_local_url('shownotice', array('notice' => $notice->id));
common_element_start('p', 'time'); common_element_start('p', 'time');
common_element('a', array('class' => 'permalink', common_element('a', array('class' => 'permalink',
'href' => $noticeurl, 'href' => $noticeurl,
'title' => common_exact_date($notice->created)), 'title' => common_exact_date($notice->created)),
common_date_string($notice->created)); common_date_string($notice->created));
if ($notice->reply_to) { if ($notice->reply_to) {
$replyurl = common_local_url('shownotice', array('notice' => $notice->reply_to)); $replyurl = common_local_url('shownotice', array('notice' => $notice->reply_to));
common_text(' ('); common_text(' (');
common_element('a', array('class' => 'inreplyto', common_element('a', array('class' => 'inreplyto',
'href' => $replyurl), 'href' => $replyurl),
_('in reply to...')); _('in reply to...'));
common_text(')'); common_text(')');
} }
common_element_start('a', common_element_start('a',
array('href' => common_local_url('newnotice', array('href' => common_local_url('newnotice',
array('replyto' => $profile->nickname)), array('replyto' => $profile->nickname)),
'onclick' => 'doreply("'.$profile->nickname.'"); return false', 'onclick' => 'doreply("'.$profile->nickname.'"); return false',
'title' => _('reply'), 'title' => _('reply'),
'class' => 'replybutton')); 'class' => 'replybutton'));
common_hidden('posttoken', common_session_token()); common_hidden('posttoken', common_session_token());
common_raw('&rarr;'); common_raw('&rarr;');
common_element_end('a'); common_element_end('a');
common_element_end('p'); common_element_end('p');
common_element_end('li'); common_element_end('li');
} }
function highlight($text, $terms) { function highlight($text, $terms) {
/* Highligh serach terms */ /* Highligh serach terms */
$pattern = '/('.implode('|',array_map('htmlspecialchars', $terms)).')/i'; $pattern = '/('.implode('|',array_map('htmlspecialchars', $terms)).')/i';
$result = preg_replace($pattern, '<strong>\\1</strong>', $text); $result = preg_replace($pattern, '<strong>\\1</strong>', $text);
/* Remove highlighting from inside links, loop incase multiple highlights in links */ /* Remove highlighting from inside links, loop incase multiple highlights in links */
$pattern = '/(href="[^"]*)<strong>('.implode('|',array_map('htmlspecialchars', $terms)).')<\/strong>([^"]*")/iU'; $pattern = '/(href="[^"]*)<strong>('.implode('|',array_map('htmlspecialchars', $terms)).')<\/strong>([^"]*")/iU';
do { do {
$result = preg_replace($pattern, '\\1\\2\\3', $result, -1, $count); $result = preg_replace($pattern, '\\1\\2\\3', $result, -1, $count);
} while ($count); } while ($count);
return $result; return $result;
} }
} }

View File

@ -25,46 +25,46 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class NoticesearchrssAction extends Rss10Action { class NoticesearchrssAction extends Rss10Action {
function init() { function init() {
return true; return true;
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$q = $this->trimmed('q'); $q = $this->trimmed('q');
$notices = array(); $notices = array();
$notice = new Notice(); $notice = new Notice();
# lcase it for comparison # lcase it for comparison
$q = strtolower($q); $q = strtolower($q);
$search_engine = $notice->getSearchEngine('identica_notices'); $search_engine = $notice->getSearchEngine('identica_notices');
$search_engine->set_sort_mode('chron'); $search_engine->set_sort_mode('chron');
if (!$limit) $limit = 20; if (!$limit) $limit = 20;
$search_engine->limit(0, $limit, true); $search_engine->limit(0, $limit, true);
$search_engine->query($q); $search_engine->query($q);
$notice->find(); $notice->find();
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
global $config; global $config;
$q = $this->trimmed('q'); $q = $this->trimmed('q');
$c = array('url' => common_local_url('noticesearchrss', array('q' => $q)), $c = array('url' => common_local_url('noticesearchrss', array('q' => $q)),
'title' => $config['site']['name'] . sprintf(_(' Search Stream for "%s"'), $q), 'title' => $config['site']['name'] . sprintf(_(' Search Stream for "%s"'), $q),
'link' => common_local_url('noticesearch', array('q' => $q)), 'link' => common_local_url('noticesearch', array('q' => $q)),
'description' => sprintf(_('All updates matching search term "%s"'), $q)); 'description' => sprintf(_('All updates matching search term "%s"'), $q));
return $c; return $c;
} }
function get_image() { function get_image() {
return NULL; return NULL;
} }
} }

View File

@ -23,62 +23,62 @@ require_once(INSTALLDIR.'/lib/mail.php');
class NudgeAction extends Action { class NudgeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
$this->client_error(_('Not logged in.')); $this->client_error(_('Not logged in.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
$other = User::staticGet('nickname', $this->arg('nickname')); $other = User::staticGet('nickname', $this->arg('nickname'));
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
common_redirect(common_local_url('showstream', array('nickname' => $other->nickname))); common_redirect(common_local_url('showstream', array('nickname' => $other->nickname)));
return; return;
} }
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if (!$other->email || !$other->emailnotifynudge) { if (!$other->email || !$other->emailnotifynudge) {
$this->client_error(_('This user doesn\'t allow nudges or hasn\'t confirmed or set his email yet.')); $this->client_error(_('This user doesn\'t allow nudges or hasn\'t confirmed or set his email yet.'));
return; return;
} }
$this->notify($user, $other); $this->notify($user, $other);
if ($this->boolean('ajax')) { if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Nudge sent')); common_element('title', null, _('Nudge sent'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
common_nudge_response(); common_nudge_response();
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} else { } else {
// display a confirmation to the user // display a confirmation to the user
common_redirect(common_local_url('showstream', common_redirect(common_local_url('showstream',
array('nickname' => $other->nickname))); array('nickname' => $other->nickname)));
} }
} }
function notify($user, $other) { function notify($user, $other) {
if ($other->id != $user->id) { if ($other->id != $user->id) {
if ($other->email && $other->emailnotifynudge) { if ($other->email && $other->emailnotifynudge) {
mail_notify_nudge($user, $other); mail_notify_nudge($user, $other);
} }
# XXX: notify by IM # XXX: notify by IM
# XXX: notify by SMS # XXX: notify by SMS
} }
} }
} }

View File

@ -23,70 +23,70 @@ require_once(INSTALLDIR.'/lib/openid.php');
class OpenidloginAction extends Action { class OpenidloginAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_logged_in()) { if (common_logged_in()) {
common_user_error(_('Already logged in.')); common_user_error(_('Already logged in.'));
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$openid_url = $this->trimmed('openid_url'); $openid_url = $this->trimmed('openid_url');
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.'), $openid_url); $this->show_form(_('There was a problem with your session token. Try again, please.'), $openid_url);
return; return;
} }
$rememberme = $this->boolean('rememberme'); $rememberme = $this->boolean('rememberme');
common_ensure_session(); common_ensure_session();
$_SESSION['openid_rememberme'] = $rememberme; $_SESSION['openid_rememberme'] = $rememberme;
$result = oid_authenticate($openid_url, $result = oid_authenticate($openid_url,
'finishopenidlogin'); 'finishopenidlogin');
if (is_string($result)) { # error message if (is_string($result)) { # error message
unset($_SESSION['openid_rememberme']); unset($_SESSION['openid_rememberme']);
$this->show_form($result, $openid_url); $this->show_form($result, $openid_url);
} }
} else { } else {
$openid_url = oid_get_last(); $openid_url = oid_get_last();
$this->show_form(NULL, $openid_url); $this->show_form(NULL, $openid_url);
} }
} }
function get_instructions() { function get_instructions() {
return _('Login with an [OpenID](%%doc.openid%%) account.'); return _('Login with an [OpenID](%%doc.openid%%) account.');
} }
function show_top($error=NULL) { function show_top($error=NULL) {
if ($error) { if ($error) {
common_element('div', array('class' => 'error'), $error); common_element('div', array('class' => 'error'), $error);
} else { } else {
$instr = $this->get_instructions(); $instr = $this->get_instructions();
$output = common_markup_to_html($instr); $output = common_markup_to_html($instr);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
} }
} }
function show_form($error=NULL, $openid_url) { function show_form($error=NULL, $openid_url) {
common_show_header(_('OpenID Login'), NULL, $error, array($this, 'show_top')); common_show_header(_('OpenID Login'), NULL, $error, array($this, 'show_top'));
$formaction = common_local_url('openidlogin'); $formaction = common_local_url('openidlogin');
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'openidlogin', 'id' => 'openidlogin',
'action' => $formaction)); 'action' => $formaction));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_input('openid_url', _('OpenID URL'), common_input('openid_url', _('OpenID URL'),
$openid_url, $openid_url,
_('Your OpenID URL')); _('Your OpenID URL'));
common_checkbox('rememberme', _('Remember me'), false, common_checkbox('rememberme', _('Remember me'), false,
_('Automatically login in the future; ' . _('Automatically login in the future; ' .
'not for shared computers!')); 'not for shared computers!'));
common_submit('submit', _('Login')); common_submit('submit', _('Login'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
} }

View File

@ -24,133 +24,133 @@ require_once(INSTALLDIR.'/lib/openid.php');
class OpenidsettingsAction extends SettingsAction { class OpenidsettingsAction extends SettingsAction {
function get_instructions() { function get_instructions() {
return _('[OpenID](%%doc.openid%%) lets you log into many sites ' . return _('[OpenID](%%doc.openid%%) lets you log into many sites ' .
' with the same user account. '. ' with the same user account. '.
' Manage your associated OpenIDs from here.'); ' Manage your associated OpenIDs from here.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$user = common_current_user(); $user = common_current_user();
$this->form_header(_('OpenID settings'), $msg, $success); $this->form_header(_('OpenID settings'), $msg, $success);
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'openidadd', 'id' => 'openidadd',
'action' => 'action' =>
common_local_url('openidsettings'))); common_local_url('openidsettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('h2', NULL, _('Add OpenID')); common_element('h2', NULL, _('Add OpenID'));
common_element('p', NULL, common_element('p', NULL,
_('If you want to add an OpenID to your account, ' . _('If you want to add an OpenID to your account, ' .
'enter it in the box below and click "Add".')); 'enter it in the box below and click "Add".'));
common_element_start('p'); common_element_start('p');
common_element('label', array('for' => 'openid_url'), common_element('label', array('for' => 'openid_url'),
_('OpenID URL')); _('OpenID URL'));
common_element('input', array('name' => 'openid_url', common_element('input', array('name' => 'openid_url',
'type' => 'text', 'type' => 'text',
'id' => 'openid_url')); 'id' => 'openid_url'));
common_element('input', array('type' => 'submit', common_element('input', array('type' => 'submit',
'id' => 'add', 'id' => 'add',
'name' => 'add', 'name' => 'add',
'class' => 'submit', 'class' => 'submit',
'value' => _('Add'))); 'value' => _('Add')));
common_element_end('p'); common_element_end('p');
common_element_end('form'); common_element_end('form');
$oid = new User_openid(); $oid = new User_openid();
$oid->user_id = $user->id; $oid->user_id = $user->id;
$cnt = $oid->find(); $cnt = $oid->find();
if ($cnt > 0) { if ($cnt > 0) {
common_element('h2', NULL, _('Remove OpenID')); common_element('h2', NULL, _('Remove OpenID'));
if ($cnt == 1 && !$user->password) { if ($cnt == 1 && !$user->password) {
common_element('p', NULL, common_element('p', NULL,
_('Removing your only OpenID would make it impossible to log in! ' . _('Removing your only OpenID would make it impossible to log in! ' .
'If you need to remove it, add another OpenID first.')); 'If you need to remove it, add another OpenID first.'));
if ($oid->fetch()) { if ($oid->fetch()) {
common_element_start('p'); common_element_start('p');
common_element('a', array('href' => $oid->canonical), common_element('a', array('href' => $oid->canonical),
$oid->display); $oid->display);
common_element_end('p'); common_element_end('p');
} }
} else { } else {
common_element('p', NULL, common_element('p', NULL,
_('You can remove an OpenID from your account '. _('You can remove an OpenID from your account '.
'by clicking the button marked "Remove".')); 'by clicking the button marked "Remove".'));
$idx = 0; $idx = 0;
while ($oid->fetch()) { while ($oid->fetch()) {
common_element_start('form', array('method' => 'POST', common_element_start('form', array('method' => 'POST',
'id' => 'openiddelete' . $idx, 'id' => 'openiddelete' . $idx,
'action' => 'action' =>
common_local_url('openidsettings'))); common_local_url('openidsettings')));
common_element_start('p'); common_element_start('p');
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('a', array('href' => $oid->canonical), common_element('a', array('href' => $oid->canonical),
$oid->display); $oid->display);
common_element('input', array('type' => 'hidden', common_element('input', array('type' => 'hidden',
'id' => 'openid_url'.$idx, 'id' => 'openid_url'.$idx,
'name' => 'openid_url', 'name' => 'openid_url',
'value' => $oid->canonical)); 'value' => $oid->canonical));
common_element('input', array('type' => 'submit', common_element('input', array('type' => 'submit',
'id' => 'remove'.$idx, 'id' => 'remove'.$idx,
'name' => 'remove', 'name' => 'remove',
'class' => 'submit', 'class' => 'submit',
'value' => _('Remove'))); 'value' => _('Remove')));
common_element_end('p'); common_element_end('p');
common_element_end('form'); common_element_end('form');
$idx++; $idx++;
} }
} }
} }
common_show_footer(); common_show_footer();
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('add')) { if ($this->arg('add')) {
$result = oid_authenticate($this->trimmed('openid_url'), 'finishaddopenid'); $result = oid_authenticate($this->trimmed('openid_url'), 'finishaddopenid');
if (is_string($result)) { # error message if (is_string($result)) { # error message
$this->show_form($result); $this->show_form($result);
} }
} else if ($this->arg('remove')) { } else if ($this->arg('remove')) {
$this->remove_openid(); $this->remove_openid();
} else { } else {
$this->show_form(_('Something weird happened.')); $this->show_form(_('Something weird happened.'));
} }
} }
function remove_openid() { function remove_openid() {
$openid_url = $this->trimmed('openid_url'); $openid_url = $this->trimmed('openid_url');
$oid = User_openid::staticGet('canonical', $openid_url); $oid = User_openid::staticGet('canonical', $openid_url);
if (!$oid) { if (!$oid) {
$this->show_form(_('No such OpenID.')); $this->show_form(_('No such OpenID.'));
return; return;
} }
$cur = common_current_user(); $cur = common_current_user();
if (!$cur || $oid->user_id != $cur->id) { if (!$cur || $oid->user_id != $cur->id) {
$this->show_form(_('That OpenID does not belong to you.')); $this->show_form(_('That OpenID does not belong to you.'));
return; return;
} }
$oid->delete(); $oid->delete();
$this->show_form(_('OpenID removed.'), true); $this->show_form(_('OpenID removed.'), true);
return; return;
} }
} }

View File

@ -21,39 +21,39 @@ if (!defined('LACONICA')) { exit(1); }
class OpensearchAction extends Action { class OpensearchAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$type = $this->trimmed('type'); $type = $this->trimmed('type');
$short_name = ''; $short_name = '';
if ($type == 'people') { if ($type == 'people') {
$type = 'peoplesearch'; $type = 'peoplesearch';
$short_name = _('People Search'); $short_name = _('People Search');
} else { } else {
$short_name = _('Notice Search'); $short_name = _('Notice Search');
$type = 'noticesearch'; $type = 'noticesearch';
} }
header('Content-Type: text/html'); header('Content-Type: text/html');
common_start_xml(); common_start_xml();
common_element_start('OpenSearchDescription', array('xmlns' => 'http://a9.com/-/spec/opensearch/1.1/')); common_element_start('OpenSearchDescription', array('xmlns' => 'http://a9.com/-/spec/opensearch/1.1/'));
$short_name = common_config('site', 'name').' '.$short_name; $short_name = common_config('site', 'name').' '.$short_name;
common_element('ShortName', NULL, $short_name); common_element('ShortName', NULL, $short_name);
common_element('Contact', NULL, common_config('site', 'email')); common_element('Contact', NULL, common_config('site', 'email'));
common_element('Url', array('type' => 'text/html', 'method' => 'get', common_element('Url', array('type' => 'text/html', 'method' => 'get',
'template' => str_replace('---', '{searchTerms}', common_local_url($type, array('q' => '---'))))); 'template' => str_replace('---', '{searchTerms}', common_local_url($type, array('q' => '---')))));
common_element('Image', array('height' => 16, 'width' => 16, 'type' => 'image/vnd.microsoft.icon'), common_path('favicon.ico')); common_element('Image', array('height' => 16, 'width' => 16, 'type' => 'image/vnd.microsoft.icon'), common_path('favicon.ico'));
common_element('Image', array('height' => 50, 'width' => 50, 'type' => 'image/png'), theme_path('logo.png')); common_element('Image', array('height' => 50, 'width' => 50, 'type' => 'image/png'), theme_path('logo.png'));
common_element('AdultContent', NULL, 'false'); common_element('AdultContent', NULL, 'false');
common_element('Language', NULL, common_language()); common_element('Language', NULL, common_language());
common_element('OutputEncoding', NULL, 'UTF-8'); common_element('OutputEncoding', NULL, 'UTF-8');
common_element('InputEncoding', NULL, 'UTF-8'); common_element('InputEncoding', NULL, 'UTF-8');
common_element_end('OpenSearchDescription'); common_element_end('OpenSearchDescription');
common_end_xml(); common_end_xml();
} }
} }

View File

@ -23,159 +23,159 @@ require_once(INSTALLDIR.'/lib/settingsaction.php');
class OthersettingsAction extends SettingsAction { class OthersettingsAction extends SettingsAction {
function get_instructions() { function get_instructions() {
return _('Manage various other options.'); return _('Manage various other options.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$user = common_current_user(); $user = common_current_user();
$this->form_header(_('Other Settings'), $msg, $success); $this->form_header(_('Other Settings'), $msg, $success);
common_element('h2', NULL, _('URL Auto-shortening')); common_element('h2', NULL, _('URL Auto-shortening'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'othersettings', 'id' => 'othersettings',
'action' => 'action' =>
common_local_url('othersettings'))); common_local_url('othersettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
$services = array( $services = array(
'' => 'None', '' => 'None',
'ur1.ca' => 'ur1.ca (free service)', 'ur1.ca' => 'ur1.ca (free service)',
'2tu.us' => '2tu.us (free service)', '2tu.us' => '2tu.us (free service)',
'ptiturl.com' => 'ptiturl.com', 'ptiturl.com' => 'ptiturl.com',
'bit.ly' => 'bit.ly', 'bit.ly' => 'bit.ly',
'tinyurl.com' => 'tinyurl.com', 'tinyurl.com' => 'tinyurl.com',
'is.gd' => 'is.gd', 'is.gd' => 'is.gd',
'snipr.com' => 'snipr.com', 'snipr.com' => 'snipr.com',
'metamark.net' => 'metamark.net' 'metamark.net' => 'metamark.net'
); );
common_dropdown('urlshorteningservice', _('Service'), $services, _('Automatic shortening service to use.'), FALSE, $user->urlshorteningservice); common_dropdown('urlshorteningservice', _('Service'), $services, _('Automatic shortening service to use.'), FALSE, $user->urlshorteningservice);
common_submit('save', _('Save')); common_submit('save', _('Save'));
common_element_end('form'); common_element_end('form');
// common_element('h2', NULL, _('Delete my account')); // common_element('h2', NULL, _('Delete my account'));
// $this->show_delete_form(); // $this->show_delete_form();
common_show_footer(); common_show_footer();
} }
function show_feeds_list($feeds) { function show_feeds_list($feeds) {
common_element_start('div', array('class' => 'feedsdel')); common_element_start('div', array('class' => 'feedsdel'));
common_element('p', null, 'Feeds:'); common_element('p', null, 'Feeds:');
common_element_start('ul', array('class' => 'xoxo')); common_element_start('ul', array('class' => 'xoxo'));
foreach ($feeds as $key => $value) { foreach ($feeds as $key => $value) {
$this->common_feed_item($feeds[$key]); $this->common_feed_item($feeds[$key]);
} }
common_element_end('ul'); common_element_end('ul');
common_element_end('div'); common_element_end('div');
} }
//TODO move to common.php (and retrace its origin) //TODO move to common.php (and retrace its origin)
function common_feed_item($feed) { function common_feed_item($feed) {
$user = common_current_user(); $user = common_current_user();
$nickname = $user->nickname; $nickname = $user->nickname;
switch($feed['item']) { switch($feed['item']) {
case 'notices': default: case 'notices': default:
$feed_classname = $feed['type']; $feed_classname = $feed['type'];
$feed_mimetype = "application/".$feed['type']."+xml"; $feed_mimetype = "application/".$feed['type']."+xml";
$feed_title = "$nickname's ".$feed['version']." notice feed"; $feed_title = "$nickname's ".$feed['version']." notice feed";
$feed['textContent'] = "RSS"; $feed['textContent'] = "RSS";
break; break;
case 'foaf': case 'foaf':
$feed_classname = "foaf"; $feed_classname = "foaf";
$feed_mimetype = "application/".$feed['type']."+xml"; $feed_mimetype = "application/".$feed['type']."+xml";
$feed_title = "$nickname's FOAF file"; $feed_title = "$nickname's FOAF file";
$feed['textContent'] = "FOAF"; $feed['textContent'] = "FOAF";
break; break;
} }
common_element_start('li'); common_element_start('li');
common_element('a', array('href' => $feed['href'], common_element('a', array('href' => $feed['href'],
'class' => $feed_classname, 'class' => $feed_classname,
'type' => $feed_mimetype, 'type' => $feed_mimetype,
'title' => $feed_title), 'title' => $feed_title),
$feed['textContent']); $feed['textContent']);
common_element_end('li'); common_element_end('li');
} }
// function show_delete_form() { // function show_delete_form() {
// $user = common_current_user(); // $user = common_current_user();
// $notices = DB_DataObject::factory('notice'); // $notices = DB_DataObject::factory('notice');
// $notices->profile_id = $user->id; // $notices->profile_id = $user->id;
// $notice_count = (int) $notices->count(); // $notice_count = (int) $notices->count();
// //
// common_element_start('form', array('method' => 'POST', // common_element_start('form', array('method' => 'POST',
// 'id' => 'delete', // 'id' => 'delete',
// 'action' => // 'action' =>
// common_local_url('deleteprofile'))); // common_local_url('deleteprofile')));
// //
// common_hidden('token', common_session_token()); // common_hidden('token', common_session_token());
// common_element('p', null, "You can copy your notices and contacts by saving the two links below before deleting your account. Be careful, this operation cannot be undone."); // common_element('p', null, "You can copy your notices and contacts by saving the two links below before deleting your account. Be careful, this operation cannot be undone.");
// //
// $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)), // $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)),
// 'type' => 'rss', // 'type' => 'rss',
// 'version' => 'RSS 1.0', // 'version' => 'RSS 1.0',
// 'item' => 'notices'), // 'item' => 'notices'),
// 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), // 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)),
// 'type' => 'rdf', // 'type' => 'rdf',
// 'version' => 'FOAF', // 'version' => 'FOAF',
// 'item' => 'foaf'))); // 'item' => 'foaf')));
// //
// common_submit('deleteaccount', _('Delete my account')); // common_submit('deleteaccount', _('Delete my account'));
// common_element_end('form'); // common_element_end('form');
// } // }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('save')) { if ($this->arg('save')) {
$this->save_preferences(); $this->save_preferences();
}else { }else {
$this->show_form(_('Unexpected form submission.')); $this->show_form(_('Unexpected form submission.'));
} }
} }
function save_preferences() { function save_preferences() {
$urlshorteningservice = $this->trimmed('urlshorteningservice'); $urlshorteningservice = $this->trimmed('urlshorteningservice');
if (!is_null($urlshorteningservice) && strlen($urlshorteningservice) > 50) { if (!is_null($urlshorteningservice) && strlen($urlshorteningservice) > 50) {
$this->show_form(_('URL shortening service is too long (max 50 chars).')); $this->show_form(_('URL shortening service is too long (max 50 chars).'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
assert(!is_null($user)); # should already be checked assert(!is_null($user)); # should already be checked
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->urlshorteningservice = $urlshorteningservice; $user->urlshorteningservice = $urlshorteningservice;
$result = $user->update($original); $result = $user->update($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
$this->show_form(_('Preferences saved.'), true); $this->show_form(_('Preferences saved.'), true);
} }
} }

View File

@ -24,61 +24,61 @@ require_once(INSTALLDIR.'/lib/profilelist.php');
class PeoplesearchAction extends SearchAction { class PeoplesearchAction extends SearchAction {
function get_instructions() { function get_instructions() {
return _('Search for people on %%site.name%% by their name, location, or interests. ' . return _('Search for people on %%site.name%% by their name, location, or interests. ' .
'Separate the terms by spaces; they must be 3 characters or more.'); 'Separate the terms by spaces; they must be 3 characters or more.');
} }
function get_title() { function get_title() {
return _('People search'); return _('People search');
} }
function show_results($q, $page) { function show_results($q, $page) {
$profile = new Profile(); $profile = new Profile();
# lcase it for comparison # lcase it for comparison
$q = strtolower($q); $q = strtolower($q);
$search_engine = $profile->getSearchEngine('identica_people'); $search_engine = $profile->getSearchEngine('identica_people');
$search_engine->set_sort_mode('chron'); $search_engine->set_sort_mode('chron');
# Ask for an extra to see if there's more. # Ask for an extra to see if there's more.
$search_engine->limit((($page-1)*PROFILES_PER_PAGE), PROFILES_PER_PAGE + 1); $search_engine->limit((($page-1)*PROFILES_PER_PAGE), PROFILES_PER_PAGE + 1);
if (false === $search_engine->query($q)) { if (false === $search_engine->query($q)) {
$cnt = 0; $cnt = 0;
} }
else { else {
$cnt = $profile->find(); $cnt = $profile->find();
}
if ($cnt > 0) {
$terms = preg_split('/[\s,]+/', $q);
$results = new PeopleSearchResults($profile, $terms);
$results->show_list();
} else {
common_element('p', 'error', _('No results'));
} }
if ($cnt > 0) {
$terms = preg_split('/[\s,]+/', $q);
$results = new PeopleSearchResults($profile, $terms);
$results->show_list();
} else {
common_element('p', 'error', _('No results'));
}
$profile->free(); $profile->free();
common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, common_pagination($page > 1, $cnt > PROFILES_PER_PAGE,
$page, 'peoplesearch', array('q' => $q)); $page, 'peoplesearch', array('q' => $q));
} }
} }
class PeopleSearchResults extends ProfileList { class PeopleSearchResults extends ProfileList {
var $terms = NULL; var $terms = NULL;
var $pattern = NULL; var $pattern = NULL;
function __construct($profile, $terms) { function __construct($profile, $terms) {
parent::__construct($profile); parent::__construct($profile);
$this->terms = array_map('preg_quote', $this->terms = array_map('preg_quote',
array_map('htmlspecialchars', $terms)); array_map('htmlspecialchars', $terms));
$this->pattern = '/('.implode('|',$terms).')/i'; $this->pattern = '/('.implode('|',$terms).')/i';
} }
function highlight($text) { function highlight($text) {
return preg_replace($this->pattern, '<strong>\\1</strong>', htmlspecialchars($text)); return preg_replace($this->pattern, '<strong>\\1</strong>', htmlspecialchars($text));
} }
} }

View File

@ -22,82 +22,82 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/profilelist.php'); require_once(INSTALLDIR.'/lib/profilelist.php');
class PeopletagAction extends Action { class PeopletagAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$tag = $this->trimmed('tag'); $tag = $this->trimmed('tag');
if (!common_valid_profile_tag($tag)) { if (!common_valid_profile_tag($tag)) {
$this->client_error(sprintf(_('Not a valid people tag: %s'), $tag)); $this->client_error(sprintf(_('Not a valid people tag: %s'), $tag));
return; return;
} }
$page = $this->trimmed('page'); $page = $this->trimmed('page');
if (!$page) { if (!$page) {
$page = 1; $page = 1;
} }
# Looks like we're good; show the header # Looks like we're good; show the header
common_show_header(sprintf(_('Users self-tagged with %s - page %d'), $tag, $page), common_show_header(sprintf(_('Users self-tagged with %s - page %d'), $tag, $page),
NULL, $tag, array($this, 'show_top')); NULL, $tag, array($this, 'show_top'));
$this->show_people($tag, $page); $this->show_people($tag, $page);
common_show_footer(); common_show_footer();
} }
function show_people($tag, $page) { function show_people($tag, $page) {
$profile = new Profile(); $profile = new Profile();
$offset = ($page-1)*PROFILES_PER_PAGE; $offset = ($page-1)*PROFILES_PER_PAGE;
$limit = PROFILES_PER_PAGE + 1; $limit = PROFILES_PER_PAGE + 1;
if (common_config('db','type') == 'pgsql') { if (common_config('db','type') == 'pgsql') {
$lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset;
} else { } else {
$lim = ' LIMIT ' . $offset . ', ' . $limit; $lim = ' LIMIT ' . $offset . ', ' . $limit;
} }
# XXX: memcached this # XXX: memcached this
$profile->query(sprintf('SELECT profile.* ' . $profile->query(sprintf('SELECT profile.* ' .
'FROM profile JOIN profile_tag ' . 'FROM profile JOIN profile_tag ' .
'ON profile.id = profile_tag.tagger ' . 'ON profile.id = profile_tag.tagger ' .
'WHERE profile_tag.tagger = profile_tag.tagged ' . 'WHERE profile_tag.tagger = profile_tag.tagged ' .
'AND tag = "%s" ' . 'AND tag = "%s" ' .
'ORDER BY profile_tag.modified DESC ' . 'ORDER BY profile_tag.modified DESC ' .
$lim, $tag)); $lim, $tag));
$pl = new ProfileList($profile); $pl = new ProfileList($profile);
$cnt = $pl->show_list(); $cnt = $pl->show_list();
common_pagination($page > 1, common_pagination($page > 1,
$cnt > PROFILES_PER_PAGE, $cnt > PROFILES_PER_PAGE,
$page, $page,
$this->trimmed('action'), $this->trimmed('action'),
array('tag' => $tag)); array('tag' => $tag));
} }
function show_top($tag) { function show_top($tag) {
$instr = sprintf(_('These are users who have tagged themselves "%s" ' . $instr = sprintf(_('These are users who have tagged themselves "%s" ' .
'to show a common interest, characteristic, hobby or job.'), $tag); 'to show a common interest, characteristic, hobby or job.'), $tag);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_element_start('p'); common_element_start('p');
common_text($instr); common_text($instr);
common_element_end('p'); common_element_end('p');
common_element_end('div'); common_element_end('div');
} }
function get_title() { function get_title() {
return NULL; return NULL;
} }
function show_header($arr) { function show_header($arr) {
return; return;
} }
} }

View File

@ -22,67 +22,67 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/omb.php'); require_once(INSTALLDIR.'/lib/omb.php');
class PostnoticeAction extends Action { class PostnoticeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
try { try {
common_remove_magic_from_request(); common_remove_magic_from_request();
$req = OAuthRequest::from_request(); $req = OAuthRequest::from_request();
# Note: server-to-server function! # Note: server-to-server function!
$server = omb_oauth_server(); $server = omb_oauth_server();
list($consumer, $token) = $server->verify_request($req); list($consumer, $token) = $server->verify_request($req);
if ($this->save_notice($req, $consumer, $token)) { if ($this->save_notice($req, $consumer, $token)) {
print "omb_version=".OMB_VERSION_01; print "omb_version=".OMB_VERSION_01;
} }
} catch (OAuthException $e) { } catch (OAuthException $e) {
common_server_error($e->getMessage()); common_server_error($e->getMessage());
return; return;
} }
} }
function save_notice(&$req, &$consumer, &$token) { function save_notice(&$req, &$consumer, &$token) {
$version = $req->get_parameter('omb_version'); $version = $req->get_parameter('omb_version');
if ($version != OMB_VERSION_01) { if ($version != OMB_VERSION_01) {
common_user_error(_('Unsupported OMB version'), 400); common_user_error(_('Unsupported OMB version'), 400);
return false; return false;
} }
# First, check to see # First, check to see
$listenee = $req->get_parameter('omb_listenee'); $listenee = $req->get_parameter('omb_listenee');
$remote_profile = Remote_profile::staticGet('uri', $listenee); $remote_profile = Remote_profile::staticGet('uri', $listenee);
if (!$remote_profile) { if (!$remote_profile) {
common_user_error(_('Profile unknown'), 403); common_user_error(_('Profile unknown'), 403);
return false; return false;
} }
$sub = Subscription::staticGet('token', $token->key); $sub = Subscription::staticGet('token', $token->key);
if (!$sub) { if (!$sub) {
common_user_error(_('No such subscription'), 403); common_user_error(_('No such subscription'), 403);
return false; return false;
} }
$content = $req->get_parameter('omb_notice_content'); $content = $req->get_parameter('omb_notice_content');
$content_shortened = common_shorten_links($content); $content_shortened = common_shorten_links($content);
if (mb_strlen($content_shortened) > 140) { if (mb_strlen($content_shortened) > 140) {
common_user_error(_('Invalid notice content'), 400); common_user_error(_('Invalid notice content'), 400);
return false; return false;
} }
$notice_uri = $req->get_parameter('omb_notice'); $notice_uri = $req->get_parameter('omb_notice');
if (!Validate::uri($notice_uri) && if (!Validate::uri($notice_uri) &&
!common_valid_tag($notice_uri)) { !common_valid_tag($notice_uri)) {
common_user_error(_('Invalid notice uri'), 400); common_user_error(_('Invalid notice uri'), 400);
return false; return false;
} }
$notice_url = $req->get_parameter('omb_notice_url'); $notice_url = $req->get_parameter('omb_notice_url');
if ($notice_url && !common_valid_http_url($notice_url)) { if ($notice_url && !common_valid_http_url($notice_url)) {
common_user_error(_('Invalid notice url'), 400); common_user_error(_('Invalid notice url'), 400);
return false; return false;
} }
$notice = Notice::staticGet('uri', $notice_uri); $notice = Notice::staticGet('uri', $notice_uri);
if (!$notice) { if (!$notice) {
$notice = Notice::saveNew($remote_profile->id, $content, 'omb', false, 0, $notice_uri); $notice = Notice::saveNew($remote_profile->id, $content, 'omb', false, 0, $notice_uri);
if (is_string($notice)) { if (is_string($notice)) {
common_server_serror($notice, 500); common_server_serror($notice, 500);
return false; return false;
} }
common_broadcast_notice($notice, true); common_broadcast_notice($notice, true);
} }
return true; return true;
} }
} }

View File

@ -23,417 +23,417 @@ require_once(INSTALLDIR.'/lib/settingsaction.php');
class ProfilesettingsAction extends SettingsAction { class ProfilesettingsAction extends SettingsAction {
function get_instructions() { function get_instructions() {
return _('You can update your personal profile info here '. return _('You can update your personal profile info here '.
'so people know more about you.'); 'so people know more about you.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$this->form_header(_('Profile settings'), $msg, $success); $this->form_header(_('Profile settings'), $msg, $success);
$this->show_settings_form(); $this->show_settings_form();
common_element('h2', NULL, _('Avatar')); common_element('h2', NULL, _('Avatar'));
$this->show_avatar_form(); $this->show_avatar_form();
common_element('h2', NULL, _('Change password')); common_element('h2', NULL, _('Change password'));
$this->show_password_form(); $this->show_password_form();
// common_element('h2', NULL, _('Delete my account')); // common_element('h2', NULL, _('Delete my account'));
// $this->show_delete_form(); // $this->show_delete_form();
common_show_footer(); common_show_footer();
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('save')) { if ($this->arg('save')) {
$this->save_profile(); $this->save_profile();
} else if ($this->arg('upload')) { } else if ($this->arg('upload')) {
$this->upload_avatar(); $this->upload_avatar();
} else if ($this->arg('changepass')) { } else if ($this->arg('changepass')) {
$this->change_password(); $this->change_password();
} }
} }
function show_settings_form() { function show_settings_form() {
$user = common_current_user(); $user = common_current_user();
$profile = $user->getProfile(); $profile = $user->getProfile();
common_element_start('form', array('method' => 'POST', common_element_start('form', array('method' => 'POST',
'id' => 'profilesettings', 'id' => 'profilesettings',
'action' => 'action' =>
common_local_url('profilesettings'))); common_local_url('profilesettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
# too much common patterns here... abstractable? # too much common patterns here... abstractable?
common_input('nickname', _('Nickname'), common_input('nickname', _('Nickname'),
($this->arg('nickname')) ? $this->arg('nickname') : $profile->nickname, ($this->arg('nickname')) ? $this->arg('nickname') : $profile->nickname,
_('1-64 lowercase letters or numbers, no punctuation or spaces')); _('1-64 lowercase letters or numbers, no punctuation or spaces'));
common_input('fullname', _('Full name'), common_input('fullname', _('Full name'),
($this->arg('fullname')) ? $this->arg('fullname') : $profile->fullname); ($this->arg('fullname')) ? $this->arg('fullname') : $profile->fullname);
common_input('homepage', _('Homepage'), common_input('homepage', _('Homepage'),
($this->arg('homepage')) ? $this->arg('homepage') : $profile->homepage, ($this->arg('homepage')) ? $this->arg('homepage') : $profile->homepage,
_('URL of your homepage, blog, or profile on another site')); _('URL of your homepage, blog, or profile on another site'));
common_textarea('bio', _('Bio'), common_textarea('bio', _('Bio'),
($this->arg('bio')) ? $this->arg('bio') : $profile->bio, ($this->arg('bio')) ? $this->arg('bio') : $profile->bio,
_('Describe yourself and your interests in 140 chars')); _('Describe yourself and your interests in 140 chars'));
common_input('location', _('Location'), common_input('location', _('Location'),
($this->arg('location')) ? $this->arg('location') : $profile->location, ($this->arg('location')) ? $this->arg('location') : $profile->location,
_('Where you are, like "City, State (or Region), Country"')); _('Where you are, like "City, State (or Region), Country"'));
common_input('tags', _('Tags'), common_input('tags', _('Tags'),
($this->arg('tags')) ? $this->arg('tags') : implode(' ', $user->getSelfTags()), ($this->arg('tags')) ? $this->arg('tags') : implode(' ', $user->getSelfTags()),
_('Tags for yourself (letters, numbers, -, ., and _), comma- or space- separated')); _('Tags for yourself (letters, numbers, -, ., and _), comma- or space- separated'));
$language = common_language(); $language = common_language();
common_dropdown('language', _('Language'), get_nice_language_list(), _('Preferred language'), TRUE, $language); common_dropdown('language', _('Language'), get_nice_language_list(), _('Preferred language'), TRUE, $language);
$timezone = common_timezone(); $timezone = common_timezone();
$timezones = array(); $timezones = array();
foreach(DateTimeZone::listIdentifiers() as $k => $v) { foreach(DateTimeZone::listIdentifiers() as $k => $v) {
$timezones[$v] = $v; $timezones[$v] = $v;
} }
common_dropdown('timezone', _('Timezone'), $timezones, _('What timezone are you normally in?'), TRUE, $timezone); common_dropdown('timezone', _('Timezone'), $timezones, _('What timezone are you normally in?'), TRUE, $timezone);
common_checkbox('autosubscribe', _('Automatically subscribe to whoever subscribes to me (best for non-humans)'), common_checkbox('autosubscribe', _('Automatically subscribe to whoever subscribes to me (best for non-humans)'),
($this->arg('autosubscribe')) ? $this->boolean('autosubscribe') : $user->autosubscribe); ($this->arg('autosubscribe')) ? $this->boolean('autosubscribe') : $user->autosubscribe);
common_submit('save', _('Save')); common_submit('save', _('Save'));
common_element_end('form'); common_element_end('form');
} }
function show_avatar_form() { function show_avatar_form() {
$user = common_current_user(); $user = common_current_user();
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_log_db_error($user, 'SELECT', __FILE__); common_log_db_error($user, 'SELECT', __FILE__);
$this->server_error(_('User without matching profile')); $this->server_error(_('User without matching profile'));
return; return;
} }
$original = $profile->getOriginalAvatar(); $original = $profile->getOriginalAvatar();
common_element_start('form', array('enctype' => 'multipart/form-data', common_element_start('form', array('enctype' => 'multipart/form-data',
'method' => 'POST', 'method' => 'POST',
'id' => 'avatar', 'id' => 'avatar',
'action' => 'action' =>
common_local_url('profilesettings'))); common_local_url('profilesettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
if ($original) { if ($original) {
common_element('img', array('src' => $original->url, common_element('img', array('src' => $original->url,
'class' => 'avatar original', 'class' => 'avatar original',
'width' => $original->width, 'width' => $original->width,
'height' => $original->height, 'height' => $original->height,
'alt' => $user->nickname)); 'alt' => $user->nickname));
} }
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
if ($avatar) { if ($avatar) {
common_element('img', array('src' => $avatar->url, common_element('img', array('src' => $avatar->url,
'class' => 'avatar profile', 'class' => 'avatar profile',
'width' => AVATAR_PROFILE_SIZE, 'width' => AVATAR_PROFILE_SIZE,
'height' => AVATAR_PROFILE_SIZE, 'height' => AVATAR_PROFILE_SIZE,
'alt' => $user->nickname)); 'alt' => $user->nickname));
} }
common_element('input', array('name' => 'MAX_FILE_SIZE', common_element('input', array('name' => 'MAX_FILE_SIZE',
'type' => 'hidden', 'type' => 'hidden',
'id' => 'MAX_FILE_SIZE', 'id' => 'MAX_FILE_SIZE',
'value' => MAX_AVATAR_SIZE)); 'value' => MAX_AVATAR_SIZE));
common_element_start('p'); common_element_start('p');
common_element('input', array('name' => 'avatarfile', common_element('input', array('name' => 'avatarfile',
'type' => 'file', 'type' => 'file',
'id' => 'avatarfile')); 'id' => 'avatarfile'));
common_element_end('p'); common_element_end('p');
common_submit('upload', _('Upload')); common_submit('upload', _('Upload'));
common_element_end('form'); common_element_end('form');
} }
function show_password_form() { function show_password_form() {
$user = common_current_user(); $user = common_current_user();
common_element_start('form', array('method' => 'POST', common_element_start('form', array('method' => 'POST',
'id' => 'password', 'id' => 'password',
'action' => 'action' =>
common_local_url('profilesettings'))); common_local_url('profilesettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
# Users who logged in with OpenID won't have a pwd # Users who logged in with OpenID won't have a pwd
if ($user->password) { if ($user->password) {
common_password('oldpassword', _('Old password')); common_password('oldpassword', _('Old password'));
} }
common_password('newpassword', _('New password'), common_password('newpassword', _('New password'),
_('6 or more characters')); _('6 or more characters'));
common_password('confirm', _('Confirm'), common_password('confirm', _('Confirm'),
_('same as password above')); _('same as password above'));
common_submit('changepass', _('Change')); common_submit('changepass', _('Change'));
common_element_end('form'); common_element_end('form');
} }
function save_profile() { function save_profile() {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$fullname = $this->trimmed('fullname'); $fullname = $this->trimmed('fullname');
$homepage = $this->trimmed('homepage'); $homepage = $this->trimmed('homepage');
$bio = $this->trimmed('bio'); $bio = $this->trimmed('bio');
$location = $this->trimmed('location'); $location = $this->trimmed('location');
$autosubscribe = $this->boolean('autosubscribe'); $autosubscribe = $this->boolean('autosubscribe');
$language = $this->trimmed('language'); $language = $this->trimmed('language');
$timezone = $this->trimmed('timezone'); $timezone = $this->trimmed('timezone');
$tagstring = $this->trimmed('tags'); $tagstring = $this->trimmed('tags');
# Some validation # Some validation
if (!Validate::string($nickname, array('min_length' => 1, if (!Validate::string($nickname, array('min_length' => 1,
'max_length' => 64, 'max_length' => 64,
'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
$this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
return; return;
} else if (!User::allowed_nickname($nickname)) { } else if (!User::allowed_nickname($nickname)) {
$this->show_form(_('Not a valid nickname.')); $this->show_form(_('Not a valid nickname.'));
return; return;
} else if (!is_null($homepage) && (strlen($homepage) > 0) && } else if (!is_null($homepage) && (strlen($homepage) > 0) &&
!Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) {
$this->show_form(_('Homepage is not a valid URL.')); $this->show_form(_('Homepage is not a valid URL.'));
return; return;
} else if (!is_null($fullname) && strlen($fullname) > 255) { } else if (!is_null($fullname) && strlen($fullname) > 255) {
$this->show_form(_('Full name is too long (max 255 chars).')); $this->show_form(_('Full name is too long (max 255 chars).'));
return; return;
} else if (!is_null($bio) && strlen($bio) > 140) { } else if (!is_null($bio) && strlen($bio) > 140) {
$this->show_form(_('Bio is too long (max 140 chars).')); $this->show_form(_('Bio is too long (max 140 chars).'));
return; return;
} else if (!is_null($location) && strlen($location) > 255) { } else if (!is_null($location) && strlen($location) > 255) {
$this->show_form(_('Location is too long (max 255 chars).')); $this->show_form(_('Location is too long (max 255 chars).'));
return; return;
} else if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) { } else if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) {
$this->show_form(_('Timezone not selected.')); $this->show_form(_('Timezone not selected.'));
return; return;
} else if ($this->nickname_exists($nickname)) { } else if ($this->nickname_exists($nickname)) {
$this->show_form(_('Nickname already in use. Try another one.')); $this->show_form(_('Nickname already in use. Try another one.'));
return; return;
} else if (!is_null($language) && strlen($language) > 50) { } else if (!is_null($language) && strlen($language) > 50) {
$this->show_form(_('Language is too long (max 50 chars).')); $this->show_form(_('Language is too long (max 50 chars).'));
return; return;
} }
if ($tagstring) { if ($tagstring) {
$tags = array_map('common_canonical_tag', preg_split('/[\s,]+/', $tagstring)); $tags = array_map('common_canonical_tag', preg_split('/[\s,]+/', $tagstring));
} else { } else {
$tags = array(); $tags = array();
} }
foreach ($tags as $tag) { foreach ($tags as $tag) {
if (!common_valid_profile_tag($tag)) { if (!common_valid_profile_tag($tag)) {
$this->show_form(sprintf(_('Invalid tag: "%s"'), $tag)); $this->show_form(sprintf(_('Invalid tag: "%s"'), $tag));
return; return;
} }
} }
$user = common_current_user(); $user = common_current_user();
$user->query('BEGIN'); $user->query('BEGIN');
if ($user->nickname != $nickname || if ($user->nickname != $nickname ||
$user->language != $language || $user->language != $language ||
$user->timezone != $timezone) { $user->timezone != $timezone) {
common_debug('Updating user nickname from ' . $user->nickname . ' to ' . $nickname, common_debug('Updating user nickname from ' . $user->nickname . ' to ' . $nickname,
__FILE__); __FILE__);
common_debug('Updating user language from ' . $user->language . ' to ' . $language, common_debug('Updating user language from ' . $user->language . ' to ' . $language,
__FILE__); __FILE__);
common_debug('Updating user timezone from ' . $user->timezone . ' to ' . $timezone, common_debug('Updating user timezone from ' . $user->timezone . ' to ' . $timezone,
__FILE__); __FILE__);
$original = clone($user); $original = clone($user);
$user->nickname = $nickname; $user->nickname = $nickname;
$user->language = $language; $user->language = $language;
$user->timezone = $timezone; $user->timezone = $timezone;
$result = $user->updateKeys($original); $result = $user->updateKeys($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} else { } else {
# Re-initialize language environment if it changed # Re-initialize language environment if it changed
common_init_language(); common_init_language();
} }
} }
# XXX: XOR # XXX: XOR
if ($user->autosubscribe ^ $autosubscribe) { if ($user->autosubscribe ^ $autosubscribe) {
$original = clone($user); $original = clone($user);
$user->autosubscribe = $autosubscribe; $user->autosubscribe = $autosubscribe;
$result = $user->update($original); $result = $user->update($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user for autosubscribe.')); common_server_error(_('Couldn\'t update user for autosubscribe.'));
return; return;
} }
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
$orig_profile = clone($profile); $orig_profile = clone($profile);
$profile->nickname = $user->nickname; $profile->nickname = $user->nickname;
$profile->fullname = $fullname; $profile->fullname = $fullname;
$profile->homepage = $homepage; $profile->homepage = $homepage;
$profile->bio = $bio; $profile->bio = $bio;
$profile->location = $location; $profile->location = $location;
$profile->profileurl = common_profile_url($nickname); $profile->profileurl = common_profile_url($nickname);
common_debug('Old profile: ' . common_log_objstring($orig_profile), __FILE__); common_debug('Old profile: ' . common_log_objstring($orig_profile), __FILE__);
common_debug('New profile: ' . common_log_objstring($profile), __FILE__); common_debug('New profile: ' . common_log_objstring($profile), __FILE__);
$result = $profile->update($orig_profile); $result = $profile->update($orig_profile);
if (!$result) { if (!$result) {
common_log_db_error($profile, 'UPDATE', __FILE__); common_log_db_error($profile, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t save profile.')); common_server_error(_('Couldn\'t save profile.'));
return; return;
} }
# Set the user tags # Set the user tags
$result = $user->setSelfTags($tags); $result = $user->setSelfTags($tags);
if (!$result) { if (!$result) {
common_server_error(_('Couldn\'t save tags.')); common_server_error(_('Couldn\'t save tags.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
common_broadcast_profile($profile); common_broadcast_profile($profile);
$this->show_form(_('Settings saved.'), TRUE); $this->show_form(_('Settings saved.'), TRUE);
} }
function upload_avatar() { function upload_avatar() {
switch ($_FILES['avatarfile']['error']) { switch ($_FILES['avatarfile']['error']) {
case UPLOAD_ERR_OK: # success, jump out case UPLOAD_ERR_OK: # success, jump out
break; break;
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
$this->show_form(_('That file is too big.')); $this->show_form(_('That file is too big.'));
return; return;
case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_PARTIAL:
@unlink($_FILES['avatarfile']['tmp_name']); @unlink($_FILES['avatarfile']['tmp_name']);
$this->show_form(_('Partial upload.')); $this->show_form(_('Partial upload.'));
return; return;
default: default:
$this->show_form(_('System error uploading file.')); $this->show_form(_('System error uploading file.'));
return; return;
} }
$info = @getimagesize($_FILES['avatarfile']['tmp_name']); $info = @getimagesize($_FILES['avatarfile']['tmp_name']);
if (!$info) { if (!$info) {
@unlink($_FILES['avatarfile']['tmp_name']); @unlink($_FILES['avatarfile']['tmp_name']);
$this->show_form(_('Not an image or corrupt file.')); $this->show_form(_('Not an image or corrupt file.'));
return; return;
} }
switch ($info[2]) { switch ($info[2]) {
case IMAGETYPE_GIF: case IMAGETYPE_GIF:
case IMAGETYPE_JPEG: case IMAGETYPE_JPEG:
case IMAGETYPE_PNG: case IMAGETYPE_PNG:
break; break;
default: default:
$this->show_form(_('Unsupported image file format.')); $this->show_form(_('Unsupported image file format.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
$profile = $user->getProfile(); $profile = $user->getProfile();
if ($profile->setOriginal($_FILES['avatarfile']['tmp_name'])) { if ($profile->setOriginal($_FILES['avatarfile']['tmp_name'])) {
$this->show_form(_('Avatar updated.'), true); $this->show_form(_('Avatar updated.'), true);
} else { } else {
$this->show_form(_('Failed updating avatar.')); $this->show_form(_('Failed updating avatar.'));
} }
@unlink($_FILES['avatarfile']['tmp_name']); @unlink($_FILES['avatarfile']['tmp_name']);
} }
function nickname_exists($nickname) { function nickname_exists($nickname) {
$user = common_current_user(); $user = common_current_user();
$other = User::staticGet('nickname', $nickname); $other = User::staticGet('nickname', $nickname);
if (!$other) { if (!$other) {
return false; return false;
} else { } else {
return $other->id != $user->id; return $other->id != $user->id;
} }
} }
function change_password() { function change_password() {
$user = common_current_user(); $user = common_current_user();
assert(!is_null($user)); # should already be checked assert(!is_null($user)); # should already be checked
# FIXME: scrub input # FIXME: scrub input
$newpassword = $this->arg('newpassword'); $newpassword = $this->arg('newpassword');
$confirm = $this->arg('confirm'); $confirm = $this->arg('confirm');
$token = $this->arg('token'); $token = $this->arg('token');
if (0 != strcmp($newpassword, $confirm)) { if (0 != strcmp($newpassword, $confirm)) {
$this->show_form(_('Passwords don\'t match.')); $this->show_form(_('Passwords don\'t match.'));
return; return;
} }
if ($user->password) { if ($user->password) {
$oldpassword = $this->arg('oldpassword'); $oldpassword = $this->arg('oldpassword');
if (!common_check_user($user->nickname, $oldpassword)) { if (!common_check_user($user->nickname, $oldpassword)) {
$this->show_form(_('Incorrect old password')); $this->show_form(_('Incorrect old password'));
return; return;
} }
} }
$original = clone($user); $original = clone($user);
$user->password = common_munge_password($newpassword, $user->id); $user->password = common_munge_password($newpassword, $user->id);
$val = $user->validate(); $val = $user->validate();
if ($val !== TRUE) { if ($val !== TRUE) {
$this->show_form(_('Error saving user; invalid.')); $this->show_form(_('Error saving user; invalid.'));
return; return;
} }
if (!$user->update($original)) { if (!$user->update($original)) {
common_server_error(_('Can\'t save new password.')); common_server_error(_('Can\'t save new password.'));
return; return;
} }
$this->show_form(_('Password saved.'), true); $this->show_form(_('Password saved.'), true);
} }
} }

View File

@ -23,77 +23,77 @@ require_once(INSTALLDIR.'/lib/stream.php');
class PublicAction extends StreamAction { class PublicAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
header('X-XRDS-Location: '. common_local_url('publicxrds')); header('X-XRDS-Location: '. common_local_url('publicxrds'));
common_show_header(_('Public timeline'), common_show_header(_('Public timeline'),
array($this, 'show_header'), NULL, array($this, 'show_header'), NULL,
array($this, 'show_top')); array($this, 'show_top'));
# XXX: Public sidebar here? # XXX: Public sidebar here?
$this->show_notices($page); $this->show_notices($page);
common_show_footer(); common_show_footer();
} }
function show_top() { function show_top() {
if (common_logged_in()) { if (common_logged_in()) {
common_notice_form('public'); common_notice_form('public');
} else { } else {
$instr = $this->get_instructions(); $instr = $this->get_instructions();
$output = common_markup_to_html($instr); $output = common_markup_to_html($instr);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
} }
$this->public_views_menu(); $this->public_views_menu();
$this->show_feeds_list(array(0=>array('href'=>common_local_url('publicrss'), $this->show_feeds_list(array(0=>array('href'=>common_local_url('publicrss'),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'publicrss'), 'item' => 'publicrss'),
1=>array('href'=>common_local_url('publicatom'), 1=>array('href'=>common_local_url('publicatom'),
'type' => 'atom', 'type' => 'atom',
'version' => 'Atom 1.0', 'version' => 'Atom 1.0',
'item' => 'publicatom'))); 'item' => 'publicatom')));
} }
function get_instructions() { function get_instructions() {
return _('This is %%site.name%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' . return _('This is %%site.name%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' .
'based on the Free Software [Laconica](http://laconi.ca/) tool. ' . 'based on the Free Software [Laconica](http://laconi.ca/) tool. ' .
'[Join now](%%action.register%%) to share notices about yourself with friends, family, and colleagues! ([Read more](%%doc.help%%))'); '[Join now](%%action.register%%) to share notices about yourself with friends, family, and colleagues! ([Read more](%%doc.help%%))');
} }
function show_header() { function show_header() {
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('publicrss'), 'href' => common_local_url('publicrss'),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => _('Public Stream Feed'))); 'title' => _('Public Stream Feed')));
# for client side of OpenID authentication # for client side of OpenID authentication
common_element('meta', array('http-equiv' => 'X-XRDS-Location', common_element('meta', array('http-equiv' => 'X-XRDS-Location',
'content' => common_local_url('publicxrds'))); 'content' => common_local_url('publicxrds')));
} }
function show_notices($page) { function show_notices($page) {
$cnt = 0; $cnt = 0;
$notice = Notice::publicStream(($page-1)*NOTICES_PER_PAGE, $notice = Notice::publicStream(($page-1)*NOTICES_PER_PAGE,
NOTICES_PER_PAGE + 1); NOTICES_PER_PAGE + 1);
if (!$notice) { if (!$notice) {
$this->server_error(_('Could not retrieve public stream.')); $this->server_error(_('Could not retrieve public stream.'));
return; return;
} }
$cnt = $this->show_notice_list($notice); $cnt = $this->show_notice_list($notice);
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'public'); $page, 'public');
} }
} }

View File

@ -25,33 +25,33 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class PublicrssAction extends Rss10Action { class PublicrssAction extends Rss10Action {
function init() { function init() {
return true; return true;
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$notices = array(); $notices = array();
$notice = Notice::publicStream(0, ($limit == 0) ? 48 : $limit); $notice = Notice::publicStream(0, ($limit == 0) ? 48 : $limit);
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
global $config; global $config;
$c = array('url' => common_local_url('publicrss'), $c = array('url' => common_local_url('publicrss'),
'title' => sprintf(_('%s Public Stream'), $config['site']['name']), 'title' => sprintf(_('%s Public Stream'), $config['site']['name']),
'link' => common_local_url('public'), 'link' => common_local_url('public'),
'description' => sprintf(_('All updates for %s'), $config['site']['name'])); 'description' => sprintf(_('All updates for %s'), $config['site']['name']));
return $c; return $c;
} }
function get_image() { function get_image() {
return NULL; return NULL;
} }
} }

View File

@ -25,55 +25,55 @@ require_once(INSTALLDIR.'/lib/openid.php');
class PublicxrdsAction extends Action { class PublicxrdsAction extends Action {
function is_readonly() { function is_readonly() {
return true; return true;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
header('Content-Type: application/xrds+xml'); header('Content-Type: application/xrds+xml');
common_start_xml(); common_start_xml();
common_element_start('XRDS', array('xmlns' => 'xri://$xrds')); common_element_start('XRDS', array('xmlns' => 'xri://$xrds'));
common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
'xmlns:simple' => 'http://xrds-simple.net/core/1.0', 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
'version' => '2.0')); 'version' => '2.0'));
common_element('Type', NULL, 'xri://$xrds*simple'); common_element('Type', NULL, 'xri://$xrds*simple');
foreach (array('finishopenidlogin', 'finishaddopenid', 'finishimmediate') as $finish) { foreach (array('finishopenidlogin', 'finishaddopenid', 'finishimmediate') as $finish) {
$this->show_service(Auth_OpenID_RP_RETURN_TO_URL_TYPE, $this->show_service(Auth_OpenID_RP_RETURN_TO_URL_TYPE,
common_local_url($finish)); common_local_url($finish));
} }
common_element_end('XRD'); common_element_end('XRD');
common_element_end('XRDS'); common_element_end('XRDS');
common_end_xml(); common_end_xml();
} }
function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) { function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) {
common_element_start('Service'); common_element_start('Service');
if ($uri) { if ($uri) {
common_element('URI', NULL, $uri); common_element('URI', NULL, $uri);
} }
common_element('Type', NULL, $type); common_element('Type', NULL, $type);
if ($params) { if ($params) {
foreach ($params as $param) { foreach ($params as $param) {
common_element('Type', NULL, $param); common_element('Type', NULL, $param);
} }
} }
if ($sigs) { if ($sigs) {
foreach ($sigs as $sig) { foreach ($sigs as $sig) {
common_element('Type', NULL, $sig); common_element('Type', NULL, $sig);
} }
} }
if ($localId) { if ($localId) {
common_element('LocalID', NULL, $localId); common_element('LocalID', NULL, $localId);
} }
common_element_end('Service'); common_element_end('Service');
} }
} }

View File

@ -28,304 +28,304 @@ class RecoverpasswordAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_logged_in()) { if (common_logged_in()) {
$this->client_error(_('You are already logged in!')); $this->client_error(_('You are already logged in!'));
return; return;
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($this->arg('recover')) { if ($this->arg('recover')) {
$this->recover_password(); $this->recover_password();
} else if ($this->arg('reset')) { } else if ($this->arg('reset')) {
$this->reset_password(); $this->reset_password();
} else { } else {
$this->client_error(_('Unexpected form submission.')); $this->client_error(_('Unexpected form submission.'));
} }
} else { } else {
if ($this->trimmed('code')) { if ($this->trimmed('code')) {
$this->check_code(); $this->check_code();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
} }
function check_code() { function check_code() {
$code = $this->trimmed('code'); $code = $this->trimmed('code');
$confirm = Confirm_address::staticGet('code', $code); $confirm = Confirm_address::staticGet('code', $code);
if (!$confirm) { if (!$confirm) {
$this->client_error(_('No such recovery code.')); $this->client_error(_('No such recovery code.'));
return; return;
} }
if ($confirm->address_type != 'recover') { if ($confirm->address_type != 'recover') {
$this->client_error(_('Not a recovery code.')); $this->client_error(_('Not a recovery code.'));
return; return;
} }
$user = User::staticGet($confirm->user_id); $user = User::staticGet($confirm->user_id);
if (!$user) { if (!$user) {
$this->server_error(_('Recovery code for unknown user.')); $this->server_error(_('Recovery code for unknown user.'));
return; return;
} }
$touched = strtotime($confirm->modified); $touched = strtotime($confirm->modified);
$email = $confirm->address; $email = $confirm->address;
# Burn this code # Burn this code
$result = $confirm->delete(); $result = $confirm->delete();
if (!$result) { if (!$result) {
common_log_db_error($confirm, 'DELETE', __FILE__); common_log_db_error($confirm, 'DELETE', __FILE__);
common_server_error(_('Error with confirmation code.')); common_server_error(_('Error with confirmation code.'));
return; return;
} }
# These should be reaped, but for now we just check mod time # These should be reaped, but for now we just check mod time
# Note: it's still deleted; let's avoid a second attempt! # Note: it's still deleted; let's avoid a second attempt!
if ((time() - $touched) > MAX_RECOVERY_TIME) { if ((time() - $touched) > MAX_RECOVERY_TIME) {
common_log(LOG_WARNING, common_log(LOG_WARNING,
'Attempted redemption on recovery code ' . 'Attempted redemption on recovery code ' .
'that is ' . $touched . ' seconds old. '); 'that is ' . $touched . ' seconds old. ');
$this->client_error(_('This confirmation code is too old. ' . $this->client_error(_('This confirmation code is too old. ' .
'Please start again.')); 'Please start again.'));
return; return;
} }
# If we used an outstanding confirmation to send the email, # If we used an outstanding confirmation to send the email,
# it's been confirmed at this point. # it's been confirmed at this point.
if (!$user->email) { if (!$user->email) {
$orig = clone($user); $orig = clone($user);
$user->email = $email; $user->email = $email;
$result = $user->updateKeys($orig); $result = $user->updateKeys($orig);
if (!$result) { if (!$result) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
$this->server_error(_('Could not update user with confirmed email address.')); $this->server_error(_('Could not update user with confirmed email address.'));
return; return;
} }
} }
# Success! # Success!
$this->set_temp_user($user); $this->set_temp_user($user);
$this->show_password_form(); $this->show_password_form();
} }
function set_temp_user(&$user) { function set_temp_user(&$user) {
common_ensure_session(); common_ensure_session();
$_SESSION['tempuser'] = $user->id; $_SESSION['tempuser'] = $user->id;
} }
function get_temp_user() { function get_temp_user() {
common_ensure_session(); common_ensure_session();
$user_id = $_SESSION['tempuser']; $user_id = $_SESSION['tempuser'];
if ($user_id) { if ($user_id) {
$user = User::staticGet($user_id); $user = User::staticGet($user_id);
} }
return $user; return $user;
} }
function clear_temp_user() { function clear_temp_user() {
common_ensure_session(); common_ensure_session();
unset($_SESSION['tempuser']); unset($_SESSION['tempuser']);
} }
function show_top($msg=NULL) { function show_top($msg=NULL) {
if ($msg) { if ($msg) {
common_element('div', 'error', $msg); common_element('div', 'error', $msg);
} else { } else {
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_element('p', NULL, common_element('p', NULL,
_('If you\'ve forgotten or lost your' . _('If you\'ve forgotten or lost your' .
' password, you can get a new one sent to' . ' password, you can get a new one sent to' .
' the email address you have stored ' . ' the email address you have stored ' .
' in your account.')); ' in your account.'));
common_element_end('div'); common_element_end('div');
} }
} }
function show_password_top($msg=NULL) { function show_password_top($msg=NULL) {
if ($msg) { if ($msg) {
common_element('div', 'error', $msg); common_element('div', 'error', $msg);
} else { } else {
common_element('div', 'instructions', common_element('div', 'instructions',
_('You\'ve been identified. Enter a ' . _('You\'ve been identified. Enter a ' .
' new password below. ')); ' new password below. '));
} }
} }
function show_form($msg=NULL) { function show_form($msg=NULL) {
common_show_header(_('Recover password'), NULL, common_show_header(_('Recover password'), NULL,
$msg, array($this, 'show_top')); $msg, array($this, 'show_top'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'recoverpassword', 'id' => 'recoverpassword',
'action' => common_local_url('recoverpassword'))); 'action' => common_local_url('recoverpassword')));
common_input('nicknameoremail', _('Nickname or email'), common_input('nicknameoremail', _('Nickname or email'),
$this->trimmed('nicknameoremail'), $this->trimmed('nicknameoremail'),
_('Your nickname on this server, ' . _('Your nickname on this server, ' .
'or your registered email address.')); 'or your registered email address.'));
common_submit('recover', _('Recover')); common_submit('recover', _('Recover'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function show_password_form($msg=NULL) { function show_password_form($msg=NULL) {
common_show_header(_('Reset password'), NULL, common_show_header(_('Reset password'), NULL,
$msg, array($this, 'show_password_top')); $msg, array($this, 'show_password_top'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'recoverpassword', 'id' => 'recoverpassword',
'action' => common_local_url('recoverpassword'))); 'action' => common_local_url('recoverpassword')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_password('newpassword', _('New password'), common_password('newpassword', _('New password'),
_('6 or more characters, and don\'t forget it!')); _('6 or more characters, and don\'t forget it!'));
common_password('confirm', _('Confirm'), common_password('confirm', _('Confirm'),
_('Same as password above')); _('Same as password above'));
common_submit('reset', _('Reset')); common_submit('reset', _('Reset'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function recover_password() { function recover_password() {
$nore = $this->trimmed('nicknameoremail'); $nore = $this->trimmed('nicknameoremail');
if (!$nore) { if (!$nore) {
$this->show_form(_('Enter a nickname or email address.')); $this->show_form(_('Enter a nickname or email address.'));
return; return;
} }
$user = User::staticGet('email', common_canonical_email($nore)); $user = User::staticGet('email', common_canonical_email($nore));
if (!$user) { if (!$user) {
$user = User::staticGet('nickname', common_canonical_nickname($nore)); $user = User::staticGet('nickname', common_canonical_nickname($nore));
} }
# See if it's an unconfirmed email address # See if it's an unconfirmed email address
if (!$user) { if (!$user) {
$confirm_email = Confirm_address::staticGet('address', common_canonical_email($nore)); $confirm_email = Confirm_address::staticGet('address', common_canonical_email($nore));
if ($confirm_email && $confirm_email->address_type == 'email') { if ($confirm_email && $confirm_email->address_type == 'email') {
$user = User::staticGet($confirm_email->user_id); $user = User::staticGet($confirm_email->user_id);
} }
} }
if (!$user) { if (!$user) {
$this->show_form(_('No user with that email address or username.')); $this->show_form(_('No user with that email address or username.'));
return; return;
} }
# Try to get an unconfirmed email address if they used a user name # Try to get an unconfirmed email address if they used a user name
if (!$user->email && !$confirm_email) { if (!$user->email && !$confirm_email) {
$confirm_email = Confirm_address::staticGet('user_id', $user->id); $confirm_email = Confirm_address::staticGet('user_id', $user->id);
if ($confirm_email && $confirm_email->address_type != 'email') { if ($confirm_email && $confirm_email->address_type != 'email') {
# Skip non-email confirmations # Skip non-email confirmations
$confirm_email = NULL; $confirm_email = NULL;
} }
} }
if (!$user->email && !$confirm_email) { if (!$user->email && !$confirm_email) {
$this->client_error(_('No registered email address for that user.')); $this->client_error(_('No registered email address for that user.'));
return; return;
} }
# Success! We have a valid user and a confirmed or unconfirmed email address # Success! We have a valid user and a confirmed or unconfirmed email address
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->code = common_confirmation_code(128); $confirm->code = common_confirmation_code(128);
$confirm->address_type = 'recover'; $confirm->address_type = 'recover';
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->address = (isset($user->email)) ? $user->email : $confirm_email->address; $confirm->address = (isset($user->email)) ? $user->email : $confirm_email->address;
if (!$confirm->insert()) { if (!$confirm->insert()) {
common_log_db_error($confirm, 'INSERT', __FILE__); common_log_db_error($confirm, 'INSERT', __FILE__);
$this->server_error(_('Error saving address confirmation.')); $this->server_error(_('Error saving address confirmation.'));
return; return;
} }
$body = "Hey, $user->nickname."; $body = "Hey, $user->nickname.";
$body .= "\n\n"; $body .= "\n\n";
$body .= 'Someone just asked for a new password ' . $body .= 'Someone just asked for a new password ' .
'for this account on ' . common_config('site', 'name') . '.'; 'for this account on ' . common_config('site', 'name') . '.';
$body .= "\n\n"; $body .= "\n\n";
$body .= 'If it was you, and you want to confirm, use the URL below:'; $body .= 'If it was you, and you want to confirm, use the URL below:';
$body .= "\n\n"; $body .= "\n\n";
$body .= "\t".common_local_url('recoverpassword', $body .= "\t".common_local_url('recoverpassword',
array('code' => $confirm->code)); array('code' => $confirm->code));
$body .= "\n\n"; $body .= "\n\n";
$body .= 'If not, just ignore this message.'; $body .= 'If not, just ignore this message.';
$body .= "\n\n"; $body .= "\n\n";
$body .= 'Thanks for your time, '; $body .= 'Thanks for your time, ';
$body .= "\n"; $body .= "\n";
$body .= common_config('site', 'name'); $body .= common_config('site', 'name');
$body .= "\n"; $body .= "\n";
mail_to_user($user, _('Password recovery requested'), $body, $confirm->address); mail_to_user($user, _('Password recovery requested'), $body, $confirm->address);
common_show_header(_('Password recovery requested')); common_show_header(_('Password recovery requested'));
common_element('p', NULL, common_element('p', NULL,
_('Instructions for recovering your password ' . _('Instructions for recovering your password ' .
'have been sent to the email address registered to your ' . 'have been sent to the email address registered to your ' .
'account.')); 'account.'));
common_show_footer(); common_show_footer();
} }
function reset_password() { function reset_password() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$user = $this->get_temp_user(); $user = $this->get_temp_user();
if (!$user) { if (!$user) {
$this->client_error(_('Unexpected password reset.')); $this->client_error(_('Unexpected password reset.'));
return; return;
} }
$newpassword = $this->trimmed('newpassword'); $newpassword = $this->trimmed('newpassword');
$confirm = $this->trimmed('confirm'); $confirm = $this->trimmed('confirm');
if (!$newpassword || strlen($newpassword) < 6) { if (!$newpassword || strlen($newpassword) < 6) {
$this->show_password_form(_('Password must be 6 chars or more.')); $this->show_password_form(_('Password must be 6 chars or more.'));
return; return;
} }
if ($newpassword != $confirm) { if ($newpassword != $confirm) {
$this->show_password_form(_('Password and confirmation do not match.')); $this->show_password_form(_('Password and confirmation do not match.'));
return; return;
} }
# OK, we're ready to go # OK, we're ready to go
$original = clone($user); $original = clone($user);
$user->password = common_munge_password($newpassword, $user->id); $user->password = common_munge_password($newpassword, $user->id);
if (!$user->update($original)) { if (!$user->update($original)) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Can\'t save new password.')); common_server_error(_('Can\'t save new password.'));
return; return;
} }
$this->clear_temp_user(); $this->clear_temp_user();
if (!common_set_user($user->nickname)) { if (!common_set_user($user->nickname)) {
common_server_error(_('Error setting user.')); common_server_error(_('Error setting user.'));
return; return;
} }
common_real_login(true); common_real_login(true);
common_show_header(_('Password saved.')); common_show_header(_('Password saved.'));
common_element('p', NULL, _('New password successfully saved. ' . common_element('p', NULL, _('New password successfully saved. ' .
'You are now logged in.')); 'You are now logged in.'));
common_show_footer(); common_show_footer();
} }
} }

View File

@ -21,242 +21,242 @@ if (!defined('LACONICA')) { exit(1); }
class RegisterAction extends Action { class RegisterAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_config('site', 'closed')) { if (common_config('site', 'closed')) {
common_user_error(_('Registration not allowed.')); common_user_error(_('Registration not allowed.'));
} else if (common_logged_in()) { } else if (common_logged_in()) {
common_user_error(_('Already logged in.')); common_user_error(_('Already logged in.'));
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') { } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->try_register(); $this->try_register();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
function try_register() { function try_register() {
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$email = $this->trimmed('email'); $email = $this->trimmed('email');
$fullname = $this->trimmed('fullname'); $fullname = $this->trimmed('fullname');
$homepage = $this->trimmed('homepage'); $homepage = $this->trimmed('homepage');
$bio = $this->trimmed('bio'); $bio = $this->trimmed('bio');
$location = $this->trimmed('location'); $location = $this->trimmed('location');
# We don't trim these... whitespace is OK in a password! # We don't trim these... whitespace is OK in a password!
$password = $this->arg('password'); $password = $this->arg('password');
$confirm = $this->arg('confirm'); $confirm = $this->arg('confirm');
# invitation code, if any # invitation code, if any
$code = $this->trimmed('code'); $code = $this->trimmed('code');
if ($code) { if ($code) {
$invite = Invitation::staticGet($code); $invite = Invitation::staticGet($code);
} }
if (common_config('site', 'inviteonly') && !($code && $invite)) { if (common_config('site', 'inviteonly') && !($code && $invite)) {
$this->client_error(_('Sorry, only invited people can register.')); $this->client_error(_('Sorry, only invited people can register.'));
return; return;
} }
# Input scrubbing # Input scrubbing
$nickname = common_canonical_nickname($nickname); $nickname = common_canonical_nickname($nickname);
$email = common_canonical_email($email); $email = common_canonical_email($email);
if (!$this->boolean('license')) { if (!$this->boolean('license')) {
$this->show_form(_('You can\'t register if you don\'t agree to the license.')); $this->show_form(_('You can\'t register if you don\'t agree to the license.'));
} else if ($email && !Validate::email($email, true)) { } else if ($email && !Validate::email($email, true)) {
$this->show_form(_('Not a valid email address.')); $this->show_form(_('Not a valid email address.'));
} else if (!Validate::string($nickname, array('min_length' => 1, } else if (!Validate::string($nickname, array('min_length' => 1,
'max_length' => 64, 'max_length' => 64,
'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
$this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.'));
} else if ($this->nickname_exists($nickname)) { } else if ($this->nickname_exists($nickname)) {
$this->show_form(_('Nickname already in use. Try another one.')); $this->show_form(_('Nickname already in use. Try another one.'));
} else if (!User::allowed_nickname($nickname)) { } else if (!User::allowed_nickname($nickname)) {
$this->show_form(_('Not a valid nickname.')); $this->show_form(_('Not a valid nickname.'));
} else if ($this->email_exists($email)) { } else if ($this->email_exists($email)) {
$this->show_form(_('Email address already exists.')); $this->show_form(_('Email address already exists.'));
} else if (!is_null($homepage) && (strlen($homepage) > 0) && } else if (!is_null($homepage) && (strlen($homepage) > 0) &&
!Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) {
$this->show_form(_('Homepage is not a valid URL.')); $this->show_form(_('Homepage is not a valid URL.'));
return; return;
} else if (!is_null($fullname) && strlen($fullname) > 255) { } else if (!is_null($fullname) && strlen($fullname) > 255) {
$this->show_form(_('Full name is too long (max 255 chars).')); $this->show_form(_('Full name is too long (max 255 chars).'));
return; return;
} else if (!is_null($bio) && strlen($bio) > 140) { } else if (!is_null($bio) && strlen($bio) > 140) {
$this->show_form(_('Bio is too long (max 140 chars).')); $this->show_form(_('Bio is too long (max 140 chars).'));
return; return;
} else if (!is_null($location) && strlen($location) > 255) { } else if (!is_null($location) && strlen($location) > 255) {
$this->show_form(_('Location is too long (max 255 chars).')); $this->show_form(_('Location is too long (max 255 chars).'));
return; return;
} else if (strlen($password) < 6) { } else if (strlen($password) < 6) {
$this->show_form(_('Password must be 6 or more characters.')); $this->show_form(_('Password must be 6 or more characters.'));
return; return;
} else if ($password != $confirm) { } else if ($password != $confirm) {
$this->show_form(_('Passwords don\'t match.')); $this->show_form(_('Passwords don\'t match.'));
} else if ($user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, } else if ($user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email,
'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio,
'location' => $location, 'code' => $code))) { 'location' => $location, 'code' => $code))) {
if (!$user) { if (!$user) {
$this->show_form(_('Invalid username or password.')); $this->show_form(_('Invalid username or password.'));
return; return;
} }
# success! # success!
if (!common_set_user($user)) { if (!common_set_user($user)) {
common_server_error(_('Error setting user.')); common_server_error(_('Error setting user.'));
return; return;
} }
# this is a real login # this is a real login
common_real_login(true); common_real_login(true);
if ($this->boolean('rememberme')) { if ($this->boolean('rememberme')) {
common_debug('Adding rememberme cookie for ' . $nickname); common_debug('Adding rememberme cookie for ' . $nickname);
common_rememberme($user); common_rememberme($user);
} }
# Re-init language env in case it changed (not yet, but soon) # Re-init language env in case it changed (not yet, but soon)
common_init_language(); common_init_language();
$this->show_success(); $this->show_success();
} else { } else {
$this->show_form(_('Invalid username or password.')); $this->show_form(_('Invalid username or password.'));
} }
} }
# checks if *CANONICAL* nickname exists # checks if *CANONICAL* nickname exists
function nickname_exists($nickname) { function nickname_exists($nickname) {
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
return ($user !== false); return ($user !== false);
} }
# checks if *CANONICAL* email exists # checks if *CANONICAL* email exists
function email_exists($email) { function email_exists($email) {
$email = common_canonical_email($email); $email = common_canonical_email($email);
if (!$email || strlen($email) == 0) { if (!$email || strlen($email) == 0) {
return false; return false;
} }
$user = User::staticGet('email', $email); $user = User::staticGet('email', $email);
return ($user !== false); return ($user !== false);
} }
function show_top($error=NULL) { function show_top($error=NULL) {
if ($error) { if ($error) {
common_element('p', 'error', $error); common_element('p', 'error', $error);
} else { } else {
$instr = common_markup_to_html(_('With this form you can create a new account. ' . $instr = common_markup_to_html(_('With this form you can create a new account. ' .
'You can then post notices and link up to friends and colleagues. '. 'You can then post notices and link up to friends and colleagues. '.
'(Have an [OpenID](http://openid.net/)? ' . '(Have an [OpenID](http://openid.net/)? ' .
'Try our [OpenID registration](%%action.openidlogin%%)!)')); 'Try our [OpenID registration](%%action.openidlogin%%)!)'));
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($instr); common_raw($instr);
common_element_end('div'); common_element_end('div');
} }
} }
function show_form($error=NULL) { function show_form($error=NULL) {
global $config; global $config;
$code = $this->trimmed('code'); $code = $this->trimmed('code');
if ($code) { if ($code) {
$invite = Invitation::staticGet($code); $invite = Invitation::staticGet($code);
} }
if (common_config('site', 'inviteonly') && !($code && $invite)) { if (common_config('site', 'inviteonly') && !($code && $invite)) {
$this->client_error(_('Sorry, only invited people can register.')); $this->client_error(_('Sorry, only invited people can register.'));
return; return;
} }
common_show_header(_('Register'), NULL, $error, array($this, 'show_top')); common_show_header(_('Register'), NULL, $error, array($this, 'show_top'));
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'login', 'id' => 'login',
'action' => common_local_url('register'))); 'action' => common_local_url('register')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
if ($code) { if ($code) {
common_hidden('code', $code); common_hidden('code', $code);
} }
common_input('nickname', _('Nickname'), $this->trimmed('nickname'), common_input('nickname', _('Nickname'), $this->trimmed('nickname'),
_('1-64 lowercase letters or numbers, no punctuation or spaces. Required.')); _('1-64 lowercase letters or numbers, no punctuation or spaces. Required.'));
common_password('password', _('Password'), common_password('password', _('Password'),
_('6 or more characters. Required.')); _('6 or more characters. Required.'));
common_password('confirm', _('Confirm'), common_password('confirm', _('Confirm'),
_('Same as password above. Required.')); _('Same as password above. Required.'));
if ($invite && $invite->address_type == 'email') { if ($invite && $invite->address_type == 'email') {
common_input('email', _('Email'), $invite->address, common_input('email', _('Email'), $invite->address,
_('Used only for updates, announcements, and password recovery')); _('Used only for updates, announcements, and password recovery'));
} else { } else {
common_input('email', _('Email'), $this->trimmed('email'), common_input('email', _('Email'), $this->trimmed('email'),
_('Used only for updates, announcements, and password recovery')); _('Used only for updates, announcements, and password recovery'));
} }
common_input('fullname', _('Full name'), common_input('fullname', _('Full name'),
$this->trimmed('fullname'), $this->trimmed('fullname'),
_('Longer name, preferably your "real" name')); _('Longer name, preferably your "real" name'));
common_input('homepage', _('Homepage'), common_input('homepage', _('Homepage'),
$this->trimmed('homepage'), $this->trimmed('homepage'),
_('URL of your homepage, blog, or profile on another site')); _('URL of your homepage, blog, or profile on another site'));
common_textarea('bio', _('Bio'), common_textarea('bio', _('Bio'),
$this->trimmed('bio'), $this->trimmed('bio'),
_('Describe yourself and your interests in 140 chars')); _('Describe yourself and your interests in 140 chars'));
common_input('location', _('Location'), common_input('location', _('Location'),
$this->trimmed('location'), $this->trimmed('location'),
_('Where you are, like "City, State (or Region), Country"')); _('Where you are, like "City, State (or Region), Country"'));
common_checkbox('rememberme', _('Remember me'), common_checkbox('rememberme', _('Remember me'),
$this->boolean('rememberme'), $this->boolean('rememberme'),
_('Automatically login in the future; not for shared computers!')); _('Automatically login in the future; not for shared computers!'));
common_element_start('p'); common_element_start('p');
$attrs = array('type' => 'checkbox', $attrs = array('type' => 'checkbox',
'id' => 'license', 'id' => 'license',
'name' => 'license', 'name' => 'license',
'value' => 'true'); 'value' => 'true');
if ($this->boolean('license')) { if ($this->boolean('license')) {
$attrs['checked'] = 'checked'; $attrs['checked'] = 'checked';
} }
common_element('input', $attrs); common_element('input', $attrs);
common_text(_('My text and files are available under ')); common_text(_('My text and files are available under '));
common_element('a', array('href' => $config['license']['url']), common_element('a', array('href' => $config['license']['url']),
$config['license']['title']); $config['license']['title']);
common_text(_(' except this private data: password, email address, IM address, phone number.')); common_text(_(' except this private data: password, email address, IM address, phone number.'));
common_element_end('p'); common_element_end('p');
common_submit('submit', _('Register')); common_submit('submit', _('Register'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function show_success() { function show_success() {
$nickname = $this->arg('nickname'); $nickname = $this->arg('nickname');
common_show_header(_('Registration successful')); common_show_header(_('Registration successful'));
common_element_start('div', 'success'); common_element_start('div', 'success');
$instr = sprintf(_('Congratulations, %s! And welcome to %%%%site.name%%%%. From here, you may want to...'. "\n\n" . $instr = sprintf(_('Congratulations, %s! And welcome to %%%%site.name%%%%. From here, you may want to...'. "\n\n" .
'* Go to [your profile](%s) and post your first message.' . "\n" . '* Go to [your profile](%s) and post your first message.' . "\n" .
'* Add a [Jabber/GTalk address](%%%%action.imsettings%%%%) so you can send notices through instant messages.' . "\n" . '* Add a [Jabber/GTalk address](%%%%action.imsettings%%%%) so you can send notices through instant messages.' . "\n" .
'* [Search for people](%%%%action.peoplesearch%%%%) that you may know or that share your interests. ' . "\n" . '* [Search for people](%%%%action.peoplesearch%%%%) that you may know or that share your interests. ' . "\n" .
'* Update your [profile settings](%%%%action.profilesettings%%%%) to tell others more about you. ' . "\n" . '* Update your [profile settings](%%%%action.profilesettings%%%%) to tell others more about you. ' . "\n" .
'* Read over the [online docs](%%%%doc.help%%%%) for features you may have missed. ' . "\n\n" . '* Read over the [online docs](%%%%doc.help%%%%) for features you may have missed. ' . "\n\n" .
'Thanks for signing up and we hope you enjoy using this service.'), 'Thanks for signing up and we hope you enjoy using this service.'),
$nickname, common_local_url('showstream', array('nickname' => $nickname))); $nickname, common_local_url('showstream', array('nickname' => $nickname)));
common_raw(common_markup_to_html($instr)); common_raw(common_markup_to_html($instr));
$have_email = $this->trimmed('email'); $have_email = $this->trimmed('email');
if ($have_email) { if ($have_email) {
$emailinstr = _('(You should receive a message by email momentarily, with ' . $emailinstr = _('(You should receive a message by email momentarily, with ' .
'instructions on how to confirm your email address.)'); 'instructions on how to confirm your email address.)');
common_raw(common_markup_to_html($emailinstr)); common_raw(common_markup_to_html($emailinstr));
} }
common_element_end('div'); common_element_end('div');
common_show_footer(); common_show_footer();
} }
} }

View File

@ -23,364 +23,364 @@ require_once(INSTALLDIR.'/lib/omb.php');
class RemotesubscribeAction extends Action { class RemotesubscribeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (common_logged_in()) { if (common_logged_in()) {
common_user_error(_('You can use the local subscription!')); common_user_error(_('You can use the local subscription!'));
return; return;
} }
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$this->remote_subscription(); $this->remote_subscription();
} else { } else {
$this->show_form(); $this->show_form();
} }
} }
function get_instructions() { function get_instructions() {
return _('To subscribe, you can [login](%%action.login%%),' . return _('To subscribe, you can [login](%%action.login%%),' .
' or [register](%%action.register%%) a new ' . ' or [register](%%action.register%%) a new ' .
' account. If you already have an account ' . ' account. If you already have an account ' .
' on a [compatible microblogging site](%%doc.openmublog%%), ' . ' on a [compatible microblogging site](%%doc.openmublog%%), ' .
' enter your profile URL below.'); ' enter your profile URL below.');
} }
function show_top($err=NULL) { function show_top($err=NULL) {
if ($err) { if ($err) {
common_element('div', 'error', $err); common_element('div', 'error', $err);
} else { } else {
$instructions = $this->get_instructions(); $instructions = $this->get_instructions();
$output = common_markup_to_html($instructions); $output = common_markup_to_html($instructions);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('p'); common_element_end('p');
} }
} }
function show_form($err=NULL) { function show_form($err=NULL) {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$profile = $this->trimmed('profile_url'); $profile = $this->trimmed('profile_url');
common_show_header(_('Remote subscribe'), NULL, $err, common_show_header(_('Remote subscribe'), NULL, $err,
array($this, 'show_top')); array($this, 'show_top'));
# id = remotesubscribe conflicts with the # id = remotesubscribe conflicts with the
# button on profile page # button on profile page
common_element_start('form', array('id' => 'remsub', 'method' => 'post', common_element_start('form', array('id' => 'remsub', 'method' => 'post',
'action' => common_local_url('remotesubscribe'))); 'action' => common_local_url('remotesubscribe')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_input('nickname', _('User nickname'), $nickname, common_input('nickname', _('User nickname'), $nickname,
_('Nickname of the user you want to follow')); _('Nickname of the user you want to follow'));
common_input('profile_url', _('Profile URL'), $profile, common_input('profile_url', _('Profile URL'), $profile,
_('URL of your profile on another compatible microblogging service')); _('URL of your profile on another compatible microblogging service'));
common_submit('submit', _('Subscribe')); common_submit('submit', _('Subscribe'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function remote_subscription() { function remote_subscription() {
$user = $this->get_user(); $user = $this->get_user();
if (!$user) { if (!$user) {
$this->show_form(_('No such user.')); $this->show_form(_('No such user.'));
return; return;
} }
$profile = $this->trimmed('profile_url'); $profile = $this->trimmed('profile_url');
if (!$profile) { if (!$profile) {
$this->show_form(_('No such user.')); $this->show_form(_('No such user.'));
return; return;
} }
if (!Validate::uri($profile, array('allowed_schemes' => array('http', 'https')))) { if (!Validate::uri($profile, array('allowed_schemes' => array('http', 'https')))) {
$this->show_form(_('Invalid profile URL (bad format)')); $this->show_form(_('Invalid profile URL (bad format)'));
return; return;
} }
$fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
$yadis = Auth_Yadis_Yadis::discover($profile, $fetcher); $yadis = Auth_Yadis_Yadis::discover($profile, $fetcher);
if (!$yadis || $yadis->failed) { if (!$yadis || $yadis->failed) {
$this->show_form(_('Not a valid profile URL (no YADIS document).')); $this->show_form(_('Not a valid profile URL (no YADIS document).'));
return; return;
} }
# XXX: a little liberal for sites that accidentally put whitespace before the xml declaration # XXX: a little liberal for sites that accidentally put whitespace before the xml declaration
$xrds =& Auth_Yadis_XRDS::parseXRDS(trim($yadis->response_text)); $xrds =& Auth_Yadis_XRDS::parseXRDS(trim($yadis->response_text));
if (!$xrds) { if (!$xrds) {
$this->show_form(_('Not a valid profile URL (no XRDS defined).')); $this->show_form(_('Not a valid profile URL (no XRDS defined).'));
return; return;
} }
$omb = $this->getOmb($xrds); $omb = $this->getOmb($xrds);
if (!$omb) { if (!$omb) {
$this->show_form(_('Not a valid profile URL (incorrect services).')); $this->show_form(_('Not a valid profile URL (incorrect services).'));
return; return;
} }
if (omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]) == if (omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]) ==
common_local_url('requesttoken')) common_local_url('requesttoken'))
{ {
$this->show_form(_('That\'s a local profile! Login to subscribe.')); $this->show_form(_('That\'s a local profile! Login to subscribe.'));
return; return;
} }
if (User::staticGet('uri', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]))) { if (User::staticGet('uri', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]))) {
$this->show_form(_('That\'s a local profile! Login to subscribe.')); $this->show_form(_('That\'s a local profile! Login to subscribe.'));
return; return;
} }
list($token, $secret) = $this->request_token($omb); list($token, $secret) = $this->request_token($omb);
if (!$token || !$secret) { if (!$token || !$secret) {
$this->show_form(_('Couldn\'t get a request token.')); $this->show_form(_('Couldn\'t get a request token.'));
return; return;
} }
$this->request_authorization($user, $omb, $token, $secret); $this->request_authorization($user, $omb, $token, $secret);
} }
function get_user() { function get_user() {
$user = NULL; $user = NULL;
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
if ($nickname) { if ($nickname) {
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
} }
return $user; return $user;
} }
function getOmb($xrds) { function getOmb($xrds) {
static $omb_endpoints = array(OMB_ENDPOINT_UPDATEPROFILE, OMB_ENDPOINT_POSTNOTICE); static $omb_endpoints = array(OMB_ENDPOINT_UPDATEPROFILE, OMB_ENDPOINT_POSTNOTICE);
static $oauth_endpoints = array(OAUTH_ENDPOINT_REQUEST, OAUTH_ENDPOINT_AUTHORIZE, static $oauth_endpoints = array(OAUTH_ENDPOINT_REQUEST, OAUTH_ENDPOINT_AUTHORIZE,
OAUTH_ENDPOINT_ACCESS); OAUTH_ENDPOINT_ACCESS);
$omb = array(); $omb = array();
# XXX: the following code could probably be refactored to eliminate dupes # XXX: the following code could probably be refactored to eliminate dupes
$oauth_services = omb_get_services($xrds, OAUTH_DISCOVERY); $oauth_services = omb_get_services($xrds, OAUTH_DISCOVERY);
if (!$oauth_services) { if (!$oauth_services) {
return NULL; return NULL;
} }
$oauth_service = $oauth_services[0]; $oauth_service = $oauth_services[0];
$oauth_xrd = $this->getXRD($oauth_service, $xrds); $oauth_xrd = $this->getXRD($oauth_service, $xrds);
if (!$oauth_xrd) { if (!$oauth_xrd) {
return NULL; return NULL;
} }
if (!$this->addServices($oauth_xrd, $oauth_endpoints, $omb)) { if (!$this->addServices($oauth_xrd, $oauth_endpoints, $omb)) {
return NULL; return NULL;
} }
$omb_services = omb_get_services($xrds, OMB_NAMESPACE); $omb_services = omb_get_services($xrds, OMB_NAMESPACE);
if (!$omb_services) { if (!$omb_services) {
return NULL; return NULL;
} }
$omb_service = $omb_services[0]; $omb_service = $omb_services[0];
$omb_xrd = $this->getXRD($omb_service, $xrds); $omb_xrd = $this->getXRD($omb_service, $xrds);
if (!$omb_xrd) { if (!$omb_xrd) {
return NULL; return NULL;
} }
if (!$this->addServices($omb_xrd, $omb_endpoints, $omb)) { if (!$this->addServices($omb_xrd, $omb_endpoints, $omb)) {
return NULL; return NULL;
} }
# XXX: check that we got all the services we needed # XXX: check that we got all the services we needed
foreach (array_merge($omb_endpoints, $oauth_endpoints) as $type) { foreach (array_merge($omb_endpoints, $oauth_endpoints) as $type) {
if (!array_key_exists($type, $omb) || !$omb[$type]) { if (!array_key_exists($type, $omb) || !$omb[$type]) {
return NULL; return NULL;
} }
} }
if (!omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])) { if (!omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])) {
return NULL; return NULL;
} }
return $omb; return $omb;
} }
function getXRD($main_service, $main_xrds) { function getXRD($main_service, $main_xrds) {
$uri = omb_service_uri($main_service); $uri = omb_service_uri($main_service);
if (strpos($uri, "#") !== 0) { if (strpos($uri, "#") !== 0) {
# FIXME: more rigorous handling of external service definitions # FIXME: more rigorous handling of external service definitions
return NULL; return NULL;
} }
$id = substr($uri, 1); $id = substr($uri, 1);
$nodes = $main_xrds->allXrdNodes; $nodes = $main_xrds->allXrdNodes;
$parser = $main_xrds->parser; $parser = $main_xrds->parser;
foreach ($nodes as $node) { foreach ($nodes as $node) {
$attrs = $parser->attributes($node); $attrs = $parser->attributes($node);
if (array_key_exists('xml:id', $attrs) && if (array_key_exists('xml:id', $attrs) &&
$attrs['xml:id'] == $id) { $attrs['xml:id'] == $id) {
# XXX: trick the constructor into thinking this is the only node # XXX: trick the constructor into thinking this is the only node
$bogus_nodes = array($node); $bogus_nodes = array($node);
return new Auth_Yadis_XRDS($parser, $bogus_nodes); return new Auth_Yadis_XRDS($parser, $bogus_nodes);
} }
} }
return NULL; return NULL;
} }
function addServices($xrd, $types, &$omb) { function addServices($xrd, $types, &$omb) {
foreach ($types as $type) { foreach ($types as $type) {
$matches = omb_get_services($xrd, $type); $matches = omb_get_services($xrd, $type);
if ($matches) { if ($matches) {
$omb[$type] = $matches[0]; $omb[$type] = $matches[0];
} else { } else {
# no match for type # no match for type
return false; return false;
} }
} }
return true; return true;
} }
function request_token($omb) { function request_token($omb) {
$con = omb_oauth_consumer(); $con = omb_oauth_consumer();
$url = omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]); $url = omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]);
# XXX: Is this the right thing to do? Strip off GET params and make them # XXX: Is this the right thing to do? Strip off GET params and make them
# POST params? Seems wrong to me. # POST params? Seems wrong to me.
$parsed = parse_url($url); $parsed = parse_url($url);
$params = array(); $params = array();
parse_str($parsed['query'], $params); parse_str($parsed['query'], $params);
$req = OAuthRequest::from_consumer_and_token($con, NULL, "POST", $url, $params); $req = OAuthRequest::from_consumer_and_token($con, NULL, "POST", $url, $params);
$listener = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]); $listener = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]);
if (!$listener) { if (!$listener) {
return NULL; return NULL;
} }
$req->set_parameter('omb_listener', $listener); $req->set_parameter('omb_listener', $listener);
$req->set_parameter('omb_version', OMB_VERSION_01); $req->set_parameter('omb_version', OMB_VERSION_01);
# XXX: test to see if endpoint accepts this signature method # XXX: test to see if endpoint accepts this signature method
$req->sign_request(omb_hmac_sha1(), $con, NULL); $req->sign_request(omb_hmac_sha1(), $con, NULL);
# We re-use this tool's fetcher, since it's pretty good # We re-use this tool's fetcher, since it's pretty good
$fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
$result = $fetcher->post($req->get_normalized_http_url(), $result = $fetcher->post($req->get_normalized_http_url(),
$req->to_postdata(), $req->to_postdata(),
array('User-Agent' => 'Laconica/' . LACONICA_VERSION)); array('User-Agent' => 'Laconica/' . LACONICA_VERSION));
if ($result->status != 200) { if ($result->status != 200) {
return NULL; return NULL;
} }
parse_str($result->body, $return); parse_str($result->body, $return);
return array($return['oauth_token'], $return['oauth_token_secret']); return array($return['oauth_token'], $return['oauth_token_secret']);
} }
function request_authorization($user, $omb, $token, $secret) { function request_authorization($user, $omb, $token, $secret) {
global $config; # for license URL global $config; # for license URL
$con = omb_oauth_consumer(); $con = omb_oauth_consumer();
$tok = new OAuthToken($token, $secret); $tok = new OAuthToken($token, $secret);
$url = omb_service_uri($omb[OAUTH_ENDPOINT_AUTHORIZE]); $url = omb_service_uri($omb[OAUTH_ENDPOINT_AUTHORIZE]);
# XXX: Is this the right thing to do? Strip off GET params and make them # XXX: Is this the right thing to do? Strip off GET params and make them
# POST params? Seems wrong to me. # POST params? Seems wrong to me.
$parsed = parse_url($url); $parsed = parse_url($url);
$params = array(); $params = array();
parse_str($parsed['query'], $params); parse_str($parsed['query'], $params);
$req = OAuthRequest::from_consumer_and_token($con, $tok, 'GET', $url, $params); $req = OAuthRequest::from_consumer_and_token($con, $tok, 'GET', $url, $params);
# We send over a ton of information. This lets the other # We send over a ton of information. This lets the other
# server store info about our user, and it lets the current # server store info about our user, and it lets the current
# user decide if they really want to authorize the subscription. # user decide if they really want to authorize the subscription.
$req->set_parameter('omb_version', OMB_VERSION_01); $req->set_parameter('omb_version', OMB_VERSION_01);
$req->set_parameter('omb_listener', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])); $req->set_parameter('omb_listener', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]));
$req->set_parameter('omb_listenee', $user->uri); $req->set_parameter('omb_listenee', $user->uri);
$req->set_parameter('omb_listenee_profile', common_profile_url($user->nickname)); $req->set_parameter('omb_listenee_profile', common_profile_url($user->nickname));
$req->set_parameter('omb_listenee_nickname', $user->nickname); $req->set_parameter('omb_listenee_nickname', $user->nickname);
$req->set_parameter('omb_listenee_license', $config['license']['url']); $req->set_parameter('omb_listenee_license', $config['license']['url']);
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_log_db_error($user, 'SELECT', __FILE__); common_log_db_error($user, 'SELECT', __FILE__);
$this->server_error(_('User without matching profile')); $this->server_error(_('User without matching profile'));
return; return;
} }
if ($profile->fullname) { if ($profile->fullname) {
$req->set_parameter('omb_listenee_fullname', $profile->fullname); $req->set_parameter('omb_listenee_fullname', $profile->fullname);
} }
if ($profile->homepage) { if ($profile->homepage) {
$req->set_parameter('omb_listenee_homepage', $profile->homepage); $req->set_parameter('omb_listenee_homepage', $profile->homepage);
} }
if ($profile->bio) { if ($profile->bio) {
$req->set_parameter('omb_listenee_bio', $profile->bio); $req->set_parameter('omb_listenee_bio', $profile->bio);
} }
if ($profile->location) { if ($profile->location) {
$req->set_parameter('omb_listenee_location', $profile->location); $req->set_parameter('omb_listenee_location', $profile->location);
} }
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
if ($avatar) { if ($avatar) {
$req->set_parameter('omb_listenee_avatar', $avatar->url); $req->set_parameter('omb_listenee_avatar', $avatar->url);
} }
# XXX: add a nonce to prevent replay attacks # XXX: add a nonce to prevent replay attacks
$req->set_parameter('oauth_callback', common_local_url('finishremotesubscribe')); $req->set_parameter('oauth_callback', common_local_url('finishremotesubscribe'));
# XXX: test to see if endpoint accepts this signature method # XXX: test to see if endpoint accepts this signature method
$req->sign_request(omb_hmac_sha1(), $con, $tok); $req->sign_request(omb_hmac_sha1(), $con, $tok);
# store all our info here # store all our info here
$omb['listenee'] = $user->nickname; $omb['listenee'] = $user->nickname;
$omb['listener'] = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]); $omb['listener'] = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]);
$omb['token'] = $token; $omb['token'] = $token;
$omb['secret'] = $secret; $omb['secret'] = $secret;
# call doesn't work after bounce back so we cache; maybe serialization issue...? # call doesn't work after bounce back so we cache; maybe serialization issue...?
$omb['access_token_url'] = omb_service_uri($omb[OAUTH_ENDPOINT_ACCESS]); $omb['access_token_url'] = omb_service_uri($omb[OAUTH_ENDPOINT_ACCESS]);
$omb['post_notice_url'] = omb_service_uri($omb[OMB_ENDPOINT_POSTNOTICE]); $omb['post_notice_url'] = omb_service_uri($omb[OMB_ENDPOINT_POSTNOTICE]);
$omb['update_profile_url'] = omb_service_uri($omb[OMB_ENDPOINT_UPDATEPROFILE]); $omb['update_profile_url'] = omb_service_uri($omb[OMB_ENDPOINT_UPDATEPROFILE]);
common_ensure_session(); common_ensure_session();
$_SESSION['oauth_authorization_request'] = $omb; $_SESSION['oauth_authorization_request'] = $omb;
# Redirect to authorization service # Redirect to authorization service
common_redirect($req->to_url()); common_redirect($req->to_url());
return; return;
} }
function make_nonce() { function make_nonce() {
return common_good_rand(16); return common_good_rand(16);
} }
} }

View File

@ -23,72 +23,72 @@ require_once(INSTALLDIR.'/actions/showstream.php');
class RepliesAction extends StreamAction { class RepliesAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname = common_canonical_nickname($this->arg('nickname')); $nickname = common_canonical_nickname($this->arg('nickname'));
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
$this->no_such_user(); $this->no_such_user();
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.')); common_server_error(_('User has no profile.'));
return; return;
} }
# Looks like we're good; show the header # Looks like we're good; show the header
common_show_header(sprintf(_("Replies to %s"), $profile->nickname), common_show_header(sprintf(_("Replies to %s"), $profile->nickname),
array($this, 'show_header'), $user, array($this, 'show_header'), $user,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_replies($user); $this->show_replies($user);
common_show_footer(); common_show_footer();
} }
function no_such_user() { function no_such_user() {
common_user_error(_('No such user.')); common_user_error(_('No such user.'));
} }
function show_header($user) { function show_header($user) {
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('repliesrss', array('nickname' => 'href' => common_local_url('repliesrss', array('nickname' =>
$user->nickname)), $user->nickname)),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => sprintf(_('Feed for replies to %s'), $user->nickname))); 'title' => sprintf(_('Feed for replies to %s'), $user->nickname)));
} }
function show_top($user) { function show_top($user) {
$cur = common_current_user(); $cur = common_current_user();
if ($cur && $cur->id == $user->id) { if ($cur && $cur->id == $user->id) {
common_notice_form('replies'); common_notice_form('replies');
} }
$this->views_menu(); $this->views_menu();
$this->show_feeds_list(array(0=>array('href'=>common_local_url('repliesrss', array('nickname' => $user->nickname)), $this->show_feeds_list(array(0=>array('href'=>common_local_url('repliesrss', array('nickname' => $user->nickname)),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'repliesrss'))); 'item' => 'repliesrss')));
} }
function show_replies($user) { function show_replies($user) {
$page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
$notice = $user->getReplies(($page-1) * NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $notice = $user->getReplies(($page-1) * NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1);
$cnt = $this->show_notice_list($notice); $cnt = $this->show_notice_list($notice);
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'replies', array('nickname' => $user->nickname)); $page, 'replies', array('nickname' => $user->nickname));
} }
} }

View File

@ -25,55 +25,55 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class RepliesrssAction extends Rss10Action { class RepliesrssAction extends Rss10Action {
var $user = NULL; var $user = NULL;
function init() { function init() {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$this->user = User::staticGet('nickname', $nickname); $this->user = User::staticGet('nickname', $nickname);
if (!$this->user) { if (!$this->user) {
common_user_error(_('No such user.')); common_user_error(_('No such user.'));
return false; return false;
} else { } else {
return true; return true;
} }
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$user = $this->user; $user = $this->user;
$notice = $user->getReplies(0, ($limit == 0) ? 48 : $limit); $notice = $user->getReplies(0, ($limit == 0) ? 48 : $limit);
$notices = array(); $notices = array();
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
$user = $this->user; $user = $this->user;
$c = array('url' => common_local_url('repliesrss', $c = array('url' => common_local_url('repliesrss',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'title' => sprintf(_("Replies to %s"), $user->nickname), 'title' => sprintf(_("Replies to %s"), $user->nickname),
'link' => common_local_url('replies', 'link' => common_local_url('replies',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'description' => sprintf(_('Feed for replies to %s'), $user->nickname)); 'description' => sprintf(_('Feed for replies to %s'), $user->nickname));
return $c; return $c;
} }
function get_image() { function get_image() {
$user = $this->user; $user = $this->user;
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
return NULL; return NULL;
} }
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
return ($avatar) ? $avatar->url : NULL; return ($avatar) ? $avatar->url : NULL;
} }
} }

View File

@ -22,21 +22,21 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/omb.php'); require_once(INSTALLDIR.'/lib/omb.php');
class RequesttokenAction extends Action { class RequesttokenAction extends Action {
function is_readonly() { function is_readonly() {
return false; return false;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
try { try {
common_remove_magic_from_request(); common_remove_magic_from_request();
$req = OAuthRequest::from_request(); $req = OAuthRequest::from_request();
$server = omb_oauth_server(); $server = omb_oauth_server();
$token = $server->fetch_request_token($req); $token = $server->fetch_request_token($req);
print $token; print $token;
} catch (OAuthException $e) { } catch (OAuthException $e) {
common_server_error($e->getMessage()); common_server_error($e->getMessage());
} }
} }
} }

View File

@ -23,75 +23,75 @@ require_once(INSTALLDIR.'/actions/showstream.php');
class ShowfavoritesAction extends StreamAction { class ShowfavoritesAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname = common_canonical_nickname($this->arg('nickname')); $nickname = common_canonical_nickname($this->arg('nickname'));
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
$this->client_error(_('No such user.')); $this->client_error(_('No such user.'));
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.')); common_server_error(_('User has no profile.'));
return; return;
} }
# Looks like we're good; show the header # Looks like we're good; show the header
common_show_header(sprintf(_("%s favorite notices"), $profile->nickname), common_show_header(sprintf(_("%s favorite notices"), $profile->nickname),
array($this, 'show_header'), $user, array($this, 'show_header'), $user,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_notices($user); $this->show_notices($user);
common_show_footer(); common_show_footer();
} }
function show_header($user) { function show_header($user) {
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('favoritesrss', array('nickname' => 'href' => common_local_url('favoritesrss', array('nickname' =>
$user->nickname)), $user->nickname)),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => sprintf(_('Feed for favorites of %s'), $user->nickname))); 'title' => sprintf(_('Feed for favorites of %s'), $user->nickname)));
} }
function show_top($user) { function show_top($user) {
$cur = common_current_user(); $cur = common_current_user();
if ($cur && $cur->id == $user->id) { if ($cur && $cur->id == $user->id) {
common_notice_form('all'); common_notice_form('all');
} }
$this->show_feeds_list(array(0=>array('href'=>common_local_url('favoritesrss', array('nickname' => $user->nickname)), $this->show_feeds_list(array(0=>array('href'=>common_local_url('favoritesrss', array('nickname' => $user->nickname)),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'Favorites'))); 'item' => 'Favorites')));
$this->views_menu(); $this->views_menu();
} }
function show_notices($user) { function show_notices($user) {
$page = $this->trimmed('page'); $page = $this->trimmed('page');
if (!$page) { if (!$page) {
$page = 1; $page = 1;
} }
$notice = $user->favoriteNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $notice = $user->favoriteNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1);
if (!$notice) { if (!$notice) {
$this->server_error(_('Could not retrieve favorite notices.')); $this->server_error(_('Could not retrieve favorite notices.'));
return; return;
} }
$cnt = $this->show_notice_list($notice); $cnt = $this->show_notice_list($notice);
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'showfavorites', array('nickname' => $user->nickname)); $page, 'showfavorites', array('nickname' => $user->nickname));
} }
} }

View File

@ -23,78 +23,78 @@ require_once(INSTALLDIR.'/lib/mailbox.php');
class ShowmessageAction extends MailboxAction { class ShowmessageAction extends MailboxAction {
function handle($args) { function handle($args) {
Action::handle($args); Action::handle($args);
$message = $this->get_message(); $message = $this->get_message();
if (!$message) { if (!$message) {
$this->client_error(_('No such message.'), 404); $this->client_error(_('No such message.'), 404);
return; return;
} }
$cur = common_current_user(); $cur = common_current_user();
if ($cur && ($cur->id == $message->from_profile || $cur->id == $message->to_profile)) { if ($cur && ($cur->id == $message->from_profile || $cur->id == $message->to_profile)) {
$this->show_page($cur, 1); $this->show_page($cur, 1);
} else { } else {
$this->client_error(_('Only the sender and recipient may read this message.'), 403); $this->client_error(_('Only the sender and recipient may read this message.'), 403);
return; return;
} }
} }
function get_message() { function get_message() {
$id = $this->trimmed('message'); $id = $this->trimmed('message');
$message = Message::staticGet('id', $id); $message = Message::staticGet('id', $id);
return $message; return $message;
} }
function get_title($user, $page) { function get_title($user, $page) {
$message = $this->get_message(); $message = $this->get_message();
if (!$message) { if (!$message) {
return NULL; return NULL;
} }
if ($user->id == $message->from_profile) { if ($user->id == $message->from_profile) {
$to = $message->getTo(); $to = $message->getTo();
$title = sprintf(_("Message to %1\$s on %2\$s"), $title = sprintf(_("Message to %1\$s on %2\$s"),
$to->nickname, $to->nickname,
common_exact_date($message->created)); common_exact_date($message->created));
} else if ($user->id == $message->to_profile) { } else if ($user->id == $message->to_profile) {
$from = $message->getFrom(); $from = $message->getFrom();
$title = sprintf(_("Message from %1\$s on %2\$s"), $title = sprintf(_("Message from %1\$s on %2\$s"),
$from->nickname, $from->nickname,
common_exact_date($message->created)); common_exact_date($message->created));
} }
return $title; return $title;
} }
function get_messages($user, $page) { function get_messages($user, $page) {
$message = new Message(); $message = new Message();
$message->id = $this->trimmed('message'); $message->id = $this->trimmed('message');
$message->find(); $message->find();
return $message; return $message;
} }
function get_message_profile($message) { function get_message_profile($message) {
$user = common_current_user(); $user = common_current_user();
if ($user->id == $message->from_profile) { if ($user->id == $message->from_profile) {
return $message->getTo(); return $message->getTo();
} else if ($user->id == $message->to_profile) { } else if ($user->id == $message->to_profile) {
return $message->getFrom(); return $message->getFrom();
} else { } else {
# This shouldn't happen # This shouldn't happen
return NULL; return NULL;
} }
} }
function get_instructions() { function get_instructions() {
return ''; return '';
} }
function views_menu() { function views_menu() {
return; return;
} }
} }

View File

@ -23,94 +23,94 @@ require_once(INSTALLDIR.'/lib/stream.php');
class ShownoticeAction extends StreamAction { class ShownoticeAction extends StreamAction {
var $notice = NULL; var $notice = NULL;
var $profile = NULL; var $profile = NULL;
var $avatar = NULL; var $avatar = NULL;
function prepare($args) { function prepare($args) {
parent::prepare($args); parent::prepare($args);
$id = $this->arg('notice'); $id = $this->arg('notice');
$this->notice = Notice::staticGet($id); $this->notice = Notice::staticGet($id);
if (!$this->notice) { if (!$this->notice) {
$this->client_error(_('No such notice.'), 404); $this->client_error(_('No such notice.'), 404);
return false; return false;
} }
$this->profile = $this->notice->getProfile(); $this->profile = $this->notice->getProfile();
if (!$this->profile) { if (!$this->profile) {
$this->server_error(_('Notice has no profile'), 500); $this->server_error(_('Notice has no profile'), 500);
return false; return false;
} }
$this->avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); $this->avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE);
return true; return true;
} }
function last_modified() { function last_modified() {
return max(strtotime($this->notice->created), return max(strtotime($this->notice->created),
strtotime($this->profile->modified), strtotime($this->profile->modified),
($this->avatar) ? strtotime($this->avatar->modified) : 0); ($this->avatar) ? strtotime($this->avatar->modified) : 0);
} }
function etag() { function etag() {
return 'W/"' . implode(':', array($this->arg('action'), return 'W/"' . implode(':', array($this->arg('action'),
common_language(), common_language(),
$this->notice->id, $this->notice->id,
strtotime($this->notice->created), strtotime($this->notice->created),
strtotime($this->profile->modified), strtotime($this->profile->modified),
($this->avatar) ? strtotime($this->avatar->modified) : 0)) . '"'; ($this->avatar) ? strtotime($this->avatar->modified) : 0)) . '"';
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
common_show_header(sprintf(_('%1$s\'s status on %2$s'), common_show_header(sprintf(_('%1$s\'s status on %2$s'),
$this->profile->nickname, $this->profile->nickname,
common_exact_date($this->notice->created)), common_exact_date($this->notice->created)),
array($this, 'show_header'), NULL, array($this, 'show_header'), NULL,
array($this, 'show_top')); array($this, 'show_top'));
common_element_start('ul', array('id' => 'notices')); common_element_start('ul', array('id' => 'notices'));
$nli = new NoticeListItem($this->notice); $nli = new NoticeListItem($this->notice);
$nli->show(); $nli->show();
common_element_end('ul'); common_element_end('ul');
common_show_footer(); common_show_footer();
} }
function show_header() { function show_header() {
$user = User::staticGet($this->profile->id); $user = User::staticGet($this->profile->id);
if (!$user) { if (!$user) {
return; return;
} }
if ($user->emailmicroid && $user->email && $this->notice->uri) { if ($user->emailmicroid && $user->email && $this->notice->uri) {
common_element('meta', array('name' => 'microid', common_element('meta', array('name' => 'microid',
'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($this->notice->uri)))); 'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($this->notice->uri))));
} }
if ($user->jabbermicroid && $user->jabber && $this->notice->uri) { if ($user->jabbermicroid && $user->jabber && $this->notice->uri) {
common_element('meta', array('name' => 'microid', common_element('meta', array('name' => 'microid',
'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($this->notice->uri)))); 'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($this->notice->uri))));
} }
} }
function show_top() { function show_top() {
$cur = common_current_user(); $cur = common_current_user();
if ($cur && $cur->id == $this->profile->id) { if ($cur && $cur->id == $this->profile->id) {
common_notice_form(); common_notice_form();
} }
} }
function no_such_notice() { function no_such_notice() {
common_user_error(_('No such notice.')); common_user_error(_('No such notice.'));
} }
} }

View File

@ -26,12 +26,12 @@ define('SUBSCRIPTIONS', 80);
class ShowstreamAction extends StreamAction { class ShowstreamAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname_arg = $this->arg('nickname'); $nickname_arg = $this->arg('nickname');
$nickname = common_canonical_nickname($nickname_arg); $nickname = common_canonical_nickname($nickname_arg);
# Permanent redirect on non-canonical nickname # Permanent redirect on non-canonical nickname
@ -44,163 +44,163 @@ class ShowstreamAction extends StreamAction {
return; return;
} }
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
$this->no_such_user(); $this->no_such_user();
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.')); common_server_error(_('User has no profile.'));
return; return;
} }
# Looks like we're good; start output # Looks like we're good; start output
# For YADIS discovery, we also have a <meta> tag # For YADIS discovery, we also have a <meta> tag
header('X-XRDS-Location: '. common_local_url('xrds', array('nickname' => header('X-XRDS-Location: '. common_local_url('xrds', array('nickname' =>
$user->nickname))); $user->nickname)));
common_show_header($profile->nickname, common_show_header($profile->nickname,
array($this, 'show_header'), $user, array($this, 'show_header'), $user,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_profile($profile); $this->show_profile($profile);
$this->show_notices($user); $this->show_notices($user);
common_show_footer(); common_show_footer();
} }
function show_top($user) { function show_top($user) {
$cur = common_current_user(); $cur = common_current_user();
if ($cur && $cur->id == $user->id) { if ($cur && $cur->id == $user->id) {
common_notice_form('showstream'); common_notice_form('showstream');
} }
$this->views_menu(); $this->views_menu();
$this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('nickname' => $user->nickname)), $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('nickname' => $user->nickname)),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'notices'), 'item' => 'notices'),
1=>array('href'=>common_local_url('usertimeline', array('nickname' => $user->nickname)), 1=>array('href'=>common_local_url('usertimeline', array('nickname' => $user->nickname)),
'type' => 'atom', 'type' => 'atom',
'version' => 'Atom 1.0', 'version' => 'Atom 1.0',
'item' => 'usertimeline'), 'item' => 'usertimeline'),
2=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), 2=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)),
'type' => 'rdf', 'type' => 'rdf',
'version' => 'FOAF', 'version' => 'FOAF',
'item' => 'foaf'))); 'item' => 'foaf')));
} }
function show_header($user) { function show_header($user) {
# Feeds # Feeds
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('api', 'href' => common_local_url('api',
array('apiaction' => 'statuses', array('apiaction' => 'statuses',
'method' => 'user_timeline.rss', 'method' => 'user_timeline.rss',
'argument' => $user->nickname)), 'argument' => $user->nickname)),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => sprintf(_('Notice feed for %s'), $user->nickname))); 'title' => sprintf(_('Notice feed for %s'), $user->nickname)));
common_element('link', array('rel' => 'alternate feed', common_element('link', array('rel' => 'alternate feed',
'href' => common_local_url('api', 'href' => common_local_url('api',
array('apiaction' => 'statuses', array('apiaction' => 'statuses',
'method' => 'user_timeline.atom', 'method' => 'user_timeline.atom',
'argument' => $user->nickname)), 'argument' => $user->nickname)),
'type' => 'application/atom+xml', 'type' => 'application/atom+xml',
'title' => sprintf(_('Notice feed for %s'), $user->nickname))); 'title' => sprintf(_('Notice feed for %s'), $user->nickname)));
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('userrss', array('nickname' => 'href' => common_local_url('userrss', array('nickname' =>
$user->nickname)), $user->nickname)),
'type' => 'application/rdf+xml', 'type' => 'application/rdf+xml',
'title' => sprintf(_('Notice feed for %s'), $user->nickname))); 'title' => sprintf(_('Notice feed for %s'), $user->nickname)));
# FOAF # FOAF
common_element('link', array('rel' => 'meta', common_element('link', array('rel' => 'meta',
'href' => common_local_url('foaf', array('nickname' => 'href' => common_local_url('foaf', array('nickname' =>
$user->nickname)), $user->nickname)),
'type' => 'application/rdf+xml', 'type' => 'application/rdf+xml',
'title' => 'FOAF')); 'title' => 'FOAF'));
# for remote subscriptions etc. # for remote subscriptions etc.
common_element('meta', array('http-equiv' => 'X-XRDS-Location', common_element('meta', array('http-equiv' => 'X-XRDS-Location',
'content' => common_local_url('xrds', array('nickname' => 'content' => common_local_url('xrds', array('nickname' =>
$user->nickname)))); $user->nickname))));
$profile = $user->getProfile(); $profile = $user->getProfile();
if ($profile->bio) { if ($profile->bio) {
common_element('meta', array('name' => 'description', common_element('meta', array('name' => 'description',
'content' => $profile->bio)); 'content' => $profile->bio));
} }
if ($user->emailmicroid && $user->email && $profile->profileurl) { if ($user->emailmicroid && $user->email && $profile->profileurl) {
common_element('meta', array('name' => 'microid', common_element('meta', array('name' => 'microid',
'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($profile->profileurl)))); 'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($profile->profileurl))));
} }
if ($user->jabbermicroid && $user->jabber && $profile->profileurl) { if ($user->jabbermicroid && $user->jabber && $profile->profileurl) {
common_element('meta', array('name' => 'microid', common_element('meta', array('name' => 'microid',
'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($profile->profileurl)))); 'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($profile->profileurl))));
} }
# See https://wiki.mozilla.org/Microsummaries # See https://wiki.mozilla.org/Microsummaries
common_element('link', array('rel' => 'microsummary', common_element('link', array('rel' => 'microsummary',
'href' => common_local_url('microsummary', 'href' => common_local_url('microsummary',
array('nickname' => $profile->nickname)))); array('nickname' => $profile->nickname))));
} }
function no_such_user() { function no_such_user() {
$this->client_error(_('No such user.'), 404); $this->client_error(_('No such user.'), 404);
} }
function show_profile($profile) { function show_profile($profile) {
common_element_start('div', array('id' => 'profile', 'class' => 'vcard')); common_element_start('div', array('id' => 'profile', 'class' => 'vcard'));
$this->show_personal($profile); $this->show_personal($profile);
$this->show_last_notice($profile); $this->show_last_notice($profile);
$cur = common_current_user(); $cur = common_current_user();
$this->show_subscriptions($profile); $this->show_subscriptions($profile);
common_element_end('div'); common_element_end('div');
} }
function show_personal($profile) { function show_personal($profile) {
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
common_element_start('div', array('id' => 'profile_avatar')); common_element_start('div', array('id' => 'profile_avatar'));
common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE), common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE),
'class' => 'avatar profile photo', 'class' => 'avatar profile photo',
'width' => AVATAR_PROFILE_SIZE, 'width' => AVATAR_PROFILE_SIZE,
'height' => AVATAR_PROFILE_SIZE, 'height' => AVATAR_PROFILE_SIZE,
'alt' => $profile->nickname)); 'alt' => $profile->nickname));
common_element_start('ul', array('id' => 'profile_actions')); common_element_start('ul', array('id' => 'profile_actions'));
common_element_start('li', array('id' => 'profile_subscribe')); common_element_start('li', array('id' => 'profile_subscribe'));
$cur = common_current_user(); $cur = common_current_user();
if ($cur) { if ($cur) {
if ($cur->id != $profile->id) { if ($cur->id != $profile->id) {
if ($cur->isSubscribed($profile)) { if ($cur->isSubscribed($profile)) {
common_unsubscribe_form($profile); common_unsubscribe_form($profile);
} else { } else {
common_subscribe_form($profile); common_subscribe_form($profile);
} }
} }
} else { } else {
$this->show_remote_subscribe_link($profile); $this->show_remote_subscribe_link($profile);
} }
common_element_end('li'); common_element_end('li');
$user = User::staticGet('id', $profile->id); $user = User::staticGet('id', $profile->id);
common_profile_new_message_nudge($cur, $user, $profile); common_profile_new_message_nudge($cur, $user, $profile);
if ($cur && $cur->id != $profile->id) { if ($cur && $cur->id != $profile->id) {
$blocked = $cur->hasBlocked($profile); $blocked = $cur->hasBlocked($profile);
@ -215,224 +215,224 @@ class ShowstreamAction extends StreamAction {
common_element_end('li'); common_element_end('li');
} }
common_element_end('ul'); common_element_end('ul');
common_element_end('div'); common_element_end('div');
common_element_start('div', array('id' => 'profile_information')); common_element_start('div', array('id' => 'profile_information'));
if ($profile->fullname) { if ($profile->fullname) {
common_element('h1', array('class' => 'fn'), $profile->fullname . ' (' . $profile->nickname . ')'); common_element('h1', array('class' => 'fn'), $profile->fullname . ' (' . $profile->nickname . ')');
} else { } else {
common_element('h1', array('class' => 'fn nickname'), $profile->nickname); common_element('h1', array('class' => 'fn nickname'), $profile->nickname);
} }
if ($profile->location) { if ($profile->location) {
common_element('p', 'location', $profile->location); common_element('p', 'location', $profile->location);
} }
if ($profile->bio) { if ($profile->bio) {
common_element('p', 'description note', $profile->bio); common_element('p', 'description note', $profile->bio);
} }
if ($profile->homepage) { if ($profile->homepage) {
common_element_start('p', 'website'); common_element_start('p', 'website');
common_element('a', array('href' => $profile->homepage, common_element('a', array('href' => $profile->homepage,
'rel' => 'me', 'class' => 'url'), 'rel' => 'me', 'class' => 'url'),
$profile->homepage); $profile->homepage);
common_element_end('p'); common_element_end('p');
} }
$this->show_statistics($profile); $this->show_statistics($profile);
common_element_end('div'); common_element_end('div');
} }
function show_remote_subscribe_link($profile) { function show_remote_subscribe_link($profile) {
$url = common_local_url('remotesubscribe', $url = common_local_url('remotesubscribe',
array('nickname' => $profile->nickname)); array('nickname' => $profile->nickname));
common_element('a', array('href' => $url, common_element('a', array('href' => $url,
'id' => 'remotesubscribe'), 'id' => 'remotesubscribe'),
_('Subscribe')); _('Subscribe'));
} }
function show_unsubscribe_form($profile) { function show_unsubscribe_form($profile) {
common_element_start('form', array('id' => 'unsubscribe', 'method' => 'post', common_element_start('form', array('id' => 'unsubscribe', 'method' => 'post',
'action' => common_local_url('unsubscribe'))); 'action' => common_local_url('unsubscribe')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('input', array('id' => 'unsubscribeto', common_element('input', array('id' => 'unsubscribeto',
'name' => 'unsubscribeto', 'name' => 'unsubscribeto',
'type' => 'hidden', 'type' => 'hidden',
'value' => $profile->nickname)); 'value' => $profile->nickname));
common_element('input', array('type' => 'submit', common_element('input', array('type' => 'submit',
'class' => 'submit', 'class' => 'submit',
'value' => _('Unsubscribe'))); 'value' => _('Unsubscribe')));
common_element_end('form'); common_element_end('form');
} }
function show_subscriptions($profile) { function show_subscriptions($profile) {
global $config; global $config;
$subs = DB_DataObject::factory('subscription'); $subs = DB_DataObject::factory('subscription');
$subs->subscriber = $profile->id; $subs->subscriber = $profile->id;
$subs->whereAdd('subscribed != ' . $profile->id); $subs->whereAdd('subscribed != ' . $profile->id);
$subs->orderBy('created DESC'); $subs->orderBy('created DESC');
# We ask for an extra one to know if we need to do another page # We ask for an extra one to know if we need to do another page
$subs->limit(0, SUBSCRIPTIONS + 1); $subs->limit(0, SUBSCRIPTIONS + 1);
$subs_count = $subs->find(); $subs_count = $subs->find();
common_element_start('div', array('id' => 'subscriptions')); common_element_start('div', array('id' => 'subscriptions'));
common_element('h2', NULL, _('Subscriptions')); common_element('h2', NULL, _('Subscriptions'));
if ($subs_count > 0) { if ($subs_count > 0) {
common_element_start('ul', array('id' => 'subscriptions_avatars')); common_element_start('ul', array('id' => 'subscriptions_avatars'));
for ($i = 0; $i < min($subs_count, SUBSCRIPTIONS); $i++) { for ($i = 0; $i < min($subs_count, SUBSCRIPTIONS); $i++) {
if (!$subs->fetch()) { if (!$subs->fetch()) {
common_debug('Weirdly, broke out of subscriptions loop early', __FILE__); common_debug('Weirdly, broke out of subscriptions loop early', __FILE__);
break; break;
} }
$other = Profile::staticGet($subs->subscribed); $other = Profile::staticGet($subs->subscribed);
if (!$other) { if (!$other) {
common_log_db_error($subs, 'SELECT', __FILE__); common_log_db_error($subs, 'SELECT', __FILE__);
continue; continue;
} }
common_element_start('li', 'vcard'); common_element_start('li', 'vcard');
common_element_start('a', array('title' => ($other->fullname) ? common_element_start('a', array('title' => ($other->fullname) ?
$other->fullname : $other->fullname :
$other->nickname, $other->nickname,
'href' => $other->profileurl, 'href' => $other->profileurl,
'rel' => 'contact', 'rel' => 'contact',
'class' => 'subscription fn url')); 'class' => 'subscription fn url'));
$avatar = $other->getAvatar(AVATAR_MINI_SIZE); $avatar = $other->getAvatar(AVATAR_MINI_SIZE);
common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)), common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)),
'width' => AVATAR_MINI_SIZE, 'width' => AVATAR_MINI_SIZE,
'height' => AVATAR_MINI_SIZE, 'height' => AVATAR_MINI_SIZE,
'class' => 'avatar mini photo', 'class' => 'avatar mini photo',
'alt' => ($other->fullname) ? 'alt' => ($other->fullname) ?
$other->fullname : $other->fullname :
$other->nickname)); $other->nickname));
common_element_end('a'); common_element_end('a');
common_element_end('li'); common_element_end('li');
} }
common_element_end('ul'); common_element_end('ul');
} }
if ($subs_count > SUBSCRIPTIONS) { if ($subs_count > SUBSCRIPTIONS) {
common_element_start('p', array('id' => 'subscriptions_viewall')); common_element_start('p', array('id' => 'subscriptions_viewall'));
common_element('a', array('href' => common_local_url('subscriptions', common_element('a', array('href' => common_local_url('subscriptions',
array('nickname' => $profile->nickname)), array('nickname' => $profile->nickname)),
'class' => 'moresubscriptions'), 'class' => 'moresubscriptions'),
_('All subscriptions')); _('All subscriptions'));
common_element_end('p'); common_element_end('p');
} }
common_element_end('div'); common_element_end('div');
} }
function show_statistics($profile) { function show_statistics($profile) {
// XXX: WORM cache this // XXX: WORM cache this
$subs = DB_DataObject::factory('subscription'); $subs = DB_DataObject::factory('subscription');
$subs->subscriber = $profile->id; $subs->subscriber = $profile->id;
$subs_count = (int) $subs->count() - 1; $subs_count = (int) $subs->count() - 1;
$subbed = DB_DataObject::factory('subscription'); $subbed = DB_DataObject::factory('subscription');
$subbed->subscribed = $profile->id; $subbed->subscribed = $profile->id;
$subbed_count = (int) $subbed->count() - 1; $subbed_count = (int) $subbed->count() - 1;
$notices = DB_DataObject::factory('notice'); $notices = DB_DataObject::factory('notice');
$notices->profile_id = $profile->id; $notices->profile_id = $profile->id;
$notice_count = (int) $notices->count(); $notice_count = (int) $notices->count();
common_element_start('div', 'statistics'); common_element_start('div', 'statistics');
common_element('h2', 'statistics', _('Statistics')); common_element('h2', 'statistics', _('Statistics'));
# Other stats...? # Other stats...?
common_element_start('dl', 'statistics'); common_element_start('dl', 'statistics');
common_element('dt', 'membersince', _('Member since')); common_element('dt', 'membersince', _('Member since'));
common_element('dd', 'membersince', date('j M Y', common_element('dd', 'membersince', date('j M Y',
strtotime($profile->created))); strtotime($profile->created)));
common_element_start('dt', 'subscriptions'); common_element_start('dt', 'subscriptions');
common_element('a', array('href' => common_local_url('subscriptions', common_element('a', array('href' => common_local_url('subscriptions',
array('nickname' => $profile->nickname))), array('nickname' => $profile->nickname))),
_('Subscriptions')); _('Subscriptions'));
common_element_end('dt'); common_element_end('dt');
common_element('dd', 'subscriptions', (is_int($subs_count)) ? $subs_count : '0'); common_element('dd', 'subscriptions', (is_int($subs_count)) ? $subs_count : '0');
common_element_start('dt', 'subscribers'); common_element_start('dt', 'subscribers');
common_element('a', array('href' => common_local_url('subscribers', common_element('a', array('href' => common_local_url('subscribers',
array('nickname' => $profile->nickname))), array('nickname' => $profile->nickname))),
_('Subscribers')); _('Subscribers'));
common_element_end('dt'); common_element_end('dt');
common_element('dd', 'subscribers', (is_int($subbed_count)) ? $subbed_count : '0'); common_element('dd', 'subscribers', (is_int($subbed_count)) ? $subbed_count : '0');
common_element('dt', 'notices', _('Notices')); common_element('dt', 'notices', _('Notices'));
common_element('dd', 'notices', (is_int($notice_count)) ? $notice_count : '0'); common_element('dd', 'notices', (is_int($notice_count)) ? $notice_count : '0');
# XXX: link these to something # XXX: link these to something
common_element('dt', 'tags', _('Tags')); common_element('dt', 'tags', _('Tags'));
common_element_start('dd', 'tags'); common_element_start('dd', 'tags');
$tags = Profile_tag::getTags($profile->id, $profile->id); $tags = Profile_tag::getTags($profile->id, $profile->id);
common_element_start('ul', 'tags xoxo'); common_element_start('ul', 'tags xoxo');
foreach ($tags as $tag) { foreach ($tags as $tag) {
common_element_start('li'); common_element_start('li');
common_element('a', array('rel' => 'bookmark tag', common_element('a', array('rel' => 'bookmark tag',
'href' => common_local_url('peopletag', 'href' => common_local_url('peopletag',
array('tag' => $tag))), array('tag' => $tag))),
$tag); $tag);
common_element_end('li'); common_element_end('li');
} }
common_element_end('ul'); common_element_end('ul');
common_element_end('dd'); common_element_end('dd');
common_element_end('dl'); common_element_end('dl');
common_element_end('div'); common_element_end('div');
} }
function show_notices($user) { function show_notices($user) {
$page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
$notice = $user->getNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $notice = $user->getNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1);
$pnl = new ProfileNoticeList($notice); $pnl = new ProfileNoticeList($notice);
$cnt = $pnl->show(); $cnt = $pnl->show();
common_pagination($page>1, $cnt>NOTICES_PER_PAGE, $page, common_pagination($page>1, $cnt>NOTICES_PER_PAGE, $page,
'showstream', array('nickname' => $user->nickname)); 'showstream', array('nickname' => $user->nickname));
} }
function show_last_notice($profile) { function show_last_notice($profile) {
common_element('h2', NULL, _('Currently')); common_element('h2', NULL, _('Currently'));
$notice = $profile->getCurrentNotice(); $notice = $profile->getCurrentNotice();
if ($notice) { if ($notice) {
# FIXME: URL, image, video, audio # FIXME: URL, image, video, audio
common_element_start('p', array('class' => 'notice_current')); common_element_start('p', array('class' => 'notice_current'));
if ($notice->rendered) { if ($notice->rendered) {
common_raw($notice->rendered); common_raw($notice->rendered);
} else { } else {
# XXX: may be some uncooked notices in the DB, # XXX: may be some uncooked notices in the DB,
# we cook them right now. This can probably disappear in future # we cook them right now. This can probably disappear in future
# versions (>> 0.4.x) # versions (>> 0.4.x)
common_raw(common_render_content($notice->content, $notice)); common_raw(common_render_content($notice->content, $notice));
} }
common_element_end('p'); common_element_end('p');
} }
} }
} }
# We don't show the author for a profile, since we already know who it is! # We don't show the author for a profile, since we already know who it is!

View File

@ -24,308 +24,308 @@ require_once(INSTALLDIR.'/actions/emailsettings.php');
class SmssettingsAction extends EmailsettingsAction { class SmssettingsAction extends EmailsettingsAction {
function get_instructions() { function get_instructions() {
return _('You can receive SMS messages through email from %%site.name%%.'); return _('You can receive SMS messages through email from %%site.name%%.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$user = common_current_user(); $user = common_current_user();
$this->form_header(_('SMS Settings'), $msg, $success); $this->form_header(_('SMS Settings'), $msg, $success);
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'smssettings', 'id' => 'smssettings',
'action' => 'action' =>
common_local_url('smssettings'))); common_local_url('smssettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('h2', NULL, _('Address')); common_element('h2', NULL, _('Address'));
if ($user->sms) { if ($user->sms) {
common_element_start('p'); common_element_start('p');
$carrier = $user->getCarrier(); $carrier = $user->getCarrier();
common_element('span', 'address confirmed', $user->sms . ' (' . $carrier->name . ')'); common_element('span', 'address confirmed', $user->sms . ' (' . $carrier->name . ')');
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Current confirmed SMS-enabled phone number.')); _('Current confirmed SMS-enabled phone number.'));
common_hidden('sms', $user->sms); common_hidden('sms', $user->sms);
common_hidden('carrier', $user->carrier); common_hidden('carrier', $user->carrier);
common_element_end('p'); common_element_end('p');
common_submit('remove', _('Remove')); common_submit('remove', _('Remove'));
} else { } else {
$confirm = $this->get_confirmation(); $confirm = $this->get_confirmation();
if ($confirm) { if ($confirm) {
$carrier = Sms_carrier::staticGet($confirm->address_extra); $carrier = Sms_carrier::staticGet($confirm->address_extra);
common_element_start('p'); common_element_start('p');
common_element('span', 'address unconfirmed', $confirm->address . ' (' . $carrier->name . ')'); common_element('span', 'address unconfirmed', $confirm->address . ' (' . $carrier->name . ')');
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Awaiting confirmation on this phone number.')); _('Awaiting confirmation on this phone number.'));
common_hidden('sms', $confirm->address); common_hidden('sms', $confirm->address);
common_hidden('carrier', $confirm->address_extra); common_hidden('carrier', $confirm->address_extra);
common_element_end('p'); common_element_end('p');
common_submit('cancel', _('Cancel')); common_submit('cancel', _('Cancel'));
common_input('code', _('Confirmation code'), NULL, common_input('code', _('Confirmation code'), NULL,
_('Enter the code you received on your phone.')); _('Enter the code you received on your phone.'));
common_submit('confirm', _('Confirm')); common_submit('confirm', _('Confirm'));
} else { } else {
common_input('sms', _('SMS Phone number'), common_input('sms', _('SMS Phone number'),
($this->arg('sms')) ? $this->arg('sms') : NULL, ($this->arg('sms')) ? $this->arg('sms') : NULL,
_('Phone number, no punctuation or spaces, with area code')); _('Phone number, no punctuation or spaces, with area code'));
$this->carrier_select(); $this->carrier_select();
common_submit('add', _('Add')); common_submit('add', _('Add'));
} }
} }
if ($user->sms) { if ($user->sms) {
common_element('h2', NULL, _('Incoming email')); common_element('h2', NULL, _('Incoming email'));
if ($user->incomingemail) { if ($user->incomingemail) {
common_element_start('p'); common_element_start('p');
common_element('span', 'address', $user->incomingemail); common_element('span', 'address', $user->incomingemail);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Send email to this address to post new notices.')); _('Send email to this address to post new notices.'));
common_element_end('p'); common_element_end('p');
common_submit('removeincoming', _('Remove')); common_submit('removeincoming', _('Remove'));
} }
common_element_start('p'); common_element_start('p');
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Make a new email address for posting to; cancels the old one.')); _('Make a new email address for posting to; cancels the old one.'));
common_element_end('p'); common_element_end('p');
common_submit('newincoming', _('New')); common_submit('newincoming', _('New'));
} }
common_element('h2', NULL, _('Preferences')); common_element('h2', NULL, _('Preferences'));
common_checkbox('smsnotify', common_checkbox('smsnotify',
_('Send me notices through SMS; I understand I may incur exorbitant charges from my carrier.'), _('Send me notices through SMS; I understand I may incur exorbitant charges from my carrier.'),
$user->smsnotify); $user->smsnotify);
common_submit('save', _('Save')); common_submit('save', _('Save'));
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function get_confirmation() { function get_confirmation() {
$user = common_current_user(); $user = common_current_user();
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->address_type = 'sms'; $confirm->address_type = 'sms';
if ($confirm->find(TRUE)) { if ($confirm->find(TRUE)) {
return $confirm; return $confirm;
} else { } else {
return NULL; return NULL;
} }
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('save')) { if ($this->arg('save')) {
$this->save_preferences(); $this->save_preferences();
} else if ($this->arg('add')) { } else if ($this->arg('add')) {
$this->add_address(); $this->add_address();
} else if ($this->arg('cancel')) { } else if ($this->arg('cancel')) {
$this->cancel_confirmation(); $this->cancel_confirmation();
} else if ($this->arg('remove')) { } else if ($this->arg('remove')) {
$this->remove_address(); $this->remove_address();
} else if ($this->arg('removeincoming')) { } else if ($this->arg('removeincoming')) {
$this->remove_incoming(); $this->remove_incoming();
} else if ($this->arg('newincoming')) { } else if ($this->arg('newincoming')) {
$this->new_incoming(); $this->new_incoming();
} else if ($this->arg('confirm')) { } else if ($this->arg('confirm')) {
$this->confirm_code(); $this->confirm_code();
} else { } else {
$this->show_form(_('Unexpected form submission.')); $this->show_form(_('Unexpected form submission.'));
} }
} }
function save_preferences() { function save_preferences() {
$smsnotify = $this->boolean('smsnotify'); $smsnotify = $this->boolean('smsnotify');
$user = common_current_user(); $user = common_current_user();
assert(!is_null($user)); # should already be checked assert(!is_null($user)); # should already be checked
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->smsnotify = $smsnotify; $user->smsnotify = $smsnotify;
$result = $user->update($original); $result = $user->update($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
$this->show_form(_('Preferences saved.'), true); $this->show_form(_('Preferences saved.'), true);
} }
function add_address() { function add_address() {
$user = common_current_user(); $user = common_current_user();
$sms = $this->trimmed('sms'); $sms = $this->trimmed('sms');
$carrier_id = $this->trimmed('carrier'); $carrier_id = $this->trimmed('carrier');
# Some validation # Some validation
if (!$sms) { if (!$sms) {
$this->show_form(_('No phone number.')); $this->show_form(_('No phone number.'));
return; return;
} }
if (!$carrier_id) { if (!$carrier_id) {
$this->show_form(_('No carrier selected.')); $this->show_form(_('No carrier selected.'));
return; return;
} }
$sms = common_canonical_sms($sms); $sms = common_canonical_sms($sms);
if ($user->sms == $sms) { if ($user->sms == $sms) {
$this->show_form(_('That is already your phone number.')); $this->show_form(_('That is already your phone number.'));
return; return;
} else if ($this->sms_exists($sms)) { } else if ($this->sms_exists($sms)) {
$this->show_form(_('That phone number already belongs to another user.')); $this->show_form(_('That phone number already belongs to another user.'));
return; return;
} }
$confirm = new Confirm_address(); $confirm = new Confirm_address();
$confirm->address = $sms; $confirm->address = $sms;
$confirm->address_extra = $carrier_id; $confirm->address_extra = $carrier_id;
$confirm->address_type = 'sms'; $confirm->address_type = 'sms';
$confirm->user_id = $user->id; $confirm->user_id = $user->id;
$confirm->code = common_confirmation_code(40); $confirm->code = common_confirmation_code(40);
$result = $confirm->insert(); $result = $confirm->insert();
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($confirm, 'INSERT', __FILE__); common_log_db_error($confirm, 'INSERT', __FILE__);
common_server_error(_('Couldn\'t insert confirmation code.')); common_server_error(_('Couldn\'t insert confirmation code.'));
return; return;
} }
$carrier = Sms_carrier::staticGet($carrier_id); $carrier = Sms_carrier::staticGet($carrier_id);
mail_confirm_sms($confirm->code, mail_confirm_sms($confirm->code,
$user->nickname, $user->nickname,
$carrier->toEmailAddress($sms)); $carrier->toEmailAddress($sms));
$msg = _('A confirmation code was sent to the phone number you added. Check your inbox (and spam box!) for the code and instructions on how to use it.'); $msg = _('A confirmation code was sent to the phone number you added. Check your inbox (and spam box!) for the code and instructions on how to use it.');
$this->show_form($msg, TRUE); $this->show_form($msg, TRUE);
} }
function cancel_confirmation() { function cancel_confirmation() {
$sms = $this->trimmed('sms'); $sms = $this->trimmed('sms');
$carrier = $this->trimmed('carrier'); $carrier = $this->trimmed('carrier');
$confirm = $this->get_confirmation(); $confirm = $this->get_confirmation();
if (!$confirm) { if (!$confirm) {
$this->show_form(_('No pending confirmation to cancel.')); $this->show_form(_('No pending confirmation to cancel.'));
return; return;
} }
if ($confirm->address != $sms) { if ($confirm->address != $sms) {
$this->show_form(_('That is the wrong confirmation number.')); $this->show_form(_('That is the wrong confirmation number.'));
return; return;
} }
$result = $confirm->delete(); $result = $confirm->delete();
if (!$result) { if (!$result) {
common_log_db_error($confirm, 'DELETE', __FILE__); common_log_db_error($confirm, 'DELETE', __FILE__);
$this->server_error(_('Couldn\'t delete email confirmation.')); $this->server_error(_('Couldn\'t delete email confirmation.'));
return; return;
} }
$this->show_form(_('Confirmation cancelled.'), TRUE); $this->show_form(_('Confirmation cancelled.'), TRUE);
} }
function remove_address() { function remove_address() {
$user = common_current_user(); $user = common_current_user();
$sms = $this->arg('sms'); $sms = $this->arg('sms');
$carrier = $this->arg('carrier'); $carrier = $this->arg('carrier');
# Maybe an old tab open...? # Maybe an old tab open...?
if ($user->sms != $sms) { if ($user->sms != $sms) {
$this->show_form(_('That is not your phone number.')); $this->show_form(_('That is not your phone number.'));
return; return;
} }
$user->query('BEGIN'); $user->query('BEGIN');
$original = clone($user); $original = clone($user);
$user->sms = NULL; $user->sms = NULL;
$user->carrier = NULL; $user->carrier = NULL;
$user->smsemail = NULL; $user->smsemail = NULL;
$result = $user->updateKeys($original); $result = $user->updateKeys($original);
if (!$result) { if (!$result) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t update user.')); common_server_error(_('Couldn\'t update user.'));
return; return;
} }
$user->query('COMMIT'); $user->query('COMMIT');
$this->show_form(_('The address was removed.'), TRUE); $this->show_form(_('The address was removed.'), TRUE);
} }
function sms_exists($sms) { function sms_exists($sms) {
$user = common_current_user(); $user = common_current_user();
$other = User::staticGet('sms', $sms); $other = User::staticGet('sms', $sms);
if (!$other) { if (!$other) {
return false; return false;
} else { } else {
return $other->id != $user->id; return $other->id != $user->id;
} }
} }
function carrier_select() { function carrier_select() {
$carrier = new Sms_carrier(); $carrier = new Sms_carrier();
$cnt = $carrier->find(); $cnt = $carrier->find();
common_element_start('p'); common_element_start('p');
common_element('label', array('for' => 'carrier')); common_element('label', array('for' => 'carrier'));
common_element_start('select', array('name' => 'carrier', common_element_start('select', array('name' => 'carrier',
'id' => 'carrier')); 'id' => 'carrier'));
common_element('option', array('value' => 0), common_element('option', array('value' => 0),
_('Select a carrier')); _('Select a carrier'));
while ($carrier->fetch()) { while ($carrier->fetch()) {
common_element('option', array('value' => $carrier->id), common_element('option', array('value' => $carrier->id),
$carrier->name); $carrier->name);
} }
common_element_end('select'); common_element_end('select');
common_element_end('p'); common_element_end('p');
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
sprintf(_('Mobile carrier for your phone. '. sprintf(_('Mobile carrier for your phone. '.
'If you know a carrier that accepts ' . 'If you know a carrier that accepts ' .
'SMS over email but isn\'t listed here, ' . 'SMS over email but isn\'t listed here, ' .
'send email to let us know at %s.'), 'send email to let us know at %s.'),
common_config('site', 'email'))); common_config('site', 'email')));
} }
function confirm_code() { function confirm_code() {
$code = $this->trimmed('code'); $code = $this->trimmed('code');
if (!$code) { if (!$code) {
$this->show_form(_('No code entered')); $this->show_form(_('No code entered'));
return; return;
} }
common_redirect(common_local_url('confirmaddress', common_redirect(common_local_url('confirmaddress',
array('code' => $code))); array('code' => $code)));
} }
} }

View File

@ -32,12 +32,12 @@ class SubeditAction extends Action {
return false; return false;
} }
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$id = $this->trimmed('profile'); $id = $this->trimmed('profile');

View File

@ -21,58 +21,58 @@ if (!defined('LACONICA')) { exit(1); }
class SubscribeAction extends Action { class SubscribeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname))); common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname)));
return; return;
} }
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$other_id = $this->arg('subscribeto'); $other_id = $this->arg('subscribeto');
$other = User::staticGet('id', $other_id); $other = User::staticGet('id', $other_id);
if (!$other) { if (!$other) {
$this->client_error(_('Not a local user.')); $this->client_error(_('Not a local user.'));
return; return;
} }
$result = subs_subscribe_to($user, $other); $result = subs_subscribe_to($user, $other);
if($result != true) { if($result != true) {
common_user_error($result); common_user_error($result);
return; return;
}
if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true);
common_element_start('head');
common_element('title', null, _('Subscribed'));
common_element_end('head');
common_element_start('body');
common_unsubscribe_form($other->getProfile());
common_element_end('body');
common_element_end('html');
} else {
common_redirect(common_local_url('subscriptions', array('nickname' =>
$user->nickname)));
} }
}
if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true);
common_element_start('head');
common_element('title', null, _('Subscribed'));
common_element_end('head');
common_element_start('body');
common_unsubscribe_form($other->getProfile());
common_element_end('body');
common_element_end('html');
} else {
common_redirect(common_local_url('subscriptions', array('nickname' =>
$user->nickname)));
}
}
} }

View File

@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/gallery.php');
class SubscribersAction extends GalleryAction { class SubscribersAction extends GalleryAction {
function gallery_type() { function gallery_type() {
return _('Subscribers'); return _('Subscribers');
} }
function get_instructions(&$profile) { function get_instructions(&$profile) {
$user =& common_current_user(); $user =& common_current_user();
if ($user && ($user->id == $profile->id)) { if ($user && ($user->id == $profile->id)) {
return _('These are the people who listen to your notices.'); return _('These are the people who listen to your notices.');
} else { } else {
return sprintf(_('These are the people who listen to %s\'s notices.'), $profile->nickname); return sprintf(_('These are the people who listen to %s\'s notices.'), $profile->nickname);
} }
} }
function fields() { function fields() {
return array('subscriber', 'subscribed'); return array('subscriber', 'subscribed');
} }
function div_class() { function div_class() {
return 'subscribers'; return 'subscribers';
} }
function get_other(&$subs) { function get_other(&$subs) {
return $subs->subscriber; return $subs->subscriber;
} }
function profile_list_class() { function profile_list_class() {
return 'SubscribersList'; return 'SubscribersList';

View File

@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/gallery.php');
class SubscriptionsAction extends GalleryAction { class SubscriptionsAction extends GalleryAction {
function gallery_type() { function gallery_type() {
return _('Subscriptions'); return _('Subscriptions');
} }
function get_instructions(&$profile) { function get_instructions(&$profile) {
$user =& common_current_user(); $user =& common_current_user();
if ($user && ($user->id == $profile->id)) { if ($user && ($user->id == $profile->id)) {
return _('These are the people whose notices you listen to.'); return _('These are the people whose notices you listen to.');
} else { } else {
return sprintf(_('These are the people whose notices %s listens to.'), $profile->nickname); return sprintf(_('These are the people whose notices %s listens to.'), $profile->nickname);
} }
} }
function fields() { function fields() {
return array('subscribed', 'subscriber'); return array('subscribed', 'subscriber');
} }
function div_class() { function div_class() {
return 'subscriptions'; return 'subscriptions';
} }
function get_other(&$subs) { function get_other(&$subs) {
return $subs->subscribed; return $subs->subscribed;
} }
function profile_list_class() { function profile_list_class() {
return 'SubscriptionsList'; return 'SubscriptionsList';
@ -57,8 +57,8 @@ class SubscriptionsList extends ProfileList {
function show_owner_controls($profile) { function show_owner_controls($profile) {
$sub = Subscription::pkeyGet(array('subscriber' => $this->owner->id, $sub = Subscription::pkeyGet(array('subscriber' => $this->owner->id,
'subscribed' => $profile->id)); 'subscribed' => $profile->id));
if (!$sub) { if (!$sub) {
return; return;
} }

View File

@ -20,62 +20,62 @@
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
class SupAction extends Action { class SupAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$seconds = $this->trimmed('seconds'); $seconds = $this->trimmed('seconds');
if (!$seconds) { if (!$seconds) {
$seconds = 15; $seconds = 15;
} }
$updates = $this->get_updates($seconds); $updates = $this->get_updates($seconds);
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
print json_encode(array('updated_time' => date('c'), print json_encode(array('updated_time' => date('c'),
'since_time' => date('c', time() - $seconds), 'since_time' => date('c', time() - $seconds),
'available_periods' => $this->available_periods(), 'available_periods' => $this->available_periods(),
'period' => $seconds, 'period' => $seconds,
'updates' => $updates)); 'updates' => $updates));
} }
function available_periods() { function available_periods() {
static $periods = array(86400, 43200, 21600, 7200, static $periods = array(86400, 43200, 21600, 7200,
3600, 1800, 600, 300, 120, 3600, 1800, 600, 300, 120,
60, 30, 15); 60, 30, 15);
$available = array(); $available = array();
foreach ($periods as $period) { foreach ($periods as $period) {
$available[$period] = common_local_url('sup', $available[$period] = common_local_url('sup',
array('seconds' => $period)); array('seconds' => $period));
} }
return $available; return $available;
} }
function get_updates($seconds) { function get_updates($seconds) {
$notice = new Notice(); $notice = new Notice();
# XXX: cache this. Depends on how big this protocol becomes; # XXX: cache this. Depends on how big this protocol becomes;
# Re-doing this query every 15 seconds isn't the end of the world. # Re-doing this query every 15 seconds isn't the end of the world.
$notice->query('SELECT profile_id, max(id) AS max_id ' . $notice->query('SELECT profile_id, max(id) AS max_id ' .
'FROM notice ' . 'FROM notice ' .
'WHERE created > (now() - ' . $seconds . ') ' . 'WHERE created > (now() - ' . $seconds . ') ' .
'GROUP BY profile_id'); 'GROUP BY profile_id');
$updates = array(); $updates = array();
while ($notice->fetch()) { while ($notice->fetch()) {
$updates[] = array($notice->profile_id, $notice->max_id); $updates[] = array($notice->profile_id, $notice->max_id);
} }
return $updates; return $updates;
} }
function is_readonly() { function is_readonly() {
return true; return true;
} }
} }

View File

@ -24,142 +24,142 @@ define('TAGS_PER_PAGE', 100);
class TagAction extends StreamAction { class TagAction extends StreamAction {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
# Looks like we're good; show the header # Looks like we're good; show the header
if (isset($args['tag']) && $args['tag']) { if (isset($args['tag']) && $args['tag']) {
$tag = $args['tag']; $tag = $args['tag'];
common_show_header(sprintf(_("Notices tagged with %s"), $tag), common_show_header(sprintf(_("Notices tagged with %s"), $tag),
array($this, 'show_header'), $tag, array($this, 'show_header'), $tag,
array($this, 'show_top')); array($this, 'show_top'));
$this->show_notices($tag); $this->show_notices($tag);
} else { } else {
common_show_header(_("Tags"), common_show_header(_("Tags"),
array($this, 'show_header'), '', array($this, 'show_header'), '',
array($this, 'show_top')); array($this, 'show_top'));
$this->show_tags(); $this->show_tags();
} }
common_show_footer(); common_show_footer();
} }
function show_header($tag = false) { function show_header($tag = false) {
if ($tag) { if ($tag) {
common_element('link', array('rel' => 'alternate', common_element('link', array('rel' => 'alternate',
'href' => common_local_url('tagrss', array('tag' => $tag)), 'href' => common_local_url('tagrss', array('tag' => $tag)),
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => sprintf(_('Feed for tag %s'), $tag))); 'title' => sprintf(_('Feed for tag %s'), $tag)));
} }
} }
function get_instructions() { function get_instructions() {
return _('Showing most popular tags from the last week'); return _('Showing most popular tags from the last week');
} }
function show_top($tag = false) { function show_top($tag = false) {
if (!$tag) { if (!$tag) {
$instr = $this->get_instructions(); $instr = $this->get_instructions();
$output = common_markup_to_html($instr); $output = common_markup_to_html($instr);
common_element_start('div', 'instructions'); common_element_start('div', 'instructions');
common_raw($output); common_raw($output);
common_element_end('div'); common_element_end('div');
$this->public_views_menu(); $this->public_views_menu();
} }
else { else {
$this->show_feeds_list(array(0=>array('href'=>common_local_url('tagrss'), $this->show_feeds_list(array(0=>array('href'=>common_local_url('tagrss'),
'type' => 'rss', 'type' => 'rss',
'version' => 'RSS 1.0', 'version' => 'RSS 1.0',
'item' => 'tagrss'))); 'item' => 'tagrss')));
} }
} }
function show_tags() function show_tags()
{ {
# This should probably be cached rather than recalculated # This should probably be cached rather than recalculated
$tags = DB_DataObject::factory('Notice_tag'); $tags = DB_DataObject::factory('Notice_tag');
#Need to clear the selection and then only re-add the field #Need to clear the selection and then only re-add the field
#we are grouping by, otherwise it's not a valid 'group by' #we are grouping by, otherwise it's not a valid 'group by'
#even though MySQL seems to let it slide... #even though MySQL seems to let it slide...
$tags->selectAdd(); $tags->selectAdd();
$tags->selectAdd('tag'); $tags->selectAdd('tag');
#Add the aggregated columns... #Add the aggregated columns...
$tags->selectAdd('max(notice_id) as last_notice_id'); $tags->selectAdd('max(notice_id) as last_notice_id');
if(common_config('db','type')=='pgsql') { if(common_config('db','type')=='pgsql') {
$calc='sum(exp(-extract(epoch from (now()-created))/%s)) as weight'; $calc='sum(exp(-extract(epoch from (now()-created))/%s)) as weight';
} else { } else {
$calc='sum(exp(-(now() - created)/%s)) as weight'; $calc='sum(exp(-(now() - created)/%s)) as weight';
} }
$tags->selectAdd(sprintf($calc, common_config('tag', 'dropoff'))); $tags->selectAdd(sprintf($calc, common_config('tag', 'dropoff')));
$tags->groupBy('tag'); $tags->groupBy('tag');
$tags->orderBy('weight DESC'); $tags->orderBy('weight DESC');
# $tags->whereAdd('created > "' . strftime('%Y-%m-%d %H:%M:%S', strtotime('-1 MONTH')) . '"'); # $tags->whereAdd('created > "' . strftime('%Y-%m-%d %H:%M:%S', strtotime('-1 MONTH')) . '"');
$tags->limit(TAGS_PER_PAGE); $tags->limit(TAGS_PER_PAGE);
$cnt = $tags->find(); $cnt = $tags->find();
if ($cnt > 0) { if ($cnt > 0) {
common_element_start('p', 'tagcloud'); common_element_start('p', 'tagcloud');
$tw = array(); $tw = array();
$sum = 0; $sum = 0;
while ($tags->fetch()) { while ($tags->fetch()) {
$tw[$tags->tag] = $tags->weight; $tw[$tags->tag] = $tags->weight;
$sum += $tags->weight; $sum += $tags->weight;
} }
ksort($tw); ksort($tw);
foreach ($tw as $tag => $weight) { foreach ($tw as $tag => $weight) {
$this->show_tag($tag, $weight, $weight/$sum); $this->show_tag($tag, $weight, $weight/$sum);
} }
common_element_end('p'); common_element_end('p');
} }
} }
function show_tag($tag, $weight, $relative) { function show_tag($tag, $weight, $relative) {
# XXX: these should probably tune to the size of the site # XXX: these should probably tune to the size of the site
if ($relative > 0.1) { if ($relative > 0.1) {
$cls = 'largest'; $cls = 'largest';
} else if ($relative > 0.05) { } else if ($relative > 0.05) {
$cls = 'verylarge'; $cls = 'verylarge';
} else if ($relative > 0.02) { } else if ($relative > 0.02) {
$cls = 'large'; $cls = 'large';
} else if ($relative > 0.01) { } else if ($relative > 0.01) {
$cls = 'medium'; $cls = 'medium';
} else if ($relative > 0.005) { } else if ($relative > 0.005) {
$cls = 'small'; $cls = 'small';
} else if ($relative > 0.002) { } else if ($relative > 0.002) {
$cls = 'verysmall'; $cls = 'verysmall';
} else { } else {
$cls = 'smallest'; $cls = 'smallest';
} }
common_element('a', array('class' => "$cls weight-$weight relative-$relative", common_element('a', array('class' => "$cls weight-$weight relative-$relative",
'href' => common_local_url('tag', array('tag' => $tag))), 'href' => common_local_url('tag', array('tag' => $tag))),
$tag); $tag);
common_text(' '); common_text(' ');
} }
function show_notices($tag) { function show_notices($tag) {
$cnt = 0; $cnt = 0;
$page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
$notice = Notice_tag::getStream($tag, (($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1); $notice = Notice_tag::getStream($tag, (($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1);
$cnt = $this->show_notice_list($notice); $cnt = $this->show_notice_list($notice);
common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, common_pagination($page > 1, $cnt > NOTICES_PER_PAGE,
$page, 'tag', array('tag' => $tag)); $page, 'tag', array('tag' => $tag));
} }
} }

View File

@ -23,171 +23,171 @@ require_once(INSTALLDIR.'/lib/settingsaction.php');
class TagotherAction extends Action { class TagotherAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
$this->client_error(_('Not logged in'), 403); $this->client_error(_('Not logged in'), 403);
return; return;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->save_tags();
} else {
$id = $this->trimmed('id');
if (!$id) {
$this->client_error(_('No id argument.'));
return;
}
$profile = Profile::staticGet('id', $id);
if (!$profile) {
$this->client_error(_('No profile with that ID.'));
return;
}
$this->show_form($profile);
}
}
function show_form($profile, $error=NULL) {
$user = common_current_user();
common_show_header(_('Tag a person'),
NULL, array($profile, $error), array($this, 'show_top'));
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE),
'class' => 'avatar stream',
'width' => AVATAR_PROFILE_SIZE,
'height' => AVATAR_PROFILE_SIZE,
'alt' =>
($profile->fullname) ? $profile->fullname :
$profile->nickname));
common_element('a', array('href' => $profile->profileurl,
'class' => 'external profile nickname'),
$profile->nickname);
if ($profile->fullname) {
common_element_start('div', 'fullname');
if ($profile->homepage) {
common_element('a', array('href' => $profile->homepage),
$profile->fullname);
} else {
common_text($profile->fullname);
}
common_element_end('div');
}
if ($profile->location) {
common_element('div', 'location', $profile->location);
}
if ($profile->bio) {
common_element('div', 'bio', $profile->bio);
}
common_element_start('form', array('method' => 'post',
'id' => 'tag_user',
'name' => 'tagother',
'action' => $this->self_url()));
common_hidden('token', common_session_token());
common_hidden('id', $profile->id);
common_input('tags', _('Tags'),
($this->arg('tags')) ? $this->arg('tags') : implode(' ', Profile_tag::getTags($user->id, $profile->id)),
_('Tags for this user (letters, numbers, -, ., and _), comma- or space- separated'));
common_submit('save', _('Save'));
common_element_end('form');
common_show_footer();
}
function save_tags() {
$id = $this->trimmed('id');
$tagstring = $this->trimmed('tags');
$token = $this->trimmed('token');
if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.'));
return;
}
$profile = Profile::staticGet('id', $id);
if (!$profile) {
$this->client_error(_('No such profile.'));
return;
}
if (is_string($tagstring) && strlen($tagstring) > 0) {
$tags = array_map('common_canonical_tag',
preg_split('/[\s,]+/', $tagstring));
foreach ($tags as $tag) {
if (!common_valid_profile_tag($tag)) {
$this->show_form($profile, sprintf(_('Invalid tag: "%s"'), $tag));
return;
}
}
} else {
$tags = array();
}
$user = common_current_user();
if (!Subscription::pkeyGet(array('subscriber' => $user->id,
'subscribed' => $profile->id)) &&
!Subscription::pkeyGet(array('subscriber' => $profile->id,
'subscribed' => $user->id)))
{
$this->client_error(_('You can only tag people you are subscribed to or who are subscribed to you.'));
return;
}
$result = Profile_tag::setTags($user->id, $profile->id, $tags);
if (!$result) {
$this->client_error(_('Could not save tags.'));
return;
}
$action = $user->isSubscribed($profile) ? 'subscriptions' : 'subscribers';
if ($this->boolean('ajax')) {
common_start_html('text/xml');
common_element_start('head');
common_element('title', null, _('Tags'));
common_element_end('head');
common_element_start('body');
common_element_start('p', 'subtags');
foreach ($tags as $tag) {
common_element('a', array('href' => common_local_url($action,
array('nickname' => $user->nickname,
'tag' => $tag))),
$tag);
}
common_element_end('p');
common_element_end('body');
common_element_end('html');
} else {
common_redirect(common_local_url($action, array('nickname' =>
$user->nickname)));
} }
}
function show_top($arr = NULL) { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
list($profile, $error) = $arr; $this->save_tags();
if ($error) { } else {
common_element('p', 'error', $error); $id = $this->trimmed('id');
} else { if (!$id) {
common_element_start('div', 'instructions'); $this->client_error(_('No id argument.'));
common_element('p', NULL, return;
_('Use this form to add tags to your subscribers or subscriptions.')); }
common_element_end('div'); $profile = Profile::staticGet('id', $id);
} if (!$profile) {
} $this->client_error(_('No profile with that ID.'));
return;
}
$this->show_form($profile);
}
}
function show_form($profile, $error=NULL) {
$user = common_current_user();
common_show_header(_('Tag a person'),
NULL, array($profile, $error), array($this, 'show_top'));
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE),
'class' => 'avatar stream',
'width' => AVATAR_PROFILE_SIZE,
'height' => AVATAR_PROFILE_SIZE,
'alt' =>
($profile->fullname) ? $profile->fullname :
$profile->nickname));
common_element('a', array('href' => $profile->profileurl,
'class' => 'external profile nickname'),
$profile->nickname);
if ($profile->fullname) {
common_element_start('div', 'fullname');
if ($profile->homepage) {
common_element('a', array('href' => $profile->homepage),
$profile->fullname);
} else {
common_text($profile->fullname);
}
common_element_end('div');
}
if ($profile->location) {
common_element('div', 'location', $profile->location);
}
if ($profile->bio) {
common_element('div', 'bio', $profile->bio);
}
common_element_start('form', array('method' => 'post',
'id' => 'tag_user',
'name' => 'tagother',
'action' => $this->self_url()));
common_hidden('token', common_session_token());
common_hidden('id', $profile->id);
common_input('tags', _('Tags'),
($this->arg('tags')) ? $this->arg('tags') : implode(' ', Profile_tag::getTags($user->id, $profile->id)),
_('Tags for this user (letters, numbers, -, ., and _), comma- or space- separated'));
common_submit('save', _('Save'));
common_element_end('form');
common_show_footer();
}
function save_tags() {
$id = $this->trimmed('id');
$tagstring = $this->trimmed('tags');
$token = $this->trimmed('token');
if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.'));
return;
}
$profile = Profile::staticGet('id', $id);
if (!$profile) {
$this->client_error(_('No such profile.'));
return;
}
if (is_string($tagstring) && strlen($tagstring) > 0) {
$tags = array_map('common_canonical_tag',
preg_split('/[\s,]+/', $tagstring));
foreach ($tags as $tag) {
if (!common_valid_profile_tag($tag)) {
$this->show_form($profile, sprintf(_('Invalid tag: "%s"'), $tag));
return;
}
}
} else {
$tags = array();
}
$user = common_current_user();
if (!Subscription::pkeyGet(array('subscriber' => $user->id,
'subscribed' => $profile->id)) &&
!Subscription::pkeyGet(array('subscriber' => $profile->id,
'subscribed' => $user->id)))
{
$this->client_error(_('You can only tag people you are subscribed to or who are subscribed to you.'));
return;
}
$result = Profile_tag::setTags($user->id, $profile->id, $tags);
if (!$result) {
$this->client_error(_('Could not save tags.'));
return;
}
$action = $user->isSubscribed($profile) ? 'subscriptions' : 'subscribers';
if ($this->boolean('ajax')) {
common_start_html('text/xml');
common_element_start('head');
common_element('title', null, _('Tags'));
common_element_end('head');
common_element_start('body');
common_element_start('p', 'subtags');
foreach ($tags as $tag) {
common_element('a', array('href' => common_local_url($action,
array('nickname' => $user->nickname,
'tag' => $tag))),
$tag);
}
common_element_end('p');
common_element_end('body');
common_element_end('html');
} else {
common_redirect(common_local_url($action, array('nickname' =>
$user->nickname)));
}
}
function show_top($arr = NULL) {
list($profile, $error) = $arr;
if ($error) {
common_element('p', 'error', $error);
} else {
common_element_start('div', 'instructions');
common_element('p', NULL,
_('Use this form to add tags to your subscribers or subscriptions.'));
common_element_end('div');
}
}
} }

View File

@ -25,41 +25,41 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class TagrssAction extends Rss10Action { class TagrssAction extends Rss10Action {
function init() { function init() {
$tag = $this->trimmed('tag'); $tag = $this->trimmed('tag');
$this->tag = Notice_tag::staticGet('tag', $tag); $this->tag = Notice_tag::staticGet('tag', $tag);
if (!$this->tag) { if (!$this->tag) {
common_user_error(_('No such tag.')); common_user_error(_('No such tag.'));
return false; return false;
} else { } else {
return true; return true;
} }
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$tag = $this->tag; $tag = $this->tag;
if (is_null($tag)) { if (is_null($tag)) {
return NULL; return NULL;
} }
$notice = Notice_tag::getStream($tag->tag, 0, ($limit == 0) ? NOTICES_PER_PAGE : $limit); $notice = Notice_tag::getStream($tag->tag, 0, ($limit == 0) ? NOTICES_PER_PAGE : $limit);
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
$tag = $this->tag->tag; $tag = $this->tag->tag;
$c = array('url' => common_local_url('tagrss', array('tag' => $tagname)), $c = array('url' => common_local_url('tagrss', array('tag' => $tagname)),
'title' => $tagname, 'title' => $tagname,
'link' => common_local_url('tagrss', array('tag' => $tagname)), 'link' => common_local_url('tagrss', array('tag' => $tagname)),
'description' => sprintf(_('Microblog tagged with %s'), $tagname)); 'description' => sprintf(_('Microblog tagged with %s'), $tagname));
return $c; return $c;
} }
} }

View File

@ -23,74 +23,74 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class TwitapiaccountAction extends TwitterapiAction { class TwitapiaccountAction extends TwitterapiAction {
function verify_credentials($args, $apidata) { function verify_credentials($args, $apidata) {
parent::handle($args); parent::handle($args);
if (!in_array($apidata['content-type'], array('xml', 'json'))) { if (!in_array($apidata['content-type'], array('xml', 'json'))) {
common_user_error(_('API method not found!'), $code = 404); common_user_error(_('API method not found!'), $code = 404);
return; return;
} }
$this->show_extended_profile($apidata['user'], $apidata); $this->show_extended_profile($apidata['user'], $apidata);
} }
function end_session($args, $apidata) { function end_session($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
function update_location($args, $apidata) { function update_location($args, $apidata) {
parent::handle($args); parent::handle($args);
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
$this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']);
return; return;
} }
$location = trim($this->arg('location')); $location = trim($this->arg('location'));
if (!is_null($location) && strlen($location) > 255) { if (!is_null($location) && strlen($location) > 255) {
// XXX: But Twitter just truncates and runs with it. -- Zach // XXX: But Twitter just truncates and runs with it. -- Zach
$this->client_error(_('That\'s too long. Max notice size is 255 chars.'), 406, $apidate['content-type']); $this->client_error(_('That\'s too long. Max notice size is 255 chars.'), 406, $apidate['content-type']);
return; return;
} }
$user = $apidata['user']; $user = $apidata['user'];
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.')); common_server_error(_('User has no profile.'));
return; return;
} }
$orig_profile = clone($profile); $orig_profile = clone($profile);
$profile->location = $location; $profile->location = $location;
$result = $profile->update($orig_profile); $result = $profile->update($orig_profile);
if (!$result) { if (!$result) {
common_log_db_error($profile, 'UPDATE', __FILE__); common_log_db_error($profile, 'UPDATE', __FILE__);
common_server_error(_('Couldn\'t save profile.')); common_server_error(_('Couldn\'t save profile.'));
return; return;
} }
common_broadcast_profile($profile); common_broadcast_profile($profile);
$type = $apidata['content-type']; $type = $apidata['content-type'];
$this->init_document($type); $this->init_document($type);
$this->show_profile($profile, $type); $this->show_profile($profile, $type);
$this->end_document($type); $this->end_document($type);
} }
function update_delivery_device($args, $apidata) { function update_delivery_device($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
function rate_limit_status($args, $apidata) { function rate_limit_status($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
} }

View File

@ -23,15 +23,15 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class TwitapiblocksAction extends TwitterapiAction { class TwitapiblocksAction extends TwitterapiAction {
function create($args, $apidata) { function create($args, $apidata) {
parent::handle($args); parent::handle($args);
$blockee = $this->get_user($apidata['api_arg'], $apidata); $blockee = $this->get_user($apidata['api_arg'], $apidata);
if (!$blockee) { if (!$blockee) {
$this->client_error('Not Found', 404, $apidata['content-type']); $this->client_error('Not Found', 404, $apidata['content-type']);
return; return;
} }
$user = $apidata['user']; $user = $apidata['user'];
@ -42,17 +42,17 @@ class TwitapiblocksAction extends TwitterapiAction {
$this->show_profile($blockee, $type); $this->show_profile($blockee, $type);
$this->end_document($type); $this->end_document($type);
} else { } else {
common_server_error(_('Block user failed.')); common_server_error(_('Block user failed.'));
} }
} }
function destroy($args, $apidata) { function destroy($args, $apidata) {
parent::handle($args); parent::handle($args);
$blockee = $this->get_user($apidata['api_arg'], $apidata); $blockee = $this->get_user($apidata['api_arg'], $apidata);
if (!$blockee) { if (!$blockee) {
$this->client_error('Not Found', 404, $apidata['content-type']); $this->client_error('Not Found', 404, $apidata['content-type']);
return; return;
} }
$user = $apidata['user']; $user = $apidata['user'];
@ -63,7 +63,7 @@ class TwitapiblocksAction extends TwitterapiAction {
$this->show_profile($blockee, $type); $this->show_profile($blockee, $type);
$this->end_document($type); $this->end_document($type);
} else { } else {
common_server_error(_('Unblock user failed.')); common_server_error(_('Unblock user failed.'));
} }
} }
} }

View File

@ -23,265 +23,265 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class Twitapidirect_messagesAction extends TwitterapiAction { class Twitapidirect_messagesAction extends TwitterapiAction {
function direct_messages($args, $apidata) { function direct_messages($args, $apidata) {
parent::handle($args); parent::handle($args);
return $this->show_messages($args, $apidata, 'received'); return $this->show_messages($args, $apidata, 'received');
} }
function sent($args, $apidata) { function sent($args, $apidata) {
parent::handle($args); parent::handle($args);
return $this->show_messages($args, $apidata, 'sent'); return $this->show_messages($args, $apidata, 'sent');
} }
function show_messages($args, $apidata, $type) { function show_messages($args, $apidata, $type) {
$user = $apidata['user']; $user = $apidata['user'];
$count = $this->arg('count'); $count = $this->arg('count');
$since = $this->arg('since'); $since = $this->arg('since');
$since_id = $this->arg('since_id'); $since_id = $this->arg('since_id');
$before_id = $this->arg('before_id'); $before_id = $this->arg('before_id');
$page = $this->arg('page'); $page = $this->arg('page');
if (!$page) { if (!$page) {
$page = 1; $page = 1;
} }
if (!$count) { if (!$count) {
$count = 20; $count = 20;
} }
$message = new Message(); $message = new Message();
$title = null; $title = null;
$subtitle = null; $subtitle = null;
$link = null; $link = null;
$server = common_root_url(); $server = common_root_url();
if ($type == 'received') { if ($type == 'received') {
$message->to_profile = $user->id; $message->to_profile = $user->id;
$title = sprintf(_("Direct messages to %s"), $user->nickname); $title = sprintf(_("Direct messages to %s"), $user->nickname);
$subtitle = sprintf(_("All the direct messages sent to %s"), $user->nickname); $subtitle = sprintf(_("All the direct messages sent to %s"), $user->nickname);
$link = $server . $user->nickname . '/inbox'; $link = $server . $user->nickname . '/inbox';
} else { } else {
$message->from_profile = $user->id; $message->from_profile = $user->id;
$title = _('Direct Messages You\'ve Sent'); $title = _('Direct Messages You\'ve Sent');
$subtitle = sprintf(_("All the direct messages sent from %s"), $user->nickname); $subtitle = sprintf(_("All the direct messages sent from %s"), $user->nickname);
$link = $server . $user->nickname . '/outbox'; $link = $server . $user->nickname . '/outbox';
} }
if ($before_id) { if ($before_id) {
$message->whereAdd("id < $before_id"); $message->whereAdd("id < $before_id");
} }
if ($since_id) { if ($since_id) {
$message->whereAdd("id > $since_id"); $message->whereAdd("id > $since_id");
} }
$since = strtotime($this->arg('since')); $since = strtotime($this->arg('since'));
if ($since) { if ($since) {
$d = date('Y-m-d H:i:s', $since); $d = date('Y-m-d H:i:s', $since);
$message->whereAdd("created > '$d'"); $message->whereAdd("created > '$d'");
} }
$message->orderBy('created DESC, id DESC'); $message->orderBy('created DESC, id DESC');
$message->limit((($page-1)*20), $count); $message->limit((($page-1)*20), $count);
$message->find(); $message->find();
switch($apidata['content-type']) { switch($apidata['content-type']) {
case 'xml': case 'xml':
$this->show_xml_dmsgs($message); $this->show_xml_dmsgs($message);
break; break;
case 'rss': case 'rss':
$this->show_rss_dmsgs($message, $title, $link, $subtitle); $this->show_rss_dmsgs($message, $title, $link, $subtitle);
break; break;
case 'atom': case 'atom':
$this->show_atom_dmsgs($message, $title, $link, $subtitle); $this->show_atom_dmsgs($message, $title, $link, $subtitle);
break; break;
case 'json': case 'json':
$this->show_json_dmsgs($message); $this->show_json_dmsgs($message);
break; break;
default: default:
common_user_error(_('API method not found!'), $code = 404); common_user_error(_('API method not found!'), $code = 404);
} }
} }
// had to change this from "new" to "create" to avoid PHP reserved word // had to change this from "new" to "create" to avoid PHP reserved word
function create($args, $apidata) { function create($args, $apidata) {
parent::handle($args); parent::handle($args);
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
$this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']);
return; return;
} }
$user = $apidata['user']; $user = $apidata['user'];
$source = $this->trimmed('source'); // Not supported by Twitter. $source = $this->trimmed('source'); // Not supported by Twitter.
$reserved_sources = array('web', 'omb', 'mail', 'xmpp', 'api'); $reserved_sources = array('web', 'omb', 'mail', 'xmpp', 'api');
if (!$source || in_array($source, $reserved_sources)) { if (!$source || in_array($source, $reserved_sources)) {
$source = 'api'; $source = 'api';
} }
$content = $this->trimmed('text'); $content = $this->trimmed('text');
if (!$content) { if (!$content) {
$this->client_error(_('No message text!'), $code = 406, $apidata['content-type']); $this->client_error(_('No message text!'), $code = 406, $apidata['content-type']);
} else { } else {
$content_shortened = common_shorten_links($content); $content_shortened = common_shorten_links($content);
if (mb_strlen($content_shortened) > 140) { if (mb_strlen($content_shortened) > 140) {
$this->client_error(_('That\'s too long. Max message size is 140 chars.'), $this->client_error(_('That\'s too long. Max message size is 140 chars.'),
$code = 406, $apidata['content-type']); $code = 406, $apidata['content-type']);
return; return;
} }
} }
$other = $this->get_user($this->trimmed('user')); $other = $this->get_user($this->trimmed('user'));
if (!$other) { if (!$other) {
$this->client_error(_('Recipient user not found.'), $code = 403, $apidata['content-type']); $this->client_error(_('Recipient user not found.'), $code = 403, $apidata['content-type']);
return; return;
} else if (!$user->mutuallySubscribed($other)) { } else if (!$user->mutuallySubscribed($other)) {
$this->client_error(_('Can\'t send direct messages to users who aren\'t your friend.'), $this->client_error(_('Can\'t send direct messages to users who aren\'t your friend.'),
$code = 403, $apidata['content-type']); $code = 403, $apidata['content-type']);
return; return;
} else if ($user->id == $other->id) { } else if ($user->id == $other->id) {
// Sending msgs to yourself is allowed by Twitter // Sending msgs to yourself is allowed by Twitter
$this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), $this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'),
$code = 403, $apidata['content-type']); $code = 403, $apidata['content-type']);
return; return;
} }
$message = Message::saveNew($user->id, $other->id, $message = Message::saveNew($user->id, $other->id,
html_entity_decode($content, ENT_NOQUOTES, 'UTF-8'), $source); html_entity_decode($content, ENT_NOQUOTES, 'UTF-8'), $source);
if (is_string($message)) { if (is_string($message)) {
$this->server_error($message); $this->server_error($message);
return; return;
} }
$this->notify($user, $other, $message); $this->notify($user, $other, $message);
if ($apidata['content-type'] == 'xml') { if ($apidata['content-type'] == 'xml') {
$this->show_single_xml_dmsg($message); $this->show_single_xml_dmsg($message);
} elseif ($apidata['content-type'] == 'json') { } elseif ($apidata['content-type'] == 'json') {
$this->show_single_json_dmsg($message); $this->show_single_json_dmsg($message);
} }
} }
function destroy($args, $apidata) { function destroy($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
function show_xml_dmsgs($message) { function show_xml_dmsgs($message) {
$this->init_document('xml'); $this->init_document('xml');
common_element_start('direct-messages', array('type' => 'array')); common_element_start('direct-messages', array('type' => 'array'));
if (is_array($messages)) { if (is_array($messages)) {
foreach ($message as $m) { foreach ($message as $m) {
$twitter_dm = $this->twitter_dmsg_array($m); $twitter_dm = $this->twitter_dmsg_array($m);
$this->show_twitter_xml_dmsg($twitter_dm); $this->show_twitter_xml_dmsg($twitter_dm);
} }
} else { } else {
while ($message->fetch()) { while ($message->fetch()) {
$twitter_dm = $this->twitter_dmsg_array($message); $twitter_dm = $this->twitter_dmsg_array($message);
$this->show_twitter_xml_dmsg($twitter_dm); $this->show_twitter_xml_dmsg($twitter_dm);
} }
} }
common_element_end('direct-messages'); common_element_end('direct-messages');
$this->end_document('xml'); $this->end_document('xml');
} }
function show_json_dmsgs($message) { function show_json_dmsgs($message) {
$this->init_document('json'); $this->init_document('json');
$dmsgs = array(); $dmsgs = array();
if (is_array($message)) { if (is_array($message)) {
foreach ($message as $m) { foreach ($message as $m) {
$twitter_dm = $this->twitter_dmsg_array($m); $twitter_dm = $this->twitter_dmsg_array($m);
array_push($dmsgs, $twitter_dm); array_push($dmsgs, $twitter_dm);
} }
} else { } else {
while ($message->fetch()) { while ($message->fetch()) {
$twitter_dm = $this->twitter_dmsg_array($message); $twitter_dm = $this->twitter_dmsg_array($message);
array_push($dmsgs, $twitter_dm); array_push($dmsgs, $twitter_dm);
} }
} }
$this->show_json_objects($dmsgs); $this->show_json_objects($dmsgs);
$this->end_document('json'); $this->end_document('json');
} }
function show_rss_dmsgs($message, $title, $link, $subtitle) { function show_rss_dmsgs($message, $title, $link, $subtitle) {
$this->init_document('rss'); $this->init_document('rss');
common_element_start('channel'); common_element_start('channel');
common_element('title', NULL, $title); common_element('title', NULL, $title);
common_element('link', NULL, $link); common_element('link', NULL, $link);
common_element('description', NULL, $subtitle); common_element('description', NULL, $subtitle);
common_element('language', NULL, 'en-us'); common_element('language', NULL, 'en-us');
common_element('ttl', NULL, '40'); common_element('ttl', NULL, '40');
if (is_array($message)) { if (is_array($message)) {
foreach ($message as $m) { foreach ($message as $m) {
$entry = $this->twitter_rss_dmsg_array($m); $entry = $this->twitter_rss_dmsg_array($m);
$this->show_twitter_rss_item($entry); $this->show_twitter_rss_item($entry);
} }
} else { } else {
while ($message->fetch()) { while ($message->fetch()) {
$entry = $this->twitter_rss_dmsg_array($message); $entry = $this->twitter_rss_dmsg_array($message);
$this->show_twitter_rss_item($entry); $this->show_twitter_rss_item($entry);
} }
} }
common_element_end('channel'); common_element_end('channel');
$this->end_twitter_rss(); $this->end_twitter_rss();
} }
function show_atom_dmsgs($message, $title, $link, $subtitle) { function show_atom_dmsgs($message, $title, $link, $subtitle) {
$this->init_document('atom'); $this->init_document('atom');
common_element('title', NULL, $title); common_element('title', NULL, $title);
$siteserver = common_config('site', 'server'); $siteserver = common_config('site', 'server');
common_element('id', NULL, "tag:$siteserver,2008:DirectMessage"); common_element('id', NULL, "tag:$siteserver,2008:DirectMessage");
common_element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), NULL); common_element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), NULL);
common_element('updated', NULL, common_date_iso8601(strftime('%c'))); common_element('updated', NULL, common_date_iso8601(strftime('%c')));
common_element('subtitle', NULL, $subtitle); common_element('subtitle', NULL, $subtitle);
if (is_array($message)) { if (is_array($message)) {
foreach ($message as $m) { foreach ($message as $m) {
$entry = $this->twitter_rss_dmsg_array($m); $entry = $this->twitter_rss_dmsg_array($m);
$this->show_twitter_atom_entry($entry); $this->show_twitter_atom_entry($entry);
} }
} else { } else {
while ($message->fetch()) { while ($message->fetch()) {
$entry = $this->twitter_rss_dmsg_array($message); $entry = $this->twitter_rss_dmsg_array($message);
$this->show_twitter_atom_entry($entry); $this->show_twitter_atom_entry($entry);
} }
} }
$this->end_document('atom'); $this->end_document('atom');
} }
// swiped from MessageAction. Should it be place in util.php? // swiped from MessageAction. Should it be place in util.php?
function notify($from, $to, $message) { function notify($from, $to, $message) {
mail_notify_message($message, $from, $to); mail_notify_message($message, $from, $to);
# XXX: Jabber, SMS notifications... probably queued # XXX: Jabber, SMS notifications... probably queued
} }
} }

View File

@ -23,153 +23,153 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class TwitapifavoritesAction extends TwitterapiAction { class TwitapifavoritesAction extends TwitterapiAction {
function favorites($args, $apidata) { function favorites($args, $apidata) {
parent::handle($args); parent::handle($args);
$this->auth_user = $apidata['user']; $this->auth_user = $apidata['user'];
$user = $this->get_user($apidata['api_arg'], $apidata); $user = $this->get_user($apidata['api_arg'], $apidata);
if (!$user) { if (!$user) {
$this->client_error('Not Found', 404, $apidata['content-type']); $this->client_error('Not Found', 404, $apidata['content-type']);
return; return;
} }
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_server_error(_('User has no profile.')); common_server_error(_('User has no profile.'));
return; return;
} }
$page = $this->arg('page'); $page = $this->arg('page');
if (!$page) { if (!$page) {
$page = 1; $page = 1;
} }
if (!$count) { if (!$count) {
$count = 20; $count = 20;
} }
$notice = $user->favoriteNotices((($page-1)*20), $count); $notice = $user->favoriteNotices((($page-1)*20), $count);
if (!$notice) { if (!$notice) {
common_server_error(_('Could not retrieve favorite notices.')); common_server_error(_('Could not retrieve favorite notices.'));
return; return;
} }
$sitename = common_config('site', 'name'); $sitename = common_config('site', 'name');
$siteserver = common_config('site', 'server'); $siteserver = common_config('site', 'server');
$title = sprintf(_('%s / Favorites from %s'), $sitename, $user->nickname); $title = sprintf(_('%s / Favorites from %s'), $sitename, $user->nickname);
$id = "tag:$siteserver:favorites:".$user->id; $id = "tag:$siteserver:favorites:".$user->id;
$link = common_local_url('favorites', array('nickname' => $user->nickname)); $link = common_local_url('favorites', array('nickname' => $user->nickname));
$subtitle = sprintf(_('%s updates favorited by %s / %s.'), $sitename, $profile->getBestName(), $user->nickname); $subtitle = sprintf(_('%s updates favorited by %s / %s.'), $sitename, $profile->getBestName(), $user->nickname);
switch($apidata['content-type']) { switch($apidata['content-type']) {
case 'xml': case 'xml':
$this->show_xml_timeline($notice); $this->show_xml_timeline($notice);
break; break;
case 'rss': case 'rss':
$this->show_rss_timeline($notice, $title, $link, $subtitle); $this->show_rss_timeline($notice, $title, $link, $subtitle);
break; break;
case 'atom': case 'atom':
$this->show_atom_timeline($notice, $title, $id, $link, $subtitle); $this->show_atom_timeline($notice, $title, $id, $link, $subtitle);
break; break;
case 'json': case 'json':
$this->show_json_timeline($notice); $this->show_json_timeline($notice);
break; break;
default: default:
common_user_error(_('API method not found!'), $code = 404); common_user_error(_('API method not found!'), $code = 404);
} }
} }
function create($args, $apidata) { function create($args, $apidata) {
parent::handle($args); parent::handle($args);
// Check for RESTfulness // Check for RESTfulness
if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) {
// XXX: Twitter just prints the err msg, no XML / JSON. // XXX: Twitter just prints the err msg, no XML / JSON.
$this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']);
return; return;
} }
if (!in_array($apidata['content-type'], array('xml', 'json'))) { if (!in_array($apidata['content-type'], array('xml', 'json'))) {
common_user_error(_('API method not found!'), $code = 404); common_user_error(_('API method not found!'), $code = 404);
return; return;
} }
$this->auth_user = $apidata['user']; $this->auth_user = $apidata['user'];
$user = $this->auth_user; $user = $this->auth_user;
$notice_id = $apidata['api_arg']; $notice_id = $apidata['api_arg'];
$notice = Notice::staticGet($notice_id); $notice = Notice::staticGet($notice_id);
if (!$notice) { if (!$notice) {
$this->client_error(_('No status found with that ID.'), 404, $apidata['content-type']); $this->client_error(_('No status found with that ID.'), 404, $apidata['content-type']);
return; return;
} }
// XXX: Twitter lets you fave things repeatedly via api. // XXX: Twitter lets you fave things repeatedly via api.
if ($user->hasFave($notice)) { if ($user->hasFave($notice)) {
$this->client_error(_('This notice is already a favorite!'), 403, $apidata['content-type']); $this->client_error(_('This notice is already a favorite!'), 403, $apidata['content-type']);
return; return;
} }
$fave = Fave::addNew($user, $notice); $fave = Fave::addNew($user, $notice);
if (!$fave) { if (!$fave) {
common_server_error(_('Could not create favorite.')); common_server_error(_('Could not create favorite.'));
return; return;
} }
$this->notify($fave, $notice, $user); $this->notify($fave, $notice, $user);
$user->blowFavesCache(); $user->blowFavesCache();
if ($apidata['content-type'] == 'xml') { if ($apidata['content-type'] == 'xml') {
$this->show_single_xml_status($notice); $this->show_single_xml_status($notice);
} elseif ($apidata['content-type'] == 'json') { } elseif ($apidata['content-type'] == 'json') {
$this->show_single_json_status($notice); $this->show_single_json_status($notice);
} }
} }
function destroy($args, $apidata) { function destroy($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
// XXX: these two funcs swiped from faves. Maybe put in util.php, or some common base class? // XXX: these two funcs swiped from faves. Maybe put in util.php, or some common base class?
function notify($fave, $notice, $user) { function notify($fave, $notice, $user) {
$other = User::staticGet('id', $notice->profile_id); $other = User::staticGet('id', $notice->profile_id);
if ($other && $other->id != $user->id) { if ($other && $other->id != $user->id) {
if ($other->email && $other->emailnotifyfav) { if ($other->email && $other->emailnotifyfav) {
$this->notify_mail($other, $user, $notice); $this->notify_mail($other, $user, $notice);
} }
# XXX: notify by IM # XXX: notify by IM
# XXX: notify by SMS # XXX: notify by SMS
} }
} }
function notify_mail($other, $user, $notice) { function notify_mail($other, $user, $notice) {
$profile = $user->getProfile(); $profile = $user->getProfile();
$bestname = $profile->getBestName(); $bestname = $profile->getBestName();
$subject = sprintf(_('%s added your notice as a favorite'), $bestname); $subject = sprintf(_('%s added your notice as a favorite'), $bestname);
$body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" .
"In case you forgot, you can see the text of your notice here:\n\n" . "In case you forgot, you can see the text of your notice here:\n\n" .
"%3\$s\n\n" . "%3\$s\n\n" .
"You can see the list of %1\$s's favorites here:\n\n" . "You can see the list of %1\$s's favorites here:\n\n" .
"%4\$s\n\n" . "%4\$s\n\n" .
"Faithfully yours,\n" . "Faithfully yours,\n" .
"%5\$s\n"), "%5\$s\n"),
$bestname, $bestname,
common_exact_date($notice->created), common_exact_date($notice->created),
common_local_url('shownotice', array('notice' => $notice->id)), common_local_url('shownotice', array('notice' => $notice->id)),
common_local_url('showfavorites', array('nickname' => $user->nickname)), common_local_url('showfavorites', array('nickname' => $user->nickname)),
common_config('site', 'name')); common_config('site', 'name'));
mail_to_user($other, $subject, $body); mail_to_user($other, $subject, $body);
} }
} }

View File

@ -23,133 +23,133 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class TwitapifriendshipsAction extends TwitterapiAction { class TwitapifriendshipsAction extends TwitterapiAction {
function create($args, $apidata) { function create($args, $apidata) {
parent::handle($args); parent::handle($args);
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
$this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']);
return; return;
} }
$id = $apidata['api_arg']; $id = $apidata['api_arg'];
$other = $this->get_user($id); $other = $this->get_user($id);
if (!$other) { if (!$other) {
$this->client_error(_('Could not follow user: User not found.'), 403, $apidata['content-type']); $this->client_error(_('Could not follow user: User not found.'), 403, $apidata['content-type']);
return; return;
} }
$user = $apidata['user']; $user = $apidata['user'];
if ($user->isSubscribed($other)) { if ($user->isSubscribed($other)) {
$errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname); $errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname);
$this->client_error($errmsg, 403, $apidata['content-type']); $this->client_error($errmsg, 403, $apidata['content-type']);
return; return;
} }
$sub = new Subscription(); $sub = new Subscription();
$sub->query('BEGIN'); $sub->query('BEGIN');
$sub->subscriber = $user->id; $sub->subscriber = $user->id;
$sub->subscribed = $other->id; $sub->subscribed = $other->id;
$sub->created = DB_DataObject_Cast::dateTime(); # current time $sub->created = DB_DataObject_Cast::dateTime(); # current time
$result = $sub->insert(); $result = $sub->insert();
if (!$result) { if (!$result) {
$errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname); $errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname);
$this->client_error($errmsg, 400, $apidata['content-type']); $this->client_error($errmsg, 400, $apidata['content-type']);
return; return;
} }
$sub->query('COMMIT'); $sub->query('COMMIT');
mail_subscribe_notify($other, $user); mail_subscribe_notify($other, $user);
$type = $apidata['content-type']; $type = $apidata['content-type'];
$this->init_document($type); $this->init_document($type);
$this->show_profile($other, $type); $this->show_profile($other, $type);
$this->end_document($type); $this->end_document($type);
} }
function destroy($args, $apidata) { function destroy($args, $apidata) {
parent::handle($args); parent::handle($args);
if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) {
$this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']);
return; return;
} }
$id = $apidata['api_arg']; $id = $apidata['api_arg'];
# We can't subscribe to a remote person, but we can unsub # We can't subscribe to a remote person, but we can unsub
$other = $this->get_profile($id); $other = $this->get_profile($id);
$user = $apidata['user']; $user = $apidata['user'];
$sub = new Subscription(); $sub = new Subscription();
$sub->subscriber = $user->id; $sub->subscriber = $user->id;
$sub->subscribed = $other->id; $sub->subscribed = $other->id;
if ($sub->find(TRUE)) { if ($sub->find(TRUE)) {
$sub->query('BEGIN'); $sub->query('BEGIN');
$sub->delete(); $sub->delete();
$sub->query('COMMIT'); $sub->query('COMMIT');
} else { } else {
$this->client_error(_('You are not friends with the specified user.'), 403, $apidata['content-type']); $this->client_error(_('You are not friends with the specified user.'), 403, $apidata['content-type']);
return; return;
} }
$type = $apidata['content-type']; $type = $apidata['content-type'];
$this->init_document($type); $this->init_document($type);
$this->show_profile($other, $type); $this->show_profile($other, $type);
$this->end_document($type); $this->end_document($type);
} }
function exists($args, $apidata) { function exists($args, $apidata) {
parent::handle($args); parent::handle($args);
if (!in_array($apidata['content-type'], array('xml', 'json'))) { if (!in_array($apidata['content-type'], array('xml', 'json'))) {
common_user_error(_('API method not found!'), $code = 404); common_user_error(_('API method not found!'), $code = 404);
return; return;
} }
$user_a_id = $this->trimmed('user_a'); $user_a_id = $this->trimmed('user_a');
$user_b_id = $this->trimmed('user_b'); $user_b_id = $this->trimmed('user_b');
$user_a = $this->get_user($user_a_id); $user_a = $this->get_user($user_a_id);
$user_b = $this->get_user($user_b_id); $user_b = $this->get_user($user_b_id);
if (!$user_a || !$user_b) { if (!$user_a || !$user_b) {
$this->client_error(_('Two user ids or screen_names must be supplied.'), 400, $apidata['content-type']); $this->client_error(_('Two user ids or screen_names must be supplied.'), 400, $apidata['content-type']);
return; return;
} }
if ($user_a->isSubscribed($user_b)) { if ($user_a->isSubscribed($user_b)) {
$result = 'true'; $result = 'true';
} else { } else {
$result = 'false'; $result = 'false';
} }
switch ($apidata['content-type']) { switch ($apidata['content-type']) {
case 'xml': case 'xml':
$this->init_document('xml'); $this->init_document('xml');
common_element('friends', NULL, $result); common_element('friends', NULL, $result);
$this->end_document('xml'); $this->end_document('xml');
break; break;
case 'json': case 'json':
$this->init_document('json'); $this->init_document('json');
print json_encode($result); print json_encode($result);
$this->end_document('json'); $this->end_document('json');
break; break;
default: default:
break; break;
} }
} }
} }

View File

@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class TwitapihelpAction extends TwitterapiAction { class TwitapihelpAction extends TwitterapiAction {
/* Returns the string "ok" in the requested format with a 200 OK HTTP status code. /* Returns the string "ok" in the requested format with a 200 OK HTTP status code.
* URL:http://identi.ca/api/help/test.format * URL:http://identi.ca/api/help/test.format
* Formats: xml, json * Formats: xml, json
*/ */
function test($args, $apidata) { function test($args, $apidata) {
parent::handle($args); parent::handle($args);
if ($apidata['content-type'] == 'xml') { if ($apidata['content-type'] == 'xml') {
$this->init_document('xml'); $this->init_document('xml');
common_element('ok', NULL, 'true'); common_element('ok', NULL, 'true');
$this->end_document('xml'); $this->end_document('xml');
} elseif ($apidata['content-type'] == 'json') { } elseif ($apidata['content-type'] == 'json') {
$this->init_document('json'); $this->init_document('json');
print '"ok"'; print '"ok"';
$this->end_document('json'); $this->end_document('json');
} else { } else {
common_user_error(_('API method not found!'), $code=404); common_user_error(_('API method not found!'), $code=404);
} }
} }
function downtime_schedule($args, $apidata) { function downtime_schedule($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
} }

View File

@ -24,14 +24,14 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
# This naming convention looks real sick # This naming convention looks real sick
class TwitapinotificationsAction extends TwitterapiAction { class TwitapinotificationsAction extends TwitterapiAction {
function follow($args, $apidata) { function follow($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
function leave($args, $apidata) { function leave($args, $apidata) {
parent::handle($args); parent::handle($args);
common_server_error(_('API method under construction.'), $code=501); common_server_error(_('API method under construction.'), $code=501);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/twitterapi.php');
class TwitapiusersAction extends TwitterapiAction { class TwitapiusersAction extends TwitterapiAction {
function show($args, $apidata) { function show($args, $apidata) {
parent::handle($args); parent::handle($args);
if (!in_array($apidata['content-type'], array('xml', 'json'))) { if (!in_array($apidata['content-type'], array('xml', 'json'))) {
common_user_error(_('API method not found!'), $code = 404); common_user_error(_('API method not found!'), $code = 404);
return; return;
} }
$user = null; $user = null;
$email = $this->arg('email'); $email = $this->arg('email');
if ($email) { if ($email) {
$user = User::staticGet('email', $email); $user = User::staticGet('email', $email);
} elseif (isset($apidata['api_arg'])) { } elseif (isset($apidata['api_arg'])) {
$user = $this->get_user($apidata['api_arg']); $user = $this->get_user($apidata['api_arg']);
} }
if (!$user) { if (!$user) {
// XXX: Twitter returns a random(?) user instead of throwing and err! -- Zach // XXX: Twitter returns a random(?) user instead of throwing and err! -- Zach
$this->client_error(_('Not found.'), 404, $apidata['content-type']); $this->client_error(_('Not found.'), 404, $apidata['content-type']);
return; return;
} }
$this->show_extended_profile($user, $apidata); $this->show_extended_profile($user, $apidata);
} }
} }

View File

@ -25,354 +25,354 @@ define('SUBSCRIPTIONS', 80);
class TwittersettingsAction extends SettingsAction { class TwittersettingsAction extends SettingsAction {
function get_instructions() { function get_instructions() {
return _('Add your Twitter account to automatically send your notices to Twitter, ' . return _('Add your Twitter account to automatically send your notices to Twitter, ' .
'and subscribe to Twitter friends already here.'); 'and subscribe to Twitter friends already here.');
} }
function show_form($msg=NULL, $success=false) { function show_form($msg=NULL, $success=false) {
$user = common_current_user(); $user = common_current_user();
$profile = $user->getProfile(); $profile = $user->getProfile();
$fuser = NULL; $fuser = NULL;
$flink = Foreign_link::getByUserID($user->id, 1); // 1 == Twitter $flink = Foreign_link::getByUserID($user->id, 1); // 1 == Twitter
if ($flink) { if ($flink) {
$fuser = $flink->getForeignUser(); $fuser = $flink->getForeignUser();
} }
$this->form_header(_('Twitter settings'), $msg, $success); $this->form_header(_('Twitter settings'), $msg, $success);
common_element_start('form', array('method' => 'post', common_element_start('form', array('method' => 'post',
'id' => 'twittersettings', 'id' => 'twittersettings',
'action' => 'action' =>
common_local_url('twittersettings'))); common_local_url('twittersettings')));
common_hidden('token', common_session_token()); common_hidden('token', common_session_token());
common_element('h2', NULL, _('Twitter Account')); common_element('h2', NULL, _('Twitter Account'));
if ($fuser) { if ($fuser) {
common_element_start('p'); common_element_start('p');
common_element('span', 'twitter_user', $fuser->nickname); common_element('span', 'twitter_user', $fuser->nickname);
common_element('a', array('href' => $fuser->uri), $fuser->uri); common_element('a', array('href' => $fuser->uri), $fuser->uri);
common_element('span', 'input_instructions', common_element('span', 'input_instructions',
_('Current verified Twitter account.')); _('Current verified Twitter account.'));
common_hidden('flink_foreign_id', $flink->foreign_id); common_hidden('flink_foreign_id', $flink->foreign_id);
common_element_end('p'); common_element_end('p');
common_submit('remove', _('Remove')); common_submit('remove', _('Remove'));
} else { } else {
common_input('twitter_username', _('Twitter user name'), common_input('twitter_username', _('Twitter user name'),
($this->arg('twitter_username')) ? $this->arg('twitter_username') : $profile->nickname, ($this->arg('twitter_username')) ? $this->arg('twitter_username') : $profile->nickname,
_('No spaces, please.')); // hey, it's what Twitter says _('No spaces, please.')); // hey, it's what Twitter says
common_password('twitter_password', _('Twitter password')); common_password('twitter_password', _('Twitter password'));
} }
common_element('h2', NULL, _('Preferences')); common_element('h2', NULL, _('Preferences'));
common_checkbox('noticesync', _('Automatically send my notices to Twitter.'), common_checkbox('noticesync', _('Automatically send my notices to Twitter.'),
($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND) : true); ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND) : true);
common_checkbox('replysync', _('Send local "@" replies to Twitter.'), common_checkbox('replysync', _('Send local "@" replies to Twitter.'),
($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : true); ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : true);
common_checkbox('friendsync', _('Subscribe to my Twitter friends here.'), common_checkbox('friendsync', _('Subscribe to my Twitter friends here.'),
($flink) ? ($flink->friendsync & FOREIGN_FRIEND_RECV) : false); ($flink) ? ($flink->friendsync & FOREIGN_FRIEND_RECV) : false);
if ($flink) { if ($flink) {
common_submit('save', _('Save')); common_submit('save', _('Save'));
} else { } else {
common_submit('add', _('Add')); common_submit('add', _('Add'));
} }
$this->show_twitter_subscriptions(); $this->show_twitter_subscriptions();
common_element_end('form'); common_element_end('form');
common_show_footer(); common_show_footer();
} }
function subscribed_twitter_users() { function subscribed_twitter_users() {
$current_user = common_current_user(); $current_user = common_current_user();
$qry = 'SELECT user.* ' . $qry = 'SELECT user.* ' .
'FROM subscription ' . 'FROM subscription ' .
'JOIN user ON subscription.subscribed = user.id ' . 'JOIN user ON subscription.subscribed = user.id ' .
'JOIN foreign_link ON foreign_link.user_id = user.id ' . 'JOIN foreign_link ON foreign_link.user_id = user.id ' .
'WHERE subscriber = %d ' . 'WHERE subscriber = %d ' .
'ORDER BY user.nickname'; 'ORDER BY user.nickname';
$user = new User(); $user = new User();
$user->query(sprintf($qry, $current_user->id)); $user->query(sprintf($qry, $current_user->id));
$users = array(); $users = array();
while ($user->fetch()) { while ($user->fetch()) {
// Don't include the user's own self-subscription // Don't include the user's own self-subscription
if ($user->id != $current_user->id) { if ($user->id != $current_user->id) {
$users[] = clone($user); $users[] = clone($user);
} }
} }
return $users; return $users;
} }
function show_twitter_subscriptions() { function show_twitter_subscriptions() {
$friends = $this->subscribed_twitter_users(); $friends = $this->subscribed_twitter_users();
$friends_count = count($friends); $friends_count = count($friends);
if ($friends_count > 0) { if ($friends_count > 0) {
common_element('h3', NULL, _('Twitter Friends')); common_element('h3', NULL, _('Twitter Friends'));
common_element_start('div', array('id' => 'subscriptions')); common_element_start('div', array('id' => 'subscriptions'));
common_element_start('ul', array('id' => 'subscriptions_avatars')); common_element_start('ul', array('id' => 'subscriptions_avatars'));
for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) { for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) {
$other = Profile::staticGet($friends[$i]->id); $other = Profile::staticGet($friends[$i]->id);
if (!$other) { if (!$other) {
common_log_db_error($subs, 'SELECT', __FILE__); common_log_db_error($subs, 'SELECT', __FILE__);
continue; continue;
} }
common_element_start('li'); common_element_start('li');
common_element_start('a', array('title' => ($other->fullname) ? common_element_start('a', array('title' => ($other->fullname) ?
$other->fullname : $other->fullname :
$other->nickname, $other->nickname,
'href' => $other->profileurl, 'href' => $other->profileurl,
'rel' => 'contact', 'rel' => 'contact',
'class' => 'subscription')); 'class' => 'subscription'));
$avatar = $other->getAvatar(AVATAR_MINI_SIZE); $avatar = $other->getAvatar(AVATAR_MINI_SIZE);
common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)), common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)),
'width' => AVATAR_MINI_SIZE, 'width' => AVATAR_MINI_SIZE,
'height' => AVATAR_MINI_SIZE, 'height' => AVATAR_MINI_SIZE,
'class' => 'avatar mini', 'class' => 'avatar mini',
'alt' => ($other->fullname) ? 'alt' => ($other->fullname) ?
$other->fullname : $other->fullname :
$other->nickname)); $other->nickname));
common_element_end('a'); common_element_end('a');
common_element_end('li'); common_element_end('li');
} }
common_element_end('ul'); common_element_end('ul');
common_element_end('div'); common_element_end('div');
} }
// XXX Figure out a way to show all Twitter friends... ? // XXX Figure out a way to show all Twitter friends... ?
/* /*
if ($subs_count > SUBSCRIPTIONS) { if ($subs_count > SUBSCRIPTIONS) {
common_element_start('p', array('id' => 'subscriptions_viewall')); common_element_start('p', array('id' => 'subscriptions_viewall'));
common_element('a', array('href' => common_local_url('subscriptions', common_element('a', array('href' => common_local_url('subscriptions',
array('nickname' => $profile->nickname)), array('nickname' => $profile->nickname)),
'class' => 'moresubscriptions'), 'class' => 'moresubscriptions'),
_('All subscriptions')); _('All subscriptions'));
common_element_end('p'); common_element_end('p');
} }
*/ */
} }
function handle_post() { function handle_post() {
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->show_form(_('There was a problem with your session token. Try again, please.')); $this->show_form(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
if ($this->arg('save')) { if ($this->arg('save')) {
$this->save_preferences(); $this->save_preferences();
} else if ($this->arg('add')) { } else if ($this->arg('add')) {
$this->add_twitter_acct(); $this->add_twitter_acct();
} else if ($this->arg('remove')) { } else if ($this->arg('remove')) {
$this->remove_twitter_acct(); $this->remove_twitter_acct();
} else { } else {
$this->show_form(_('Unexpected form submission.')); $this->show_form(_('Unexpected form submission.'));
} }
} }
function add_twitter_acct() { function add_twitter_acct() {
$screen_name = $this->trimmed('twitter_username'); $screen_name = $this->trimmed('twitter_username');
$password = $this->trimmed('twitter_password'); $password = $this->trimmed('twitter_password');
$noticesync = $this->boolean('noticesync'); $noticesync = $this->boolean('noticesync');
$replysync = $this->boolean('replysync'); $replysync = $this->boolean('replysync');
$friendsync = $this->boolean('friendsync'); $friendsync = $this->boolean('friendsync');
if (!Validate::string($screen_name, if (!Validate::string($screen_name,
array( 'min_length' => 1, array( 'min_length' => 1,
'max_length' => 15, 'max_length' => 15,
'format' => VALIDATE_NUM . VALIDATE_ALPHA . '_'))) { 'format' => VALIDATE_NUM . VALIDATE_ALPHA . '_'))) {
$this->show_form( $this->show_form(
_('Username must have only numbers, upper- and lowercase letters, and underscore (_). 15 chars max.')); _('Username must have only numbers, upper- and lowercase letters, and underscore (_). 15 chars max.'));
return; return;
} }
if (!$this->verify_credentials($screen_name, $password)) { if (!$this->verify_credentials($screen_name, $password)) {
$this->show_form(_('Could not verify your Twitter credentials!')); $this->show_form(_('Could not verify your Twitter credentials!'));
return; return;
} }
$twit_user = twitter_user_info($screen_name, $password); $twit_user = twitter_user_info($screen_name, $password);
if (!$twit_user) { if (!$twit_user) {
$this->show_form(sprintf(_('Unable to retrieve account information for "%s" from Twitter.'), $this->show_form(sprintf(_('Unable to retrieve account information for "%s" from Twitter.'),
$screen_name)); $screen_name));
return; return;
} }
if (!save_twitter_user($twit_user->id, $screen_name)) { if (!save_twitter_user($twit_user->id, $screen_name)) {
$this->show_form(_('Unable to save your Twitter settings!')); $this->show_form(_('Unable to save your Twitter settings!'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
$flink = DB_DataObject::factory('foreign_link'); $flink = DB_DataObject::factory('foreign_link');
$flink->user_id = $user->id; $flink->user_id = $user->id;
$flink->foreign_id = $twit_user->id; $flink->foreign_id = $twit_user->id;
$flink->service = 1; // Twitter $flink->service = 1; // Twitter
$flink->credentials = $password; $flink->credentials = $password;
$flink->created = common_sql_now(); $flink->created = common_sql_now();
$this->set_flags($flink, $noticesync, $replysync, $friendsync); $this->set_flags($flink, $noticesync, $replysync, $friendsync);
$flink_id = $flink->insert(); $flink_id = $flink->insert();
if (!$flink_id) { if (!$flink_id) {
common_log_db_error($flink, 'INSERT', __FILE__); common_log_db_error($flink, 'INSERT', __FILE__);
$this->show_form(_('Unable to save your Twitter settings!')); $this->show_form(_('Unable to save your Twitter settings!'));
return; return;
} }
if ($friendsync) { if ($friendsync) {
save_twitter_friends($user, $twit_user->id, $screen_name, $password); save_twitter_friends($user, $twit_user->id, $screen_name, $password);
} }
$this->show_form(_('Twitter settings saved.'), true); $this->show_form(_('Twitter settings saved.'), true);
} }
function remove_twitter_acct() { function remove_twitter_acct() {
$user = common_current_user(); $user = common_current_user();
$flink = Foreign_link::getByUserID($user->id, 1); $flink = Foreign_link::getByUserID($user->id, 1);
$flink_foreign_id = $this->arg('flink_foreign_id'); $flink_foreign_id = $this->arg('flink_foreign_id');
# Maybe an old tab open...? # Maybe an old tab open...?
if ($flink->foreign_id != $flink_foreign_id) { if ($flink->foreign_id != $flink_foreign_id) {
$this->show_form(_('That is not your Twitter account.')); $this->show_form(_('That is not your Twitter account.'));
return; return;
} }
$result = $flink->delete(); $result = $flink->delete();
if (!$result) { if (!$result) {
common_log_db_error($flink, 'DELETE', __FILE__); common_log_db_error($flink, 'DELETE', __FILE__);
common_server_error(_('Couldn\'t remove Twitter user.')); common_server_error(_('Couldn\'t remove Twitter user.'));
return; return;
} }
$this->show_form(_('Twitter account removed.'), TRUE); $this->show_form(_('Twitter account removed.'), TRUE);
} }
function save_preferences() { function save_preferences() {
$noticesync = $this->boolean('noticesync'); $noticesync = $this->boolean('noticesync');
$friendsync = $this->boolean('friendsync'); $friendsync = $this->boolean('friendsync');
$replysync = $this->boolean('replysync'); $replysync = $this->boolean('replysync');
$user = common_current_user(); $user = common_current_user();
$flink = Foreign_link::getByUserID($user->id, 1); $flink = Foreign_link::getByUserID($user->id, 1);
if (!$flink) { if (!$flink) {
common_log_db_error($flink, 'SELECT', __FILE__); common_log_db_error($flink, 'SELECT', __FILE__);
$this->show_form(_('Couldn\'t save Twitter preferences.')); $this->show_form(_('Couldn\'t save Twitter preferences.'));
return; return;
} }
$twitter_id = $flink->foreign_id; $twitter_id = $flink->foreign_id;
$password = $flink->credentials; $password = $flink->credentials;
$fuser = $flink->getForeignUser(); $fuser = $flink->getForeignUser();
if (!$fuser) { if (!$fuser) {
common_log_db_error($fuser, 'SELECT', __FILE__); common_log_db_error($fuser, 'SELECT', __FILE__);
$this->show_form(_('Couldn\'t save Twitter preferences.')); $this->show_form(_('Couldn\'t save Twitter preferences.'));
return; return;
} }
$screen_name = $fuser->nickname; $screen_name = $fuser->nickname;
$original = clone($flink); $original = clone($flink);
$this->set_flags($flink, $noticesync, $replysync, $friendsync); $this->set_flags($flink, $noticesync, $replysync, $friendsync);
$result = $flink->update($original); $result = $flink->update($original);
if ($result === FALSE) { if ($result === FALSE) {
common_log_db_error($flink, 'UPDATE', __FILE__); common_log_db_error($flink, 'UPDATE', __FILE__);
$this->show_form(_('Couldn\'t save Twitter preferences.')); $this->show_form(_('Couldn\'t save Twitter preferences.'));
return; return;
} }
if ($friendsync) { if ($friendsync) {
save_twitter_friends($user, $flink->foreign_id, $screen_name, $password); save_twitter_friends($user, $flink->foreign_id, $screen_name, $password);
} }
$this->show_form(_('Twitter preferences saved.')); $this->show_form(_('Twitter preferences saved.'));
} }
function verify_credentials($screen_name, $password) { function verify_credentials($screen_name, $password) {
$uri = 'http://twitter.com/account/verify_credentials.json'; $uri = 'http://twitter.com/account/verify_credentials.json';
$data = get_twitter_data($uri, $screen_name, $password); $data = get_twitter_data($uri, $screen_name, $password);
if (!$data) { if (!$data) {
return false; return false;
} }
$user = json_decode($data); $user = json_decode($data);
if (!$user) { if (!$user) {
return false; return false;
} }
$twitter_id = $user->status->id; $twitter_id = $user->status->id;
if ($twitter_id) { if ($twitter_id) {
return $twitter_id; return $twitter_id;
} }
return false; return false;
} }
function set_flags(&$flink, $noticesync, $replysync, $friendsync) { function set_flags(&$flink, $noticesync, $replysync, $friendsync) {
if ($noticesync) { if ($noticesync) {
$flink->noticesync |= FOREIGN_NOTICE_SEND; $flink->noticesync |= FOREIGN_NOTICE_SEND;
} else { } else {
$flink->noticesync &= ~FOREIGN_NOTICE_SEND; $flink->noticesync &= ~FOREIGN_NOTICE_SEND;
} }
if ($replysync) { if ($replysync) {
$flink->noticesync |= FOREIGN_NOTICE_SEND_REPLY; $flink->noticesync |= FOREIGN_NOTICE_SEND_REPLY;
} else { } else {
$flink->noticesync &= ~FOREIGN_NOTICE_SEND_REPLY; $flink->noticesync &= ~FOREIGN_NOTICE_SEND_REPLY;
} }
if ($friendsync) { if ($friendsync) {
$flink->friendsync |= FOREIGN_FRIEND_RECV; $flink->friendsync |= FOREIGN_FRIEND_RECV;
} else { } else {
$flink->friendsync &= ~FOREIGN_FRIEND_RECV; $flink->friendsync &= ~FOREIGN_FRIEND_RECV;
} }
$flink->profilesync = 0; $flink->profilesync = 0;
} }
} }

View File

@ -32,12 +32,12 @@ class UnblockAction extends Action {
return false; return false;
} }
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$id = $this->trimmed('unblockto'); $id = $this->trimmed('unblockto');

View File

@ -19,30 +19,30 @@
class UnsubscribeAction extends Action { class UnsubscribeAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
if (!common_logged_in()) { if (!common_logged_in()) {
common_user_error(_('Not logged in.')); common_user_error(_('Not logged in.'));
return; return;
} }
$user = common_current_user(); $user = common_current_user();
if ($_SERVER['REQUEST_METHOD'] != 'POST') { if ($_SERVER['REQUEST_METHOD'] != 'POST') {
common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname))); common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname)));
return; return;
} }
# CSRF protection # CSRF protection
$token = $this->trimmed('token'); $token = $this->trimmed('token');
if (!$token || $token != common_session_token()) { if (!$token || $token != common_session_token()) {
$this->client_error(_('There was a problem with your session token. Try again, please.')); $this->client_error(_('There was a problem with your session token. Try again, please.'));
return; return;
} }
$other_id = $this->arg('unsubscribeto'); $other_id = $this->arg('unsubscribeto');
if (!$other_id) { if (!$other_id) {
$this->client_error(_('No profile id in request.')); $this->client_error(_('No profile id in request.'));
@ -56,25 +56,25 @@ class UnsubscribeAction extends Action {
return; return;
} }
$result = subs_unsubscribe_to($user, $other); $result = subs_unsubscribe_to($user, $other);
if ($result != true) { if ($result != true) {
common_user_error($result); common_user_error($result);
return; return;
}
if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true);
common_element_start('head');
common_element('title', null, _('Unsubscribed'));
common_element_end('head');
common_element_start('body');
common_subscribe_form($other);
common_element_end('body');
common_element_end('html');
} else {
common_redirect(common_local_url('subscriptions', array('nickname' =>
$user->nickname)));
} }
}
if ($this->boolean('ajax')) {
common_start_html('text/xml;charset=utf-8', true);
common_element_start('head');
common_element('title', null, _('Unsubscribed'));
common_element_end('head');
common_element_start('body');
common_subscribe_form($other);
common_element_end('body');
common_element_end('html');
} else {
common_redirect(common_local_url('subscriptions', array('nickname' =>
$user->nickname)));
}
}
} }

View File

@ -22,153 +22,153 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/lib/omb.php'); require_once(INSTALLDIR.'/lib/omb.php');
class UpdateprofileAction extends Action { class UpdateprofileAction extends Action {
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
try { try {
common_remove_magic_from_request(); common_remove_magic_from_request();
$req = OAuthRequest::from_request(); $req = OAuthRequest::from_request();
# Note: server-to-server function! # Note: server-to-server function!
$server = omb_oauth_server(); $server = omb_oauth_server();
list($consumer, $token) = $server->verify_request($req); list($consumer, $token) = $server->verify_request($req);
if ($this->update_profile($req, $consumer, $token)) { if ($this->update_profile($req, $consumer, $token)) {
print "omb_version=".OMB_VERSION_01; print "omb_version=".OMB_VERSION_01;
} }
} catch (OAuthException $e) { } catch (OAuthException $e) {
$this->server_error($e->getMessage()); $this->server_error($e->getMessage());
return; return;
} }
} }
function update_profile($req, $consumer, $token) { function update_profile($req, $consumer, $token) {
$version = $req->get_parameter('omb_version'); $version = $req->get_parameter('omb_version');
if ($version != OMB_VERSION_01) { if ($version != OMB_VERSION_01) {
$this->client_error(_('Unsupported OMB version'), 400); $this->client_error(_('Unsupported OMB version'), 400);
return false; return false;
} }
# First, check to see if listenee exists # First, check to see if listenee exists
$listenee = $req->get_parameter('omb_listenee'); $listenee = $req->get_parameter('omb_listenee');
$remote = Remote_profile::staticGet('uri', $listenee); $remote = Remote_profile::staticGet('uri', $listenee);
if (!$remote) { if (!$remote) {
$this->client_error(_('Profile unknown'), 404); $this->client_error(_('Profile unknown'), 404);
return false; return false;
} }
# Second, check to see if they should be able to post updates! # Second, check to see if they should be able to post updates!
# We see if there are any subscriptions to that remote user with # We see if there are any subscriptions to that remote user with
# the given token. # the given token.
$sub = new Subscription(); $sub = new Subscription();
$sub->subscribed = $remote->id; $sub->subscribed = $remote->id;
$sub->token = $token->key; $sub->token = $token->key;
if (!$sub->find(true)) { if (!$sub->find(true)) {
$this->client_error(_('You did not send us that profile'), 403); $this->client_error(_('You did not send us that profile'), 403);
return false; return false;
} }
$profile = Profile::staticGet('id', $remote->id); $profile = Profile::staticGet('id', $remote->id);
if (!$profile) { if (!$profile) {
# This one is our fault # This one is our fault
$this->server_error(_('Remote profile with no matching profile'), 500); $this->server_error(_('Remote profile with no matching profile'), 500);
return false; return false;
} }
$nickname = $req->get_parameter('omb_listenee_nickname'); $nickname = $req->get_parameter('omb_listenee_nickname');
if ($nickname && !Validate::string($nickname, array('min_length' => 1, if ($nickname && !Validate::string($nickname, array('min_length' => 1,
'max_length' => 64, 'max_length' => 64,
'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
$this->client_error(_('Nickname must have only lowercase letters and numbers and no spaces.')); $this->client_error(_('Nickname must have only lowercase letters and numbers and no spaces.'));
return false; return false;
} }
$license = $req->get_parameter('omb_listenee_license'); $license = $req->get_parameter('omb_listenee_license');
if ($license && !common_valid_http_url($license)) { if ($license && !common_valid_http_url($license)) {
$this->client_error(sprintf(_("Invalid license URL '%s'"), $license)); $this->client_error(sprintf(_("Invalid license URL '%s'"), $license));
return false; return false;
} }
$profile_url = $req->get_parameter('omb_listenee_profile'); $profile_url = $req->get_parameter('omb_listenee_profile');
if ($profile_url && !common_valid_http_url($profile_url)) { if ($profile_url && !common_valid_http_url($profile_url)) {
$this->client_error(sprintf(_("Invalid profile URL '%s'."), $profile_url)); $this->client_error(sprintf(_("Invalid profile URL '%s'."), $profile_url));
return false; return false;
} }
# optional stuff # optional stuff
$fullname = $req->get_parameter('omb_listenee_fullname'); $fullname = $req->get_parameter('omb_listenee_fullname');
if ($fullname && strlen($fullname) > 255) { if ($fullname && strlen($fullname) > 255) {
$this->client_error(_("Full name is too long (max 255 chars).")); $this->client_error(_("Full name is too long (max 255 chars)."));
return false; return false;
} }
$homepage = $req->get_parameter('omb_listenee_homepage'); $homepage = $req->get_parameter('omb_listenee_homepage');
if ($homepage && (!common_valid_http_url($homepage) || strlen($homepage) > 255)) { if ($homepage && (!common_valid_http_url($homepage) || strlen($homepage) > 255)) {
$this->client_error(sprintf(_("Invalid homepage '%s'"), $homepage)); $this->client_error(sprintf(_("Invalid homepage '%s'"), $homepage));
return false; return false;
} }
$bio = $req->get_parameter('omb_listenee_bio'); $bio = $req->get_parameter('omb_listenee_bio');
if ($bio && strlen($bio) > 140) { if ($bio && strlen($bio) > 140) {
$this->client_error(_("Bio is too long (max 140 chars).")); $this->client_error(_("Bio is too long (max 140 chars)."));
return false; return false;
} }
$location = $req->get_parameter('omb_listenee_location'); $location = $req->get_parameter('omb_listenee_location');
if ($location && strlen($location) > 255) { if ($location && strlen($location) > 255) {
$this->client_error(_("Location is too long (max 255 chars).")); $this->client_error(_("Location is too long (max 255 chars)."));
return false; return false;
} }
$avatar = $req->get_parameter('omb_listenee_avatar'); $avatar = $req->get_parameter('omb_listenee_avatar');
if ($avatar) { if ($avatar) {
if (!common_valid_http_url($avatar) || strlen($avatar) > 255) { if (!common_valid_http_url($avatar) || strlen($avatar) > 255) {
$this->client_error(sprintf(_("Invalid avatar URL '%s'"), $avatar)); $this->client_error(sprintf(_("Invalid avatar URL '%s'"), $avatar));
return false; return false;
} }
$size = @getimagesize($avatar); $size = @getimagesize($avatar);
if (!$size) { if (!$size) {
$this->client_error(sprintf(_("Can't read avatar URL '%s'"), $avatar)); $this->client_error(sprintf(_("Can't read avatar URL '%s'"), $avatar));
return false; return false;
} }
if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) { if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) {
$this->client_error(sprintf(_("Wrong size image at '%s'"), $avatar)); $this->client_error(sprintf(_("Wrong size image at '%s'"), $avatar));
return false; return false;
} }
if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG,
IMAGETYPE_PNG))) { IMAGETYPE_PNG))) {
$this->client_error(sprintf(_("Wrong image type for '%s'"), $avatar)); $this->client_error(sprintf(_("Wrong image type for '%s'"), $avatar));
return false; return false;
} }
} }
$orig_profile = clone($profile); $orig_profile = clone($profile);
if ($nickname) { if ($nickname) {
$profile->nickname = $nickname; $profile->nickname = $nickname;
} }
if ($profile_url) { if ($profile_url) {
$profile->profileurl = $profile_url; $profile->profileurl = $profile_url;
} }
if ($fullname) { if ($fullname) {
$profile->fullname = $fullname; $profile->fullname = $fullname;
} }
if ($homepage) { if ($homepage) {
$profile->homepage = $homepage; $profile->homepage = $homepage;
} }
if ($bio) { if ($bio) {
$profile->bio = $bio; $profile->bio = $bio;
} }
if ($location) { if ($location) {
$profile->location = $location; $profile->location = $location;
} }
if (!$profile->update($orig_profile)) { if (!$profile->update($orig_profile)) {
$this->server_error(_('Could not save new profile info'), 500); $this->server_error(_('Could not save new profile info'), 500);
return false; return false;
} else { } else {
if ($avatar) { if ($avatar) {
$temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar'); $temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar');
copy($avatar, $temp_filename); copy($avatar, $temp_filename);
if (!$profile->setOriginal($temp_filename)) { if (!$profile->setOriginal($temp_filename)) {
$this->server_error(_('Could not save avatar info'), 500); $this->server_error(_('Could not save avatar info'), 500);
return false; return false;
} }
} }
header('HTTP/1.1 200 OK'); header('HTTP/1.1 200 OK');
header('Content-type: text/plain'); header('Content-type: text/plain');
print 'Updated profile'; print 'Updated profile';
print "\n"; print "\n";
return true; return true;
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -20,30 +20,30 @@
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
class UserbyidAction extends Action { class UserbyidAction extends Action {
function is_readonly() { function is_readonly() {
return true; return true;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$id = $this->trimmed('id'); $id = $this->trimmed('id');
if (!$id) { if (!$id) {
$this->client_error(_('No id.')); $this->client_error(_('No id.'));
} }
$user =& User::staticGet($id); $user =& User::staticGet($id);
if (!$user) { if (!$user) {
$this->client_error(_('No such user.')); $this->client_error(_('No such user.'));
} }
// support redirecting to FOAF rdf/xml if the agent prefers it // support redirecting to FOAF rdf/xml if the agent prefers it
$page_prefs = 'application/rdf+xml,text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2'; $page_prefs = 'application/rdf+xml,text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2';
$httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL; $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
$type = common_negotiate_type(common_accept_to_prefs($httpaccept), $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
common_accept_to_prefs($page_prefs)); common_accept_to_prefs($page_prefs));
$page = $type == 'application/rdf+xml' ? 'foaf' : 'showstream'; $page = $type == 'application/rdf+xml' ? 'foaf' : 'showstream';
$url = common_local_url($page, array('nickname' => $user->nickname)); $url = common_local_url($page, array('nickname' => $user->nickname));
common_redirect($url, 303); common_redirect($url, 303);
} }
} }

View File

@ -25,66 +25,66 @@ require_once(INSTALLDIR.'/lib/rssaction.php');
class UserrssAction extends Rss10Action { class UserrssAction extends Rss10Action {
var $user = NULL; var $user = NULL;
function init() { function init() {
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$this->user = User::staticGet('nickname', $nickname); $this->user = User::staticGet('nickname', $nickname);
if (!$this->user) { if (!$this->user) {
common_user_error(_('No such user.')); common_user_error(_('No such user.'));
return false; return false;
} else { } else {
return true; return true;
} }
} }
function get_notices($limit=0) { function get_notices($limit=0) {
$user = $this->user; $user = $this->user;
if (is_null($user)) { if (is_null($user)) {
return NULL; return NULL;
} }
$notice = $user->getNotices(0, ($limit == 0) ? NOTICES_PER_PAGE : $limit); $notice = $user->getNotices(0, ($limit == 0) ? NOTICES_PER_PAGE : $limit);
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
return $notices; return $notices;
} }
function get_channel() { function get_channel() {
$user = $this->user; $user = $this->user;
$profile = $user->getProfile(); $profile = $user->getProfile();
$c = array('url' => common_local_url('userrss', $c = array('url' => common_local_url('userrss',
array('nickname' => array('nickname' =>
$user->nickname)), $user->nickname)),
'title' => $user->nickname, 'title' => $user->nickname,
'link' => $profile->profileurl, 'link' => $profile->profileurl,
'description' => sprintf(_('Microblog by %s'), $user->nickname)); 'description' => sprintf(_('Microblog by %s'), $user->nickname));
return $c; return $c;
} }
function get_image() { function get_image() {
$user = $this->user; $user = $this->user;
$profile = $user->getProfile(); $profile = $user->getProfile();
if (!$profile) { if (!$profile) {
common_log_db_error($user, 'SELECT', __FILE__); common_log_db_error($user, 'SELECT', __FILE__);
$this->server_error(_('User without matching profile')); $this->server_error(_('User without matching profile'));
return NULL; return NULL;
} }
$avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
return ($avatar) ? $avatar->url : NULL; return ($avatar) ? $avatar->url : NULL;
} }
# override parent to add X-SUP-ID URL # override parent to add X-SUP-ID URL
function init_rss($limit=0) { function init_rss($limit=0) {
$url = common_local_url('sup', NULL, $this->user->id); $url = common_local_url('sup', NULL, $this->user->id);
header('X-SUP-ID: '.$url); header('X-SUP-ID: '.$url);
parent::init_rss($limit); parent::init_rss($limit);
} }
} }

View File

@ -23,110 +23,110 @@ require_once(INSTALLDIR.'/lib/omb.php');
class XrdsAction extends Action { class XrdsAction extends Action {
function is_readonly() { function is_readonly() {
return true; return true;
} }
function handle($args) { function handle($args) {
parent::handle($args); parent::handle($args);
$nickname = $this->trimmed('nickname'); $nickname = $this->trimmed('nickname');
$user = User::staticGet('nickname', $nickname); $user = User::staticGet('nickname', $nickname);
if (!$user) { if (!$user) {
common_user_error(_('No such user.')); common_user_error(_('No such user.'));
return; return;
} }
$this->show_xrds($user); $this->show_xrds($user);
} }
function show_xrds($user) { function show_xrds($user) {
header('Content-Type: application/xrds+xml'); header('Content-Type: application/xrds+xml');
common_start_xml(); common_start_xml();
common_element_start('XRDS', array('xmlns' => 'xri://$xrds')); common_element_start('XRDS', array('xmlns' => 'xri://$xrds'));
common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
'xml:id' => 'oauth', 'xml:id' => 'oauth',
'xmlns:simple' => 'http://xrds-simple.net/core/1.0', 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
'version' => '2.0')); 'version' => '2.0'));
common_element('Type', NULL, 'xri://$xrds*simple'); common_element('Type', NULL, 'xri://$xrds*simple');
$this->show_service(OAUTH_ENDPOINT_REQUEST, $this->show_service(OAUTH_ENDPOINT_REQUEST,
common_local_url('requesttoken'), common_local_url('requesttoken'),
array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY),
array(OAUTH_HMAC_SHA1), array(OAUTH_HMAC_SHA1),
$user->uri); $user->uri);
$this->show_service(OAUTH_ENDPOINT_AUTHORIZE, $this->show_service(OAUTH_ENDPOINT_AUTHORIZE,
common_local_url('userauthorization'), common_local_url('userauthorization'),
array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY),
array(OAUTH_HMAC_SHA1)); array(OAUTH_HMAC_SHA1));
$this->show_service(OAUTH_ENDPOINT_ACCESS, $this->show_service(OAUTH_ENDPOINT_ACCESS,
common_local_url('accesstoken'), common_local_url('accesstoken'),
array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY),
array(OAUTH_HMAC_SHA1)); array(OAUTH_HMAC_SHA1));
$this->show_service(OAUTH_ENDPOINT_RESOURCE, $this->show_service(OAUTH_ENDPOINT_RESOURCE,
NULL, NULL,
array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY),
array(OAUTH_HMAC_SHA1)); array(OAUTH_HMAC_SHA1));
common_element_end('XRD'); common_element_end('XRD');
# XXX: decide whether to include user's ID/nickname in postNotice URL # XXX: decide whether to include user's ID/nickname in postNotice URL
common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
'xml:id' => 'omb', 'xml:id' => 'omb',
'xmlns:simple' => 'http://xrds-simple.net/core/1.0', 'xmlns:simple' => 'http://xrds-simple.net/core/1.0',
'version' => '2.0')); 'version' => '2.0'));
common_element('Type', NULL, 'xri://$xrds*simple'); common_element('Type', NULL, 'xri://$xrds*simple');
$this->show_service(OMB_ENDPOINT_POSTNOTICE, $this->show_service(OMB_ENDPOINT_POSTNOTICE,
common_local_url('postnotice')); common_local_url('postnotice'));
$this->show_service(OMB_ENDPOINT_UPDATEPROFILE, $this->show_service(OMB_ENDPOINT_UPDATEPROFILE,
common_local_url('updateprofile')); common_local_url('updateprofile'));
common_element_end('XRD'); common_element_end('XRD');
common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)',
'version' => '2.0')); 'version' => '2.0'));
common_element('Type', NULL, 'xri://$xrds*simple'); common_element('Type', NULL, 'xri://$xrds*simple');
$this->show_service(OAUTH_DISCOVERY, $this->show_service(OAUTH_DISCOVERY,
'#oauth'); '#oauth');
$this->show_service(OMB_NAMESPACE, $this->show_service(OMB_NAMESPACE,
'#omb'); '#omb');
common_element_end('XRD'); common_element_end('XRD');
common_element_end('XRDS'); common_element_end('XRDS');
common_end_xml(); common_end_xml();
} }
function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) { function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) {
common_element_start('Service'); common_element_start('Service');
if ($uri) { if ($uri) {
common_element('URI', NULL, $uri); common_element('URI', NULL, $uri);
} }
common_element('Type', NULL, $type); common_element('Type', NULL, $type);
if ($params) { if ($params) {
foreach ($params as $param) { foreach ($params as $param) {
common_element('Type', NULL, $param); common_element('Type', NULL, $param);
} }
} }
if ($sigs) { if ($sigs) {
foreach ($sigs as $sig) { foreach ($sigs as $sig) {
common_element('Type', NULL, $sig); common_element('Type', NULL, $sig);
} }
} }
if ($localId) { if ($localId) {
common_element('LocalID', NULL, $localId); common_element('LocalID', NULL, $localId);
} }
common_element_end('Service'); common_element_end('Service');
} }
} }

View File

@ -26,70 +26,70 @@ class Avatar extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
# We clean up the file, too # We clean up the file, too
function delete() { function delete() {
$filename = $this->filename; $filename = $this->filename;
if (parent::delete()) { if (parent::delete()) {
@unlink(common_avatar_path($filename)); @unlink(common_avatar_path($filename));
} }
} }
# Create and save scaled version of this avatar # Create and save scaled version of this avatar
# XXX: maybe break into different methods # XXX: maybe break into different methods
function scale($size) { function scale($size) {
$image_s = imagecreatetruecolor($size, $size); $image_s = imagecreatetruecolor($size, $size);
$image_a = $this->to_image(); $image_a = $this->to_image();
$square = min($this->width, $this->height); $square = min($this->width, $this->height);
imagecolortransparent($image_s, imagecolorallocate($image_s, 0, 0, 0)); imagecolortransparent($image_s, imagecolorallocate($image_s, 0, 0, 0));
imagealphablending($image_s, false); imagealphablending($image_s, false);
imagesavealpha($image_s, true); imagesavealpha($image_s, true);
imagecopyresampled($image_s, $image_a, 0, 0, 0, 0, imagecopyresampled($image_s, $image_a, 0, 0, 0, 0,
$size, $size, $square, $square); $size, $size, $square, $square);
$ext = ($this->mediattype == 'image/jpeg') ? ".jpeg" : ".png"; $ext = ($this->mediattype == 'image/jpeg') ? ".jpeg" : ".png";
$filename = common_avatar_filename($this->profile_id, $ext, $size, common_timestamp()); $filename = common_avatar_filename($this->profile_id, $ext, $size, common_timestamp());
if ($this->mediatype == 'image/jpeg') { if ($this->mediatype == 'image/jpeg') {
imagejpeg($image_s, common_avatar_path($filename)); imagejpeg($image_s, common_avatar_path($filename));
} else { } else {
imagepng($image_s, common_avatar_path($filename)); imagepng($image_s, common_avatar_path($filename));
} }
$scaled = DB_DataObject::factory('avatar'); $scaled = DB_DataObject::factory('avatar');
$scaled->profile_id = $this->profile_id; $scaled->profile_id = $this->profile_id;
$scaled->width = $size; $scaled->width = $size;
$scaled->height = $size; $scaled->height = $size;
$scaled->original = false; $scaled->original = false;
$scaled->mediatype = ($this->mediattype == 'image/jpeg') ? 'image/jpeg' : 'image/png'; $scaled->mediatype = ($this->mediattype == 'image/jpeg') ? 'image/jpeg' : 'image/png';
$scaled->filename = $filename; $scaled->filename = $filename;
$scaled->url = common_avatar_url($filename); $scaled->url = common_avatar_url($filename);
$scaled->created = DB_DataObject_Cast::dateTime(); # current time $scaled->created = DB_DataObject_Cast::dateTime(); # current time
if ($scaled->insert()) { if ($scaled->insert()) {
return $scaled; return $scaled;
} else { } else {
return NULL; return NULL;
} }
} }
function to_image() { function to_image() {
$filepath = common_avatar_path($this->filename); $filepath = common_avatar_path($this->filename);
if ($this->mediatype == 'image/gif') { if ($this->mediatype == 'image/gif') {
return imagecreatefromgif($filepath); return imagecreatefromgif($filepath);
} else if ($this->mediatype == 'image/jpeg') { } else if ($this->mediatype == 'image/jpeg') {
return imagecreatefromjpeg($filepath); return imagecreatefromjpeg($filepath);
} else if ($this->mediatype == 'image/png') { } else if ($this->mediatype == 'image/png') {
return imagecreatefrompng($filepath); return imagecreatefrompng($filepath);
} else { } else {
return NULL; return NULL;
} }
} }
function &pkeyGet($kv) { function &pkeyGet($kv) {
return Memcached_DataObject::pkeyGet('Avatar', $kv); return Memcached_DataObject::pkeyGet('Avatar', $kv);
} }
} }

View File

@ -20,181 +20,181 @@
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
class Channel { class Channel {
function on($user) { function on($user) {
return false; return false;
} }
function off($user) { function off($user) {
return false; return false;
} }
function output($user, $text) { function output($user, $text) {
return false; return false;
} }
function error($user, $text) { function error($user, $text) {
return false; return false;
} }
function source() { function source() {
return NULL; return NULL;
} }
} }
class XMPPChannel extends Channel { class XMPPChannel extends Channel {
var $conn = NULL; var $conn = NULL;
function source() { function source() {
return 'xmpp'; return 'xmpp';
} }
function __construct($conn) { function __construct($conn) {
$this->conn = $conn; $this->conn = $conn;
} }
function on($user) { function on($user) {
return $this->set_notify($user, 1); return $this->set_notify($user, 1);
} }
function off($user) { function off($user) {
return $this->set_notify($user, 0); return $this->set_notify($user, 0);
} }
function output($user, $text) { function output($user, $text) {
$text = '['.common_config('site', 'name') . '] ' . $text; $text = '['.common_config('site', 'name') . '] ' . $text;
jabber_send_message($user->jabber, $text); jabber_send_message($user->jabber, $text);
} }
function error($user, $text) { function error($user, $text) {
$text = '['.common_config('site', 'name') . '] ' . $text; $text = '['.common_config('site', 'name') . '] ' . $text;
jabber_send_message($user->jabber, $text); jabber_send_message($user->jabber, $text);
} }
function set_notify(&$user, $notify) { function set_notify(&$user, $notify) {
$orig = clone($user); $orig = clone($user);
$user->jabbernotify = $notify; $user->jabbernotify = $notify;
$result = $user->update($orig); $result = $user->update($orig);
if (!$result) { if (!$result) {
$last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
common_log(LOG_ERR, common_log(LOG_ERR,
'Could not set notify flag to ' . $notify . 'Could not set notify flag to ' . $notify .
' for user ' . common_log_objstring($user) . ' for user ' . common_log_objstring($user) .
': ' . $last_error->message); ': ' . $last_error->message);
return false; return false;
} else { } else {
common_log(LOG_INFO, common_log(LOG_INFO,
'User ' . $user->nickname . ' set notify flag to ' . $notify); 'User ' . $user->nickname . ' set notify flag to ' . $notify);
return true; return true;
} }
} }
} }
class WebChannel extends Channel { class WebChannel extends Channel {
function source() { function source() {
return 'web'; return 'web';
} }
function on($user) { function on($user) {
return false; return false;
} }
function off($user) { function off($user) {
return false; return false;
} }
function output($user, $text) { function output($user, $text) {
# XXX: buffer all output and send it at the end # XXX: buffer all output and send it at the end
# XXX: even better, redirect to appropriate page # XXX: even better, redirect to appropriate page
# depending on what command was run # depending on what command was run
common_show_header(_('Command results')); common_show_header(_('Command results'));
common_element('p', NULL, $text); common_element('p', NULL, $text);
common_show_footer(); common_show_footer();
} }
function error($user, $text) { function error($user, $text) {
common_user_error($text); common_user_error($text);
} }
} }
class AjaxWebChannel extends WebChannel { class AjaxWebChannel extends WebChannel {
function output($user, $text) { function output($user, $text) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Command results')); common_element('title', null, _('Command results'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
common_element('p', array('id' => 'command_result'), $text); common_element('p', array('id' => 'command_result'), $text);
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} }
function error($user, $text) { function error($user, $text) {
common_start_html('text/xml;charset=utf-8', true); common_start_html('text/xml;charset=utf-8', true);
common_element_start('head'); common_element_start('head');
common_element('title', null, _('Ajax Error')); common_element('title', null, _('Ajax Error'));
common_element_end('head'); common_element_end('head');
common_element_start('body'); common_element_start('body');
common_element('p', array('id' => 'error'), $text); common_element('p', array('id' => 'error'), $text);
common_element_end('body'); common_element_end('body');
common_element_end('html'); common_element_end('html');
} }
} }
class MailChannel extends Channel { class MailChannel extends Channel {
var $addr = NULL; var $addr = NULL;
function source() { function source() {
return 'mail'; return 'mail';
} }
function __construct($addr=NULL) { function __construct($addr=NULL) {
$this->addr = $addr; $this->addr = $addr;
} }
function on($user) { function on($user) {
return $this->set_notify($user, 1); return $this->set_notify($user, 1);
} }
function off($user) { function off($user) {
return $this->set_notify($user, 0); return $this->set_notify($user, 0);
} }
function output($user, $text) { function output($user, $text) {
$headers['From'] = $user->incomingemail; $headers['From'] = $user->incomingemail;
$headers['To'] = $this->addr; $headers['To'] = $this->addr;
$headers['Subject'] = _('Command complete'); $headers['Subject'] = _('Command complete');
return mail_send(array($this->addr), $headers, $text); return mail_send(array($this->addr), $headers, $text);
} }
function error($user, $text) { function error($user, $text) {
$headers['From'] = $user->incomingemail; $headers['From'] = $user->incomingemail;
$headers['To'] = $this->addr; $headers['To'] = $this->addr;
$headers['Subject'] = _('Command failed'); $headers['Subject'] = _('Command failed');
return mail_send(array($this->addr), $headers, $text); return mail_send(array($this->addr), $headers, $text);
} }
function set_notify($user, $value) { function set_notify($user, $value) {
$orig = clone($user); $orig = clone($user);
$user->smsnotify = $value; $user->smsnotify = $value;
$result = $user->update($orig); $result = $user->update($orig);
if (!$result) { if (!$result) {
common_log_db_error($user, 'UPDATE', __FILE__); common_log_db_error($user, 'UPDATE', __FILE__);
return false; return false;
} }
return true; return true;
} }
} }

View File

@ -22,22 +22,22 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/classes/Channel.php'); require_once(INSTALLDIR.'/classes/Channel.php');
class Command { class Command {
var $user = NULL; var $user = NULL;
function __construct($user=NULL) { function __construct($user=NULL) {
$this->user = $user; $this->user = $user;
} }
function execute($channel) { function execute($channel) {
return false; return false;
} }
} }
class UnimplementedCommand extends Command { class UnimplementedCommand extends Command {
function execute($channel) { function execute($channel) {
$channel->error($this->user, _("Sorry, this command is not yet implemented.")); $channel->error($this->user, _("Sorry, this command is not yet implemented."));
} }
} }
class TrackingCommand extends UnimplementedCommand { class TrackingCommand extends UnimplementedCommand {
@ -47,330 +47,330 @@ class TrackOffCommand extends UnimplementedCommand {
} }
class TrackCommand extends UnimplementedCommand { class TrackCommand extends UnimplementedCommand {
var $word = NULL; var $word = NULL;
function __construct($user, $word) { function __construct($user, $word) {
parent::__construct($user); parent::__construct($user);
$this->word = $word; $this->word = $word;
} }
} }
class UntrackCommand extends UnimplementedCommand { class UntrackCommand extends UnimplementedCommand {
var $word = NULL; var $word = NULL;
function __construct($user, $word) { function __construct($user, $word) {
parent::__construct($user); parent::__construct($user);
$this->word = $word; $this->word = $word;
} }
} }
class NudgeCommand extends UnimplementedCommand { class NudgeCommand extends UnimplementedCommand {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
} }
class InviteCommand extends UnimplementedCommand { class InviteCommand extends UnimplementedCommand {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
} }
class StatsCommand extends Command { class StatsCommand extends Command {
function execute($channel) { function execute($channel) {
$subs = new Subscription(); $subs = new Subscription();
$subs->subscriber = $this->user->id; $subs->subscriber = $this->user->id;
$subs_count = (int) $subs->count() - 1; $subs_count = (int) $subs->count() - 1;
$subbed = new Subscription(); $subbed = new Subscription();
$subbed->subscribed = $this->user->id; $subbed->subscribed = $this->user->id;
$subbed_count = (int) $subbed->count() - 1; $subbed_count = (int) $subbed->count() - 1;
$notices = new Notice(); $notices = new Notice();
$notices->profile_id = $this->user->id; $notices->profile_id = $this->user->id;
$notice_count = (int) $notices->count(); $notice_count = (int) $notices->count();
$channel->output($this->user, sprintf(_("Subscriptions: %1\$s\n". $channel->output($this->user, sprintf(_("Subscriptions: %1\$s\n".
"Subscribers: %2\$s\n". "Subscribers: %2\$s\n".
"Notices: %3\$s"), "Notices: %3\$s"),
$subs_count, $subs_count,
$subbed_count, $subbed_count,
$notice_count)); $notice_count));
} }
} }
class FavCommand extends Command { class FavCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
$recipient = $recipient =
common_relative_profile($this->user, common_canonical_nickname($this->other)); common_relative_profile($this->user, common_canonical_nickname($this->other));
if (!$recipient) { if (!$recipient) {
$channel->error($this->user, _('No such user.')); $channel->error($this->user, _('No such user.'));
return; return;
} }
$notice = $recipient->getCurrentNotice(); $notice = $recipient->getCurrentNotice();
if (!$notice) { if (!$notice) {
$channel->error($this->user, _('User has no last notice')); $channel->error($this->user, _('User has no last notice'));
return; return;
} }
$fave = Fave::addNew($this->user, $notice); $fave = Fave::addNew($this->user, $notice);
if (!$fave) { if (!$fave) {
$channel->error($this->user, _('Could not create favorite.')); $channel->error($this->user, _('Could not create favorite.'));
return; return;
} }
$other = User::staticGet('id', $recipient->id); $other = User::staticGet('id', $recipient->id);
if ($other && $other->id != $user->id) { if ($other && $other->id != $user->id) {
if ($other->email && $other->emailnotifyfav) { if ($other->email && $other->emailnotifyfav) {
mail_notify_fave($other, $this->user, $notice); mail_notify_fave($other, $this->user, $notice);
} }
} }
$this->user->blowFavesCache(); $this->user->blowFavesCache();
$channel->output($this->user, _('Notice marked as fave.')); $channel->output($this->user, _('Notice marked as fave.'));
} }
} }
class WhoisCommand extends Command { class WhoisCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
$recipient = $recipient =
common_relative_profile($this->user, common_canonical_nickname($this->other)); common_relative_profile($this->user, common_canonical_nickname($this->other));
if (!$recipient) { if (!$recipient) {
$channel->error($this->user, _('No such user.')); $channel->error($this->user, _('No such user.'));
return; return;
} }
$whois = sprintf(_("%1\$s (%2\$s)"), $recipient->nickname, $whois = sprintf(_("%1\$s (%2\$s)"), $recipient->nickname,
$recipient->profileurl); $recipient->profileurl);
if ($recipient->fullname) { if ($recipient->fullname) {
$whois .= "\n" . sprintf(_('Fullname: %s'), $recipient->fullname); $whois .= "\n" . sprintf(_('Fullname: %s'), $recipient->fullname);
} }
if ($recipient->location) { if ($recipient->location) {
$whois .= "\n" . sprintf(_('Location: %s'), $recipient->location); $whois .= "\n" . sprintf(_('Location: %s'), $recipient->location);
} }
if ($recipient->homepage) { if ($recipient->homepage) {
$whois .= "\n" . sprintf(_('Homepage: %s'), $recipient->homepage); $whois .= "\n" . sprintf(_('Homepage: %s'), $recipient->homepage);
} }
if ($recipient->bio) { if ($recipient->bio) {
$whois .= "\n" . sprintf(_('About: %s'), $recipient->bio); $whois .= "\n" . sprintf(_('About: %s'), $recipient->bio);
} }
$channel->output($this->user, $whois); $channel->output($this->user, $whois);
} }
} }
class MessageCommand extends Command { class MessageCommand extends Command {
var $other = NULL; var $other = NULL;
var $text = NULL; var $text = NULL;
function __construct($user, $other, $text) { function __construct($user, $other, $text) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
$this->text = $text; $this->text = $text;
} }
function execute($channel) { function execute($channel) {
$other = User::staticGet('nickname', common_canonical_nickname($this->other)); $other = User::staticGet('nickname', common_canonical_nickname($this->other));
$len = mb_strlen($this->text); $len = mb_strlen($this->text);
if ($len == 0) { if ($len == 0) {
$channel->error($this->user, _('No content!')); $channel->error($this->user, _('No content!'));
return; return;
} else if ($len > 140) { } else if ($len > 140) {
$content = common_shorten_links($content); $content = common_shorten_links($content);
if (mb_strlen($content) > 140) { if (mb_strlen($content) > 140) {
$channel->error($this->user, sprintf(_('Message too long - maximum is 140 characters, you sent %d'), $len)); $channel->error($this->user, sprintf(_('Message too long - maximum is 140 characters, you sent %d'), $len));
return; return;
} }
} }
if (!$other) { if (!$other) {
$channel->error($this->user, _('No such user.')); $channel->error($this->user, _('No such user.'));
return; return;
} else if (!$this->user->mutuallySubscribed($other)) { } else if (!$this->user->mutuallySubscribed($other)) {
$channel->error($this->user, _('You can\'t send a message to this user.')); $channel->error($this->user, _('You can\'t send a message to this user.'));
return; return;
} else if ($this->user->id == $other->id) { } else if ($this->user->id == $other->id) {
$channel->error($this->user, _('Don\'t send a message to yourself; just say it to yourself quietly instead.')); $channel->error($this->user, _('Don\'t send a message to yourself; just say it to yourself quietly instead.'));
return; return;
} }
$message = Message::saveNew($this->user->id, $other->id, $this->text, $channel->source()); $message = Message::saveNew($this->user->id, $other->id, $this->text, $channel->source());
if ($message) { if ($message) {
$channel->output($this->user, sprintf(_('Direct message to %s sent'), $this->other)); $channel->output($this->user, sprintf(_('Direct message to %s sent'), $this->other));
} else { } else {
$channel->error($this->user, _('Error sending direct message.')); $channel->error($this->user, _('Error sending direct message.'));
} }
} }
} }
class GetCommand extends Command { class GetCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
$target_nickname = common_canonical_nickname($this->other); $target_nickname = common_canonical_nickname($this->other);
$target = $target =
common_relative_profile($this->user, $target_nickname); common_relative_profile($this->user, $target_nickname);
if (!$target) { if (!$target) {
$channel->error($this->user, _('No such user.')); $channel->error($this->user, _('No such user.'));
return; return;
} }
$notice = $target->getCurrentNotice(); $notice = $target->getCurrentNotice();
if (!$notice) { if (!$notice) {
$channel->error($this->user, _('User has no last notice')); $channel->error($this->user, _('User has no last notice'));
return; return;
} }
$notice_content = $notice->content; $notice_content = $notice->content;
$channel->output($this->user, $target_nickname . ": " . $notice_content); $channel->output($this->user, $target_nickname . ": " . $notice_content);
} }
} }
class SubCommand extends Command { class SubCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
if (!$this->other) { if (!$this->other) {
$channel->error($this->user, _('Specify the name of the user to subscribe to')); $channel->error($this->user, _('Specify the name of the user to subscribe to'));
return; return;
} }
$result = subs_subscribe_user($this->user, $this->other); $result = subs_subscribe_user($this->user, $this->other);
if ($result == 'true') { if ($result == 'true') {
$channel->output($this->user, sprintf(_('Subscribed to %s'), $this->other)); $channel->output($this->user, sprintf(_('Subscribed to %s'), $this->other));
} else { } else {
$channel->error($this->user, $result); $channel->error($this->user, $result);
} }
} }
} }
class UnsubCommand extends Command { class UnsubCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other) { function __construct($user, $other) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
if(!$this->other) { if(!$this->other) {
$channel->error($this->user, _('Specify the name of the user to unsubscribe from')); $channel->error($this->user, _('Specify the name of the user to unsubscribe from'));
return; return;
} }
$result=subs_unsubscribe_user($this->user, $this->other); $result=subs_unsubscribe_user($this->user, $this->other);
if ($result) { if ($result) {
$channel->output($this->user, sprintf(_('Unsubscribed from %s'), $this->other)); $channel->output($this->user, sprintf(_('Unsubscribed from %s'), $this->other));
} else { } else {
$channel->error($this->user, $result); $channel->error($this->user, $result);
} }
} }
} }
class OffCommand extends Command { class OffCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other=NULL) { function __construct($user, $other=NULL) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
if ($other) { if ($other) {
$channel->error($this->user, _("Command not yet implemented.")); $channel->error($this->user, _("Command not yet implemented."));
} else { } else {
if ($channel->off($this->user)) { if ($channel->off($this->user)) {
$channel->output($this->user, _('Notification off.')); $channel->output($this->user, _('Notification off.'));
} else { } else {
$channel->error($this->user, _('Can\'t turn off notification.')); $channel->error($this->user, _('Can\'t turn off notification.'));
} }
} }
} }
} }
class OnCommand extends Command { class OnCommand extends Command {
var $other = NULL; var $other = NULL;
function __construct($user, $other=NULL) { function __construct($user, $other=NULL) {
parent::__construct($user); parent::__construct($user);
$this->other = $other; $this->other = $other;
} }
function execute($channel) { function execute($channel) {
if ($other) { if ($other) {
$channel->error($this->user, _("Command not yet implemented.")); $channel->error($this->user, _("Command not yet implemented."));
} else { } else {
if ($channel->on($this->user)) { if ($channel->on($this->user)) {
$channel->output($this->user, _('Notification on.')); $channel->output($this->user, _('Notification on.'));
} else { } else {
$channel->error($this->user, _('Can\'t turn on notification.')); $channel->error($this->user, _('Can\'t turn on notification.'));
} }
} }
} }
} }
class HelpCommand extends Command { class HelpCommand extends Command {
function execute($channel) { function execute($channel) {
$channel->output($this->user, $channel->output($this->user,
_("Commands:\n". _("Commands:\n".
"on - turn on notifications\n". "on - turn on notifications\n".
"off - turn off notifications\n". "off - turn off notifications\n".
"help - show this help\n". "help - show this help\n".
"follow <nickname> - subscribe to user\n". "follow <nickname> - subscribe to user\n".
"leave <nickname> - unsubscribe from user\n". "leave <nickname> - unsubscribe from user\n".
"d <nickname> <text> - direct message to user\n". "d <nickname> <text> - direct message to user\n".
"get <nickname> - get last notice from user\n". "get <nickname> - get last notice from user\n".
"whois <nickname> - get profile info on user\n". "whois <nickname> - get profile info on user\n".
"fav <nickname> - add user's last notice as a 'fave'\n". "fav <nickname> - add user's last notice as a 'fave'\n".
"stats - get your stats\n". "stats - get your stats\n".
"stop - same as 'off'\n". "stop - same as 'off'\n".
"quit - same as 'off'\n". "quit - same as 'off'\n".
"sub <nickname> - same as 'follow'\n". "sub <nickname> - same as 'follow'\n".
"unsub <nickname> - same as 'leave'\n". "unsub <nickname> - same as 'leave'\n".
"last <nickname> - same as 'get'\n". "last <nickname> - same as 'get'\n".
"on <nickname> - not yet implemented.\n". "on <nickname> - not yet implemented.\n".
"off <nickname> - not yet implemented.\n". "off <nickname> - not yet implemented.\n".
"nudge <nickname> - not yet implemented.\n". "nudge <nickname> - not yet implemented.\n".
"invite <phone number> - not yet implemented.\n". "invite <phone number> - not yet implemented.\n".
"track <word> - not yet implemented.\n". "track <word> - not yet implemented.\n".
"untrack <word> - not yet implemented.\n". "untrack <word> - not yet implemented.\n".
"track off - not yet implemented.\n". "track off - not yet implemented.\n".
"untrack all - not yet implemented.\n". "untrack all - not yet implemented.\n".
"tracks - not yet implemented.\n". "tracks - not yet implemented.\n".
"tracking - not yet implemented.\n")); "tracking - not yet implemented.\n"));
} }
} }

View File

@ -22,174 +22,174 @@ if (!defined('LACONICA')) { exit(1); }
require_once(INSTALLDIR.'/classes/Command.php'); require_once(INSTALLDIR.'/classes/Command.php');
class CommandInterpreter { class CommandInterpreter {
function handle_command($user, $text) { function handle_command($user, $text) {
# XXX: localise # XXX: localise
$text = preg_replace('/\s+/', ' ', trim($text)); $text = preg_replace('/\s+/', ' ', trim($text));
list($cmd, $arg) = explode(' ', $text, 2); list($cmd, $arg) = explode(' ', $text, 2);
# We try to support all the same commands as Twitter, see # We try to support all the same commands as Twitter, see
# http://getsatisfaction.com/twitter/topics/what_are_the_twitter_commands # http://getsatisfaction.com/twitter/topics/what_are_the_twitter_commands
# There are a few compatibility commands from earlier versions of # There are a few compatibility commands from earlier versions of
# Laconica # Laconica
switch(strtolower($cmd)) { switch(strtolower($cmd)) {
case 'help': case 'help':
if ($arg) { if ($arg) {
return NULL; return NULL;
} }
return new HelpCommand($user); return new HelpCommand($user);
case 'on': case 'on':
if ($arg) { if ($arg) {
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new OnCommand($user, $other); return new OnCommand($user, $other);
} }
} else { } else {
return new OnCommand($user); return new OnCommand($user);
} }
case 'off': case 'off':
if ($arg) { if ($arg) {
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new OffCommand($user, $other); return new OffCommand($user, $other);
} }
} else { } else {
return new OffCommand($user); return new OffCommand($user);
} }
case 'stop': case 'stop':
case 'quit': case 'quit':
if ($arg) { if ($arg) {
return NULL; return NULL;
} else { } else {
return new OffCommand($user); return new OffCommand($user);
} }
case 'follow': case 'follow':
case 'sub': case 'sub':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new SubCommand($user, $other); return new SubCommand($user, $other);
} }
case 'leave': case 'leave':
case 'unsub': case 'unsub':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new UnsubCommand($user, $other); return new UnsubCommand($user, $other);
} }
case 'get': case 'get':
case 'last': case 'last':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new GetCommand($user, $other); return new GetCommand($user, $other);
} }
case 'd': case 'd':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if (!$extra) { if (!$extra) {
return NULL; return NULL;
} else { } else {
return new MessageCommand($user, $other, $extra); return new MessageCommand($user, $other, $extra);
} }
case 'whois': case 'whois':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new WhoisCommand($user, $other); return new WhoisCommand($user, $other);
} }
case 'fav': case 'fav':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new FavCommand($user, $other); return new FavCommand($user, $other);
} }
case 'nudge': case 'nudge':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new NudgeCommand($user, $other); return new NudgeCommand($user, $other);
} }
case 'stats': case 'stats':
if ($arg) { if ($arg) {
return NULL; return NULL;
} }
return new StatsCommand($user); return new StatsCommand($user);
case 'invite': case 'invite':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($other, $extra) = explode(' ', $arg, 2); list($other, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else { } else {
return new InviteCommand($user, $other); return new InviteCommand($user, $other);
} }
case 'track': case 'track':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($word, $extra) = explode(' ', $arg, 2); list($word, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else if ($word == 'off') { } else if ($word == 'off') {
return new TrackOffCommand($user); return new TrackOffCommand($user);
} else { } else {
return new TrackCommand($user, $word); return new TrackCommand($user, $word);
} }
case 'untrack': case 'untrack':
if (!$arg) { if (!$arg) {
return NULL; return NULL;
} }
list($word, $extra) = explode(' ', $arg, 2); list($word, $extra) = explode(' ', $arg, 2);
if ($extra) { if ($extra) {
return NULL; return NULL;
} else if ($word == 'all') { } else if ($word == 'all') {
return new TrackOffCommand($user); return new TrackOffCommand($user);
} else { } else {
return new UntrackCommand($user, $word); return new UntrackCommand($user, $word);
} }
case 'tracks': case 'tracks':
case 'tracking': case 'tracking':
if ($arg) { if ($arg) {
return NULL; return NULL;
} }
return new TrackingCommand($user); return new TrackingCommand($user);
default: default:
return false; return false;
} }
} }
} }

View File

@ -20,18 +20,18 @@ class Fave extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
static function addNew($user, $notice) { static function addNew($user, $notice) {
$fave = new Fave(); $fave = new Fave();
$fave->user_id = $user->id; $fave->user_id = $user->id;
$fave->notice_id = $notice->id; $fave->notice_id = $notice->id;
if (!$fave->insert()) { if (!$fave->insert()) {
common_log_db_error($fave, 'INSERT', __FILE__); common_log_db_error($fave, 'INSERT', __FILE__);
return false; return false;
} }
return $fave; return $fave;
} }
function &pkeyGet($kv) { function &pkeyGet($kv) {
return Memcached_DataObject::pkeyGet('Fave', $kv); return Memcached_DataObject::pkeyGet('Fave', $kv);
} }
} }

View File

@ -26,51 +26,51 @@ class Foreign_link extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
// XXX: This only returns a 1->1 single obj mapping. Change? Or make // XXX: This only returns a 1->1 single obj mapping. Change? Or make
// a getForeignUsers() that returns more than one? --Zach // a getForeignUsers() that returns more than one? --Zach
static function getByUserID($user_id, $service) { static function getByUserID($user_id, $service) {
$flink = new Foreign_link(); $flink = new Foreign_link();
$flink->service = $service; $flink->service = $service;
$flink->user_id = $user_id; $flink->user_id = $user_id;
$flink->limit(1); $flink->limit(1);
if ($flink->find(TRUE)) { if ($flink->find(TRUE)) {
return $flink; return $flink;
} }
return NULL; return NULL;
} }
static function getByForeignID($foreign_id, $service) { static function getByForeignID($foreign_id, $service) {
$flink = new Foreign_link(); $flink = new Foreign_link();
$flink->service = $service; $flink->service = $service;
$flink->foreign_id = $foreign_id; $flink->foreign_id = $foreign_id;
$flink->limit(1); $flink->limit(1);
if ($flink->find(TRUE)) { if ($flink->find(TRUE)) {
return $flink; return $flink;
} }
return NULL; return NULL;
} }
# Convenience methods # Convenience methods
function getForeignUser() { function getForeignUser() {
$fuser = new Foreign_user(); $fuser = new Foreign_user();
$fuser->service = $this->service; $fuser->service = $this->service;
$fuser->id = $this->foreign_id; $fuser->id = $this->foreign_id;
$fuser->limit(1); $fuser->limit(1);
if ($fuser->find(TRUE)) { if ($fuser->find(TRUE)) {
return $fuser; return $fuser;
} }
return NULL; return NULL;
} }
function getUser() { function getUser() {
return User::staticGet($this->user_id); return User::staticGet($this->user_id);
} }
} }

View File

@ -22,49 +22,49 @@ class Foreign_user extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
// XXX: This only returns a 1->1 single obj mapping. Change? Or make // XXX: This only returns a 1->1 single obj mapping. Change? Or make
// a getForeignUsers() that returns more than one? --Zach // a getForeignUsers() that returns more than one? --Zach
static function getForeignUser($id, $service) { static function getForeignUser($id, $service) {
$fuser = new Foreign_user(); $fuser = new Foreign_user();
$fuser->whereAdd("service = $service"); $fuser->whereAdd("service = $service");
$fuser->whereAdd("id = $id"); $fuser->whereAdd("id = $id");
$fuser->limit(1); $fuser->limit(1);
if ($fuser->find()) { if ($fuser->find()) {
$fuser->fetch(); $fuser->fetch();
return $fuser; return $fuser;
} }
return NULL; return NULL;
} }
function updateKeys(&$orig) { function updateKeys(&$orig) {
$parts = array(); $parts = array();
foreach (array('id', 'service', 'uri', 'nickname') as $k) { foreach (array('id', 'service', 'uri', 'nickname') as $k) {
if (strcmp($this->$k, $orig->$k) != 0) { if (strcmp($this->$k, $orig->$k) != 0) {
$parts[] = $k . ' = ' . $this->_quote($this->$k); $parts[] = $k . ' = ' . $this->_quote($this->$k);
} }
} }
if (count($parts) == 0) { if (count($parts) == 0) {
# No changes # No changes
return true; return true;
} }
$toupdate = implode(', ', $parts); $toupdate = implode(', ', $parts);
$table = $this->tableName(); $table = $this->tableName();
if(common_config('db','quote_identifiers')) { if(common_config('db','quote_identifiers')) {
$table = '"' . $table . '"'; $table = '"' . $table . '"';
} }
$qry = 'UPDATE ' . $table . ' SET ' . $toupdate . $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
' WHERE id = ' . $this->id; ' WHERE id = ' . $this->id;
$orig->decache(); $orig->decache();
$result = $this->query($qry); $result = $this->query($qry);
if ($result) { if ($result) {
$this->encache(); $this->encache();
} }
return $result; return $result;
} }
} }

View File

@ -24,151 +24,151 @@ require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
class Memcached_DataObject extends DB_DataObject class Memcached_DataObject extends DB_DataObject
{ {
function &staticGet($cls, $k, $v=NULL) { function &staticGet($cls, $k, $v=NULL) {
if (is_null($v)) { if (is_null($v)) {
$v = $k; $v = $k;
# XXX: HACK! # XXX: HACK!
$i = new $cls; $i = new $cls;
$keys = $i->keys(); $keys = $i->keys();
$k = $keys[0]; $k = $keys[0];
unset($i); unset($i);
} }
$i = Memcached_DataObject::getcached($cls, $k, $v); $i = Memcached_DataObject::getcached($cls, $k, $v);
if ($i) { if ($i) {
return $i;
} else {
$i = DB_DataObject::staticGet($cls, $k, $v);
if ($i) {
$i->encache();
}
return $i;
}
}
function &pkeyGet($cls, $kv) {
$i = Memcached_DataObject::multicache($cls, $kv);
if ($i) {
return $i;
} else {
$i = new $cls();
foreach ($kv as $k => $v) {
$i->$k = $v;
}
if ($i->find(true)) {
$i->encache();
} else {
$i = NULL;
}
return $i; return $i;
} } else {
} $i = DB_DataObject::staticGet($cls, $k, $v);
if ($i) {
$i->encache();
}
return $i;
}
}
function insert() { function &pkeyGet($cls, $kv) {
$result = parent::insert(); $i = Memcached_DataObject::multicache($cls, $kv);
return $result; if ($i) {
} return $i;
} else {
function update($orig=NULL) { $i = new $cls();
if (is_object($orig) && $orig instanceof Memcached_DataObject) { foreach ($kv as $k => $v) {
$orig->decache(); # might be different keys $i->$k = $v;
} }
$result = parent::update($orig); if ($i->find(true)) {
if ($result) { $i->encache();
$this->encache(); } else {
} $i = NULL;
return $result; }
} return $i;
}
function delete() { }
$this->decache(); # while we still have the values!
return parent::delete();
}
static function memcache() {
return common_memcache();
}
static function cacheKey($cls, $k, $v) {
return common_cache_key(strtolower($cls).':'.$k.':'.$v);
}
static function getcached($cls, $k, $v) {
$c = Memcached_DataObject::memcache();
if (!$c) {
return false;
} else {
return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
}
}
function keyTypes() { function insert() {
global $_DB_DATAOBJECT; $result = parent::insert();
return $result;
}
function update($orig=NULL) {
if (is_object($orig) && $orig instanceof Memcached_DataObject) {
$orig->decache(); # might be different keys
}
$result = parent::update($orig);
if ($result) {
$this->encache();
}
return $result;
}
function delete() {
$this->decache(); # while we still have the values!
return parent::delete();
}
static function memcache() {
return common_memcache();
}
static function cacheKey($cls, $k, $v) {
return common_cache_key(strtolower($cls).':'.$k.':'.$v);
}
static function getcached($cls, $k, $v) {
$c = Memcached_DataObject::memcache();
if (!$c) {
return false;
} else {
return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v));
}
}
function keyTypes() {
global $_DB_DATAOBJECT;
if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) { if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
$this->databaseStructure(); $this->databaseStructure();
} }
return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]; return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
} }
function encache() { function encache() {
$c = $this->memcache(); $c = $this->memcache();
if (!$c) { if (!$c) {
return false; return false;
} else { } else {
$pkey = array(); $pkey = array();
$pval = array(); $pval = array();
$types = $this->keyTypes(); $types = $this->keyTypes();
ksort($types); ksort($types);
foreach ($types as $key => $type) { foreach ($types as $key => $type) {
if ($type == 'K') { if ($type == 'K') {
$pkey[] = $key; $pkey[] = $key;
$pval[] = $this->$key; $pval[] = $this->$key;
} else { } else {
$c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this); $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this);
} }
} }
# XXX: should work for both compound and scalar pkeys # XXX: should work for both compound and scalar pkeys
$pvals = implode(',', $pval); $pvals = implode(',', $pval);
$pkeys = implode(',', $pkey); $pkeys = implode(',', $pkey);
$c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this); $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this);
} }
} }
function decache() { function decache() {
$c = $this->memcache(); $c = $this->memcache();
if (!$c) { if (!$c) {
return false; return false;
} else { } else {
$pkey = array(); $pkey = array();
$pval = array(); $pval = array();
$types = $this->keyTypes(); $types = $this->keyTypes();
ksort($types); ksort($types);
foreach ($types as $key => $type) { foreach ($types as $key => $type) {
if ($type == 'K') { if ($type == 'K') {
$pkey[] = $key; $pkey[] = $key;
$pval[] = $this->$key; $pval[] = $this->$key;
} else { } else {
$c->delete($this->cacheKey($this->tableName(), $key, $this->$key)); $c->delete($this->cacheKey($this->tableName(), $key, $this->$key));
} }
} }
# should work for both compound and scalar pkeys # should work for both compound and scalar pkeys
# XXX: comma works for now but may not be safe separator for future keys # XXX: comma works for now but may not be safe separator for future keys
$pvals = implode(',', $pval); $pvals = implode(',', $pval);
$pkeys = implode(',', $pkey); $pkeys = implode(',', $pkey);
$c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals)); $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals));
} }
} }
function multicache($cls, $kv) { function multicache($cls, $kv) {
ksort($kv); ksort($kv);
$c = Memcached_DataObject::memcache(); $c = Memcached_DataObject::memcache();
if (!$c) { if (!$c) {
return false; return false;
} else { } else {
$pkeys = implode(',', array_keys($kv)); $pkeys = implode(',', array_keys($kv));
$pvals = implode(',', array_values($kv)); $pvals = implode(',', array_values($kv));
return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals)); return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals));
} }
} }
function getSearchEngine($table) { function getSearchEngine($table) {
require_once INSTALLDIR.'/lib/search_engines.php'; require_once INSTALLDIR.'/lib/search_engines.php';

View File

@ -26,43 +26,43 @@ class Message extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
function getFrom() { function getFrom() {
return Profile::staticGet('id', $this->from_profile); return Profile::staticGet('id', $this->from_profile);
} }
function getTo() { function getTo() {
return Profile::staticGet('id', $this->to_profile); return Profile::staticGet('id', $this->to_profile);
} }
static function saveNew($from, $to, $content, $source) { static function saveNew($from, $to, $content, $source) {
$msg = new Message(); $msg = new Message();
$msg->from_profile = $from; $msg->from_profile = $from;
$msg->to_profile = $to; $msg->to_profile = $to;
$msg->content = common_shorten_links($content); $msg->content = common_shorten_links($content);
$msg->rendered = common_render_text($content); $msg->rendered = common_render_text($content);
$msg->created = common_sql_now(); $msg->created = common_sql_now();
$msg->source = $source; $msg->source = $source;
$result = $msg->insert(); $result = $msg->insert();
if (!$result) { if (!$result) {
common_log_db_error($msg, 'INSERT', __FILE__); common_log_db_error($msg, 'INSERT', __FILE__);
return _('Could not insert message.'); return _('Could not insert message.');
} }
$orig = clone($msg); $orig = clone($msg);
$msg->uri = common_local_url('showmessage', array('message' => $msg->id)); $msg->uri = common_local_url('showmessage', array('message' => $msg->id));
$result = $msg->update($orig); $result = $msg->update($orig);
if (!$result) { if (!$result) {
common_log_db_error($msg, 'UPDATE', __FILE__); common_log_db_error($msg, 'UPDATE', __FILE__);
return _('Could not update message with new URI.'); return _('Could not update message with new URI.');
} }
return $msg; return $msg;
} }
} }

View File

@ -10,11 +10,11 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details. * GNU Affero General Public License for more details.
* *
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
if (!defined('LACONICA')) { exit(1); } if (!defined('LACONICA')) { exit(1); }
@ -31,69 +31,69 @@ define('NOTICE_CACHE_WINDOW', 61);
class Notice extends Memcached_DataObject class Notice extends Memcached_DataObject
{ {
###START_AUTOCODE ###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */ /* the code below is auto generated do not remove the above tag */
public $__table = 'notice'; // table name public $__table = 'notice'; // table name
public $id; // int(4) primary_key not_null public $id; // int(4) primary_key not_null
public $profile_id; // int(4) not_null public $profile_id; // int(4) not_null
public $uri; // varchar(255) unique_key public $uri; // varchar(255) unique_key
public $content; // varchar(140) public $content; // varchar(140)
public $rendered; // text() public $rendered; // text()
public $url; // varchar(255) public $url; // varchar(255)
public $created; // datetime() not_null public $created; // datetime() not_null
public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
public $reply_to; // int(4) public $reply_to; // int(4)
public $is_local; // tinyint(1) public $is_local; // tinyint(1)
public $source; // varchar(32) public $source; // varchar(32)
/* Static get */ /* Static get */
function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Notice',$k,$v); } function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
function getProfile() { function getProfile() {
return Profile::staticGet('id', $this->profile_id); return Profile::staticGet('id', $this->profile_id);
} }
function delete() { function delete() {
$this->blowCaches(true); $this->blowCaches(true);
$this->blowFavesCache(true); $this->blowFavesCache(true);
$this->blowInboxes(); $this->blowInboxes();
return parent::delete(); return parent::delete();
} }
function saveTags() { function saveTags() {
/* extract all #hastags */ /* extract all #hastags */
$count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match); $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
if (!$count) { if (!$count) {
return true; return true;
} }
/* elide characters we don't want in the tag */ /* elide characters we don't want in the tag */
$match[1] = str_replace(array('-', '_', '.'), '', $match[1]); $match[1] = str_replace(array('-', '_', '.'), '', $match[1]);
/* Add them to the database */ /* Add them to the database */
foreach(array_unique($match[1]) as $hashtag) { foreach(array_unique($match[1]) as $hashtag) {
$tag = DB_DataObject::factory('Notice_tag'); $tag = DB_DataObject::factory('Notice_tag');
$tag->notice_id = $this->id; $tag->notice_id = $this->id;
$tag->tag = $hashtag; $tag->tag = $hashtag;
$tag->created = $this->created; $tag->created = $this->created;
$id = $tag->insert(); $id = $tag->insert();
if (!$id) { if (!$id) {
$last_error = PEAR::getStaticProperty('DB_DataObject','lastError'); $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message); common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message);
common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message)); common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message));
return; return;
} }
} }
return true; return true;
} }
static function saveNew($profile_id, $content, $source=NULL, $is_local=1, $reply_to=NULL, $uri=NULL) { static function saveNew($profile_id, $content, $source=NULL, $is_local=1, $reply_to=NULL, $uri=NULL) {
$profile = Profile::staticGet($profile_id); $profile = Profile::staticGet($profile_id);
if (!$profile) { if (!$profile) {
common_log(LOG_ERR, 'Problem saving notice. Unknown user.'); common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
@ -102,69 +102,69 @@ class Notice extends Memcached_DataObject
if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) { if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.'); common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
return _('Too many notices too fast; take a breather and post again in a few minutes.'); return _('Too many notices too fast; take a breather and post again in a few minutes.');
} }
$banned = common_config('profile', 'banned'); $banned = common_config('profile', 'banned');
if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) { if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id)."); common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
return _('You are banned from posting notices on this site.'); return _('You are banned from posting notices on this site.');
} }
$notice = new Notice(); $notice = new Notice();
$notice->profile_id = $profile_id; $notice->profile_id = $profile_id;
$blacklist = common_config('public', 'blacklist'); $blacklist = common_config('public', 'blacklist');
# Blacklisted are non-false, but not 1, either # Blacklisted are non-false, but not 1, either
if ($blacklist && in_array($profile_id, $blacklist)) { if ($blacklist && in_array($profile_id, $blacklist)) {
$notice->is_local = -1; $notice->is_local = -1;
} else { } else {
$notice->is_local = $is_local; $notice->is_local = $is_local;
} }
$notice->reply_to = $reply_to; $notice->reply_to = $reply_to;
$notice->created = common_sql_now(); $notice->created = common_sql_now();
$notice->content = common_shorten_links($content); $notice->content = common_shorten_links($content);
$notice->rendered = common_render_content($notice->content, $notice); $notice->rendered = common_render_content($notice->content, $notice);
$notice->source = $source; $notice->source = $source;
$notice->uri = $uri; $notice->uri = $uri;
$id = $notice->insert(); $id = $notice->insert();
if (!$id) { if (!$id) {
common_log_db_error($notice, 'INSERT', __FILE__); common_log_db_error($notice, 'INSERT', __FILE__);
return _('Problem saving notice.'); return _('Problem saving notice.');
} }
# Update the URI after the notice is in the database # Update the URI after the notice is in the database
if (!$uri) { if (!$uri) {
$orig = clone($notice); $orig = clone($notice);
$notice->uri = common_notice_uri($notice); $notice->uri = common_notice_uri($notice);
if (!$notice->update($orig)) { if (!$notice->update($orig)) {
common_log_db_error($notice, 'UPDATE', __FILE__); common_log_db_error($notice, 'UPDATE', __FILE__);
return _('Problem saving notice.'); return _('Problem saving notice.');
} }
} }
# XXX: do we need to change this for remote users? # XXX: do we need to change this for remote users?
common_save_replies($notice); common_save_replies($notice);
$notice->saveTags(); $notice->saveTags();
# Clear the cache for subscribed users, so they'll update at next request # Clear the cache for subscribed users, so they'll update at next request
# XXX: someone clever could prepend instead of clearing the cache # XXX: someone clever could prepend instead of clearing the cache
if (common_config('memcached', 'enabled')) { if (common_config('memcached', 'enabled')) {
$notice->blowCaches(); $notice->blowCaches();
} }
$notice->addToInboxes(); $notice->addToInboxes();
return $notice; return $notice;
} }
static function checkEditThrottle($profile_id) { static function checkEditThrottle($profile_id) {
$profile = Profile::staticGet($profile_id); $profile = Profile::staticGet($profile_id);
@ -184,356 +184,356 @@ class Notice extends Memcached_DataObject
return true; return true;
} }
function blowCaches($blowLast=false) { function blowCaches($blowLast=false) {
$this->blowSubsCache($blowLast); $this->blowSubsCache($blowLast);
$this->blowNoticeCache($blowLast); $this->blowNoticeCache($blowLast);
$this->blowRepliesCache($blowLast); $this->blowRepliesCache($blowLast);
$this->blowPublicCache($blowLast); $this->blowPublicCache($blowLast);
$this->blowTagCache($blowLast); $this->blowTagCache($blowLast);
} }
function blowTagCache($blowLast=false) { function blowTagCache($blowLast=false) {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$tag = new Notice_tag(); $tag = new Notice_tag();
$tag->notice_id = $this->id; $tag->notice_id = $this->id;
if ($tag->find()) { if ($tag->find()) {
while ($tag->fetch()) { while ($tag->fetch()) {
$cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag)); $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag));
if ($blowLast) { if ($blowLast) {
$cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last')); $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last'));
} }
} }
} }
$tag->free(); $tag->free();
unset($tag); unset($tag);
} }
} }
function blowSubsCache($blowLast=false) { function blowSubsCache($blowLast=false) {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$user = new User(); $user = new User();
$user->query('SELECT id ' . $user->query('SELECT id ' .
'FROM user JOIN subscription ON user.id = subscription.subscriber ' . 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
'WHERE subscription.subscribed = ' . $this->profile_id); 'WHERE subscription.subscribed = ' . $this->profile_id);
while ($user->fetch()) { while ($user->fetch()) {
$cache->delete(common_cache_key('user:notices_with_friends:' . $user->id)); $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id));
if ($blowLast) { if ($blowLast) {
$cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last')); $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last'));
} }
} }
$user->free(); $user->free();
unset($user); unset($user);
} }
} }
function blowNoticeCache($blowLast=false) { function blowNoticeCache($blowLast=false) {
if ($this->is_local) { if ($this->is_local) {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$cache->delete(common_cache_key('profile:notices:'.$this->profile_id)); $cache->delete(common_cache_key('profile:notices:'.$this->profile_id));
if ($blowLast) { if ($blowLast) {
$cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last')); $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last'));
} }
} }
} }
} }
function blowRepliesCache($blowLast=false) { function blowRepliesCache($blowLast=false) {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$reply = new Reply(); $reply = new Reply();
$reply->notice_id = $this->id; $reply->notice_id = $this->id;
if ($reply->find()) { if ($reply->find()) {
while ($reply->fetch()) { while ($reply->fetch()) {
$cache->delete(common_cache_key('user:replies:'.$reply->profile_id)); $cache->delete(common_cache_key('user:replies:'.$reply->profile_id));
if ($blowLast) { if ($blowLast) {
$cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last')); $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last'));
} }
} }
} }
$reply->free(); $reply->free();
unset($reply); unset($reply);
} }
} }
function blowPublicCache($blowLast=false) { function blowPublicCache($blowLast=false) {
if ($this->is_local == 1) { if ($this->is_local == 1) {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$cache->delete(common_cache_key('public')); $cache->delete(common_cache_key('public'));
if ($blowLast) { if ($blowLast) {
$cache->delete(common_cache_key('public').';last'); $cache->delete(common_cache_key('public').';last');
} }
} }
} }
} }
function blowFavesCache($blowLast=false) { function blowFavesCache($blowLast=false) {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$fave = new Fave(); $fave = new Fave();
$fave->notice_id = $this->id; $fave->notice_id = $this->id;
if ($fave->find()) { if ($fave->find()) {
while ($fave->fetch()) { while ($fave->fetch()) {
$cache->delete(common_cache_key('user:faves:'.$fave->user_id)); $cache->delete(common_cache_key('user:faves:'.$fave->user_id));
if ($blowLast) { if ($blowLast) {
$cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last')); $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last'));
} }
} }
} }
$fave->free(); $fave->free();
unset($fave); unset($fave);
} }
} }
# XXX: too many args; we need to move to named params or even a separate # XXX: too many args; we need to move to named params or even a separate
# class for notice streams # class for notice streams
static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL, $since=NULL) { static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL, $since=NULL) {
if (common_config('memcached', 'enabled')) { if (common_config('memcached', 'enabled')) {
# Skip the cache if this is a since, since_id or before_id qry # Skip the cache if this is a since, since_id or before_id qry
if ($since_id > 0 || $before_id > 0 || $since) { if ($since_id > 0 || $before_id > 0 || $since) {
return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since); return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
} else { } else {
return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order); return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
} }
} }
return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since); return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since);
} }
static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) { static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
$needAnd = FALSE; $needAnd = FALSE;
$needWhere = TRUE; $needWhere = TRUE;
if (preg_match('/\bWHERE\b/i', $qry)) { if (preg_match('/\bWHERE\b/i', $qry)) {
$needWhere = FALSE; $needWhere = FALSE;
$needAnd = TRUE; $needAnd = TRUE;
} }
if ($since_id > 0) { if ($since_id > 0) {
if ($needWhere) { if ($needWhere) {
$qry .= ' WHERE '; $qry .= ' WHERE ';
$needWhere = FALSE; $needWhere = FALSE;
} else { } else {
$qry .= ' AND '; $qry .= ' AND ';
} }
$qry .= ' notice.id > ' . $since_id; $qry .= ' notice.id > ' . $since_id;
} }
if ($before_id > 0) { if ($before_id > 0) {
if ($needWhere) { if ($needWhere) {
$qry .= ' WHERE '; $qry .= ' WHERE ';
$needWhere = FALSE; $needWhere = FALSE;
} else { } else {
$qry .= ' AND '; $qry .= ' AND ';
} }
$qry .= ' notice.id < ' . $before_id; $qry .= ' notice.id < ' . $before_id;
} }
if ($since) { if ($since) {
if ($needWhere) { if ($needWhere) {
$qry .= ' WHERE '; $qry .= ' WHERE ';
$needWhere = FALSE; $needWhere = FALSE;
} else { } else {
$qry .= ' AND '; $qry .= ' AND ';
} }
$qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\''; $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
} }
# Allow ORDER override # Allow ORDER override
if ($order) { if ($order) {
$qry .= $order; $qry .= $order;
} else { } else {
$qry .= ' ORDER BY notice.created DESC, notice.id DESC '; $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
} }
if (common_config('db','type') == 'pgsql') { if (common_config('db','type') == 'pgsql') {
$qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
} else { } else {
$qry .= ' LIMIT ' . $offset . ', ' . $limit; $qry .= ' LIMIT ' . $offset . ', ' . $limit;
} }
$notice = new Notice(); $notice = new Notice();
$notice->query($qry); $notice->query($qry);
return $notice; return $notice;
} }
# XXX: this is pretty long and should probably be broken up into # XXX: this is pretty long and should probably be broken up into
# some helper functions # some helper functions
static function getCachedStream($qry, $cachekey, $offset, $limit, $order) { static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
# If outside our cache window, just go to the DB # If outside our cache window, just go to the DB
if ($offset + $limit > NOTICE_CACHE_WINDOW) { if ($offset + $limit > NOTICE_CACHE_WINDOW) {
return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL); return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL);
} }
# Get the cache; if we can't, just go to the DB # Get the cache; if we can't, just go to the DB
$cache = common_memcache(); $cache = common_memcache();
if (!$cache) { if (!$cache) {
return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL); return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL);
} }
# Get the notices out of the cache # Get the notices out of the cache
$notices = $cache->get(common_cache_key($cachekey)); $notices = $cache->get(common_cache_key($cachekey));
# On a cache hit, return a DB-object-like wrapper # On a cache hit, return a DB-object-like wrapper
if ($notices !== FALSE) { if ($notices !== FALSE) {
$wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit)); $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
return $wrapper; return $wrapper;
} }
# If the cache was invalidated because of new data being # If the cache was invalidated because of new data being
# added, we can try and just get the new stuff. We keep an additional # added, we can try and just get the new stuff. We keep an additional
# copy of the data at the key + ';last' # copy of the data at the key + ';last'
# No cache hit. Try to get the *last* cached version # No cache hit. Try to get the *last* cached version
$last_notices = $cache->get(common_cache_key($cachekey) . ';last'); $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
if ($last_notices) { if ($last_notices) {
# Reverse-chron order, so last ID is last. # Reverse-chron order, so last ID is last.
$last_id = $last_notices[0]->id; $last_id = $last_notices[0]->id;
# XXX: this assumes monotonically increasing IDs; a fair # XXX: this assumes monotonically increasing IDs; a fair
# bet with our DB. # bet with our DB.
$new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
$last_id, NULL, $order, NULL); $last_id, NULL, $order, NULL);
if ($new_notice) { if ($new_notice) {
$new_notices = array(); $new_notices = array();
while ($new_notice->fetch()) { while ($new_notice->fetch()) {
$new_notices[] = clone($new_notice); $new_notices[] = clone($new_notice);
} }
$new_notice->free(); $new_notice->free();
$notices = array_slice(array_merge($new_notices, $last_notices), $notices = array_slice(array_merge($new_notices, $last_notices),
0, NOTICE_CACHE_WINDOW); 0, NOTICE_CACHE_WINDOW);
# Store the array in the cache for next time # Store the array in the cache for next time
$result = $cache->set(common_cache_key($cachekey), $notices); $result = $cache->set(common_cache_key($cachekey), $notices);
$result = $cache->set(common_cache_key($cachekey) . ';last', $notices); $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
# return a wrapper of the array for use now # return a wrapper of the array for use now
return new NoticeWrapper(array_slice($notices, $offset, $limit)); return new NoticeWrapper(array_slice($notices, $offset, $limit));
} }
} }
# Otherwise, get the full cache window out of the DB # Otherwise, get the full cache window out of the DB
$notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order, NULL); $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order, NULL);
# If there are no hits, just return the value # If there are no hits, just return the value
if (!$notice) { if (!$notice) {
return $notice; return $notice;
} }
# Pack results into an array # Pack results into an array
$notices = array(); $notices = array();
while ($notice->fetch()) { while ($notice->fetch()) {
$notices[] = clone($notice); $notices[] = clone($notice);
} }
$notice->free(); $notice->free();
# Store the array in the cache for next time # Store the array in the cache for next time
$result = $cache->set(common_cache_key($cachekey), $notices); $result = $cache->set(common_cache_key($cachekey), $notices);
$result = $cache->set(common_cache_key($cachekey) . ';last', $notices); $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
# return a wrapper of the array for use now # return a wrapper of the array for use now
$wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit)); $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit));
return $wrapper; return $wrapper;
} }
function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=NULL) { function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=NULL) {
$parts = array(); $parts = array();
$qry = 'SELECT * FROM notice '; $qry = 'SELECT * FROM notice ';
if (common_config('public', 'localonly')) { if (common_config('public', 'localonly')) {
$parts[] = 'is_local = 1'; $parts[] = 'is_local = 1';
} else { } else {
# -1 == blacklisted # -1 == blacklisted
$parts[] = 'is_local != -1'; $parts[] = 'is_local != -1';
} }
if ($parts) { if ($parts) {
$qry .= ' WHERE ' . implode(' AND ', $parts); $qry .= ' WHERE ' . implode(' AND ', $parts);
} }
return Notice::getStream($qry, return Notice::getStream($qry,
'public', 'public',
$offset, $limit, $since_id, $before_id, NULL, $since); $offset, $limit, $since_id, $before_id, NULL, $since);
} }
function addToInboxes() { function addToInboxes() {
$enabled = common_config('inboxes', 'enabled'); $enabled = common_config('inboxes', 'enabled');
if ($enabled === true || $enabled === 'transitional') { if ($enabled === true || $enabled === 'transitional') {
$inbox = new Notice_inbox(); $inbox = new Notice_inbox();
$qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' . $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' . 'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' .
'FROM user JOIN subscription ON user.id = subscription.subscriber ' . 'FROM user JOIN subscription ON user.id = subscription.subscriber ' .
'WHERE subscription.subscribed = ' . $this->profile_id . ' ' . 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
'AND NOT EXISTS (SELECT user_id, notice_id ' . 'AND NOT EXISTS (SELECT user_id, notice_id ' .
'FROM notice_inbox ' . 'FROM notice_inbox ' .
'WHERE user_id = user.id ' . 'WHERE user_id = user.id ' .
'AND notice_id = ' . $this->id . ' )'; 'AND notice_id = ' . $this->id . ' )';
if ($enabled === 'transitional') { if ($enabled === 'transitional') {
$qry .= ' AND user.inboxed = 1'; $qry .= ' AND user.inboxed = 1';
} }
$inbox->query($qry); $inbox->query($qry);
} }
return; return;
} }
# Delete from inboxes if we're deleted. # Delete from inboxes if we're deleted.
function blowInboxes() { function blowInboxes() {
$enabled = common_config('inboxes', 'enabled'); $enabled = common_config('inboxes', 'enabled');
if ($enabled === true || $enabled === 'transitional') { if ($enabled === true || $enabled === 'transitional') {
$inbox = new Notice_inbox(); $inbox = new Notice_inbox();
$inbox->notice_id = $this->id; $inbox->notice_id = $this->id;
$inbox->delete(); $inbox->delete();
} }
return; return;
} }
} }

View File

@ -35,25 +35,25 @@ class NoticeWrapper extends Notice {
public $is_local; // tinyint(1) public $is_local; // tinyint(1)
public $source; // varchar(32) public $source; // varchar(32)
var $notices = NULL; var $notices = NULL;
var $i = -1; var $i = -1;
function __construct($arr) { function __construct($arr) {
$this->notices = $arr; $this->notices = $arr;
} }
function fetch() { function fetch() {
static $fields = array('id', 'profile_id', 'uri', 'content', 'rendered', static $fields = array('id', 'profile_id', 'uri', 'content', 'rendered',
'url', 'created', 'modified', 'reply_to', 'is_local', 'source'); 'url', 'created', 'modified', 'reply_to', 'is_local', 'source');
$this->i++; $this->i++;
if ($this->i >= count($this->notices)) { if ($this->i >= count($this->notices)) {
return false; return false;
} else { } else {
$n = $this->notices[$this->i]; $n = $this->notices[$this->i];
foreach ($fields as $f) { foreach ($fields as $f) {
$this->$f = $n->$f; $this->$f = $n->$f;
} }
return true; return true;
} }
} }
} }

View File

@ -34,22 +34,22 @@ class Notice_tag extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
static function getStream($tag, $offset=0, $limit=20) { static function getStream($tag, $offset=0, $limit=20) {
$qry = $qry =
'SELECT notice.* ' . 'SELECT notice.* ' .
'FROM notice JOIN notice_tag ON notice.id = notice_tag.notice_id ' . 'FROM notice JOIN notice_tag ON notice.id = notice_tag.notice_id ' .
'WHERE notice_tag.tag = "%s" '; 'WHERE notice_tag.tag = "%s" ';
return Notice::getStream(sprintf($qry, $tag), return Notice::getStream(sprintf($qry, $tag),
'notice_tag:notice_stream:' . common_keyize($tag), 'notice_tag:notice_stream:' . common_keyize($tag),
$offset, $limit); $offset, $limit);
} }
function blowCache() { function blowCache() {
$cache = common_memcache(); $cache = common_memcache();
if ($cache) { if ($cache) {
$cache->delete(common_cache_key('notice_tag:notice_stream:' . $this->tag)); $cache->delete(common_cache_key('notice_tag:notice_stream:' . $this->tag));
} }
} }
} }

View File

@ -46,114 +46,114 @@ class Profile extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
function getAvatar($width, $height=NULL) { function getAvatar($width, $height=NULL) {
if (is_null($height)) { if (is_null($height)) {
$height = $width; $height = $width;
} }
return Avatar::pkeyGet(array('profile_id' => $this->id, return Avatar::pkeyGet(array('profile_id' => $this->id,
'width' => $width, 'width' => $width,
'height' => $height)); 'height' => $height));
} }
function getOriginalAvatar() { function getOriginalAvatar() {
$avatar = DB_DataObject::factory('avatar'); $avatar = DB_DataObject::factory('avatar');
$avatar->profile_id = $this->id; $avatar->profile_id = $this->id;
$avatar->original = true; $avatar->original = true;
if ($avatar->find(true)) { if ($avatar->find(true)) {
return $avatar; return $avatar;
} else { } else {
return NULL; return NULL;
} }
} }
function setOriginal($source) { function setOriginal($source) {
$info = @getimagesize($source); $info = @getimagesize($source);
if (!$info) { if (!$info) {
return NULL; return NULL;
} }
$filename = common_avatar_filename($this->id, $filename = common_avatar_filename($this->id,
image_type_to_extension($info[2]), image_type_to_extension($info[2]),
NULL, common_timestamp()); NULL, common_timestamp());
$filepath = common_avatar_path($filename); $filepath = common_avatar_path($filename);
copy($source, $filepath); copy($source, $filepath);
$avatar = new Avatar(); $avatar = new Avatar();
$avatar->profile_id = $this->id; $avatar->profile_id = $this->id;
$avatar->width = $info[0]; $avatar->width = $info[0];
$avatar->height = $info[1]; $avatar->height = $info[1];
$avatar->mediatype = image_type_to_mime_type($info[2]); $avatar->mediatype = image_type_to_mime_type($info[2]);
$avatar->filename = $filename; $avatar->filename = $filename;
$avatar->original = true; $avatar->original = true;
$avatar->url = common_avatar_url($filename); $avatar->url = common_avatar_url($filename);
$avatar->created = DB_DataObject_Cast::dateTime(); # current time $avatar->created = DB_DataObject_Cast::dateTime(); # current time
# XXX: start a transaction here # XXX: start a transaction here
if (!$this->delete_avatars()) { if (!$this->delete_avatars()) {
@unlink($filepath); @unlink($filepath);
return NULL; return NULL;
} }
if (!$avatar->insert()) { if (!$avatar->insert()) {
@unlink($filepath); @unlink($filepath);
return NULL; return NULL;
} }
foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) { foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
# We don't do a scaled one if original is our scaled size # We don't do a scaled one if original is our scaled size
if (!($avatar->width == $size && $avatar->height == $size)) { if (!($avatar->width == $size && $avatar->height == $size)) {
$s = $avatar->scale($size); $s = $avatar->scale($size);
if (!$s) { if (!$s) {
return NULL; return NULL;
} }
} }
} }
return $avatar; return $avatar;
} }
function delete_avatars() { function delete_avatars() {
$avatar = new Avatar(); $avatar = new Avatar();
$avatar->profile_id = $this->id; $avatar->profile_id = $this->id;
$avatar->find(); $avatar->find();
while ($avatar->fetch()) { while ($avatar->fetch()) {
$avatar->delete(); $avatar->delete();
} }
return true; return true;
} }
function getBestName() { function getBestName() {
return ($this->fullname) ? $this->fullname : $this->nickname; return ($this->fullname) ? $this->fullname : $this->nickname;
} }
# Get latest notice on or before date; default now # Get latest notice on or before date; default now
function getCurrentNotice($dt=NULL) { function getCurrentNotice($dt=NULL) {
$notice = new Notice(); $notice = new Notice();
$notice->profile_id = $this->id; $notice->profile_id = $this->id;
if ($dt) { if ($dt) {
$notice->whereAdd('created < "' . $dt . '"'); $notice->whereAdd('created < "' . $dt . '"');
} }
$notice->orderBy('created DESC, notice.id DESC'); $notice->orderBy('created DESC, notice.id DESC');
$notice->limit(1); $notice->limit(1);
if ($notice->find(true)) { if ($notice->find(true)) {
return $notice; return $notice;
} }
return NULL; return NULL;
} }
function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) { function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
$qry = $qry =
'SELECT * ' . 'SELECT * ' .
'FROM notice ' . 'FROM notice ' .
'WHERE profile_id = %d '; 'WHERE profile_id = %d ';
return Notice::getStream(sprintf($qry, $this->id), return Notice::getStream(sprintf($qry, $this->id),
'profile:notices:'.$this->id, 'profile:notices:'.$this->id,
$offset, $limit, $since_id, $before_id); $offset, $limit, $since_id, $before_id);
} }
} }

View File

@ -21,81 +21,81 @@ class Profile_tag extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
static function getTags($tagger, $tagged) { static function getTags($tagger, $tagged) {
$tags = array(); $tags = array();
# XXX: store this in memcached # XXX: store this in memcached
$profile_tag = new Profile_tag(); $profile_tag = new Profile_tag();
$profile_tag->tagger = $tagger; $profile_tag->tagger = $tagger;
$profile_tag->tagged = $tagged; $profile_tag->tagged = $tagged;
$profile_tag->find(); $profile_tag->find();
while ($profile_tag->fetch()) { while ($profile_tag->fetch()) {
$tags[] = $profile_tag->tag; $tags[] = $profile_tag->tag;
} }
$profile_tag->free(); $profile_tag->free();
return $tags; return $tags;
} }
static function setTags($tagger, $tagged, $newtags) { static function setTags($tagger, $tagged, $newtags) {
$oldtags = Profile_tag::getTags($tagger, $tagged); $oldtags = Profile_tag::getTags($tagger, $tagged);
# Delete stuff that's old that not in new # Delete stuff that's old that not in new
$to_delete = array_diff($oldtags, $newtags); $to_delete = array_diff($oldtags, $newtags);
# Insert stuff that's in new and not in old # Insert stuff that's in new and not in old
$to_insert = array_diff($newtags, $oldtags); $to_insert = array_diff($newtags, $oldtags);
$profile_tag = new Profile_tag(); $profile_tag = new Profile_tag();
$profile_tag->tagger = $tagger; $profile_tag->tagger = $tagger;
$profile_tag->tagged = $tagged; $profile_tag->tagged = $tagged;
$profile_tag->query('BEGIN'); $profile_tag->query('BEGIN');
foreach ($to_delete as $deltag) { foreach ($to_delete as $deltag) {
$profile_tag->tag = $deltag; $profile_tag->tag = $deltag;
$result = $profile_tag->delete(); $result = $profile_tag->delete();
if (!$result) { if (!$result) {
common_log_db_error($profile_tag, 'DELETE', __FILE__); common_log_db_error($profile_tag, 'DELETE', __FILE__);
return false; return false;
} }
} }
foreach ($to_insert as $instag) { foreach ($to_insert as $instag) {
$profile_tag->tag = $instag; $profile_tag->tag = $instag;
$result = $profile_tag->insert(); $result = $profile_tag->insert();
if (!$result) { if (!$result) {
common_log_db_error($profile_tag, 'INSERT', __FILE__); common_log_db_error($profile_tag, 'INSERT', __FILE__);
return false; return false;
} }
} }
$profile_tag->query('COMMIT'); $profile_tag->query('COMMIT');
return true; return true;
} }
# Return profiles with a given tag # Return profiles with a given tag
static function getTagged($tagger, $tag) { static function getTagged($tagger, $tag) {
$profile = new Profile(); $profile = new Profile();
$profile->query('SELECT profile.* ' . $profile->query('SELECT profile.* ' .
'FROM profile JOIN profile_tag ' . 'FROM profile JOIN profile_tag ' .
'ON profile.id = profile_tag.tagged ' . 'ON profile.id = profile_tag.tagged ' .
'WHERE profile_tag.tagger = ' . $tagger . ' ' . 'WHERE profile_tag.tagger = ' . $tagger . ' ' .
'AND profile_tag.tag = "' . $tag . '" '); 'AND profile_tag.tag = "' . $tag . '" ');
$tagged = array(); $tagged = array();
while ($profile->fetch()) { while ($profile->fetch()) {
$tagged[] = clone($profile); $tagged[] = clone($profile);
} }
return $tagged; return $tagged;
} }
} }

View File

@ -22,34 +22,34 @@ class Queue_item extends Memcached_DataObject
###END_AUTOCODE ###END_AUTOCODE
function sequenceKey() { return array(false, false); } function sequenceKey() { return array(false, false); }
static function top($transport) { static function top($transport) {
$qi = new Queue_item(); $qi = new Queue_item();
$qi->transport = $transport; $qi->transport = $transport;
$qi->orderBy('created'); $qi->orderBy('created');
$qi->whereAdd('claimed is NULL'); $qi->whereAdd('claimed is NULL');
$qi->limit(1); $qi->limit(1);
$cnt = $qi->find(TRUE); $cnt = $qi->find(TRUE);
if ($cnt) { if ($cnt) {
# XXX: potential race condition # XXX: potential race condition
# can we force it to only update if claimed is still NULL # can we force it to only update if claimed is still NULL
# (or old)? # (or old)?
common_log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id . ' for transport ' . $transport); common_log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id . ' for transport ' . $transport);
$orig = clone($qi); $orig = clone($qi);
$qi->claimed = common_sql_now(); $qi->claimed = common_sql_now();
$result = $qi->update($orig); $result = $qi->update($orig);
if ($result) { if ($result) {
common_log(LOG_INFO, 'claim succeeded.'); common_log(LOG_INFO, 'claim succeeded.');
return $qi; return $qi;
} else { } else {
common_log(LOG_INFO, 'claim failed.'); common_log(LOG_INFO, 'claim failed.');
} }
} }
$qi = NULL; $qi = NULL;
return NULL; return NULL;
} }
} }

View File

@ -21,8 +21,8 @@ class Sms_carrier extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */ /* the code above is auto generated do not remove the tag below */
###END_AUTOCODE ###END_AUTOCODE
function toEmailAddress($sms) { function toEmailAddress($sms) {
return sprintf($this->email_pattern, $sms); return sprintf($this->email_pattern, $sms);
} }
} }

Some files were not shown because too many files have changed in this diff Show More