summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/action.php217
-rw-r--r--lib/channel.php237
-rw-r--r--lib/clienterroraction.php15
-rw-r--r--lib/command.php419
-rw-r--r--lib/commandinterpreter.php197
-rw-r--r--lib/common.php39
-rw-r--r--lib/dberroraction.php73
-rw-r--r--lib/facebookutil.php109
-rw-r--r--lib/featureduserssection.php14
-rw-r--r--lib/feed.php110
-rw-r--r--lib/feedlist.php101
-rw-r--r--lib/galleryaction.php7
-rw-r--r--lib/grouplist.php4
-rw-r--r--lib/groupminilist.php7
-rw-r--r--lib/groupsbymemberssection.php2
-rw-r--r--lib/groupsbypostssection.php2
-rw-r--r--lib/grouptagcloudsection.php8
-rw-r--r--lib/htmloutputter.php19
-rw-r--r--lib/jabber.php63
-rw-r--r--lib/jsonsearchresultslist.php270
-rw-r--r--lib/language.php61
-rw-r--r--lib/logingroupnav.php20
-rw-r--r--lib/mail.php67
-rw-r--r--lib/mailbox.php3
-rw-r--r--lib/messageform.php10
-rw-r--r--lib/noticeform.php9
-rw-r--r--lib/noticelist.php9
-rw-r--r--lib/noticesection.php7
-rw-r--r--lib/oauthstore.php9
-rw-r--r--lib/omb.php13
-rw-r--r--lib/openid.php7
-rw-r--r--lib/peoplesearchresults.php75
-rw-r--r--lib/personaltagcloudsection.php10
-rw-r--r--lib/ping.php122
-rw-r--r--lib/popularnoticesection.php34
-rw-r--r--lib/profileaction.php242
-rw-r--r--lib/profilelist.php28
-rw-r--r--lib/profileminilist.php2
-rw-r--r--lib/publicgroupnav.php28
-rw-r--r--lib/router.php144
-rw-r--r--lib/rssaction.php38
-rw-r--r--lib/search_engines.php34
-rw-r--r--lib/searchaction.php33
-rw-r--r--lib/section.php2
-rw-r--r--lib/servererroraction.php20
-rw-r--r--lib/settingsaction.php4
-rw-r--r--lib/subgroupnav.php2
-rw-r--r--lib/topposterssection.php2
-rw-r--r--lib/twitter.php299
-rw-r--r--lib/twitterapi.php188
-rw-r--r--lib/util.php273
-rw-r--r--lib/xmlstringer.php68
52 files changed, 3086 insertions, 690 deletions
diff --git a/lib/action.php b/lib/action.php
index 80a8969fa..dddba9eb0 100644
--- a/lib/action.php
+++ b/lib/action.php
@@ -93,10 +93,22 @@ class Action extends HTMLOutputter // lawsuit
*/
function showPage()
{
- $this->startHTML();
+ if (Event::handle('StartShowHTML', array($this))) {
+ $this->startHTML();
+ Event::handle('EndShowHTML', array($this));
+ }
+ if (Event::handle('StartShowHead', array($this))) {
$this->showHead();
+ Event::handle('EndShowHead', array($this));
+ }
+ if (Event::handle('StartShowBody', array($this))) {
$this->showBody();
+ Event::handle('EndShowBody', array($this));
+ }
+ if (Event::handle('StartEndHTML', array($this))) {
$this->endHTML();
+ Event::handle('EndEndHTML', array($this));
+ }
}
/**
@@ -109,6 +121,7 @@ class Action extends HTMLOutputter // lawsuit
// XXX: attributes (profile?)
$this->elementStart('head');
$this->showTitle();
+ $this->showShortcutIcon();
$this->showStylesheets();
$this->showScripts();
$this->showRelationshipLinks();
@@ -146,31 +159,77 @@ class Action extends HTMLOutputter // lawsuit
}
/**
+ * Show themed shortcut icon
+ *
+ * @return nothing
+ */
+ function showShortcutIcon()
+ {
+ if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/favicon.ico')) {
+ $this->element('link', array('rel' => 'shortcut icon',
+ 'href' => theme_path('favicon.ico')));
+ } else {
+ $this->element('link', array('rel' => 'shortcut icon',
+ 'href' => common_path('favicon.ico')));
+ }
+
+ if (common_config('site', 'mobile')) {
+ if (is_readable(INSTALLDIR . '/theme/' . common_config('site', 'theme') . '/apple-touch-icon.png')) {
+ $this->element('link', array('rel' => 'apple-touch-icon',
+ 'href' => theme_path('apple-touch-icon.png')));
+ } else {
+ $this->element('link', array('rel' => 'apple-touch-icon',
+ 'href' => common_path('apple-touch-icon.png')));
+ }
+ }
+ }
+
+ /**
* Show stylesheets
*
* @return nothing
*/
function showStylesheets()
{
- $this->element('link', array('rel' => 'stylesheet',
- 'type' => 'text/css',
- 'href' => theme_path('css/display.css', 'base') . '?version=' . LACONICA_VERSION,
- 'media' => 'screen, projection, tv'));
- $this->element('link', array('rel' => 'stylesheet',
- 'type' => 'text/css',
- 'href' => theme_path('css/display.css', null) . '?version=' . LACONICA_VERSION,
- 'media' => 'screen, projection, tv'));
- $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
- 'href="'.theme_path('css/ie.css', 'base').'?version='.LACONICA_VERSION.'" /><![endif]');
- foreach (array(6,7) as $ver) {
- if (file_exists(theme_file('css/ie'.$ver.'.css', 'base'))) {
- // Yes, IE people should be put in jail.
- $this->comment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
- 'href="'.theme_path('css/ie'.$ver.'.css', 'base').'?version='.LACONICA_VERSION.'" /><![endif]');
+ if (Event::handle('StartShowStyles', array($this))) {
+ if (Event::handle('StartShowLaconicaStyles', array($this))) {
+ $this->element('link', array('rel' => 'stylesheet',
+ 'type' => 'text/css',
+ 'href' => theme_path('css/display.css', 'base') . '?version=' . LACONICA_VERSION,
+ 'media' => 'screen, projection, tv'));
+ $this->element('link', array('rel' => 'stylesheet',
+ 'type' => 'text/css',
+ 'href' => theme_path('css/display.css', null) . '?version=' . LACONICA_VERSION,
+ 'media' => 'screen, projection, tv'));
+ if (common_config('site', 'mobile')) {
+ $this->element('link', array('rel' => 'stylesheet',
+ 'type' => 'text/css',
+ 'href' => theme_path('css/mobile.css', 'base') . '?version=' . LACONICA_VERSION,
+ // TODO: "handheld" CSS for other mobile devices
+ 'media' => 'only screen and (max-device-width: 480px)')); // Mobile WebKit
+ }
+ $this->element('link', array('rel' => 'stylesheet',
+ 'type' => 'text/css',
+ 'href' => theme_path('css/print.css', 'base') . '?version=' . LACONICA_VERSION,
+ 'media' => 'print'));
+ Event::handle('EndShowLaconicaStyles', array($this));
+ }
+ if (Event::handle('StartShowUAStyles', array($this))) {
+ $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
+ 'href="'.theme_path('css/ie.css', 'base').'?version='.LACONICA_VERSION.'" /><![endif]');
+ foreach (array(6,7) as $ver) {
+ if (file_exists(theme_file('css/ie'.$ver.'.css', 'base'))) {
+ // Yes, IE people should be put in jail.
+ $this->comment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
+ 'href="'.theme_path('css/ie'.$ver.'.css', 'base').'?version='.LACONICA_VERSION.'" /><![endif]');
+ }
+ }
+ $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
+ 'href="'.theme_path('css/ie.css', null).'?version='.LACONICA_VERSION.'" /><![endif]');
+ Event::handle('EndShowUAStyles', array($this));
}
+ Event::handle('EndShowStyles', array($this));
}
- $this->comment('[if IE]><link rel="stylesheet" type="text/css" '.
- 'href="'.theme_path('css/ie.css', null).'?version='.LACONICA_VERSION.'" /><![endif]');
}
/**
@@ -197,6 +256,9 @@ class Action extends HTMLOutputter // lawsuit
$this->element('script', array('type' => 'text/javascript',
'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
' ');
+ // Frame-busting code to avoid clickjacking attacks.
+ $this->element('script', array('type' => 'text/javascript'),
+ 'if (window.top !== window.self) { window.top.location.href = window.self.location.href; }');
Event::handle('EndShowLaconicaScripts', array($this));
}
Event::handle('EndShowScripts', array($this));
@@ -239,9 +301,19 @@ class Action extends HTMLOutputter // lawsuit
*
* @return nothing
*/
+
function showFeeds()
{
- // does nothing by default
+ $feeds = $this->getFeeds();
+
+ if ($feeds) {
+ foreach ($feeds as $feed) {
+ $this->element('link', array('rel' => $feed->rel(),
+ 'href' => $feed->url,
+ 'type' => $feed->mimeType(),
+ 'title' => $feed->title));
+ }
+ }
}
/**
@@ -277,11 +349,19 @@ class Action extends HTMLOutputter // lawsuit
*/
function showBody()
{
- $this->elementStart('body', array('id' => $this->trimmed('action')));
+ $this->elementStart('body', (common_current_user()) ? array('id' => $this->trimmed('action'),
+ 'class' => 'user_in')
+ : array('id' => $this->trimmed('action')));
$this->elementStart('div', array('id' => 'wrap'));
- $this->showHeader();
+ if (Event::handle('StartShowHeader', array($this))) {
+ $this->showHeader();
+ Event::handle('EndShowHeader', array($this));
+ }
$this->showCore();
- $this->showFooter();
+ if (Event::handle('StartShowFooter', array($this))) {
+ $this->showFooter();
+ Event::handle('EndShowFooter', array($this));
+ }
$this->elementEnd('div');
$this->elementEnd('body');
}
@@ -345,13 +425,8 @@ class Action extends HTMLOutputter // lawsuit
if ($user) {
$this->menuItem(common_local_url('all', array('nickname' => $user->nickname)),
_('Home'), _('Personal profile and friends timeline'), false, 'nav_home');
- }
- $this->menuItem(common_local_url('peoplesearch'),
- _('Search'), _('Search for people or text'), false, 'nav_search');
- if ($user) {
$this->menuItem(common_local_url('profilesettings'),
_('Account'), _('Change your email, avatar, password, profile'), false, 'nav_account');
-
if (common_config('xmpp', 'enabled')) {
$this->menuItem(common_local_url('imsettings'),
_('Connect'), _('Connect to IM, SMS, Twitter'), false, 'nav_connect');
@@ -359,20 +434,28 @@ class Action extends HTMLOutputter // lawsuit
$this->menuItem(common_local_url('smssettings'),
_('Connect'), _('Connect to SMS, Twitter'), false, 'nav_connect');
}
+ $this->menuItem(common_local_url('invite'),
+ _('Invite'),
+ sprintf(_('Invite friends and colleagues to join you on %s'),
+ common_config('site', 'name')),
+ false, 'nav_invitecontact');
$this->menuItem(common_local_url('logout'),
_('Logout'), _('Logout from the site'), false, 'nav_logout');
- } else {
- $this->menuItem(common_local_url('login'),
- _('Login'), _('Login to the site'), false, 'nav_login');
+ }
+ else {
if (!common_config('site', 'closed')) {
$this->menuItem(common_local_url('register'),
_('Register'), _('Create an account'), false, 'nav_register');
}
$this->menuItem(common_local_url('openidlogin'),
_('OpenID'), _('Login with OpenID'), false, 'nav_openid');
+ $this->menuItem(common_local_url('login'),
+ _('Login'), _('Login to the site'), false, 'nav_login');
}
$this->menuItem(common_local_url('doc', array('title' => 'help')),
_('Help'), _('Help me!'), false, 'nav_help');
+ $this->menuItem(common_local_url('peoplesearch'),
+ _('Search'), _('Search for people or text'), false, 'nav_search');
Event::handle('EndPrimaryNav', array($this));
}
$this->elementEnd('ul');
@@ -435,8 +518,14 @@ class Action extends HTMLOutputter // lawsuit
function showCore()
{
$this->elementStart('div', array('id' => 'core'));
- $this->showLocalNavBlock();
- $this->showContentBlock();
+ if (Event::handle('StartShowLocalNavBlock', array($this))) {
+ $this->showLocalNavBlock();
+ Event::handle('EndShowLocalNavBlock', array($this));
+ }
+ if (Event::handle('StartShowContentBlock', array($this))) {
+ $this->showContentBlock();
+ Event::handle('EndShowContentBlock', array($this));
+ }
$this->showAside();
$this->elementEnd('div');
}
@@ -543,7 +632,10 @@ class Action extends HTMLOutputter // lawsuit
{
$this->elementStart('div', array('id' => 'aside_primary',
'class' => 'aside'));
+ if (Event::handle('StartShowExportData', array($this))) {
$this->showExportData();
+ Event::handle('EndShowExportData', array($this));
+ }
if (Event::handle('StartShowSections', array($this))) {
$this->showSections();
Event::handle('EndShowSections', array($this));
@@ -554,15 +646,16 @@ class Action extends HTMLOutputter // lawsuit
/**
* Show export data feeds.
*
- * MAY overload if there are feeds
- *
- * @return nothing
+ * @return void
*/
+
function showExportData()
{
- // is there structure to this?
- // list of (visible!) feed links
- // can we reuse list of feeds from showFeeds() ?
+ $feeds = $this->getFeeds();
+ if ($feeds) {
+ $fl = new FeedList($this);
+ $fl->show($feeds);
+ }
}
/**
@@ -614,6 +707,8 @@ class Action extends HTMLOutputter // lawsuit
_('Source'));
$this->menuItem(common_local_url('doc', array('title' => 'contact')),
_('Contact'));
+ $this->menuItem(common_local_url('doc', array('title' => 'badge')),
+ _('Badge'));
Event::handle('EndSecondaryNav', array($this));
}
$this->elementEnd('ul');
@@ -764,12 +859,13 @@ class Action extends HTMLOutputter // lawsuit
}
if ($lm) {
header('Last-Modified: ' . date(DATE_RFC1123, $lm));
- $if_modified_since = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
- if ($if_modified_since) {
- $ims = strtotime($if_modified_since);
+ if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
+ $ims = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if ($lm <= $ims) {
- if (!$etag ||
- $this->_hasEtag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) {
+ $if_none_match = $_SERVER['HTTP_IF_NONE_MATCH'];
+ if (!$if_none_match ||
+ !$etag ||
+ $this->_hasEtag($etag, $if_none_match)) {
header('HTTP/1.1 304 Not Modified');
// Better way to do this?
exit(0);
@@ -787,9 +883,11 @@ class Action extends HTMLOutputter // lawsuit
*
* @return boolean
*/
+
function _hasEtag($etag, $if_none_match)
{
- return ($if_none_match) && in_array($etag, explode(',', $if_none_match));
+ $etags = explode(',', $if_none_match);
+ return in_array($etag, $etags) || in_array('*', $etags);
}
/**
@@ -852,11 +950,15 @@ class Action extends HTMLOutputter // lawsuit
*
* @return string current URL
*/
+
function selfUrl()
{
$action = $this->trimmed('action');
$args = $this->args;
unset($args['action']);
+ if (array_key_exists('submit', $args)) {
+ unset($args['submit']);
+ }
foreach (array_keys($_COOKIE) as $cookie) {
unset($args[$cookie]);
}
@@ -917,17 +1019,17 @@ class Action extends HTMLOutputter // lawsuit
}
if ($have_before) {
$pargs = array('page' => $page-1);
- $newargs = $args ? array_merge($args, $pargs) : $pargs;
$this->elementStart('li', array('class' => 'nav_prev'));
- $this->element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'),
+ $this->element('a', array('href' => common_local_url($action, $args, $pargs),
+ 'rel' => 'prev'),
_('After'));
$this->elementEnd('li');
}
if ($have_after) {
$pargs = array('page' => $page+1);
- $newargs = $args ? array_merge($args, $pargs) : $pargs;
$this->elementStart('li', array('class' => 'nav_next'));
- $this->element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'),
+ $this->element('a', array('href' => common_local_url($action, $args, $pargs),
+ 'rel' => 'next'),
_('Before'));
$this->elementEnd('li');
}
@@ -940,6 +1042,19 @@ class Action extends HTMLOutputter // lawsuit
}
/**
+ * An array of feeds for this action.
+ *
+ * Returns an array of potential feeds for this action.
+ *
+ * @return array Feed object to show in head and links
+ */
+
+ function getFeeds()
+ {
+ return null;
+ }
+
+ /**
* Generate document metadata for sequential navigation
*
* @param boolean $have_before is there something before?
@@ -958,17 +1073,15 @@ class Action extends HTMLOutputter // lawsuit
// "next" is equivalent to "after"
if ($have_next) {
$pargs = array('page' => $page-1);
- $newargs = $args ? array_merge($args, $pargs) : $pargs;
$this->element('link', array('rel' => 'next',
- 'href' => common_local_url($action, $newargs),
+ 'href' => common_local_url($action, $args, $pargs),
'title' => _('Next')));
}
// "previous" is equivalent to "before"
if ($have_previous=true) { // FIXME
$pargs = array('page' => $page+1);
- $newargs = $args ? array_merge($args, $pargs) : $pargs;
$this->element('link', array('rel' => 'prev',
- 'href' => common_local_url($action, $newargs),
+ 'href' => common_local_url($action, $args, $pargs),
'title' => _('Previous')));
}
}
diff --git a/lib/channel.php b/lib/channel.php
new file mode 100644
index 000000000..f1e205546
--- /dev/null
+++ b/lib/channel.php
@@ -0,0 +1,237 @@
+<?php
+/*
+ * Laconica - a distributed open-source microblogging tool
+ * Copyright (C) 2008, Controlez-Vous, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('LACONICA')) { exit(1); }
+
+class Channel
+{
+ function on($user)
+ {
+ return false;
+ }
+
+ function off($user)
+ {
+ return false;
+ }
+
+ function output($user, $text)
+ {
+ return false;
+ }
+
+ function error($user, $text)
+ {
+ return false;
+ }
+
+ function source()
+ {
+ return null;
+ }
+}
+
+class XMPPChannel extends Channel
+{
+
+ var $conn = null;
+
+ function source()
+ {
+ return 'xmpp';
+ }
+
+ function __construct($conn)
+ {
+ $this->conn = $conn;
+ }
+
+ function on($user)
+ {
+ return $this->set_notify($user, 1);
+ }
+
+ function off($user)
+ {
+ return $this->set_notify($user, 0);
+ }
+
+ function output($user, $text)
+ {
+ $text = '['.common_config('site', 'name') . '] ' . $text;
+ jabber_send_message($user->jabber, $text);
+ }
+
+ function error($user, $text)
+ {
+ $text = '['.common_config('site', 'name') . '] ' . $text;
+ jabber_send_message($user->jabber, $text);
+ }
+
+ function set_notify(&$user, $notify)
+ {
+ $orig = clone($user);
+ $user->jabbernotify = $notify;
+ $result = $user->update($orig);
+ if (!$result) {
+ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
+ common_log(LOG_ERR,
+ 'Could not set notify flag to ' . $notify .
+ ' for user ' . common_log_objstring($user) .
+ ': ' . $last_error->message);
+ return false;
+ } else {
+ common_log(LOG_INFO,
+ 'User ' . $user->nickname . ' set notify flag to ' . $notify);
+ return true;
+ }
+ }
+}
+
+class WebChannel extends Channel
+{
+ var $out = null;
+
+ function __construct($out=null)
+ {
+ $this->out = $out;
+ }
+
+ function source()
+ {
+ return 'web';
+ }
+
+ function on($user)
+ {
+ return false;
+ }
+
+ function off($user)
+ {
+ return false;
+ }
+
+ function output($user, $text)
+ {
+ # XXX: buffer all output and send it at the end
+ # XXX: even better, redirect to appropriate page
+ # depending on what command was run
+ $this->out->startHTML();
+ $this->out->elementStart('head');
+ $this->out->element('title', null, _('Command results'));
+ $this->out->elementEnd('head');
+ $this->out->elementStart('body');
+ $this->out->element('p', array('id' => 'command_result'), $text);
+ $this->out->elementEnd('body');
+ $this->out->endHTML();
+ }
+
+ function error($user, $text)
+ {
+ common_user_error($text);
+ }
+}
+
+class AjaxWebChannel extends WebChannel
+{
+ function output($user, $text)
+ {
+ $this->out->startHTML('text/xml;charset=utf-8');
+ $this->out->elementStart('head');
+ $this->out->element('title', null, _('Command results'));
+ $this->out->elementEnd('head');
+ $this->out->elementStart('body');
+ $this->out->element('p', array('id' => 'command_result'), $text);
+ $this->out->elementEnd('body');
+ $this->out->endHTML();
+ }
+
+ function error($user, $text)
+ {
+ $this->out->startHTML('text/xml;charset=utf-8');
+ $this->out->elementStart('head');
+ $this->out->element('title', null, _('Ajax Error'));
+ $this->out->elementEnd('head');
+ $this->out->elementStart('body');
+ $this->out->element('p', array('id' => 'error'), $text);
+ $this->out->elementEnd('body');
+ $this->out->endHTML();
+ }
+}
+
+class MailChannel extends Channel
+{
+
+ var $addr = null;
+
+ function source()
+ {
+ return 'mail';
+ }
+
+ function __construct($addr=null)
+ {
+ $this->addr = $addr;
+ }
+
+ function on($user)
+ {
+ return $this->set_notify($user, 1);
+ }
+
+ function off($user)
+ {
+ return $this->set_notify($user, 0);
+ }
+
+ function output($user, $text)
+ {
+
+ $headers['From'] = $user->incomingemail;
+ $headers['To'] = $this->addr;
+
+ $headers['Subject'] = _('Command complete');
+
+ return mail_send(array($this->addr), $headers, $text);
+ }
+
+ function error($user, $text)
+ {
+
+ $headers['From'] = $user->incomingemail;
+ $headers['To'] = $this->addr;
+
+ $headers['Subject'] = _('Command failed');
+
+ return mail_send(array($this->addr), $headers, $text);
+ }
+
+ function set_notify($user, $value)
+ {
+ $orig = clone($user);
+ $user->smsnotify = $value;
+ $result = $user->update($orig);
+ if (!$result) {
+ common_log_db_error($user, 'UPDATE', __FILE__);
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/lib/clienterroraction.php b/lib/clienterroraction.php
index 5019dc06d..0c48414d5 100644
--- a/lib/clienterroraction.php
+++ b/lib/clienterroraction.php
@@ -49,7 +49,7 @@ class ClientErrorAction extends ErrorAction
function __construct($message='Error', $code=400)
{
parent::__construct($message, $code);
-
+
$this->status = array(400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
@@ -72,7 +72,7 @@ class ClientErrorAction extends ErrorAction
}
// XXX: Should these error actions even be invokable via URI?
-
+
function handle($args)
{
parent::handle($args);
@@ -84,11 +84,16 @@ class ClientErrorAction extends ErrorAction
}
$this->message = $this->trimmed('message');
-
+
if (!$this->message) {
- $this->message = "Client Error $this->code";
- }
+ $this->message = "Client Error $this->code";
+ }
$this->showPage();
}
+
+ function title()
+ {
+ return $this->status[$this->code];
+ }
}
diff --git a/lib/command.php b/lib/command.php
new file mode 100644
index 000000000..507990a0b
--- /dev/null
+++ b/lib/command.php
@@ -0,0 +1,419 @@
+<?php
+/*
+ * Laconica - a distributed open-source microblogging tool
+ * Copyright (C) 2008, Controlez-Vous, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('LACONICA')) { exit(1); }
+
+require_once(INSTALLDIR.'/lib/channel.php');
+
+class Command
+{
+
+ var $user = null;
+
+ function __construct($user=null)
+ {
+ $this->user = $user;
+ }
+
+ function execute($channel)
+ {
+ return false;
+ }
+}
+
+class UnimplementedCommand extends Command
+{
+ function execute($channel)
+ {
+ $channel->error($this->user, _("Sorry, this command is not yet implemented."));
+ }
+}
+
+class TrackingCommand extends UnimplementedCommand
+{
+}
+
+class TrackOffCommand extends UnimplementedCommand
+{
+}
+
+class TrackCommand extends UnimplementedCommand
+{
+ var $word = null;
+ function __construct($user, $word)
+ {
+ parent::__construct($user);
+ $this->word = $word;
+ }
+}
+
+class UntrackCommand extends UnimplementedCommand
+{
+ var $word = null;
+ function __construct($user, $word)
+ {
+ parent::__construct($user);
+ $this->word = $word;
+ }
+}
+
+class NudgeCommand extends UnimplementedCommand
+{
+ var $other = null;
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+}
+
+class InviteCommand extends UnimplementedCommand
+{
+ var $other = null;
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+}
+
+class StatsCommand extends Command
+{
+ function execute($channel)
+ {
+
+ $subs = new Subscription();
+ $subs->subscriber = $this->user->id;
+ $subs_count = (int) $subs->count() - 1;
+
+ $subbed = new Subscription();
+ $subbed->subscribed = $this->user->id;
+ $subbed_count = (int) $subbed->count() - 1;
+
+ $notices = new Notice();
+ $notices->profile_id = $this->user->id;
+ $notice_count = (int) $notices->count();
+
+ $channel->output($this->user, sprintf(_("Subscriptions: %1\$s\n".
+ "Subscribers: %2\$s\n".
+ "Notices: %3\$s"),
+ $subs_count,
+ $subbed_count,
+ $notice_count));
+ }
+}
+
+class FavCommand extends Command
+{
+
+ var $other = null;
+
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+
+ function execute($channel)
+ {
+
+ $recipient =
+ common_relative_profile($this->user, common_canonical_nickname($this->other));
+
+ if (!$recipient) {
+ $channel->error($this->user, _('No such user.'));
+ return;
+ }
+ $notice = $recipient->getCurrentNotice();
+ if (!$notice) {
+ $channel->error($this->user, _('User has no last notice'));
+ return;
+ }
+
+ $fave = Fave::addNew($this->user, $notice);
+
+ if (!$fave) {
+ $channel->error($this->user, _('Could not create favorite.'));
+ return;
+ }
+
+ $other = User::staticGet('id', $recipient->id);
+
+ if ($other && $other->id != $user->id) {
+ if ($other->email && $other->emailnotifyfav) {
+ mail_notify_fave($other, $this->user, $notice);
+ }
+ }
+
+ $this->user->blowFavesCache();
+
+ $channel->output($this->user, _('Notice marked as fave.'));
+ }
+}
+
+class WhoisCommand extends Command
+{
+ var $other = null;
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+
+ function execute($channel)
+ {
+ $recipient =
+ common_relative_profile($this->user, common_canonical_nickname($this->other));
+
+ if (!$recipient) {
+ $channel->error($this->user, _('No such user.'));
+ return;
+ }
+
+ $whois = sprintf(_("%1\$s (%2\$s)"), $recipient->nickname,
+ $recipient->profileurl);
+ if ($recipient->fullname) {
+ $whois .= "\n" . sprintf(_('Fullname: %s'), $recipient->fullname);
+ }
+ if ($recipient->location) {
+ $whois .= "\n" . sprintf(_('Location: %s'), $recipient->location);
+ }
+ if ($recipient->homepage) {
+ $whois .= "\n" . sprintf(_('Homepage: %s'), $recipient->homepage);
+ }
+ if ($recipient->bio) {
+ $whois .= "\n" . sprintf(_('About: %s'), $recipient->bio);
+ }
+ $channel->output($this->user, $whois);
+ }
+}
+
+class MessageCommand extends Command
+{
+ var $other = null;
+ var $text = null;
+ function __construct($user, $other, $text)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ $this->text = $text;
+ }
+
+ function execute($channel)
+ {
+ $other = User::staticGet('nickname', common_canonical_nickname($this->other));
+ $len = mb_strlen($this->text);
+ if ($len == 0) {
+ $channel->error($this->user, _('No content!'));
+ return;
+ } else if ($len > 140) {
+ $content = common_shorten_links($content);
+ if (mb_strlen($content) > 140) {
+ $channel->error($this->user, sprintf(_('Message too long - maximum is 140 characters, you sent %d'), $len));
+ return;
+ }
+ }
+
+ if (!$other) {
+ $channel->error($this->user, _('No such user.'));
+ return;
+ } else if (!$this->user->mutuallySubscribed($other)) {
+ $channel->error($this->user, _('You can\'t send a message to this user.'));
+ return;
+ } 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.'));
+ return;
+ }
+ $message = Message::saveNew($this->user->id, $other->id, $this->text, $channel->source());
+ if ($message) {
+ $channel->output($this->user, sprintf(_('Direct message to %s sent'), $this->other));
+ } else {
+ $channel->error($this->user, _('Error sending direct message.'));
+ }
+ }
+}
+
+class GetCommand extends Command
+{
+
+ var $other = null;
+
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+
+ function execute($channel)
+ {
+ $target_nickname = common_canonical_nickname($this->other);
+
+ $target =
+ common_relative_profile($this->user, $target_nickname);
+
+ if (!$target) {
+ $channel->error($this->user, _('No such user.'));
+ return;
+ }
+ $notice = $target->getCurrentNotice();
+ if (!$notice) {
+ $channel->error($this->user, _('User has no last notice'));
+ return;
+ }
+ $notice_content = $notice->content;
+
+ $channel->output($this->user, $target_nickname . ": " . $notice_content);
+ }
+}
+
+class SubCommand extends Command
+{
+
+ var $other = null;
+
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+
+ function execute($channel)
+ {
+
+ if (!$this->other) {
+ $channel->error($this->user, _('Specify the name of the user to subscribe to'));
+ return;
+ }
+
+ $result = subs_subscribe_user($this->user, $this->other);
+
+ if ($result == 'true') {
+ $channel->output($this->user, sprintf(_('Subscribed to %s'), $this->other));
+ } else {
+ $channel->error($this->user, $result);
+ }
+ }
+}
+
+class UnsubCommand extends Command
+{
+
+ var $other = null;
+
+ function __construct($user, $other)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+
+ function execute($channel)
+ {
+ if(!$this->other) {
+ $channel->error($this->user, _('Specify the name of the user to unsubscribe from'));
+ return;
+ }
+
+ $result=subs_unsubscribe_user($this->user, $this->other);
+
+ if ($result) {
+ $channel->output($this->user, sprintf(_('Unsubscribed from %s'), $this->other));
+ } else {
+ $channel->error($this->user, $result);
+ }
+ }
+}
+
+class OffCommand extends Command
+{
+ var $other = null;
+ function __construct($user, $other=null)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+ function execute($channel)
+ {
+ if ($other) {
+ $channel->error($this->user, _("Command not yet implemented."));
+ } else {
+ if ($channel->off($this->user)) {
+ $channel->output($this->user, _('Notification off.'));
+ } else {
+ $channel->error($this->user, _('Can\'t turn off notification.'));
+ }
+ }
+ }
+}
+
+class OnCommand extends Command
+{
+ var $other = null;
+ function __construct($user, $other=null)
+ {
+ parent::__construct($user);
+ $this->other = $other;
+ }
+
+ function execute($channel)
+ {
+ if ($other) {
+ $channel->error($this->user, _("Command not yet implemented."));
+ } else {
+ if ($channel->on($this->user)) {
+ $channel->output($this->user, _('Notification on.'));
+ } else {
+ $channel->error($this->user, _('Can\'t turn on notification.'));
+ }
+ }
+ }
+}
+
+class HelpCommand extends Command
+{
+ function execute($channel)
+ {
+ $channel->output($this->user,
+ _("Commands:\n".
+ "on - turn on notifications\n".
+ "off - turn off notifications\n".
+ "help - show this help\n".
+ "follow <nickname> - subscribe to user\n".
+ "leave <nickname> - unsubscribe from user\n".
+ "d <nickname> <text> - direct message to user\n".
+ "get <nickname> - get last notice from user\n".
+ "whois <nickname> - get profile info on user\n".
+ "fav <nickname> - add user's last notice as a 'fave'\n".
+ "stats - get your stats\n".
+ "stop - same as 'off'\n".
+ "quit - same as 'off'\n".
+ "sub <nickname> - same as 'follow'\n".
+ "unsub <nickname> - same as 'leave'\n".
+ "last <nickname> - same as 'get'\n".
+ "on <nickname> - not yet implemented.\n".
+ "off <nickname> - not yet implemented.\n".
+ "nudge <nickname> - not yet implemented.\n".
+ "invite <phone number> - not yet implemented.\n".
+ "track <word> - not yet implemented.\n".
+ "untrack <word> - not yet implemented.\n".
+ "track off - not yet implemented.\n".
+ "untrack all - not yet implemented.\n".
+ "tracks - not yet implemented.\n".
+ "tracking - not yet implemented.\n"));
+ }
+}
diff --git a/lib/commandinterpreter.php b/lib/commandinterpreter.php
new file mode 100644
index 000000000..49c733c03
--- /dev/null
+++ b/lib/commandinterpreter.php
@@ -0,0 +1,197 @@
+<?php
+/*
+ * Laconica - a distributed open-source microblogging tool
+ * Copyright (C) 2008, Controlez-Vous, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('LACONICA')) { exit(1); }
+
+require_once INSTALLDIR.'/lib/command.php';
+
+class CommandInterpreter
+{
+ function handle_command($user, $text)
+ {
+ # XXX: localise
+
+ $text = preg_replace('/\s+/', ' ', trim($text));
+ list($cmd, $arg) = explode(' ', $text, 2);
+
+ # We try to support all the same commands as Twitter, see
+ # http://getsatisfaction.com/twitter/topics/what_are_the_twitter_commands
+ # There are a few compatibility commands from earlier versions of
+ # Laconica
+
+ switch(strtolower($cmd)) {
+ case 'help':
+ if ($arg) {
+ return null;
+ }
+ return new HelpCommand($user);
+ case 'on':
+ if ($arg) {
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new OnCommand($user, $other);
+ }
+ } else {
+ return new OnCommand($user);
+ }
+ case 'off':
+ if ($arg) {
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new OffCommand($user, $other);
+ }
+ } else {
+ return new OffCommand($user);
+ }
+ case 'stop':
+ case 'quit':
+ if ($arg) {
+ return null;
+ } else {
+ return new OffCommand($user);
+ }
+ case 'follow':
+ case 'sub':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new SubCommand($user, $other);
+ }
+ case 'leave':
+ case 'unsub':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new UnsubCommand($user, $other);
+ }
+ case 'get':
+ case 'last':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new GetCommand($user, $other);
+ }
+ case 'd':
+ case 'dm':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if (!$extra) {
+ return null;
+ } else {
+ return new MessageCommand($user, $other, $extra);
+ }
+ case 'whois':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new WhoisCommand($user, $other);
+ }
+ case 'fav':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new FavCommand($user, $other);
+ }
+ case 'nudge':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new NudgeCommand($user, $other);
+ }
+ case 'stats':
+ if ($arg) {
+ return null;
+ }
+ return new StatsCommand($user);
+ case 'invite':
+ if (!$arg) {
+ return null;
+ }
+ list($other, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else {
+ return new InviteCommand($user, $other);
+ }
+ case 'track':
+ if (!$arg) {
+ return null;
+ }
+ list($word, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else if ($word == 'off') {
+ return new TrackOffCommand($user);
+ } else {
+ return new TrackCommand($user, $word);
+ }
+ case 'untrack':
+ if (!$arg) {
+ return null;
+ }
+ list($word, $extra) = explode(' ', $arg, 2);
+ if ($extra) {
+ return null;
+ } else if ($word == 'all') {
+ return new TrackOffCommand($user);
+ } else {
+ return new UntrackCommand($user, $word);
+ }
+ case 'tracks':
+ case 'tracking':
+ if ($arg) {
+ return null;
+ }
+ return new TrackingCommand($user);
+ default:
+ return false;
+ }
+ }
+}
+
diff --git a/lib/common.php b/lib/common.php
index 7bfd14c42..b3882d207 100644
--- a/lib/common.php
+++ b/lib/common.php
@@ -19,7 +19,7 @@
if (!defined('LACONICA')) { exit(1); }
-define('LACONICA_VERSION', '0.7.1');
+define('LACONICA_VERSION', '0.7.3');
define('AVATAR_PROFILE_SIZE', 96);
define('AVATAR_STREAM_SIZE', 48);
@@ -73,6 +73,8 @@ $config =
'theme' => 'default',
'path' => $_path,
'logfile' => null,
+ 'logo' => null,
+ 'logdebug' => false,
'fancy' => false,
'locale_path' => INSTALLDIR.'/locale',
'language' => 'en_US',
@@ -84,7 +86,10 @@ $config =
'broughtbyurl' => null,
'closed' => false,
'inviteonly' => false,
- 'private' => false),
+ 'private' => false,
+ 'ssl' => 'never',
+ 'sslserver' => null,
+ 'dupelimit' => 60), # default for same person saying the same thing
'syslog' =>
array('appname' => 'laconica', # for syslog
'priority' => 'debug'), # XXX: currently ignored
@@ -106,7 +111,8 @@ $config =
array('server' => null),
'public' =>
array('localonly' => true,
- 'blacklist' => array()),
+ 'blacklist' => array(),
+ 'autosource' => array()),
'theme' =>
array('server' => null),
'throttle' =>
@@ -137,13 +143,19 @@ $config =
'user' => false,
'group' => false),
'integration' =>
- array('source' => 'Laconica'), # source attribute for Twitter
+ array('source' => 'Laconica', # source attribute for Twitter
+ 'taguri' => $_server.',2009'), # base for tag URIs
'memcached' =>
array('enabled' => false,
'server' => 'localhost',
'port' => 11211),
+ 'ping' =>
+ array('notify' => array()),
'inboxes' =>
array('enabled' => true), # on by default for new sites
+ 'newuser' =>
+ array('subscribe' => null,
+ 'welcome' => null),
);
$config['db'] = &PEAR::getStaticProperty('DB_DataObject','options');
@@ -177,12 +189,31 @@ if (strlen($_path) > 0) {
$_config_files[] = INSTALLDIR.'/config.php';
+$_have_a_config = false;
+
foreach ($_config_files as $_config_file) {
if (file_exists($_config_file)) {
include_once($_config_file);
+ $_have_a_config = true;
}
}
+function _have_config()
+{
+ global $_have_a_config;
+ return $_have_a_config;
+}
+
+// XXX: Throw a conniption if database not installed
+
+// Fixup for laconica.ini
+
+$_db_name = substr($config['db']['database'], strrpos($config['db']['database'], '/') + 1);
+
+if ($_db_name != 'laconica' && !array_key_exists('ini_'.$_db_name, $config['db'])) {
+ $config['db']['ini_'.$_db_name] = INSTALLDIR.'/classes/laconica.ini';
+}
+
// XXX: how many of these could be auto-loaded on use?
require_once('Validate.php');
diff --git a/lib/dberroraction.php b/lib/dberroraction.php
new file mode 100644
index 000000000..0dc92490c
--- /dev/null
+++ b/lib/dberroraction.php
@@ -0,0 +1,73 @@
+<?php
+/**
+ * DB error action.
+ *
+ * PHP version 5
+ *
+ * @category Action
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @author Zach Copley <zach@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
+ * @link http://laconi.ca/
+ *
+ * Laconica - a distributed open-source microblogging tool
+ * Copyright (C) 2008, Controlez-Vous, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('LACONICA')) {
+ exit(1);
+}
+
+require_once INSTALLDIR.'/lib/servererroraction.php';
+
+/**
+ * Class for displaying DB Errors
+ *
+ * This only occurs if there's been a DB_DataObject_Error that's
+ * reported through PEAR, so we try to avoid doing anything that connects
+ * to the DB, so we don't trigger it again.
+ *
+ * @category Action
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
+ * @link http://laconi.ca/
+ */
+
+class DBErrorAction extends ServerErrorAction
+{
+ function __construct($message='Error', $code=500)
+ {
+ parent::__construct($message, $code);
+ }
+
+ function title()
+ {
+ return _('Database error');
+ }
+
+ function getLanguage()
+ {
+ // Don't try to figure out user's language; just show the page
+ return common_config('site', 'language');
+ }
+
+ function showPrimaryNav()
+ {
+ // don't show primary nav
+ }
+}
diff --git a/lib/facebookutil.php b/lib/facebookutil.php
index beab51366..ec3987273 100644
--- a/lib/facebookutil.php
+++ b/lib/facebookutil.php
@@ -25,21 +25,6 @@ define("FACEBOOK_SERVICE", 2); // Facebook is foreign_service ID 2
define("FACEBOOK_NOTICE_PREFIX", 1);
define("FACEBOOK_PROMPTED_UPDATE_PREF", 2);
-// Gets all the notices from users with a Facebook link since a given ID
-function getFacebookNotices($since)
-{
- $qry = 'SELECT notice.* ' .
- 'FROM notice ' .
- 'JOIN foreign_link ' .
- 'WHERE notice.profile_id = foreign_link.user_id ' .
- 'AND foreign_link.service = 2';
-
- // XXX: What should the limit be?
- //static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) {
-
- return Notice::getStreamDirect($qry, 0, 1000, 0, 0, null, $since);
-}
-
function getFacebook()
{
$apikey = common_config('facebook', 'apikey');
@@ -52,3 +37,97 @@ function updateProfileBox($facebook, $flink, $notice) {
$fbaction->updateProfileBox($notice);
}
+function isFacebookBound($notice, $flink) {
+
+ // If the user does not want to broadcast to Facebook, move along
+ if (!($flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
+ common_log(LOG_INFO, "Skipping notice $notice->id " .
+ 'because user has FOREIGN_NOTICE_SEND bit off.');
+ return false;
+ }
+
+ $success = false;
+
+ // If it's not a reply, or if the user WANTS to send @-replies...
+ if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
+ ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
+
+ $success = true;
+
+ // The two condition below are deal breakers:
+
+ // Avoid a loop
+ if ($notice->source == 'Facebook') {
+ common_log(LOG_INFO, "Skipping notice $notice->id because its " .
+ 'source is Facebook.');
+ $success = false;
+ }
+
+ $facebook = getFacebook();
+ $fbuid = $flink->foreign_id;
+
+ try {
+
+ // Check to see if the user has given the FB app status update perms
+ $result = $facebook->api_client->
+ users_hasAppPermission('status_update', $fbuid);
+
+ if ($result != 1) {
+ $user = $flink->getUser();
+ $msg = "Can't send notice $notice->id to Facebook " .
+ "because user $user->nickname hasn't given the " .
+ 'Facebook app \'status_update\' permission.';
+ common_log(LOG_INFO, $msg);
+ $success = false;
+ }
+
+ } catch(FacebookRestClientException $e){
+ common_log(LOG_ERR, $e->getMessage());
+ $success = false;
+ }
+
+ }
+
+ return $success;
+
+}
+
+
+function facebookBroadcastNotice($notice)
+{
+ $facebook = getFacebook();
+ $flink = Foreign_link::getByUserID($notice->profile_id, FACEBOOK_SERVICE);
+ $fbuid = $flink->foreign_id;
+
+ if (isFacebookBound($notice, $flink)) {
+
+ $status = null;
+
+ // Get the status 'verb' (prefix) the user has set
+ try {
+ $prefix = $facebook->api_client->
+ data_getUserPreference(FACEBOOK_NOTICE_PREFIX, $fbuid);
+
+ $status = "$prefix $notice->content";
+
+ } catch(FacebookRestClientException $e) {
+ common_log(LOG_ERR, $e->getMessage());
+ return false;
+ }
+
+ // Okay, we're good to go!
+
+ try {
+ $facebook->api_client->users_setStatus($status, $fbuid, false, true);
+ updateProfileBox($facebook, $flink, $notice);
+ } catch(FacebookRestClientException $e) {
+ common_log(LOG_ERR, $e->getMessage());
+ return false;
+
+ // Should we remove flink if this fails?
+ }
+
+ }
+
+ return true;
+}
diff --git a/lib/featureduserssection.php b/lib/featureduserssection.php
index 2935d8363..4b9238d47 100644
--- a/lib/featureduserssection.php
+++ b/lib/featureduserssection.php
@@ -57,9 +57,14 @@ class FeaturedUsersSection extends ProfileSection
$quoted[] = "'$nick'";
}
+ $table = "user";
+ if(common_config('db','quote_identifiers')) {
+ $table = '"' . $table . '"';
+ }
+
$qry = 'SELECT profile.* ' .
- 'FROM profile JOIN user on profile.id = user.id ' .
- 'WHERE user.nickname in (' . implode(',', $quoted) . ') ' .
+ 'FROM profile JOIN '. $table .' on profile.id = '. $table .'.id ' .
+ 'WHERE '. $table .'.nickname in (' . implode(',', $quoted) . ') ' .
'ORDER BY profile.created DESC ';
$limit = PROFILES_PER_SECTION + 1;
@@ -86,4 +91,9 @@ class FeaturedUsersSection extends ProfileSection
{
return 'featured_users';
}
+
+ function moreUrl()
+ {
+ return common_local_url('featured');
+ }
}
diff --git a/lib/feed.php b/lib/feed.php
new file mode 100644
index 000000000..466926844
--- /dev/null
+++ b/lib/feed.php
@@ -0,0 +1,110 @@
+<?php
+/**
+ * Laconica, the distributed open-source microblogging tool
+ *
+ * Data structure for info about syndication feeds (RSS 1.0, RSS 2.0, Atom)
+ *
+ * PHP version 5
+ *
+ * LICENCE: This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ *
+ * @category Feed
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @copyright 2009 Control Yourself, Inc.
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ */
+
+if (!defined('LACONICA')) {
+ exit(1);
+}
+
+/**
+ * Data structure for feeds
+ *
+ * This structure is a helpful container for shipping around information about syndication feeds.
+ *
+ * @category Feed
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @author Sarven Capadisli <csarven@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ */
+
+class Feed
+{
+ const RSS1 = 1;
+ const RSS2 = 2;
+ const ATOM = 3;
+ const FOAF = 4;
+
+ var $type = null;
+ var $url = null;
+ var $title = null;
+
+ function __construct($type, $url, $title)
+ {
+ $this->type = $type;
+ $this->url = $url;
+ $this->title = $title;
+ }
+
+ function mimeType()
+ {
+ switch ($this->type) {
+ case Feed::RSS1:
+ return 'application/rdf+xml';
+ case Feed::RSS2:
+ return 'application/rss+xml';
+ case Feed::ATOM:
+ return 'application/atom+xml';
+ case Feed::FOAF:
+ return 'application/rdf+xml';
+ default:
+ return null;
+ }
+ }
+
+ function typeName()
+ {
+ switch ($this->type) {
+ case Feed::RSS1:
+ return _('RSS 1.0');
+ case Feed::RSS2:
+ return _('RSS 2.0');
+ case Feed::ATOM:
+ return _('Atom');
+ case Feed::FOAF:
+ return _('FOAF');
+ default:
+ return null;
+ }
+ }
+
+ function rel()
+ {
+ switch ($this->type) {
+ case Feed::RSS1:
+ case Feed::RSS2:
+ case Feed::ATOM:
+ return 'alternate';
+ case Feed::FOAF:
+ return 'meta';
+ default:
+ return null;
+ }
+ }
+}
diff --git a/lib/feedlist.php b/lib/feedlist.php
index 8bfcb9c5a..927e43c33 100644
--- a/lib/feedlist.php
+++ b/lib/feedlist.php
@@ -50,7 +50,7 @@ if (!defined('LACONICA')) {
class FeedList extends Widget
{
var $action = null;
-
+
function __construct($action=null)
{
parent::__construct($action);
@@ -64,8 +64,8 @@ class FeedList extends Widget
$this->out->element('h2', null, _('Export data'));
$this->out->elementStart('ul', array('class' => 'xoxo'));
- foreach ($feeds as $key => $value) {
- $this->feedItem($feeds[$key]);
+ foreach ($feeds as $feed) {
+ $this->feedItem($feed);
}
$this->out->elementEnd('ul');
@@ -74,92 +74,27 @@ class FeedList extends Widget
function feedItem($feed)
{
- $nickname = $this->action->trimmed('nickname');
-
- switch($feed['item']) {
- case 'notices': default:
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "$nickname's ".$feed['version']." notice feed";
- $feed['textContent'] = "RSS";
- break;
-
- case 'allrss':
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = $feed['version']." feed for $nickname and friends";
- $feed['textContent'] = "RSS";
- break;
-
- case 'repliesrss':
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = $feed['version']." feed for replies to $nickname";
- $feed['textContent'] = "RSS";
- break;
-
- case 'publicrss':
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "Public timeline ".$feed['version']." feed";
- $feed['textContent'] = "RSS";
- break;
-
- case 'publicatom':
- $feed_classname = "atom";
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "Public timeline ".$feed['version']." feed";
- $feed['textContent'] = "Atom";
- break;
-
- case 'noticesearchrss':
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = $feed['version']." feed for this notice search";
- $feed['textContent'] = "RSS";
- break;
-
- case 'tagrss':
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = $feed['version']." feed for this tag";
- $feed['textContent'] = "RSS";
- break;
+ $classname = null;
- case 'favoritedrss':
- $feed_classname = $feed['type'];
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "Favorited ".$feed['version']." feed";
- $feed['textContent'] = "RSS";
+ switch ($feed->type) {
+ case Feed::RSS1:
+ case Feed::RSS2:
+ $classname = 'rss';
break;
-
- case 'foaf':
- $feed_classname = "foaf";
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "$nickname's FOAF file";
- $feed['textContent'] = "FOAF";
+ case Feed::ATOM:
+ $classname = 'atom';
break;
-
- case 'favoritesrss':
- $feed_classname = "favorites";
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "Feed for favorites of $nickname";
- $feed['textContent'] = "RSS";
- break;
-
- case 'usertimeline':
- $feed_classname = "atom";
- $feed_mimetype = "application/".$feed['type']."+xml";
- $feed_title = "$nickname's ".$feed['version']." notice feed";
- $feed['textContent'] = "Atom";
+ case Feed::FOAF:
+ $classname = 'foaf';
break;
}
+
$this->out->elementStart('li');
- $this->out->element('a', array('href' => $feed['href'],
- 'class' => $feed_classname,
- 'type' => $feed_mimetype,
- 'title' => $feed_title),
- $feed['textContent']);
+ $this->out->element('a', array('href' => $feed->url,
+ 'class' => $classname,
+ 'type' => $feed->mimeType(),
+ 'title' => $feed->title),
+ $feed->typeName());
$this->out->elementEnd('li');
}
}
diff --git a/lib/galleryaction.php b/lib/galleryaction.php
index 25a5e3fd5..8e21d7393 100644
--- a/lib/galleryaction.php
+++ b/lib/galleryaction.php
@@ -50,7 +50,7 @@ class GalleryAction extends Action
if ($this->arg('page') && $this->arg('page') != 1) {
$args['page'] = $this->arg['page'];
}
- common_redirect(common_local_url('subscriptions', $args), 301);
+ common_redirect(common_local_url($this->trimmed('action'), $args), 301);
return false;
}
@@ -71,6 +71,7 @@ class GalleryAction extends Action
$this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
$this->tag = $this->trimmed('tag');
+ $this->q = $this->trimmed('q');
return true;
}
@@ -87,7 +88,7 @@ class GalleryAction extends Action
# Post from the tag dropdown; redirect to a GET
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
- common_redirect($this->selfUrl(), 307);
+ common_redirect($this->selfUrl(), 303);
return;
}
@@ -136,7 +137,7 @@ class GalleryAction extends Action
'method' => 'post'));
$this->dropdown('tag', _('Tag'), $content,
_('Choose a tag to narrow list'), false, $tag);
- $this->submit('go', _('Go'));
+ $this->submit('submit', _('Go'));
$this->elementEnd('form');
$this->elementEnd('li');
$this->elementEnd('ul');
diff --git a/lib/grouplist.php b/lib/grouplist.php
index 4c448e250..1b8547499 100644
--- a/lib/grouplist.php
+++ b/lib/grouplist.php
@@ -124,7 +124,7 @@ class GroupList extends Widget
if ($this->group->location) {
$this->out->elementStart('dl', 'entity_location');
$this->out->element('dt', null, _('Location'));
- $this->out->elementStart('dd', 'location');
+ $this->out->elementStart('dd', 'label');
$this->out->raw($this->highlight($this->group->location));
$this->out->elementEnd('dd');
$this->out->elementEnd('dl');
@@ -151,7 +151,7 @@ class GroupList extends Widget
# If we're on a list with an owner (subscriptions or subscribers)...
- if ($user && $user->id == $this->owner->id) {
+ if (!empty($user) && !empty($this->owner) && $user->id == $this->owner->id) {
$this->showOwnerControls();
}
diff --git a/lib/groupminilist.php b/lib/groupminilist.php
index fe38d0340..ae2d237f1 100644
--- a/lib/groupminilist.php
+++ b/lib/groupminilist.php
@@ -33,7 +33,7 @@ if (!defined('LACONICA')) {
require_once INSTALLDIR.'/lib/grouplist.php';
-define('GROUPS_PER_MINILIST', 80);
+define('GROUPS_PER_MINILIST', 27);
/**
* Widget to show a list of groups, good for sidebar
@@ -75,8 +75,9 @@ class GroupMiniList extends GroupList
'href' => $this->group->homeUrl(),
'rel' => 'contact group',
'class' => 'url'));
- $logo = ($this->group->stream_logo) ?
- $this->group->stream_logo : User_group::defaultLogo(AVATAR_STREAM_SIZE);
+
+ $logo = ($this->group->mini_logo) ?
+ $this->group->mini_logo : User_group::defaultLogo(AVATAR_MINI_SIZE);
$this->out->element('img', array('src' => $logo,
'width' => AVATAR_MINI_SIZE,
diff --git a/lib/groupsbymemberssection.php b/lib/groupsbymemberssection.php
index 4fa07a244..963e21f15 100644
--- a/lib/groupsbymemberssection.php
+++ b/lib/groupsbymemberssection.php
@@ -48,7 +48,7 @@ class GroupsByMembersSection extends GroupSection
$qry = 'SELECT user_group.*, count(*) as value ' .
'FROM user_group JOIN group_member '.
'ON user_group.id = group_member.group_id ' .
- 'GROUP BY user_group.id ' .
+ 'GROUP BY user_group.id,user_group.nickname,user_group.fullname,user_group.homepage,user_group.description,user_group.location,user_group.original_logo,user_group.homepage_logo,user_group.stream_logo,user_group.mini_logo,user_group.created,user_group.modified ' .
'ORDER BY value DESC ';
$limit = GROUPS_PER_SECTION;
diff --git a/lib/groupsbypostssection.php b/lib/groupsbypostssection.php
index a5e33a93d..325b4033f 100644
--- a/lib/groupsbypostssection.php
+++ b/lib/groupsbypostssection.php
@@ -48,7 +48,7 @@ class GroupsByPostsSection extends GroupSection
$qry = 'SELECT user_group.*, count(*) as value ' .
'FROM user_group JOIN group_inbox '.
'ON user_group.id = group_inbox.group_id ' .
- 'GROUP BY user_group.id ' .
+ 'GROUP BY user_group.id,user_group.nickname,user_group.fullname,user_group.homepage,user_group.description,user_group.location,user_group.original_logo,user_group.homepage_logo,user_group.stream_logo,user_group.mini_logo,user_group.created,user_group.modified ' .
'ORDER BY value DESC ';
$limit = GROUPS_PER_SECTION;
diff --git a/lib/grouptagcloudsection.php b/lib/grouptagcloudsection.php
index f05be85cb..5d68af28b 100644
--- a/lib/grouptagcloudsection.php
+++ b/lib/grouptagcloudsection.php
@@ -58,8 +58,14 @@ class GroupTagCloudSection extends TagCloudSection
function getTags()
{
+ if (common_config('db', 'type') == 'pgsql') {
+ $weightexpr='sum(exp(-extract(epoch from (now() - notice_tag.created)) / %s))';
+ } else {
+ $weightexpr='sum(exp(-(now() - notice_tag.created) / %s))';
+ }
+
$qry = 'SELECT notice_tag.tag, '.
- 'sum(exp(-(now() - notice_tag.created)/%s)) as weight ' .
+ $weightexpr . ' as weight ' .
'FROM notice_tag JOIN notice ' .
'ON notice_tag.notice_id = notice.id ' .
'JOIN group_inbox on group_inbox.notice_id = notice.id ' .
diff --git a/lib/htmloutputter.php b/lib/htmloutputter.php
index e2319b1fd..06603ac05 100644
--- a/lib/htmloutputter.php
+++ b/lib/htmloutputter.php
@@ -101,29 +101,32 @@ class HTMLOutputter extends XMLOutputter
$type = common_negotiate_type($cp, $sp);
if (!$type) {
- common_user_error(_('This page is not available in a '.
- 'media type you accept'), 406);
- exit(0);
+ throw new ClientException(_('This page is not available in a '.
+ 'media type you accept'), 406);
}
}
header('Content-Type: '.$type);
-
+
$this->extraHeaders();
$this->startXML('html',
'-//W3C//DTD XHTML 1.0 Strict//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
- // FIXME: correct language for interface
-
- $language = common_language();
+ $language = $this->getLanguage();
$this->elementStart('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
'xml:lang' => $language,
'lang' => $language));
}
+ function getLanguage()
+ {
+ // FIXME: correct language for interface
+ return common_language();
+ }
+
/**
* Ends an HTML document
*
@@ -134,7 +137,7 @@ class HTMLOutputter extends XMLOutputter
$this->elementEnd('html');
$this->endXML();
}
-
+
/**
* To specify additional HTTP headers for the action
*
diff --git a/lib/jabber.php b/lib/jabber.php
index b385d3c5c..7d584ad01 100644
--- a/lib/jabber.php
+++ b/lib/jabber.php
@@ -114,7 +114,7 @@ function jabber_connect($resource=null)
try {
$conn->connect(true); // true = persistent connection
} catch (XMPPHP_Exception $e) {
- common_log(LOG_ERROR, $e->getMessage());
+ common_log(LOG_ERR, $e->getMessage());
return false;
}
@@ -163,50 +163,25 @@ function jabber_send_notice($to, $notice)
function jabber_format_entry($profile, $notice)
{
- // FIXME: notice url might be remote
-
- $noticeurl = common_local_url('shownotice',
- array('notice' => $notice->id));
-
- $msg = jabber_format_notice($profile, $notice);
-
- $self_url = common_local_url('userrss', array('nickname' => $profile->nickname));
-
- $entry = "\n<entry xmlns='http://www.w3.org/2005/Atom'>\n";
- $entry .= "<source>\n";
- $entry .= "<title>" . $profile->nickname . " - " . common_config('site', 'name') . "</title>\n";
- $entry .= "<link href='" . htmlspecialchars($profile->profileurl) . "'/>\n";
- $entry .= "<link rel='self' type='application/rss+xml' href='" . $self_url . "'/>\n";
- $entry .= "<author><name>" . $profile->nickname . "</name></author>\n";
- $entry .= "<icon>" . $profile->avatarUrl(AVATAR_PROFILE_SIZE) . "</icon>\n";
- $entry .= "</source>\n";
- $entry .= "<title>" . htmlspecialchars($msg) . "</title>\n";
- $entry .= "<summary>" . htmlspecialchars($msg) . "</summary>\n";
- $entry .= "<link rel='alternate' href='" . $noticeurl . "' />\n";
- $entry .= "<id>". $notice->uri . "</id>\n";
- $entry .= "<published>".common_date_w3dtf($notice->created)."</published>\n";
- $entry .= "<updated>".common_date_w3dtf($notice->modified)."</updated>\n";
- if ($notice->reply_to) {
- $replyurl = common_local_url('shownotice',
- array('notice' => $notice->reply_to));
- $entry .= "<link rel='related' href='" . $replyurl . "'/>\n";
+ $entry = $notice->asAtomEntry(true, true);
+
+ $xs = new XMLStringer();
+ $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
+ $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
+ $xs->element('a', array('href' => $profile->profileurl),
+ $profile->nickname);
+ $xs->text(": ");
+ if (!empty($notice->rendered)) {
+ $xs->raw($notice->rendered);
+ } else {
+ $xs->raw(common_render_content($notice->content, $notice));
}
- $entry .= "</entry>\n";
-
- $html = "\n<html xmlns='http://jabber.org/protocol/xhtml-im'>\n";
- $html .= "<body xmlns='http://www.w3.org/1999/xhtml'>\n";
- $html .= "<a href='".htmlspecialchars($profile->profileurl)."'>".$profile->nickname."</a>: ";
- $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice);
- $html .= "\n</body>\n";
- $html .= "\n</html>\n";
+ $xs->elementEnd('body');
+ $xs->elementEnd('html');
- $address = "<addresses xmlns='http://jabber.org/protocol/address'>\n";
- $address .= "<address type='replyto' jid='" . jabber_daemon_address() . "' />\n";
- $address .= "</addresses>\n";
+ $html = $xs->getString();
- // FIXME: include a pubsub event, too.
-
- return $html . $entry . $address;
+ return $html . ' ' . $entry;
}
/**
@@ -410,8 +385,8 @@ function jabber_broadcast_notice($notice)
"ON $UT.id = notice_inbox.user_id " .
'WHERE notice_inbox.notice_id = ' . $notice->id . ' ' .
'AND notice_inbox.source = 2 ' .
- 'AND user.jabber is not null ' .
- 'AND user.jabbernotify = 1 ');
+ "AND $UT.jabber is not null " .
+ "AND $UT.jabbernotify = 1 ");
while ($user->fetch()) {
if (!array_key_exists($user->id, $sent_to)) {
diff --git a/lib/jsonsearchresultslist.php b/lib/jsonsearchresultslist.php
new file mode 100644
index 000000000..f786c20a8
--- /dev/null
+++ b/lib/jsonsearchresultslist.php
@@ -0,0 +1,270 @@
+<?php
+/**
+ * Laconica, the distributed open-source microblogging tool
+ *
+ * widget for displaying a list of notices
+ *
+ * PHP version 5
+ *
+ * LICENCE: This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ *
+ * @category Search
+ * @package Laconica
+ * @author Zach Copley <zach@controlyourself.ca>
+ * @copyright 2009 Control Yourself, Inc.
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ */
+
+if (!defined('LACONICA')) {
+ exit(1);
+}
+
+/**
+ * widget-like class for showing JSON search results
+ *
+ * @category Search
+ * @package Laconica
+ * @author Zach Copley <zach@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ *
+ */
+
+class JSONSearchResultsList
+{
+ protected $notice; // protected attrs invisible to json_encode()
+ protected $rpp;
+
+ // The below attributes are carefully named so the JSON output from
+ // this obj matches the output from search.twitter.com
+
+ var $results;
+ var $since_id;
+ var $max_id;
+ var $refresh_url;
+ var $results_per_page;
+ var $completed_in;
+ var $page;
+ var $query;
+
+ /**
+ * constructor
+ *
+ * @param Notice $notice stream of notices from DB_DataObject
+ * @param string $query the original search query
+ * @param int $rpp the number of results to display per page
+ * @param int $page a page offset
+ * @param int $since_id only display notices newer than this
+ */
+
+ function __construct($notice, $query, $rpp, $page, $since_id = 0)
+ {
+ $this->notice = $notice;
+ $this->query = urlencode($query);
+ $this->results_per_page = $rpp;
+ $this->rpp = $rpp;
+ $this->page = $page;
+ $this->since_id = $since_id;
+ $this->results = array();
+ }
+
+ /**
+ * show the list of search results
+ *
+ * @return int $count of the search results listed.
+ */
+
+ function show()
+ {
+ $cnt = 0;
+
+ $time_start = microtime(true);
+
+ while ($this->notice->fetch() && $cnt <= $this->rpp) {
+ $cnt++;
+
+ // XXX: Hmmm. this depends on desc sort order
+ if (!$this->max_id) {
+ $this->max_id = (int)$this->notice->id;
+ }
+
+ if ($cnt > $this->rpp) {
+ break;
+ }
+
+ $item = new ResultItem($this->notice);
+ array_push($this->results, $item);
+ }
+
+ $time_end = microtime(true);
+ $this->completed_in = $time_end - $time_start;
+
+ // Set other attrs
+
+ $this->refresh_url = '?since_id=' . $this->max_id .
+ '&q=' . $this->query;
+
+ // pagination stuff
+
+ if ($cnt > $this->rpp) {
+ $this->next_page = '?page=' . ($this->page + 1) .
+ '&max_id=' . $this->max_id;
+ if ($this->rpp != 15) {
+ $this->next_page .= '&rpp=' . $this->rpp;
+ }
+ $this->next_page .= '&q=' . $this->query;
+ }
+
+ if ($this->page > 1) {
+ $this->previous_page = '?page=' . ($this->page - 1) .
+ '&max_id=' . $this->max_id;
+ if ($this->rpp != 15) {
+ $this->previous_page .= '&rpp=' . $this->rpp;
+ }
+ $this->previous_page .= '&q=' . $this->query;
+ }
+
+ print json_encode($this);
+
+ return $cnt;
+ }
+}
+
+/**
+ * widget for displaying a single JSON search result
+ *
+ * @category UI
+ * @package Laconica
+ * @author Zach Copley <zach@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ * @see JSONSearchResultsList
+ */
+
+class ResultItem
+{
+ /** The notice this item is based on. */
+
+ protected $notice; // protected attrs invisible to json_encode()
+
+ /** The profile associated with the notice. */
+
+ protected $profile;
+
+ // The below attributes are carefully named so the JSON output from
+ // this obj matches the output from search.twitter.com
+
+ var $text;
+ var $to_user_id;
+ var $to_user;
+ var $from_user;
+ var $id;
+ var $from_user_id;
+ var $iso_language_code;
+ var $source;
+ var $profile_image_url;
+ var $created_at;
+
+ /**
+ * constructor
+ *
+ * Also initializes the profile attribute.
+ *
+ * @param Notice $notice The notice we'll display
+ */
+
+ function __construct($notice)
+ {
+ $this->notice = $notice;
+ $this->profile = $notice->getProfile();
+ $this->buildResult();
+ }
+
+ /**
+ * Build a search result object
+ *
+ * This populates the the result in preparation for JSON encoding.
+ *
+ * @return void
+ */
+
+ function buildResult()
+ {
+ $this->text = $this->notice->content;
+ $replier_profile = null;
+
+ if ($this->notice->reply_to) {
+ $reply = Notice::staticGet(intval($notice->reply_to));
+ if ($reply) {
+ $replier_profile = $reply->getProfile();
+ }
+ }
+
+ $this->to_user_id = ($replier_profile) ?
+ intval($replier_profile->id) : null;
+ $this->to_user = ($replier_profile) ?
+ $replier_profile->nickname : null;
+
+ $this->from_user = $this->profile->nickname;
+ $this->id = $this->notice->id;
+ $this->from_user_id = $this->profile->id;
+
+ $user = User::staticGet('id', $this->profile->id);
+
+ $this->iso_language_code = $this->user->language;
+
+ $this->source = $this->getSourceLink($this->notice->source);
+
+ $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE);
+
+ $this->profile_image_url = ($avatar) ?
+ $avatar->displayUrl() : Avatar::defaultImage(AVATAR_STREAM_SIZE);
+
+ $this->created_at = common_date_rfc2822($this->notice->created);
+ }
+
+ /**
+ * Show the source of the notice
+ *
+ * Either the name (and link) of the API client that posted the notice,
+ * or one of other other channels.
+ *
+ * @param string $source the source of the Notice
+ *
+ * @return string a fully rendered source of the Notice
+ */
+
+ function getSourceLink($source)
+ {
+ $source_name = _($source);
+ switch ($source) {
+ case 'web':
+ case 'xmpp':
+ case 'mail':
+ case 'omb':
+ case 'api':
+ break;
+ default:
+ $ns = Notice_source::staticGet($source);
+ if ($ns) {
+ $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
+ }
+ break;
+ }
+
+ return $source_name;
+ }
+
+}
diff --git a/lib/language.php b/lib/language.php
index a73b73f28..cd6498d30 100644
--- a/lib/language.php
+++ b/lib/language.php
@@ -94,40 +94,43 @@ function get_nice_language_list()
* Get a list of all languages that are enabled in the default config
*
* This should ONLY be called when setting up the default config in common.php.
- * Any other attempt to get a list of lanugages should instead call
+ * Any other attempt to get a list of languages should instead call
* common_config('site','languages')
*
* @return array mapping of language codes to language info
*/
function get_all_languages() {
return array(
- 'bg' => array('q' => 0.8, 'lang' => 'bg_BG', 'name' => 'Bulgarian', 'direction' => 'ltr'),
- 'ca' => array('q' => 0.5, 'lang' => 'ca_ES', 'name' => 'Catalan', 'direction' => 'ltr'),
- 'cs' => array('q' => 0.5, 'lang' => 'cs_CZ', 'name' => 'Czech', 'direction' => 'ltr'),
- 'de' => array('q' => 0.5, 'lang' => 'de_DE', 'name' => 'German', 'direction' => 'ltr'),
- 'el' => array('q' => 0.1, 'lang' => 'el', 'name' => 'Greek', 'direction' => 'ltr'),
- 'en-us' => array('q' => 1, 'lang' => 'en_US', 'name' => 'English (US)', 'direction' => 'ltr'),
- 'en-gb' => array('q' => 0.3, 'lang' => 'en_GB', 'name' => 'English (British)', 'direction' => 'ltr'),
- 'en' => array('q' => 1, 'lang' => 'en', 'name' => 'English', 'direction' => 'ltr'),
- 'es' => array('q' => 0.5, 'lang' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'),
- 'fr-fr' => array('q' => 0.2, 'lang' => 'fr_FR', 'name' => 'French', 'direction' => 'ltr'),
- 'he' => array('q' => 0.5, 'lang' => 'he_IL', 'name' => 'Hebrew', 'direction' => 'ltr'),
- 'it' => array('q' => 0.9, 'lang' => 'it_IT', 'name' => 'Italian', 'direction' => 'rtl'),
- 'jp' => array('q' => 0.5, 'lang' => 'ja_JP', 'name' => 'Japanese', 'direction' => 'ltr'),
-# 'ko' => array('q' => 0, 'lang' => 'ko', 'name' => 'Korean', 'direction' => 'ltr'),
- 'mk' => array('q' => 0.5, 'lang' => 'mk_MK', 'name' => 'Macedonian', 'direction' => 'ltr'),
- 'nb' => array('q' => 0.1, 'lang' => 'nb_NO', 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'),
- 'nl' => array('q' => 0.5, 'lang' => 'nl_NL', 'name' => 'Dutch', 'direction' => 'ltr'),
- 'pl' => array('q' => 0.5, 'lang' => 'pl_PL', 'name' => 'Polish', 'direction' => 'ltr'),
-# 'pt' => array('q' => 0, 'lang' => 'pt', 'name' => 'Portuguese', 'direction' => 'ltr'),
- 'pt-br' => array('q' => 0.7, 'lang' => 'pt_BR', 'name' => 'Portuguese Brazil', 'direction' => 'ltr'),
- 'ru' => array('q' => 0.1, 'lang' => 'ru_RU', 'name' => 'Russian', 'direction' => 'ltr'),
- 'sv' => array('q' => 0.9, 'lang' => 'sv_SE', 'name' => 'Swedish', 'direction' => 'ltr'),
- 'te' => array('q' => 0.3, 'lang' => 'te_IN', 'name' => 'Telugu', 'direction' => 'ltr'),
- 'tr' => array('q' => 0.5, 'lang' => 'tr_TR', 'name' => 'Turkish', 'direction' => 'ltr'),
- 'uk' => array('q' => 0.7, 'lang' => 'uk_UA', 'name' => 'Ukrainian', 'direction' => 'ltr'),
- 'vi' => array('q' => 0.7, 'lang' => 'vi_VN', 'name' => 'Vietnamese', 'direction' => 'ltr'),
- 'zh-cn' => array('q' => 0.9, 'lang' => 'zh_CN', 'name' => 'Chinese (Simplified)', 'direction' => 'ltr'),
- 'zh-hant' => array('q' => 0.2, 'lang' => 'zh_hant', 'name' => 'Chinese (Taiwanese)', 'direction' => 'ltr'),
+ 'bg' => array('q' => 0.8, 'lang' => 'bg_BG', 'name' => 'Bulgarian', 'direction' => 'ltr'),
+ 'ca' => array('q' => 0.5, 'lang' => 'ca_ES', 'name' => 'Catalan', 'direction' => 'ltr'),
+ 'cs' => array('q' => 0.5, 'lang' => 'cs_CZ', 'name' => 'Czech', 'direction' => 'ltr'),
+ 'de' => array('q' => 0.8, 'lang' => 'de_DE', 'name' => 'German', 'direction' => 'ltr'),
+ 'el' => array('q' => 0.1, 'lang' => 'el', 'name' => 'Greek', 'direction' => 'ltr'),
+ 'en-us' => array('q' => 1, 'lang' => 'en_US', 'name' => 'English (US)', 'direction' => 'ltr'),
+ 'en-gb' => array('q' => 1, 'lang' => 'en_GB', 'name' => 'English (British)', 'direction' => 'ltr'),
+ 'en' => array('q' => 1, 'lang' => 'en', 'name' => 'English', 'direction' => 'ltr'),
+ 'es' => array('q' => 1, 'lang' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'),
+ 'fi' => array('q' => 1, 'lang' => 'fi', 'name' => 'Finnish', 'direction' => 'ltr'),
+ 'fr-fr' => array('q' => 1, 'lang' => 'fr_FR', 'name' => 'French', 'direction' => 'ltr'),
+ 'he' => array('q' => 0.5, 'lang' => 'he_IL', 'name' => 'Hebrew', 'direction' => 'rtl'),
+ 'it' => array('q' => 1, 'lang' => 'it_IT', 'name' => 'Italian', 'direction' => 'ltr'),
+ 'jp' => array('q' => 0.5, 'lang' => 'ja_JP', 'name' => 'Japanese', 'direction' => 'ltr'),
+ 'ko' => array('q' => 0.9, 'lang' => 'ko_KR', 'name' => 'Korean', 'direction' => 'ltr'),
+ 'mk' => array('q' => 0.5, 'lang' => 'mk_MK', 'name' => 'Macedonian', 'direction' => 'ltr'),
+ 'nb' => array('q' => 0.1, 'lang' => 'nb_NO', 'name' => 'Norwegian (Bokmål)', 'direction' => 'ltr'),
+ 'no' => array('q' => 0.1, 'lang' => 'nb_NO', 'name' => 'Norwegian (Bokmål)', 'direction' => 'ltr'),
+ 'nn' => array('q' => 1, 'lang' => 'nn_NO', 'name' => 'Norwegian (Nynorsk)', 'direction' => 'ltr'),
+ 'nl' => array('q' => 0.5, 'lang' => 'nl_NL', 'name' => 'Dutch', 'direction' => 'ltr'),
+ 'pl' => array('q' => 0.5, 'lang' => 'pl_PL', 'name' => 'Polish', 'direction' => 'ltr'),
+ 'pt' => array('q' => 0.1, 'lang' => 'pt', 'name' => 'Portuguese', 'direction' => 'ltr'),
+ 'pt-br' => array('q' => 0.9, 'lang' => 'pt_BR', 'name' => 'Portuguese Brazil', 'direction' => 'ltr'),
+ 'ru' => array('q' => 0.9, 'lang' => 'ru_RU', 'name' => 'Russian', 'direction' => 'ltr'),
+ 'sv' => array('q' => 0.8, 'lang' => 'sv_SE', 'name' => 'Swedish', 'direction' => 'ltr'),
+ 'te' => array('q' => 0.3, 'lang' => 'te_IN', 'name' => 'Telugu', 'direction' => 'ltr'),
+ 'tr' => array('q' => 0.5, 'lang' => 'tr_TR', 'name' => 'Turkish', 'direction' => 'ltr'),
+ 'uk' => array('q' => 1, 'lang' => 'uk_UA', 'name' => 'Ukrainian', 'direction' => 'ltr'),
+ 'vi' => array('q' => 0.8, 'lang' => 'vi_VN', 'name' => 'Vietnamese', 'direction' => 'ltr'),
+ 'zh-cn' => array('q' => 0.9, 'lang' => 'zh_CN', 'name' => 'Chinese (Simplified)', 'direction' => 'ltr'),
+ 'zh-hant' => array('q' => 0.2, 'lang' => 'zh_TW', 'name' => 'Chinese (Taiwanese)', 'direction' => 'ltr'),
);
}
diff --git a/lib/logingroupnav.php b/lib/logingroupnav.php
index fd909581f..f23985f3a 100644
--- a/lib/logingroupnav.php
+++ b/lib/logingroupnav.php
@@ -70,16 +70,16 @@ class LoginGroupNav extends Widget
function show()
{
// action => array('prompt', 'title')
- $menu =
- array('login' =>
- array(_('Login'),
- _('Login with a username and password')),
- 'register' =>
- array(_('Register'),
- _('Sign up for a new account')),
- 'openidlogin' =>
- array(_('OpenID'),
- _('Login or register with OpenID')));
+ $menu = array();
+
+ $menu['login'] = array(_('Login'),
+ _('Login with a username and password'));
+ if (!(common_config('site','closed') || common_config('site','inviteonly'))) {
+ $menu['register'] = array(_('Register'),
+ _('Sign up for a new account'));
+ }
+ $menu['openidlogin'] = array(_('OpenID'),
+ _('Login or register with OpenID'));
$action_name = $this->action->trimmed('action');
$this->action->elementStart('ul', array('class' => 'nav'));
diff --git a/lib/mail.php b/lib/mail.php
index a1faefc80..27a1d99dc 100644
--- a/lib/mail.php
+++ b/lib/mail.php
@@ -50,10 +50,9 @@ function mail_backend()
static $backend = null;
if (!$backend) {
- global $config;
- $backend = Mail::factory($config['mail']['backend'],
- ($config['mail']['params']) ?
- $config['mail']['params'] :
+ $backend = Mail::factory(common_config('mail', 'backend'),
+ (common_config('mail', 'params')) ?
+ common_config('mail', 'params') :
array());
if (PEAR::isError($backend)) {
common_server_error($backend->getMessage(), 500);
@@ -555,17 +554,19 @@ function mail_notify_fave($other, $user, $notice)
$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" .
+ "The URL of your notice is:\n\n" .
"%3\$s\n\n" .
- "You can see the list of %1\$s's favorites here:\n\n" .
+ "The text of your notice is:\n\n" .
"%4\$s\n\n" .
+ "You can see the list of %1\$s's favorites here:\n\n" .
+ "%5\$s\n\n" .
"Faithfully yours,\n" .
- "%5\$s\n"),
+ "%6\$s\n"),
$bestname,
common_exact_date($notice->created),
common_local_url('shownotice',
array('notice' => $notice->id)),
+ $notice->content,
common_local_url('showfavorites',
array('nickname' => $user->nickname)),
common_config('site', 'name'));
@@ -573,3 +574,53 @@ function mail_notify_fave($other, $user, $notice)
common_init_locale();
mail_to_user($other, $subject, $body);
}
+
+/**
+ * notify a user that they have received an "attn:" message AKA "@-reply"
+ *
+ * @param User $user The user who recevied the notice
+ * @param Notice $notice The notice that was sent
+ *
+ * @return void
+ */
+
+function mail_notify_attn($user, $notice)
+{
+ if (!$user->email || !$user->emailnotifyattn) {
+ return;
+ }
+
+ $sender = $notice->getProfile();
+
+ $bestname = $sender->getBestName();
+
+ common_init_locale($user->language);
+
+ $subject = sprintf(_('%s sent a notice to your attention'), $bestname);
+
+ $body = sprintf(_("%1\$s just sent a notice to your attention (an '@-reply') on %2\$s.\n\n".
+ "The notice is here:\n\n".
+ "\t%3\$s\n\n" .
+ "It reads:\n\n".
+ "\t%4\$s\n\n" .
+ "You can reply back here:\n\n".
+ "\t%5\$s\n\n" .
+ "The list of all @-replies for you here:\n\n" .
+ "%6\$s\n\n" .
+ "Faithfully yours,\n" .
+ "%2\$s\n\n" .
+ "P.S. You can turn off these email notifications here: %7\$s\n"),
+ $bestname,
+ common_config('site', 'name'),
+ common_local_url('shownotice',
+ array('notice' => $notice->id)),
+ $notice->content,
+ common_local_url('newnotice',
+ array('replyto' => $sender->nickname)),
+ common_local_url('replies',
+ array('nickname' => $user->nickname)),
+ common_local_url('emailsettings'));
+
+ common_init_locale();
+ mail_to_user($user, $subject, $body);
+}
diff --git a/lib/mailbox.php b/lib/mailbox.php
index d77234549..01bbf5721 100644
--- a/lib/mailbox.php
+++ b/lib/mailbox.php
@@ -137,6 +137,9 @@ class MailboxAction extends PersonalAction
$message->free();
unset($message);
}
+ else {
+ $this->element('p', 'guide', _('You have no private messages. You can send private message to engage other users in conversation. People can send you messages for your eyes only.'));
+ }
}
function getMessages()
diff --git a/lib/messageform.php b/lib/messageform.php
index f41508305..b8878ec1f 100644
--- a/lib/messageform.php
+++ b/lib/messageform.php
@@ -132,20 +132,14 @@ class MessageForm extends Form
$mutual_users->free();
unset($mutual_users);
- $this->out->elementStart('ul', 'form_data');
- $this->out->elementStart('li', array('id' => 'notice_to'));
$this->out->dropdown('to', _('To'), $mutual, null, false,
($this->to) ? $this->to->id : null);
- $this->out->elementEnd('li');
- $this->out->elementStart('li', array('id' => 'notice_text'));
$this->out->element('textarea', array('id' => 'notice_data-text',
'cols' => 35,
'rows' => 4,
'name' => 'content'),
($this->content) ? $this->content : '');
- $this->out->elementEnd('li');
- $this->out->elementEnd('ul');
}
/**
@@ -156,14 +150,10 @@ class MessageForm extends Form
function formActions()
{
- $this->out->elementStart('ul', 'form_actions');
- $this->out->elementStart('li', array('id' => 'notice_submit'));
$this->out->element('input', array('id' => 'notice_action-submit',
'class' => 'submit',
'name' => 'message_send',
'type' => 'submit',
'value' => _('Send')));
- $this->out->elementEnd('li');
- $this->out->elementEnd('ul');
}
}
diff --git a/lib/noticeform.php b/lib/noticeform.php
index 0c991c969..606b5d028 100644
--- a/lib/noticeform.php
+++ b/lib/noticeform.php
@@ -134,9 +134,6 @@ class NoticeForm extends Form
function formData()
{
-
- $this->out->elementStart('ul', 'form_data');
- $this->out->elementStart('li', array('id' => 'notice_text'));
$this->out->element('label', array('for' => 'notice_data-text'),
sprintf(_('What\'s up, %s?'), $this->user->nickname));
// XXX: vary by defined max size
@@ -145,8 +142,6 @@ class NoticeForm extends Form
'rows' => 4,
'name' => 'status_textarea'),
($this->content) ? $this->content : '');
- $this->out->elementEnd('li');
- $this->out->elementEnd('ul');
$this->out->elementStart('dl', 'form_note');
$this->out->element('dt', null, _('Available characters'));
@@ -168,14 +163,10 @@ class NoticeForm extends Form
function formActions()
{
- $this->out->elementStart('ul', 'form_actions');
- $this->out->elementStart('li', array('id' => 'notice_submit'));
$this->out->element('input', array('id' => 'notice_action-submit',
'class' => 'submit',
'name' => 'status_submit',
'type' => 'submit',
'value' => _('Send')));
- $this->out->elementEnd('li');
- $this->out->elementEnd('ul');
}
}
diff --git a/lib/noticelist.php b/lib/noticelist.php
index 9fc0126b3..4182d8808 100644
--- a/lib/noticelist.php
+++ b/lib/noticelist.php
@@ -258,8 +258,12 @@ class NoticeListItem extends Widget
function showAuthor()
{
$this->out->elementStart('span', 'vcard author');
- $this->out->elementStart('a', array('href' => $this->profile->profileurl,
- 'class' => 'url'));
+ $attrs = array('href' => $this->profile->profileurl,
+ 'class' => 'url');
+ if (!empty($this->profile->fullname)) {
+ $attrs['title'] = $this->profile->fullname . ' (' . $this->profile->nickname . ') ';
+ }
+ $this->out->elementStart('a', $attrs);
$this->showAvatar();
$this->showNickname();
$this->out->elementEnd('a');
@@ -387,6 +391,7 @@ class NoticeListItem extends Widget
case 'xmpp':
case 'mail':
case 'omb':
+ case 'system':
case 'api':
$this->out->element('dd', null, $source_name);
break;
diff --git a/lib/noticesection.php b/lib/noticesection.php
index 97b517529..94c2738ef 100644
--- a/lib/noticesection.php
+++ b/lib/noticesection.php
@@ -73,6 +73,11 @@ class NoticeSection extends Section
function showNotice($notice)
{
$profile = $notice->getProfile();
+ if (empty($profile)) {
+ common_log(LOG_WARNING, sprintf("Notice %d has no profile",
+ $notice->id));
+ return;
+ }
$this->out->elementStart('li', 'hentry notice');
$this->out->elementStart('div', 'entry-title');
$avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
@@ -96,7 +101,7 @@ class NoticeSection extends Section
$this->out->elementStart('p', 'entry-content');
$this->out->raw($notice->rendered);
$this->out->elementEnd('p');
- if ($notice->value) {
+ if (!empty($notice->value)) {
$this->out->elementStart('p');
$this->out->text($notice->value);
$this->out->elementEnd('p');
diff --git a/lib/oauthstore.php b/lib/oauthstore.php
index 7ad3be20e..183164e17 100644
--- a/lib/oauthstore.php
+++ b/lib/oauthstore.php
@@ -54,16 +54,21 @@ class LaconicaOAuthDataStore extends OAuthDataStore
}
}
+ // http://oauth.net/core/1.0/#nonce
+ // "The Consumer SHALL then generate a Nonce value that is unique for
+ // all requests with that timestamp."
+
+ // XXX: It's not clear why the token is here
+
function lookup_nonce($consumer, $token, $nonce, $timestamp)
{
$n = new Nonce();
$n->consumer_key = $consumer->key;
- $n->tok = $token->key;
+ $n->ts = $timestamp;
$n->nonce = $nonce;
if ($n->find(true)) {
return true;
} else {
- $n->timestamp = $timestamp;
$n->created = DB_DataObject_Cast::dateTime();
$n->insert();
return false;
diff --git a/lib/omb.php b/lib/omb.php
index f2dbef5ba..e8e1acc41 100644
--- a/lib/omb.php
+++ b/lib/omb.php
@@ -206,7 +206,7 @@ function omb_post_notice_keys($notice, $postnoticeurl, $tk, $secret)
$result = $fetcher->post($req->get_normalized_http_url(),
$req->to_postdata(),
- array('User-Agent' => 'Laconica/' . LACONICA_VERSION));
+ array('User-Agent: Laconica/' . LACONICA_VERSION));
common_debug('Got HTTP result "'.print_r($result,true).'"', __FILE__);
@@ -239,7 +239,7 @@ function omb_broadcast_profile($profile)
while ($sub->fetch()) {
$rp = Remote_profile::staticGet('id', $sub->subscriber);
if ($rp) {
- if (!$updated[$rp->updateprofileurl]) {
+ if (!array_key_exists($rp->updateprofileurl, $updated)) {
if (omb_update_profile($profile, $rp, $sub)) {
$updated[$rp->updateprofileurl] = true;
}
@@ -251,7 +251,6 @@ function omb_broadcast_profile($profile)
function omb_update_profile($profile, $remote_profile, $subscription)
{
- global $config; # for license URL
$user = User::staticGet($profile->id);
$con = omb_oauth_consumer();
$token = new OAuthToken($subscription->token, $subscription->secret);
@@ -291,11 +290,13 @@ function omb_update_profile($profile, $remote_profile, $subscription)
common_debug('postdata = '.$req->to_postdata(), __FILE__);
$result = $fetcher->post($req->get_normalized_http_url(),
$req->to_postdata(),
- array('User-Agent' => 'Laconica/' . LACONICA_VERSION));
+ array('User-Agent: Laconica/' . LACONICA_VERSION));
common_debug('Got HTTP result "'.print_r($result,true).'"', __FILE__);
- if ($result->status == 403) { # not authorized, don't send again
+ if (empty($result) || !$result) {
+ common_debug("Unable to contact " . $req->get_normalized_http_url());
+ } else if ($result->status == 403) { # not authorized, don't send again
common_debug('403 result, deleting subscription', __FILE__);
$subscription->delete();
return false;
@@ -304,7 +305,7 @@ function omb_update_profile($profile, $remote_profile, $subscription)
return false;
} else { # success!
parse_str($result->body, $return);
- if ($return['omb_version'] == OMB_VERSION_01) {
+ if (isset($return['omb_version']) && $return['omb_version'] === OMB_VERSION_01) {
return true;
} else {
return false;
diff --git a/lib/openid.php b/lib/openid.php
index 860573702..3af7a39cf 100644
--- a/lib/openid.php
+++ b/lib/openid.php
@@ -64,6 +64,9 @@ function oid_set_last($openid_url)
function oid_get_last()
{
+ if (empty($_COOKIE[OPENID_COOKIE_KEY])) {
+ return null;
+ }
$openid_url = $_COOKIE[OPENID_COOKIE_KEY];
if ($openid_url && strlen($openid_url) > 0) {
return $openid_url;
@@ -157,7 +160,7 @@ function oid_authenticate($openid_url, $returnto, $immediate=false)
$auth_request->addExtension($sreg_request);
}
- $trust_root = common_local_url('public');
+ $trust_root = common_root_url(true);
$process_url = common_local_url($returnto);
if ($auth_request->shouldSendRedirect()) {
@@ -168,7 +171,7 @@ function oid_authenticate($openid_url, $returnto, $immediate=false)
} else if (Auth_OpenID::isFailure($redirect_url)) {
return sprintf(_('Could not redirect to server: %s'), $redirect_url->message);
} else {
- common_redirect($redirect_url);
+ common_redirect($redirect_url, 303);
}
} else {
// Generate form markup and render it.
diff --git a/lib/peoplesearchresults.php b/lib/peoplesearchresults.php
new file mode 100644
index 000000000..f8ab7cf3b
--- /dev/null
+++ b/lib/peoplesearchresults.php
@@ -0,0 +1,75 @@
+<?php
+/**
+ * People search results class
+ *
+ * PHP version 5
+ *
+ * @category Widget
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @author Robin Millette <millette@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
+ * @link http://laconi.ca/
+ *
+ * Laconica - a distributed open-source microblogging tool
+ * Copyright (C) 2008, Controlez-Vous, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('LACONICA')) {
+ exit(1);
+}
+
+require_once INSTALLDIR.'/lib/profilelist.php';
+
+/**
+ * People search results class
+ *
+ * Derivative of ProfileList with specialization for highlighting search terms.
+ *
+ * @category Widget
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @author Robin Millette <millette@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
+ * @link http://laconi.ca/
+ *
+ * @see PeoplesearchAction
+ */
+
+class PeopleSearchResults extends ProfileList
+{
+ var $terms = null;
+ var $pattern = null;
+
+ function __construct($profile, $terms, $action)
+ {
+ parent::__construct($profile, $terms, $action);
+ $this->terms = array_map('preg_quote',
+ array_map('htmlspecialchars', $terms));
+ $this->pattern = '/('.implode('|',$terms).')/i';
+ }
+
+ function highlight($text)
+ {
+ return preg_replace($this->pattern, '<strong>\\1</strong>', htmlspecialchars($text));
+ }
+
+ function isReadOnly()
+ {
+ return true;
+ }
+}
+
diff --git a/lib/personaltagcloudsection.php b/lib/personaltagcloudsection.php
index 0882822db..978153a84 100644
--- a/lib/personaltagcloudsection.php
+++ b/lib/personaltagcloudsection.php
@@ -58,8 +58,14 @@ class PersonalTagCloudSection extends TagCloudSection
function getTags()
{
- $qry = 'SELECT notice_tag.tag, '.
- 'sum(exp(-(now() - notice_tag.created)/%s)) as weight ' .
+ if (common_config('db', 'type') == 'pgsql') {
+ $weightexpr='sum(exp(-extract(epoch from (now() - notice_tag.created)) / %s))';
+ } else {
+ $weightexpr='sum(exp(-(now() - notice_tag.created) / %s))';
+ }
+
+ $qry = 'SELECT notice_tag.tag, '.
+ $weightexpr . ' as weight ' .
'FROM notice_tag JOIN notice ' .
'ON notice_tag.notice_id = notice.id ' .
'WHERE notice.profile_id = %d ' .
diff --git a/lib/ping.php b/lib/ping.php
new file mode 100644
index 000000000..3de541e9a
--- /dev/null
+++ b/lib/ping.php
@@ -0,0 +1,122 @@
+<?php
+/*
+ * Laconica - a distributed open-source microblogging tool
+ * Copyright (C) 2009, Control Yourself, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('LACONICA')) { exit(1); }
+
+function ping_broadcast_notice($notice) {
+
+ if (!$notice->is_local) {
+ return true;
+ }
+
+ # Array of servers, URL => type
+ $notify = common_config('ping', 'notify');
+ $profile = $notice->getProfile();
+ $tags = ping_notice_tags($notice);
+
+ foreach ($notify as $notify_url => $type) {
+ switch ($type) {
+ case 'xmlrpc':
+ case 'extended':
+ $req = xmlrpc_encode_request('weblogUpdates.ping',
+ array($profile->nickname, # site name
+ common_local_url('showstream',
+ array('nickname' => $profile->nickname)),
+ common_local_url('shownotice',
+ array('notice' => $notice->id)),
+ common_local_url('userrss',
+ array('nickname' => $profile->nickname)),
+ $tags));
+
+ $context = stream_context_create(array('http' => array('method' => "POST",
+ 'header' =>
+ "Content-Type: text/xml\r\n".
+ "User-Agent: Laconica/".LACONICA_VERSION."\r\n",
+ 'content' => $req)));
+ $file = file_get_contents($notify_url, false, $context);
+
+ if ($file === false || mb_strlen($file) == 0) {
+ common_log(LOG_WARNING,
+ "XML-RPC empty results for ping ($notify_url, $notice->id) ");
+ continue;
+ }
+
+ $response = xmlrpc_decode($file);
+
+ if (xmlrpc_is_fault($response)) {
+ common_log(LOG_WARNING,
+ "XML-RPC error for ping ($notify_url, $notice->id) ".
+ "$response[faultString] ($response[faultCode])");
+ } else {
+ common_log(LOG_INFO,
+ "Ping success for $notify_url $notice->id");
+ }
+ break;
+
+ case 'get':
+ case 'post':
+ $args = array('name' => $profile->nickname,
+ 'url' => common_local_url('showstream',
+ array('nickname' => $profile->nickname)),
+ 'changesURL' => common_local_url('userrss',
+ array('nickname' => $profile->nickname)));
+
+ $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
+
+ if ($type === 'get') {
+ $result = $fetcher->get($notify_url . '?' . http_build_query($args),
+ array('User-Agent: Laconica/'.LACONICA_VERSION));
+ } else {
+ $result = $fetcher->post($notify_url,
+ http_build_query($args),
+ array('User-Agent: Laconica/'.LACONICA_VERSION));
+ }
+ if ($result->status != '200') {
+ common_log(LOG_WARNING,
+ "Ping error for '$notify_url' ($notice->id): ".
+ "$result->body");
+ } else {
+ common_log(LOG_INFO,
+ "Ping success for '$notify_url' ($notice->id): ".
+ "'$result->body'");
+ }
+ break;
+
+ default:
+ common_log(LOG_WARNING, 'Unknown notify type for ' . $notify_url . ': ' . $type);
+ }
+ }
+
+ return true;
+}
+
+function ping_notice_tags($notice) {
+ $tag = new Notice_tag();
+ $tag->notice_id = $notice->id;
+ $tags = array();
+ if ($tag->find()) {
+ while ($tag->fetch()) {
+ $tags[] = $tag->tag;
+ }
+ $tag->free();
+ unset($tag);
+ return implode('|', $tags);
+ }
+ return NULL;
+} \ No newline at end of file
diff --git a/lib/popularnoticesection.php b/lib/popularnoticesection.php
index 5734d8001..a8d47ef54 100644
--- a/lib/popularnoticesection.php
+++ b/lib/popularnoticesection.php
@@ -31,8 +31,6 @@ if (!defined('LACONICA')) {
exit(1);
}
-define('NOTICES_PER_SECTION', 5);
-
/**
* Base class for sections showing lists of notices
*
@@ -50,11 +48,28 @@ class PopularNoticeSection extends NoticeSection
{
function getNotices()
{
- $qry = 'SELECT notice.*, '.
- 'sum(exp(-(now() - fave.modified) / %s)) as weight ' .
- 'FROM notice JOIN fave ON notice.id = fave.notice_id ' .
- 'GROUP BY fave.notice_id ' .
- 'ORDER BY weight DESC';
+ if (common_config('db', 'type') == 'pgsql') {
+ $weightexpr='sum(exp(-extract(epoch from (now() - fave.modified)) / %s))';
+ if (!empty($this->out->tag)) {
+ $tag = pg_escape_string($this->tag);
+ }
+ } else {
+ $weightexpr='sum(exp(-(now() - fave.modified) / %s))';
+ if (!empty($this->out->tag)) {
+ $tag = mysql_escape_string($this->out->tag);
+ }
+ }
+ $qry = "SELECT notice.*, $weightexpr as weight ";
+ if(isset($tag)) {
+ $qry .= 'FROM notice_tag, notice JOIN fave ON notice.id = fave.notice_id ' .
+ "WHERE notice.id = notice_tag.notice_id and '$tag' = notice_tag.tag";
+ } else {
+ $qry .= 'FROM notice JOIN fave ON notice.id = fave.notice_id';
+ }
+ $qry .= ' GROUP BY notice.id,notice.profile_id,notice.content,notice.uri,' .
+ 'notice.rendered,notice.url,notice.created,notice.modified,' .
+ 'notice.reply_to,notice.is_local,notice.source ' .
+ 'ORDER BY weight DESC';
$offset = 0;
$limit = NOTICES_PER_SECTION + 1;
@@ -80,4 +95,9 @@ class PopularNoticeSection extends NoticeSection
{
return 'popular_notices';
}
+
+ function moreUrl()
+ {
+ return common_local_url('favorited');
+ }
}
diff --git a/lib/profileaction.php b/lib/profileaction.php
new file mode 100644
index 000000000..c81924e31
--- /dev/null
+++ b/lib/profileaction.php
@@ -0,0 +1,242 @@
+<?php
+/**
+ * Laconica, the distributed open-source microblogging tool
+ *
+ * Common parent of Personal and Profile actions
+ *
+ * PHP version 5
+ *
+ * LICENCE: This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ *
+ * @category Personal
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @author Sarven Capadisli <csarven@controlyourself.ca>
+ * @copyright 2008-2009 Control Yourself, Inc.
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ */
+
+if (!defined('LACONICA')) {
+ exit(1);
+}
+
+require_once INSTALLDIR.'/lib/profileminilist.php';
+require_once INSTALLDIR.'/lib/groupminilist.php';
+
+/**
+ * Profile action common superclass
+ *
+ * Abstracts out common code from profile and personal tabs
+ *
+ * @category Personal
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ */
+
+class ProfileAction extends Action
+{
+ var $user = null;
+ var $page = null;
+ var $profile = null;
+
+ function prepare($args)
+ {
+ parent::prepare($args);
+
+ $nickname_arg = $this->arg('nickname');
+ $nickname = common_canonical_nickname($nickname_arg);
+
+ // Permanent redirect on non-canonical nickname
+
+ if ($nickname_arg != $nickname) {
+ $args = array('nickname' => $nickname);
+ if ($this->arg('page') && $this->arg('page') != 1) {
+ $args['page'] = $this->arg['page'];
+ }
+ common_redirect(common_local_url($this->trimmed('action'), $args), 301);
+ return false;
+ }
+
+ $this->user = User::staticGet('nickname', $nickname);
+
+ if (!$this->user) {
+ $this->clientError(_('No such user.'), 404);
+ return false;
+ }
+
+ $this->profile = $this->user->getProfile();
+
+ if (!$this->profile) {
+ $this->serverError(_('User has no profile.'));
+ return false;
+ }
+
+ $this->page = ($this->arg('page')) ? ($this->arg('page')+0) : 1;
+
+ common_set_returnto($this->selfUrl());
+
+ return true;
+ }
+
+ function showSections()
+ {
+ $this->showSubscriptions();
+ $this->showSubscribers();
+ $this->showGroups();
+ $this->showStatistics();
+ }
+
+ function showSubscriptions()
+ {
+ $profile = $this->user->getSubscriptions(0, PROFILES_PER_MINILIST + 1);
+
+ $this->elementStart('div', array('id' => 'entity_subscriptions',
+ 'class' => 'section'));
+
+ $this->element('h2', null, _('Subscriptions'));
+
+ if ($profile) {
+ $pml = new ProfileMiniList($profile, $this->user, $this);
+ $cnt = $pml->show();
+ if ($cnt == 0) {
+ $this->element('p', null, _('(None)'));
+ }
+ }
+
+ if ($cnt > PROFILES_PER_MINILIST) {
+ $this->elementStart('p');
+ $this->element('a', array('href' => common_local_url('subscriptions',
+ array('nickname' => $this->profile->nickname)),
+ 'class' => 'more'),
+ _('All subscriptions'));
+ $this->elementEnd('p');
+ }
+
+ $this->elementEnd('div');
+ }
+
+ function showSubscribers()
+ {
+ $profile = $this->user->getSubscribers(0, PROFILES_PER_MINILIST + 1);
+
+ $this->elementStart('div', array('id' => 'entity_subscribers',
+ 'class' => 'section'));
+
+ $this->element('h2', null, _('Subscribers'));
+
+ if ($profile) {
+ $pml = new ProfileMiniList($profile, $this->user, $this);
+ $cnt = $pml->show();
+ if ($cnt == 0) {
+ $this->element('p', null, _('(None)'));
+ }
+ }
+
+ if ($cnt > PROFILES_PER_MINILIST) {
+ $this->elementStart('p');
+ $this->element('a', array('href' => common_local_url('subscribers',
+ array('nickname' => $this->profile->nickname)),
+ 'class' => 'more'),
+ _('All subscribers'));
+ $this->elementEnd('p');
+ }
+
+ $this->elementEnd('div');
+ }
+
+ function showStatistics()
+ {
+ // XXX: WORM cache this
+ $subs = new Subscription();
+ $subs->subscriber = $this->profile->id;
+ $subs_count = (int) $subs->count() - 1;
+
+ $subbed = new Subscription();
+ $subbed->subscribed = $this->profile->id;
+ $subbed_count = (int) $subbed->count() - 1;
+
+ $notices = new Notice();
+ $notices->profile_id = $this->profile->id;
+ $notice_count = (int) $notices->count();
+
+ $this->elementStart('div', array('id' => 'entity_statistics',
+ 'class' => 'section'));
+
+ $this->element('h2', null, _('Statistics'));
+
+ // Other stats...?
+ $this->elementStart('dl', 'entity_member-since');
+ $this->element('dt', null, _('Member since'));
+ $this->element('dd', null, date('j M Y',
+ strtotime($this->profile->created)));
+ $this->elementEnd('dl');
+
+ $this->elementStart('dl', 'entity_subscriptions');
+ $this->elementStart('dt');
+ $this->element('a', array('href' => common_local_url('subscriptions',
+ array('nickname' => $this->profile->nickname))),
+ _('Subscriptions'));
+ $this->elementEnd('dt');
+ $this->element('dd', null, (is_int($subs_count)) ? $subs_count : '0');
+ $this->elementEnd('dl');
+
+ $this->elementStart('dl', 'entity_subscribers');
+ $this->elementStart('dt');
+ $this->element('a', array('href' => common_local_url('subscribers',
+ array('nickname' => $this->profile->nickname))),
+ _('Subscribers'));
+ $this->elementEnd('dt');
+ $this->element('dd', 'subscribers', (is_int($subbed_count)) ? $subbed_count : '0');
+ $this->elementEnd('dl');
+
+ $this->elementStart('dl', 'entity_notices');
+ $this->element('dt', null, _('Notices'));
+ $this->element('dd', null, (is_int($notice_count)) ? $notice_count : '0');
+ $this->elementEnd('dl');
+
+ $this->elementEnd('div');
+ }
+
+ function showGroups()
+ {
+ $groups = $this->user->getGroups(0, GROUPS_PER_MINILIST + 1);
+
+ $this->elementStart('div', array('id' => 'entity_groups',
+ 'class' => 'section'));
+
+ $this->element('h2', null, _('Groups'));
+
+ if ($groups) {
+ $gml = new GroupMiniList($groups, $this->user, $this);
+ $cnt = $gml->show();
+ if ($cnt == 0) {
+ $this->element('p', null, _('(None)'));
+ }
+ }
+
+ if ($cnt > GROUPS_PER_MINILIST) {
+ $this->elementStart('p');
+ $this->element('a', array('href' => common_local_url('usergroups',
+ array('nickname' => $this->profile->nickname)),
+ 'class' => 'more'),
+ _('All groups'));
+ $this->elementEnd('p');
+ }
+
+ $this->elementEnd('div');
+ }
+} \ No newline at end of file
diff --git a/lib/profilelist.php b/lib/profilelist.php
index 4d924b039..a4cc23555 100644
--- a/lib/profilelist.php
+++ b/lib/profilelist.php
@@ -34,8 +34,6 @@ if (!defined('LACONICA')) {
require_once INSTALLDIR.'/lib/widget.php';
-define('PROFILES_PER_PAGE', 20);
-
/**
* Widget to show a list of profiles
*
@@ -91,6 +89,7 @@ class ProfileList extends Widget
'id' => 'profile-' . $this->profile->id));
$user = common_current_user();
+ $is_own = !is_null($user) && isset($this->owner) && ($user->id === $this->owner->id);
$this->out->elementStart('div', 'entity_profile vcard');
@@ -104,13 +103,13 @@ class ProfileList extends Widget
'alt' =>
($this->profile->fullname) ? $this->profile->fullname :
$this->profile->nickname));
- $hasFN = ($this->profile->fullname) ? 'nickname' : 'fn nickname';
+ $hasFN = ($this->profile->fullname !== '') ? 'nickname' : 'fn nickname';
$this->out->elementStart('span', $hasFN);
$this->out->raw($this->highlight($this->profile->nickname));
$this->out->elementEnd('span');
$this->out->elementEnd('a');
- if ($this->profile->fullname) {
+ if (!empty($this->profile->fullname)) {
$this->out->elementStart('dl', 'entity_fn');
$this->out->element('dt', null, 'Full name');
$this->out->elementStart('dd');
@@ -120,15 +119,15 @@ class ProfileList extends Widget
$this->out->elementEnd('dd');
$this->out->elementEnd('dl');
}
- if ($this->profile->location) {
+ if (!empty($this->profile->location)) {
$this->out->elementStart('dl', 'entity_location');
$this->out->element('dt', null, _('Location'));
- $this->out->elementStart('dd', 'location');
+ $this->out->elementStart('dd', 'label');
$this->out->raw($this->highlight($this->profile->location));
$this->out->elementEnd('dd');
$this->out->elementEnd('dl');
}
- if ($this->profile->homepage) {
+ if (!empty($this->profile->homepage)) {
$this->out->elementStart('dl', 'entity_url');
$this->out->element('dt', null, _('URL'));
$this->out->elementStart('dd');
@@ -139,7 +138,7 @@ class ProfileList extends Widget
$this->out->elementEnd('dd');
$this->out->elementEnd('dl');
}
- if ($this->profile->bio) {
+ if (!empty($this->profile->bio)) {
$this->out->elementStart('dl', 'entity_note');
$this->out->element('dt', null, _('Note'));
$this->out->elementStart('dd', 'note');
@@ -156,7 +155,7 @@ class ProfileList extends Widget
$this->out->elementStart('dl', 'entity_tags');
$this->out->elementStart('dt');
- if ($user->id == $this->owner->id) {
+ if ($is_own) {
$this->out->element('a', array('href' => common_local_url('tagother',
array('id' => $this->profile->id))),
_('Tags'));
@@ -185,7 +184,7 @@ class ProfileList extends Widget
$this->out->elementEnd('dl');
}
- if ($user && $user->id == $this->owner->id) {
+ if ($is_own) {
$this->showOwnerControls($this->profile);
}
@@ -195,9 +194,10 @@ class ProfileList extends Widget
$this->out->elementStart('ul');
- if ($user && $user->id != $this->profile->id) {
- # XXX: special-case for user looking at own
- # subscriptions page
+ // Is this a logged-in user, looking at someone else's
+ // profile?
+
+ if (!empty($user) && $this->profile->id != $user->id) {
$this->out->elementStart('li', 'entity_subscribe');
if ($user->isSubscribed($this->profile)) {
$usf = new UnsubscribeForm($this->out, $this->profile);
@@ -208,7 +208,7 @@ class ProfileList extends Widget
}
$this->out->elementEnd('li');
$this->out->elementStart('li', 'entity_block');
- if ($user && $user->id == $this->owner->id) {
+ if ($user->id == $this->owner->id) {
$this->showBlockForm();
}
$this->out->elementEnd('li');
diff --git a/lib/profileminilist.php b/lib/profileminilist.php
index 0d466bba8..57496d0e9 100644
--- a/lib/profileminilist.php
+++ b/lib/profileminilist.php
@@ -33,7 +33,7 @@ if (!defined('LACONICA')) {
require_once INSTALLDIR.'/lib/profilelist.php';
-define('PROFILES_PER_MINILIST', 80);
+define('PROFILES_PER_MINILIST', 27);
/**
* Widget to show a list of profiles, good for sidebar
diff --git a/lib/publicgroupnav.php b/lib/publicgroupnav.php
index d72475e20..485d25e20 100644
--- a/lib/publicgroupnav.php
+++ b/lib/publicgroupnav.php
@@ -39,6 +39,7 @@ require_once INSTALLDIR.'/lib/widget.php';
* @category Output
* @package Laconica
* @author Evan Prodromou <evan@controlyourself.ca>
+ * @author Sarven Capadisli <csarven@controlyourself.ca>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://laconi.ca/
*
@@ -73,23 +74,26 @@ class PublicGroupNav extends Widget
$this->action->elementStart('ul', array('class' => 'nav'));
- $this->out->menuItem(common_local_url('public'), _('Public'),
- _('Public timeline'), $action_name == 'public', 'nav_timeline_public');
+ if (Event::handle('StartPublicGroupNav', array($this))) {
+ $this->out->menuItem(common_local_url('public'), _('Public'),
+ _('Public timeline'), $action_name == 'public', 'nav_timeline_public');
- $this->out->menuItem(common_local_url('groups'), _('Groups'),
- _('User groups'), $action_name == 'groups', 'nav_groups');
+ $this->out->menuItem(common_local_url('groups'), _('Groups'),
+ _('User groups'), $action_name == 'groups', 'nav_groups');
- $this->out->menuItem(common_local_url('publictagcloud'), _('Recent tags'),
- _('Recent tags'), $action_name == 'publictagcloud', 'nav_recent-tags');
+ $this->out->menuItem(common_local_url('publictagcloud'), _('Recent tags'),
+ _('Recent tags'), $action_name == 'publictagcloud', 'nav_recent-tags');
- if (count(common_config('nickname', 'featured')) > 0) {
- $this->out->menuItem(common_local_url('featured'), _('Featured'),
- _('Featured users'), $action_name == 'featured', 'nav_featured');
- }
+ if (count(common_config('nickname', 'featured')) > 0) {
+ $this->out->menuItem(common_local_url('featured'), _('Featured'),
+ _('Featured users'), $action_name == 'featured', 'nav_featured');
+ }
- $this->out->menuItem(common_local_url('favorited'), _('Popular'),
- _("Popular notices"), $action_name == 'favorited', 'nav_timeline_favorited');
+ $this->out->menuItem(common_local_url('favorited'), _('Popular'),
+ _("Popular notices"), $action_name == 'favorited', 'nav_timeline_favorited');
+ Event::handle('EndPublicGroupNav', array($this));
+ }
$this->action->elementEnd('ul');
}
}
diff --git a/lib/router.php b/lib/router.php
index d47ad7118..6fb2f9487 100644
--- a/lib/router.php
+++ b/lib/router.php
@@ -47,8 +47,11 @@ require_once 'Net/URL/Mapper.php';
class Router
{
- static $m = null;
+ var $m = null;
static $inst = null;
+ static $bare = array('requesttoken', 'accesstoken', 'userauthorization',
+ 'postnotice', 'updateprofile', 'finishremotesubscribe',
+ 'finishopenidlogin', 'finishaddopenid');
static function get()
{
@@ -65,8 +68,8 @@ class Router
}
}
- function initialize() {
-
+ function initialize()
+ {
$m = Net_URL_Mapper::getInstance();
// In the "root"
@@ -98,12 +101,17 @@ class Router
$main = array('login', 'logout', 'register', 'subscribe',
'unsubscribe', 'confirmaddress', 'recoverpassword',
'invite', 'favor', 'disfavor', 'sup',
- 'tagother', 'block');
+ 'block', 'subedit');
foreach ($main as $a) {
$m->connect('main/'.$a, array('action' => $a));
}
+ $m->connect('main/sup/:seconds', array('action' => 'sup'),
+ array('seconds' => '[0-9]+'));
+
+ $m->connect('main/tagother/:id', array('action' => 'tagother'));
+
// these take a code
foreach (array('register', 'confirmaddress', 'recoverpassword') as $c) {
@@ -114,6 +122,11 @@ class Router
$m->connect('main/openid', array('action' => 'openidlogin'));
$m->connect('main/remote', array('action' => 'remotesubscribe'));
+ $m->connect('main/remote?nickname=:nickname', array('action' => 'remotesubscribe'), array('nickname' => '[A-Za-z0-9_-]+'));
+
+ foreach (Router::$bare as $action) {
+ $m->connect('index.php?action=' . $action, array('action' => $action));
+ }
// settings
@@ -126,13 +139,24 @@ class Router
foreach (array('group', 'people', 'notice') as $s) {
$m->connect('search/'.$s, array('action' => $s.'search'));
+ $m->connect('search/'.$s.'?q=:q',
+ array('action' => $s.'search'),
+ array('q' => '.+'));
}
+ // The second of these is needed to make the link work correctly
+ // when inserted into the page. The first is needed to match the
+ // route on the way in. Seems to be another Net_URL_Mapper bug to me.
$m->connect('search/notice/rss', array('action' => 'noticesearchrss'));
+ $m->connect('search/notice/rss?q=:q', array('action' => 'noticesearchrss'),
+ array('q' => '.+'));
// notice
$m->connect('notice/new', array('action' => 'newnotice'));
+ $m->connect('notice/new?replyto=:replyto',
+ array('action' => 'newnotice'),
+ array('replyto' => '[A-Za-z0-9_-]+'));
$m->connect('notice/:notice',
array('action' => 'shownotice'),
array('notice' => '[0-9]+'));
@@ -142,6 +166,7 @@ class Router
array('notice' => '[0-9]+'));
$m->connect('message/new', array('action' => 'newmessage'));
+ $m->connect('message/new?to=:to', array('action' => 'newmessage'), array('to' => '[A-Za-z0-9_-]+'));
$m->connect('message/:message',
array('action' => 'showmessage'),
array('message' => '[0-9]+'));
@@ -211,35 +236,47 @@ class Router
$m->connect('api/statuses/:method/:argument',
array('action' => 'api',
'apiaction' => 'statuses'),
- array('method' => '(user_timeline|show|destroy|friends|followers)'));
+ array('method' => '(user_timeline|friends_timeline|replies|show|destroy|friends|followers)'));
// users
- $m->connect('api/users/show/:argument',
+ $m->connect('api/users/:method/:argument',
array('action' => 'api',
- 'apiaction' => 'users'));
+ 'apiaction' => 'users'),
+ array('method' => 'show(\.(xml|json))?'));
$m->connect('api/users/:method',
array('action' => 'api',
'apiaction' => 'users'),
- array('method' => 'show(\.(xml|json|atom|rss))?'));
+ array('method' => 'show(\.(xml|json))?'));
// direct messages
- $m->connect('api/direct_messages/:method',
- array('action' => 'api',
- 'apiaction' => 'direct_messages'),
- array('method' => '(sent|new)(\.(xml|json|atom|rss))?'));
+ foreach (array('xml', 'json') as $e) {
+ $m->connect('api/direct_messages/new.'.$e,
+ array('action' => 'api',
+ 'apiaction' => 'direct_messages',
+ 'method' => 'create.'.$e));
+ }
+
+ foreach (array('xml', 'json', 'rss', 'atom') as $e) {
+ $m->connect('api/direct_messages.'.$e,
+ array('action' => 'api',
+ 'apiaction' => 'direct_messages',
+ 'method' => 'direct_messages.'.$e));
+ }
+
+ foreach (array('xml', 'json', 'rss', 'atom') as $e) {
+ $m->connect('api/direct_messages/sent.'.$e,
+ array('action' => 'api',
+ 'apiaction' => 'direct_messages',
+ 'method' => 'sent.'.$e));
+ }
$m->connect('api/direct_messages/destroy/:argument',
array('action' => 'api',
'apiaction' => 'direct_messages'));
- $m->connect('api/:method',
- array('action' => 'api',
- 'apiaction' => 'direct_messages'),
- array('method' => 'direct_messages(\.(xml|json|atom|rss))?'));
-
// friendships
$m->connect('api/friendships/:method/:argument',
@@ -250,7 +287,33 @@ class Router
$m->connect('api/friendships/:method',
array('action' => 'api',
'apiaction' => 'friendships'),
- array('method' => 'exists(\.(xml|json|rss|atom))'));
+ array('method' => 'exists(\.(xml|json))'));
+
+ // Social graph
+
+ $m->connect('api/friends/ids/:argument',
+ array('action' => 'api',
+ 'apiaction' => 'statuses',
+ 'method' => 'friendsIDs'));
+
+ foreach (array('xml', 'json') as $e) {
+ $m->connect('api/friends/ids.'.$e,
+ array('action' => 'api',
+ 'apiaction' => 'statuses',
+ 'method' => 'friendsIDs.'.$e));
+ }
+
+ $m->connect('api/followers/ids/:argument',
+ array('action' => 'api',
+ 'apiaction' => 'statuses',
+ 'method' => 'followersIDs'));
+
+ foreach (array('xml', 'json') as $e) {
+ $m->connect('api/followers/ids.'.$e,
+ array('action' => 'api',
+ 'apiaction' => 'statuses',
+ 'method' => 'followersIDs.'.$e));
+ }
// account
@@ -269,10 +332,12 @@ class Router
'apiaction' => 'favorites',
'method' => 'favorites'));
- $m->connect('api/:method',
- array('action' => 'api',
- 'apiaction' => 'favorites'),
- array('method' => 'favorites(\.(xml|json|rss|atom))?'));
+ foreach (array('xml', 'json', 'rss', 'atom') as $e) {
+ $m->connect('api/favorites.'.$e,
+ array('action' => 'api',
+ 'apiaction' => 'favorites',
+ 'method' => 'favorites.'.$e));
+ }
// notifications
@@ -298,6 +363,11 @@ class Router
array('action' => 'api',
'apiaction' => 'laconica'));
+ // search
+ $m->connect('api/search.atom', array('action' => 'twitapisearchatom'));
+ $m->connect('api/search.json', array('action' => 'twitapisearchjson'));
+ $m->connect('api/trends.json', array('action' => 'twitapitrends'));
+
// user stuff
foreach (array('subscriptions', 'subscribers',
@@ -340,15 +410,26 @@ class Router
array('action' => 'showstream'),
array('nickname' => '[a-zA-Z0-9]{1,64}'));
+ Event::handle('RouterInitialized', array($m));
+
return $m;
}
function map($path)
{
- return $this->m->match($path);
+ try {
+ $match = $this->m->match($path);
+ } catch (Net_URL_Mapper_InvalidException $e) {
+ common_log(LOG_ERR, "Problem getting route for $path - " .
+ $e->getMessage());
+ $cac = new ClientErrorAction("Page not found.", 404);
+ $cac->showPage();
+ }
+
+ return $match;
}
- function build($action, $args=null, $fragment=null)
+ function build($action, $args=null, $params=null, $fragment=null)
{
$action_arg = array('action' => $action);
@@ -358,6 +439,17 @@ class Router
$args = $action_arg;
}
- return $this->m->generate($args, null, $fragment);
+ $url = $this->m->generate($args, $params, $fragment);
+
+ // Due to a bug in the Net_URL_Mapper code, the returned URL may
+ // contain a malformed query of the form ?p1=v1?p2=v2?p3=v3. We
+ // repair that here rather than modifying the upstream code...
+
+ $qpos = strpos($url, '?');
+ if ($qpos !== false) {
+ $url = substr($url, 0, $qpos+1) .
+ str_replace('?', '&', substr($url, $qpos+1));
+ }
+ return $url;
}
-} \ No newline at end of file
+}
diff --git a/lib/rssaction.php b/lib/rssaction.php
index 131e8ac65..ddba862dc 100644
--- a/lib/rssaction.php
+++ b/lib/rssaction.php
@@ -38,6 +38,7 @@ class Rss10Action extends Action
var $creators = array();
var $limit = DEFAULT_RSS_LIMIT;
+ var $notices = null;
/**
* Constructor
@@ -93,8 +94,11 @@ class Rss10Action extends Action
function handle($args)
{
+ // Parent handling, including cache check
parent::handle($args);
- $this->showRss($this->limit);
+ // Get the list of notices
+ $this->notices = $this->getNotices($this->limit);
+ $this->showRss();
}
/**
@@ -128,15 +132,13 @@ class Rss10Action extends Action
return null;
}
- function showRss($limit=0)
+ function showRss()
{
- $notices = $this->getNotices($limit);
-
$this->initRss();
- $this->showChannel($notices);
+ $this->showChannel();
$this->showImage();
- foreach ($notices as $n) {
+ foreach ($this->notices as $n) {
$this->showItem($n);
}
@@ -144,7 +146,7 @@ class Rss10Action extends Action
$this->endRss();
}
- function showChannel($notices)
+ function showChannel()
{
$channel = $this->getChannel();
@@ -163,7 +165,7 @@ class Rss10Action extends Action
$this->elementStart('items');
$this->elementStart('rdf:Seq');
- foreach ($notices as $notice) {
+ foreach ($this->notices as $notice) {
$this->element('sioct:MicroblogPost', array('rdf:resource' => $notice->uri));
}
@@ -258,5 +260,25 @@ class Rss10Action extends Action
{
$this->elementEnd('rdf:RDF');
}
+
+ /**
+ * When was this page last modified?
+ *
+ */
+
+ function lastModified()
+ {
+ if (empty($this->notices)) {
+ return null;
+ }
+
+ if (count($this->notices) == 0) {
+ return null;
+ }
+
+ // FIXME: doesn't handle modified profiles, avatars, deleted notices
+
+ return strtotime($this->notices[0]->created);
+ }
}
diff --git a/lib/search_engines.php b/lib/search_engines.php
index 559107910..7b9dbb618 100644
--- a/lib/search_engines.php
+++ b/lib/search_engines.php
@@ -74,7 +74,7 @@ class SphinxSearch extends SearchEngine
{
//FIXME without LARGEST_POSSIBLE, the most recent results aren't returned
// this probably has a large impact on performance
- $LARGEST_POSSIBLE = 1e6;
+ $LARGEST_POSSIBLE = 1e6;
if ($rss) {
$this->sphinx->setLimits($offset, $count, $count, $LARGEST_POSSIBLE);
@@ -109,12 +109,25 @@ class MySQLSearch extends SearchEngine
{
function query($q)
{
- if ('identica_people' === $this->table)
- return $this->target->whereAdd('MATCH(nickname, fullname, location, bio, homepage) ' .
- 'against (\''.addslashes($q).'\')');
- if ('identica_notices' === $this->table)
- return $this->target->whereAdd('MATCH(content) ' .
- 'against (\''.addslashes($q).'\')');
+ if ('identica_people' === $this->table) {
+ $this->target->whereAdd('MATCH(nickname, fullname, location, bio, homepage) ' .
+ 'AGAINST (\''.addslashes($q).'\' IN BOOLEAN MODE)');
+ if (strtolower($q) != $q) {
+ $this->target->whereAdd('MATCH(nickname, fullname, location, bio, homepage) ' .
+ 'AGAINST (\''.addslashes(strtolower($q)).'\' IN BOOLEAN MODE)', 'OR');
+ }
+ return true;
+ } else if ('identica_notices' === $this->table) {
+ $this->target->whereAdd('MATCH(content) ' .
+ 'AGAINST (\''.addslashes($q).'\' IN BOOLEAN MODE)');
+ if (strtolower($q) != $q) {
+ $this->target->whereAdd('MATCH(content) ' .
+ 'AGAINST (\''.addslashes(strtolower($q)).'\' IN BOOLEAN MODE)', 'OR');
+ }
+ return true;
+ } else {
+ throw new ServerException('Unknown table: ' . $this->table);
+ }
}
}
@@ -122,10 +135,13 @@ class PGSearch extends SearchEngine
{
function query($q)
{
- if ('identica_people' === $this->table)
+ if ('identica_people' === $this->table) {
return $this->target->whereAdd('textsearch @@ plainto_tsquery(\''.addslashes($q).'\')');
- if ('identica_notices' === $this->table)
+ } else if ('identica_notices' === $this->table) {
return $this->target->whereAdd('to_tsvector(\'english\', content) @@ plainto_tsquery(\''.addslashes($q).'\')');
+ } else {
+ throw new ServerException('Unknown table: ' . $this->table);
+ }
}
}
diff --git a/lib/searchaction.php b/lib/searchaction.php
index fdfb8dc5a..e7ad4affd 100644
--- a/lib/searchaction.php
+++ b/lib/searchaction.php
@@ -79,10 +79,11 @@ class SearchAction extends Action
function showTop($arr=null)
{
+ $error = null;
if ($arr) {
$error = $arr[1];
}
- if ($error) {
+ if (!empty($error)) {
$this->element('p', 'error', $error);
} else {
$instr = $this->getInstructions();
@@ -109,8 +110,6 @@ class SearchAction extends Action
function showForm($error=null)
{
- global $config;
-
$q = $this->trimmed('q');
$page = $this->trimmed('page', 1);
$this->elementStart('form', array('method' => 'get',
@@ -121,7 +120,7 @@ class SearchAction extends Action
$this->element('legend', null, _('Search site'));
$this->elementStart('ul', 'form_data');
$this->elementStart('li');
- if (!isset($config['site']['fancy']) || !$config['site']['fancy']) {
+ if (!common_config('site', 'fancy')) {
$this->hidden('action', $this->trimmed('action'));
}
$this->input('q', 'Keyword(s)', $q);
@@ -134,5 +133,31 @@ class SearchAction extends Action
$this->showResults($q, $page);
}
}
+
+ function searchSuggestions($q) {
+ $qe = urlencode($q);
+ $message = sprintf(_(<<<E_O_T
+* Make sure all words are spelled correctly.
+* Try different keywords.
+* Try more general keywords.
+* Try fewer keywords.
+
+You can also try your search on other engines:
+
+* [Twingly](http://www.twingly.com/search?q=%s&content=microblog&site=identi.ca)
+* [Tweet scan](http://www.tweetscan.com/indexi.php?s=%s)
+* [Google](http://www.google.com/search?q=site%%3A%%%%site.server%%%%+%s)
+* [Yahoo](http://search.yahoo.com/search?p=site%%3A%%%%site.server%%%%+%s)
+
+
+E_O_T
+), $qe, $qe, $qe, $qe);
+ $this->elementStart('dl', array('id' => 'help_search', 'class' => 'help'));
+ $this->element('dt', null, _('Search help'));
+ $this->elementStart('dd', 'instructions');
+ $this->raw(common_markup_to_html($message));
+ $this->elementEnd('dd');
+ $this->elementEnd('div');
+ }
}
diff --git a/lib/section.php b/lib/section.php
index 0c32ddcf8..d14575086 100644
--- a/lib/section.php
+++ b/lib/section.php
@@ -103,6 +103,6 @@ class Section extends Widget
function moreTitle()
{
- return null;
+ return _('More...');
}
}
diff --git a/lib/servererroraction.php b/lib/servererroraction.php
index 80a3fdd7b..595dcf147 100644
--- a/lib/servererroraction.php
+++ b/lib/servererroraction.php
@@ -42,7 +42,7 @@ require_once INSTALLDIR.'/lib/error.php';
* says that 500 errors should be treated similarly to 400 errors, and
* it's easier to give an HTML response. Maybe we can customize these
* to display some funny animal cartoons. If not, we can probably role
- * these classes up into a single class.
+ * these classes up into a single class.
*
* See: http://tools.ietf.org/html/rfc2616#section-10
*
@@ -57,19 +57,19 @@ class ServerErrorAction extends ErrorAction
function __construct($message='Error', $code=500)
{
parent::__construct($message, $code);
-
+
$this->status = array(500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported');
-
+
$this->default = 500;
}
// XXX: Should these error actions even be invokable via URI?
-
+
function handle($args)
{
parent::handle($args);
@@ -81,12 +81,16 @@ class ServerErrorAction extends ErrorAction
}
$this->message = $this->trimmed('message');
-
+
if (!$this->message) {
- $this->message = "Server Error $this->code";
- }
+ $this->message = "Server Error $this->code";
+ }
$this->showPage();
}
-
+
+ function title()
+ {
+ return $this->status[$this->code];
+ }
}
diff --git a/lib/settingsaction.php b/lib/settingsaction.php
index 53c807c6f..db20c5804 100644
--- a/lib/settingsaction.php
+++ b/lib/settingsaction.php
@@ -78,9 +78,9 @@ class SettingsAction extends Action
common_set_returnto($this->selfUrl());
$user = common_current_user();
if ($user->hasOpenID()) {
- common_redirect(common_local_url('openidlogin'));
+ common_redirect(common_local_url('openidlogin'), 303);
} else {
- common_redirect(common_local_url('login'));
+ common_redirect(common_local_url('login'), 303);
}
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->handlePost();
diff --git a/lib/subgroupnav.php b/lib/subgroupnav.php
index 5fd8a72a2..31c3ea0b5 100644
--- a/lib/subgroupnav.php
+++ b/lib/subgroupnav.php
@@ -98,7 +98,7 @@ class SubGroupNav extends Widget
$this->user->nickname),
$action == 'usergroups',
'nav_usergroups');
- if ($this->user->id == $cur->id) {
+ if (!is_null($cur) && $this->user->id === $cur->id) {
$this->out->menuItem(common_local_url('invite'),
_('Invite'),
sprintf(_('Invite friends and colleagues to join you on %s'),
diff --git a/lib/topposterssection.php b/lib/topposterssection.php
index 4bd59ac79..1a2ce0014 100644
--- a/lib/topposterssection.php
+++ b/lib/topposterssection.php
@@ -51,7 +51,7 @@ class TopPostersSection extends ProfileSection
$qry = 'SELECT profile.*, count(*) as value ' .
'FROM profile JOIN notice ON profile.id = notice.profile_id ' .
(common_config('public', 'localonly') ? 'WHERE is_local = 1 ' : '') .
- 'GROUP BY profile.id ' .
+ 'GROUP BY profile.id,nickname,fullname,profileurl,homepage,bio,location,profile.created,profile.modified,textsearch ' .
'ORDER BY value DESC ';
$limit = PROFILES_PER_SECTION;
diff --git a/lib/twitter.php b/lib/twitter.php
index 197298549..ccc6c93ca 100644
--- a/lib/twitter.php
+++ b/lib/twitter.php
@@ -19,6 +19,8 @@
if (!defined('LACONICA')) { exit(1); }
+define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
+
function get_twitter_data($uri, $screen_name, $password)
{
@@ -28,14 +30,13 @@ function get_twitter_data($uri, $screen_name, $password)
CURLOPT_FAILONERROR => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
- # CURLOPT_USERAGENT => "identi.ca",
+ CURLOPT_USERAGENT => "Laconica",
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
# Twitter is strict about accepting invalid "Expect" headers
CURLOPT_HTTPHEADER => array('Expect:')
);
-
$ch = curl_init($uri);
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
@@ -44,6 +45,10 @@ function get_twitter_data($uri, $screen_name, $password)
if ($errmsg) {
common_debug("Twitter bridge - cURL error: $errmsg - trying to load: $uri with user $screen_name.",
__FILE__);
+
+ if (defined('SCRIPT_DEBUG')) {
+ print "cURL error: $errmsg - trying to load: $uri with user $screen_name.\n";
+ }
}
curl_close($ch);
@@ -51,63 +56,141 @@ function get_twitter_data($uri, $screen_name, $password)
return $data;
}
-function twitter_user_info($screen_name, $password)
+function twitter_json_data($uri, $screen_name, $password)
{
+ $json_data = get_twitter_data($uri, $screen_name, $password);
- $uri = "http://twitter.com/users/show/$screen_name.json";
- $data = get_twitter_data($uri, $screen_name, $password);
-
- if (!$data) {
+ if (!$json_data) {
return false;
}
- $twit_user = json_decode($data);
+ $data = json_decode($json_data);
- if (!$twit_user) {
+ if (!$data) {
return false;
}
- return $twit_user;
+ return $data;
+}
+
+function twitter_user_info($screen_name, $password)
+{
+ $uri = "http://twitter.com/users/show/$screen_name.json";
+ return twitter_json_data($uri, $screen_name, $password);
+}
+
+function twitter_friends_ids($screen_name, $password)
+{
+ $uri = "http://twitter.com/friends/ids/$screen_name.json";
+ return twitter_json_data($uri, $screen_name, $password);
}
-function update_twitter_user($fuser, $twitter_id, $screen_name)
+function update_twitter_user($twitter_id, $screen_name)
{
+ $uri = 'http://twitter.com/' . $screen_name;
- $original = clone($fuser);
- $fuser->nickname = $screen_name;
- $fuser->uri = 'http://twitter.com/' . $screen_name;
- $result = $fuser->updateKeys($original);
+ $fuser = new Foreign_user();
+
+ $fuser->query('BEGIN');
+
+ // Dropping down to SQL because regular db_object udpate stuff doesn't seem
+ // to work so good with tables that have multiple column primary keys
+
+ // Any time we update the uri for a forein user we have to make sure there
+ // are no dupe entries first -- unique constraint on the uri column
+
+ $qry = 'UPDATE foreign_user set uri = \'\' WHERE uri = ';
+ $qry .= '\'' . $uri . '\'' . ' AND service = ' . TWITTER_SERVICE;
+
+ $result = $fuser->query($qry);
+
+ if ($result) {
+ common_debug("Removed uri ($uri) from another foreign_user who was squatting on it.");
+ if (defined('SCRIPT_DEBUG')) {
+ print("Removed uri ($uri) from another Twitter user who was squatting on it.\n");
+ }
+ }
+
+ // Update the user
+ $qry = 'UPDATE foreign_user SET nickname = ';
+ $qry .= '\'' . $screen_name . '\'' . ', uri = \'' . $uri . '\' ';
+ $qry .= 'WHERE id = ' . $twitter_id . ' AND service = ' . TWITTER_SERVICE;
+
+ $result = $fuser->query($qry);
if (!$result) {
+ common_log(LOG_WARNING,
+ "Couldn't update foreign_user data for Twitter user: $screen_name");
common_log_db_error($fuser, 'UPDATE', __FILE__);
+ if (defined('SCRIPT_DEBUG')) {
+ print "UPDATE failed: for Twitter user: $twitter_id - $screen_name. - ";
+ print common_log_objstring($fuser) . "\n";
+ $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
+ print "DB_DataObject Error: " . $error->getMessage() . "\n";
+ }
return false;
}
+ $fuser->query('COMMIT');
+
+ $fuser->free();
+ unset($fuser);
+
return true;
}
function add_twitter_user($twitter_id, $screen_name)
{
+ $new_uri = 'http://twitter.com/' . $screen_name;
+
+ // Clear out any bad old foreign_users with the new user's legit URL
+ // This can happen when users move around or fakester accounts get
+ // repoed, and things like that.
+ $luser = new Foreign_user();
+ $luser->uri = $new_uri;
+ $luser->service = TWITTER_SERVICE;
+ $result = $luser->delete();
+
+ if ($result) {
+ common_log(LOG_WARNING,
+ "Twitter bridge - removed invalid Twitter user squatting on uri: $new_uri");
+ if (defined('SCRIPT_DEBUG')) {
+ print "Removed invalid Twitter user squatting on uri: $new_uri\n";
+ }
+ }
+
+ $luser->free();
+ unset($luser);
+
// Otherwise, create a new Twitter user
- $fuser = DB_DataObject::factory('foreign_user');
+ $fuser = new Foreign_user();
$fuser->nickname = $screen_name;
$fuser->uri = 'http://twitter.com/' . $screen_name;
$fuser->id = $twitter_id;
- $fuser->service = 1; // Twitter
+ $fuser->service = TWITTER_SERVICE;
$fuser->created = common_sql_now();
$result = $fuser->insert();
if (!$result) {
- common_debug("Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
+ common_log(LOG_WARNING,
+ "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
common_log_db_error($fuser, 'INSERT', __FILE__);
- return false;
+ if (defined('SCRIPT_DEBUG')) {
+ print "INSERT failed: could not add new Twitter user: $twitter_id - $screen_name. - ";
+ print common_log_objstring($fuser) . "\n";
+ $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
+ print "DB_DataObject Error: " . $error->getMessage() . "\n";
+ }
+ } else {
+ common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
+ if (defined('SCRIPT_DEBUG')) {
+ print "Added new Twitter user: $screen_name ($twitter_id).\n";
+ }
}
- common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
-
- return true;
+ return $result;
}
// Creates or Updates a Twitter user
@@ -116,53 +199,87 @@ function save_twitter_user($twitter_id, $screen_name)
// Check to see whether the Twitter user is already in the system,
// and update its screen name and uri if so.
- $fuser = Foreign_user::getForeignUser($twitter_id, 1);
+ $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
if ($fuser) {
+ $result = true;
+
// Only update if Twitter screen name has changed
if ($fuser->nickname != $screen_name) {
+ $result = update_twitter_user($twitter_id, $screen_name);
common_debug('Twitter bridge - Updated nickname (and URI) for Twitter user ' .
"$fuser->id to $screen_name, was $fuser->nickname");
- return update_twitter_user($fuser, $twitter_id, $screen_name);
+ if (defined('SCRIPT_DEBUG')) {
+ print 'Updated nickname (and URI) for Twitter user ' .
+ "$fuser->id to $screen_name, was $fuser->nickname\n";
+ }
}
+ return $result;
+
} else {
return add_twitter_user($twitter_id, $screen_name);
}
+ $fuser->free();
+ unset($fuser);
+
return true;
}
function retreive_twitter_friends($twitter_id, $screen_name, $password)
{
+ $friends = array();
$uri = "http://twitter.com/statuses/friends/$twitter_id.json?page=";
- $twitter_user = twitter_user_info($screen_name, $password);
+ $friends_ids = twitter_friends_ids($screen_name, $password);
+
+ if (!$friends_ids) {
+ return $friends;
+ }
+
+ if (defined('SCRIPT_DEBUG')) {
+ print "Twitter 'social graph' ids method says $screen_name has " .
+ count($friends_ids) . " friends.\n";
+ }
// Calculate how many pages to get...
- $pages = ceil($twitter_user->friends_count / 100);
+ $pages = ceil(count($friends_ids) / 100);
if ($pages == 0) {
- common_debug("Twitter bridge - Twitter user $screen_name has no friends! Lame.");
+ common_log(LOG_WARNING,
+ "Twitter bridge - $screen_name seems to have no friends.");
+ if (defined('SCRIPT_DEBUG')) {
+ print "$screen_name seems to have no friends.\n";
+ }
}
- $friends = array();
-
for ($i = 1; $i <= $pages; $i++) {
$data = get_twitter_data($uri . $i, $screen_name, $password);
if (!$data) {
- return null;
+ common_log(LOG_WARNING,
+ "Twitter bridge - Couldn't retrieve page $i of $screen_name's friends.");
+ if (defined('SCRIPT_DEBUG')) {
+ print "Couldn't retrieve page $i of $screen_name's friends.\n";
+ }
+ continue;
}
$more_friends = json_decode($data);
if (!$more_friends) {
- return null;
+
+ common_log(LOG_WARNING,
+ "Twitter bridge - No data for page $i of $screen_name's friends.");
+ if (defined('SCRIPT_DEBUG')) {
+ print "No data for page $i of $screen_name's friends.\n";
+ }
+ continue;
}
$friends = array_merge($friends, $more_friends);
@@ -176,19 +293,27 @@ function save_twitter_friends($user, $twitter_id, $screen_name, $password)
$friends = retreive_twitter_friends($twitter_id, $screen_name, $password);
- if (is_null($friends)) {
- common_debug("Twitter bridge - Couldn't get friends data from Twitter.");
+ if (empty($friends)) {
+ common_debug("Twitter bridge - Couldn't get friends data from Twitter for $screen_name.");
+ if (defined('SCRIPT_DEBUG')) {
+ print "Couldn't get friends data from Twitter for $screen_name.\n";
+ }
return false;
}
foreach ($friends as $friend) {
$friend_name = $friend->screen_name;
- $friend_id = $friend->id;
+ $friend_id = (int) $friend->id;
// Update or create the Foreign_user record
if (!save_twitter_user($friend_id, $friend_name)) {
- return false;
+ common_log(LOG_WARNING,
+ "Twitter bridge - couldn't save $screen_name's friend, $friend_name.");
+ if (defined('SCRIPT_DEBUG')) {
+ print "Couldn't save $screen_name's friend, $friend_name.\n";
+ }
+ continue;
}
// Check to see if there's a related local user
@@ -198,11 +323,111 @@ function save_twitter_friends($user, $twitter_id, $screen_name, $password)
// Get associated user and subscribe her
$friend_user = User::staticGet('id', $flink->user_id);
- subs_subscribe_to($user, $friend_user);
- common_debug("Twitter bridge - subscribed $friend_user->nickname to $user->nickname.");
+ if (!empty($friend_user)) {
+ $result = subs_subscribe_to($user, $friend_user);
+
+ if ($result === true) {
+ common_debug("Twitter bridge - subscribed $friend_user->nickname to $user->nickname.");
+ if (defined('SCRIPT_DEBUG')) {
+ print("Subscribed $friend_user->nickname to $user->nickname.\n");
+ }
+ } else {
+ if (defined('SCRIPT_DEBUG')) {
+ print "$result ($friend_user->nickname to $user->nickname)\n";
+ }
+ }
+ }
}
}
return true;
}
+function is_twitter_bound($notice, $flink) {
+
+ // Check to see if notice should go to Twitter
+ if ($flink->noticesync & FOREIGN_NOTICE_SEND) {
+
+ // If it's not a Twitter-style reply, or if the user WANTS to send replies.
+ if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
+ ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function broadcast_twitter($notice)
+{
+ $success = true;
+
+ $flink = Foreign_link::getByUserID($notice->profile_id,
+ TWITTER_SERVICE);
+
+ // XXX: Not sure WHERE to check whether a notice should go to
+ // Twitter. Should we even put in the queue if it shouldn't? --Zach
+ if (!is_null($flink) && is_twitter_bound($notice, $flink)) {
+
+ $fuser = $flink->getForeignUser();
+ $twitter_user = $fuser->nickname;
+ $twitter_password = $flink->credentials;
+ $uri = 'http://www.twitter.com/statuses/update.json';
+
+ // XXX: Hack to get around PHP cURL's use of @ being a a meta character
+ $statustxt = preg_replace('/^@/', ' @', $notice->content);
+
+ $options = array(
+ CURLOPT_USERPWD => "$twitter_user:$twitter_password",
+ CURLOPT_POST => true,
+ CURLOPT_POSTFIELDS =>
+ array(
+ 'status' => $statustxt,
+ 'source' => common_config('integration', 'source')
+ ),
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_FAILONERROR => true,
+ CURLOPT_HEADER => false,
+ CURLOPT_FOLLOWLOCATION => true,
+ CURLOPT_USERAGENT => "Laconica",
+ CURLOPT_CONNECTTIMEOUT => 120, // XXX: How long should this be?
+ CURLOPT_TIMEOUT => 120,
+
+ # Twitter is strict about accepting invalid "Expect" headers
+ CURLOPT_HTTPHEADER => array('Expect:')
+ );
+
+ $ch = curl_init($uri);
+ curl_setopt_array($ch, $options);
+ $data = curl_exec($ch);
+ $errmsg = curl_error($ch);
+
+ if ($errmsg) {
+ common_debug("cURL error: $errmsg - " .
+ "trying to send notice for $twitter_user.",
+ __FILE__);
+ $success = false;
+ }
+
+ curl_close($ch);
+
+ if (!$data) {
+ common_debug("No data returned by Twitter's " .
+ "API trying to send update for $twitter_user",
+ __FILE__);
+ $success = false;
+ }
+
+ // Twitter should return a status
+ $status = json_decode($data);
+
+ if (!$status->id) {
+ common_debug("Unexpected data returned by Twitter " .
+ " API trying to send update for $twitter_user",
+ __FILE__);
+ $success = false;
+ }
+ }
+
+ return $success;
+}
diff --git a/lib/twitterapi.php b/lib/twitterapi.php
index a4d183fcd..b8357c688 100644
--- a/lib/twitterapi.php
+++ b/lib/twitterapi.php
@@ -24,11 +24,33 @@ class TwitterapiAction extends Action
var $auth_user;
+ /**
+ * Initialization.
+ *
+ * @param array $args Web and URL arguments
+ *
+ * @return boolean false if user doesn't exist
+ */
+
+ function prepare($args)
+ {
+ parent::prepare($args);
+ return true;
+ }
+
+ /**
+ * Handle a request
+ *
+ * @param array $args Arguments from $_REQUEST
+ *
+ * @return void
+ */
+
function handle($args)
{
parent::handle($args);
}
-
+
function twitter_user_array($profile, $get_notice=false)
{
@@ -60,20 +82,34 @@ class TwitterapiAction extends Action
function twitter_status_array($notice, $include_user=true)
{
-
$profile = $notice->getProfile();
$twitter_status = array();
$twitter_status['text'] = $notice->content;
$twitter_status['truncated'] = 'false'; # Not possible on Laconica
$twitter_status['created_at'] = $this->date_twitter($notice->created);
- $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ? intval($notice->reply_to) : null;
+ $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
+ intval($notice->reply_to) : null;
$twitter_status['source'] = $this->source_link($notice->source);
$twitter_status['id'] = intval($notice->id);
- $twitter_status['in_reply_to_user_id'] = ($notice->reply_to) ? $this->replier_by_reply(intval($notice->reply_to)) : null;
+
+ $replier_profile = null;
+
+ if ($notice->reply_to) {
+ $reply = Notice::staticGet(intval($notice->reply_to));
+ if ($reply) {
+ $replier_profile = $reply->getProfile();
+ }
+ }
+
+ $twitter_status['in_reply_to_user_id'] =
+ ($replier_profile) ? intval($replier_profile->id) : null;
+ $twitter_status['in_reply_to_screen_name'] =
+ ($replier_profile) ? $replier_profile->nickname : null;
if (isset($this->auth_user)) {
- $twitter_status['favorited'] = ($this->auth_user->hasFave($notice)) ? 'true' : 'false';
+ $twitter_status['favorited'] =
+ ($this->auth_user->hasFave($notice)) ? 'true' : 'false';
} else {
$twitter_status['favorited'] = 'false';
}
@@ -91,8 +127,6 @@ class TwitterapiAction extends Action
{
$profile = $notice->getProfile();
-
- $server = common_config('site', 'server');
$entry = array();
# We trim() to avoid extraneous whitespace in the output
@@ -101,8 +135,12 @@ class TwitterapiAction extends Action
$entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
$entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
$entry['published'] = common_date_iso8601($notice->created);
- $entry['id'] = "tag:$server,2008:$entry[link]";
+
+ $taguribase = common_config('integration', 'taguri');
+ $entry['id'] = "tag:$taguribase:$entry[link]";
+
$entry['updated'] = $entry['published'];
+ $entry['author'] = $profile->getBestName();
# RSS Item specific
$entry['description'] = $entry['content'];
@@ -115,7 +153,6 @@ class TwitterapiAction extends Action
function twitter_rss_dmsg_array($message)
{
- $server = common_config('site', 'server');
$entry = array();
$entry['title'] = sprintf('Message from %s to %s',
@@ -124,8 +161,12 @@ class TwitterapiAction extends Action
$entry['content'] = common_xml_safe_str(trim($message->content));
$entry['link'] = common_local_url('showmessage', array('message' => $message->id));
$entry['published'] = common_date_iso8601($message->created);
- $entry['id'] = "tag:$server,2008:$entry[link]";
+
+ $taguribase = common_config('integration', 'taguri');
+
+ $entry['id'] = "tag:$taguribase,:$entry[link]";
$entry['updated'] = $entry['published'];
+ $entry['author'] = $message->getFrom()->getBestName();
# RSS Item specific
$entry['description'] = $entry['content'];
@@ -137,7 +178,6 @@ class TwitterapiAction extends Action
function twitter_dmsg_array($message)
{
-
$twitter_dm = array();
$from_profile = $message->getFrom();
@@ -198,18 +238,6 @@ class TwitterapiAction extends Action
$this->elementEnd('item');
}
- function show_twitter_atom_entry($entry)
- {
- $this->elementStart('entry');
- $this->element('title', null, $entry['title']);
- $this->element('content', array('type' => 'html'), $entry['content']);
- $this->element('id', null, $entry['id']);
- $this->element('published', null, $entry['published']);
- $this->element('updated', null, $entry['updated']);
- $this->element('link', array('href' => $entry['link'], 'rel' => 'alternate', 'type' => 'text/html'), null);
- $this->elementEnd('entry');
- }
-
function show_json_objects($objects)
{
print(json_encode($objects));
@@ -323,7 +351,7 @@ class TwitterapiAction extends Action
$this->end_twitter_rss();
}
- function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null)
+ function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
{
$this->init_document('atom');
@@ -331,23 +359,29 @@ class TwitterapiAction extends Action
$this->element('title', null, $title);
$this->element('id', null, $id);
$this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
+
if (!is_null($suplink)) {
# For FriendFeed's SUP protocol
$this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
'href' => $suplink,
'type' => 'application/json'));
}
+
+ if (!is_null($selfuri)) {
+ $this->element('link', array('href' => $selfuri,
+ 'rel' => 'self', 'type' => 'application/atom+xml'), null);
+ }
+
+ $this->element('updated', null, common_date_iso8601('now'));
$this->element('subtitle', null, $subtitle);
if (is_array($notice)) {
foreach ($notice as $n) {
- $entry = $this->twitter_rss_entry_array($n);
- $this->show_twitter_atom_entry($entry);
+ $this->raw($n->asAtomEntry());
}
} else {
while ($notice->fetch()) {
- $entry = $this->twitter_rss_entry_array($notice);
- $this->show_twitter_atom_entry($entry);
+ $this->raw($notice->asAtomEntry());
}
}
@@ -387,22 +421,6 @@ class TwitterapiAction extends Action
return date("D M d G:i:s O Y", $t);
}
- function replier_by_reply($reply_id)
- {
- $notice = Notice::staticGet($reply_id);
- if ($notice) {
- $profile = $notice->getProfile();
- if ($profile) {
- return intval($profile->id);
- } else {
- common_debug('Can\'t find a profile for notice: ' . $notice->id, __FILE__);
- }
- } else {
- common_debug("Can't get notice: $reply_id", __FILE__);
- }
- return null;
- }
-
// XXX: Candidate for a general utility method somewhere?
function count_subscriptions($profile)
{
@@ -543,13 +561,16 @@ class TwitterapiAction extends Action
function init_twitter_atom()
{
$this->startXML();
- $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom', 'xml:lang' => 'en-US'));
+ // FIXME: don't hardcode the language here!
+ $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
+ 'xml:lang' => 'en-US',
+ 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
}
function end_twitter_atom()
{
- $this->endXML();
$this->elementEnd('feed');
+ $this->endXML();
}
function show_profile($profile, $content_type='xml', $notice=null)
@@ -615,79 +636,4 @@ class TwitterapiAction extends Action
return $source_name;
}
- function show_extended_profile($user, $apidata)
- {
-
- $this->auth_user = $apidata['user'];
-
- $profile = $user->getProfile();
-
- if (!$profile) {
- common_server_error(_('User has no profile.'));
- return;
- }
-
- $twitter_user = $this->twitter_user_array($profile, true);
-
- // Add in extended user fields offered up by this method
- $twitter_user['created_at'] = $this->date_twitter($profile->created);
-
- $subbed = DB_DataObject::factory('subscription');
- $subbed->subscriber = $profile->id;
- $subbed_count = (int) $subbed->count() - 1;
-
- $notices = DB_DataObject::factory('notice');
- $notices->profile_id = $profile->id;
- $notice_count = (int) $notices->count();
-
- $twitter_user['friends_count'] = (is_int($subbed_count)) ? $subbed_count : 0;
- $twitter_user['statuses_count'] = (is_int($notice_count)) ? $notice_count : 0;
-
- // Other fields Twitter sends...
- $twitter_user['profile_background_color'] = '';
- $twitter_user['profile_text_color'] = '';
- $twitter_user['profile_link_color'] = '';
- $twitter_user['profile_sidebar_fill_color'] = '';
-
- $faves = DB_DataObject::factory('fave');
- $faves->user_id = $user->id;
- $faves_count = (int) $faves->count();
- $twitter_user['favourites_count'] = $faves_count;
-
- $timezone = 'UTC';
-
- if ($user->timezone) {
- $timezone = $user->timezone;
- }
-
- $t = new DateTime;
- $t->setTimezone(new DateTimeZone($timezone));
- $twitter_user['utc_offset'] = $t->format('Z');
- $twitter_user['time_zone'] = $timezone;
-
- $following = 'false';
-
- if (isset($this->auth_user)) {
- if ($this->auth_user->isSubscribed($profile)) {
- $following = 'true';
- }
-
- // Not implemented yet
- $twitter_user['notifications'] = 'false';
- }
-
- $twitter_user['following'] = $following;
-
- if ($apidata['content-type'] == 'xml') {
- $this->init_document('xml');
- $this->show_twitter_xml_user($twitter_user);
- $this->end_document('xml');
- } elseif ($apidata['content-type'] == 'json') {
- $this->init_document('json');
- $this->show_json_objects($twitter_user);
- $this->end_document('json');
- }
-
- }
-
}
diff --git a/lib/util.php b/lib/util.php
index c0c980111..675ff51f0 100644
--- a/lib/util.php
+++ b/lib/util.php
@@ -72,8 +72,7 @@ function common_timezone()
}
}
- global $config;
- return $config['site']['timezone'];
+ return common_config('site', 'timezone');
}
function common_language()
@@ -81,7 +80,7 @@ function common_language()
// If there is a user logged in and they've set a language preference
// then return that one...
- if (common_logged_in()) {
+ if (_have_config() && common_logged_in()) {
$user = common_current_user();
$user_language = $user->language;
if ($user_language)
@@ -315,6 +314,10 @@ function common_current_user()
{
global $_cur;
+ if (!_have_config()) {
+ return null;
+ }
+
if ($_cur === false) {
if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
@@ -394,20 +397,20 @@ function common_render_text($text)
function common_replace_urls_callback($text, $callback) {
// Start off with a regex
- $regex = '#
- (?:
- (?:
- (?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|xmpp|irc)://
- |
- (?:mailto|aim|tel):
- )
- [^.\s]+\.[^\s]+
- |
- (?:[^.\s/:]+\.)+
- (?:museum|travel|[a-z]{2,4})
- (?:[:/][^\s]*)?
- )
- #ix';
+ $regex = '#'.
+ '(?:'.
+ '(?:'.
+ '(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|xmpp|irc)://'.
+ '|'.
+ '(?:mailto|aim|tel):'.
+ ')'.
+ '[^.\s]+\.[^\s]+'.
+ '|'.
+ '(?:[^.\s/:]+\.)+'.
+ '(?:museum|travel|[a-z]{2,4})'.
+ '(?:[:/][^\s]*)?'.
+ ')'.
+ '#ix';
preg_match_all($regex, $text, $matches);
// Then clean up what the regex left behind
@@ -456,11 +459,14 @@ function common_replace_urls_callback($text, $callback) {
if (!in_array($url_parts[2], $tlds)) continue;
+ // Make sure we didn't capture a hash tag
+ if (strpos($url, '#') === 0) continue;
+
// Put the url back the way we found it.
$url = (mb_strpos($orig_url, htmlspecialchars($url)) === FALSE) ? $url:htmlspecialchars($url);
// Call user specified func
- $modified_url = $callback($url);
+ $modified_url = call_user_func($callback, $url);
// Replace it!
$start = mb_strpos($text, $url, $offset);
@@ -472,16 +478,19 @@ function common_replace_urls_callback($text, $callback) {
}
function common_linkify($url) {
+ // It comes in special'd, so we unspecial it before passing to the stringifying
+ // functions
+ $url = htmlspecialchars_decode($url);
$display = $url;
- $url = (!preg_match('#^([a-z]+://|(mailto|aim|tel):)#i', $url)) ? 'http://'.$url:$url;
+ $url = (!preg_match('#^([a-z]+://|(mailto|aim|tel):)#i', $url)) ? 'http://'.$url : $url;
+
+ $attrs = array('href' => $url, 'rel' => 'external');
if ($longurl = common_longurl($url)) {
- $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
- $title = "title=\"$longurl\"";
+ $attrs['title'] = $longurl;
}
- else $title = '';
- return "<a href=\"$url\" $title rel=\"external\">$display</a>";
+ return XMLStringer::estring('a', $attrs, $display);
}
function common_longurl($short_url)
@@ -572,17 +581,21 @@ function common_shorten_link($url, $reverse = false)
function common_xml_safe_str($str)
{
- $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
-
- // Replace control, formatting, and surrogate characters with '*', ala Twitter
- return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
+ // Neutralize control codes and surrogates
+ return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
}
function common_tag_link($tag)
{
$canonical = common_canonical_tag($tag);
$url = common_local_url('tag', array('tag' => $canonical));
- return '<span class="tag"><a href="' . htmlspecialchars($url) . '" rel="tag">' . htmlspecialchars($tag) . '</a></span>';
+ $xs = new XMLStringer();
+ $xs->elementStart('span', 'tag');
+ $xs->element('a', array('href' => $url,
+ 'rel' => 'tag'),
+ $tag);
+ $xs->elementEnd('span');
+ return $xs->getString();
}
function common_canonical_tag($tag)
@@ -600,7 +613,24 @@ function common_at_link($sender_id, $nickname)
$sender = Profile::staticGet($sender_id);
$recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
if ($recipient) {
- return '<span class="vcard"><a href="'.htmlspecialchars($recipient->profileurl).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
+ $user = User::staticGet('id', $recipient->id);
+ if ($user) {
+ $url = common_local_url('userbyid', array('id' => $user->id));
+ } else {
+ $url = $recipient->profileurl;
+ }
+ $xs = new XMLStringer(false);
+ $attrs = array('href' => $url,
+ 'class' => 'url');
+ if (!empty($recipient->fullname)) {
+ $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
+ }
+ $xs->elementStart('span', 'vcard');
+ $xs->elementStart('a', $attrs);
+ $xs->element('span', 'fn nickname', $nickname);
+ $xs->elementEnd('a');
+ $xs->elementEnd('span');
+ return $xs->getString();
} else {
return $nickname;
}
@@ -611,7 +641,18 @@ function common_group_link($sender_id, $nickname)
$sender = Profile::staticGet($sender_id);
$group = User_group::staticGet('nickname', common_canonical_nickname($nickname));
if ($group && $sender->isMember($group)) {
- return '<span class="vcard"><a href="'.htmlspecialchars($group->permalink()).'" class="url"><span class="fn nickname">'.$nickname.'</span></a></span>';
+ $attrs = array('href' => $group->permalink(),
+ 'class' => 'url');
+ if (!empty($group->fullname)) {
+ $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
+ }
+ $xs = new XMLStringer();
+ $xs->elementStart('span', 'vcard');
+ $xs->elementStart('a', $attrs);
+ $xs->element('span', 'fn nickname', $nickname);
+ $xs->elementEnd('a');
+ $xs->elementEnd('span');
+ return $xs->getString();
} else {
return $nickname;
}
@@ -628,7 +669,13 @@ function common_at_hash_link($sender_id, $tag)
$url = common_local_url('subscriptions',
array('nickname' => $user->nickname,
'tag' => $tag));
- return '<span class="tag"><a href="'.htmlspecialchars($url).'" rel="tag">'.$tag.'</a></span>';
+ $xs = new XMLStringer();
+ $xs->elementStart('span', 'tag');
+ $xs->element('a', array('href' => $url,
+ 'rel' => $tag),
+ $tag);
+ $xs->elementEnd('span');
+ return $xs->getString();
} else {
return $tag;
}
@@ -640,7 +687,7 @@ function common_relative_profile($sender, $nickname, $dt=null)
$recipient = new Profile();
// XXX: use a join instead of a subquery
$recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
- $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
+ $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
if ($recipient->find(true)) {
// XXX: should probably differentiate between profiles with
// the same name by date of most recent update
@@ -650,7 +697,7 @@ function common_relative_profile($sender, $nickname, $dt=null)
$recipient = new Profile();
// XXX: use a join instead of a subquery
$recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
- $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
+ $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
if ($recipient->find(true)) {
// XXX: should probably differentiate between profiles with
// the same name by date of most recent update
@@ -670,29 +717,48 @@ function common_relative_profile($sender, $nickname, $dt=null)
return null;
}
-function common_local_url($action, $args=null, $fragment=null)
+function common_local_url($action, $args=null, $params=null, $fragment=null)
{
- common_debug("Action = $action, args = " . (($args) ? '(' . implode($args, ',') . ')' : $args) . ", fragment = $fragment");
+ static $sensitive = array('login', 'register', 'passwordsettings',
+ 'twittersettings', 'finishopenidlogin',
+ 'finishaddopenid', 'api');
+
$r = Router::get();
- $start = microtime();
- $path = $r->build($action, $args, $fragment);
- $end = microtime();
- common_debug("Pathbuilding took " . ($end - $start));
- if ($path) {
- }
+ $path = $r->build($action, $args, $params, $fragment);
+
+ $ssl = in_array($action, $sensitive);
+
if (common_config('site','fancy')) {
- $url = common_path(mb_substr($path, 1));
+ $url = common_path(mb_substr($path, 1), $ssl);
} else {
- $url = common_path('index.php'.$path);
+ if (mb_strpos($path, '/index.php') === 0) {
+ $url = common_path(mb_substr($path, 1), $ssl);
+ } else {
+ $url = common_path('index.php'.$path, $ssl);
+ }
}
return $url;
}
-function common_path($relative)
+function common_path($relative, $ssl=false)
{
- global $config;
- $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
- return "http://".$config['site']['server'].'/'.$pathpart.$relative;
+ $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
+
+ if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
+ || common_config('site', 'ssl') === 'always') {
+ $proto = 'https';
+ if (is_string(common_config('site', 'sslserver')) &&
+ mb_strlen(common_config('site', 'sslserver')) > 0) {
+ $serverpart = common_config('site', 'sslserver');
+ } else {
+ $serverpart = common_config('site', 'server');
+ }
+ } else {
+ $proto = 'http';
+ $serverpart = common_config('site', 'server');
+ }
+
+ return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
}
function common_date_string($dt)
@@ -782,7 +848,7 @@ function common_redirect($url, $code=307)
303 => "See Other",
307 => "Temporary Redirect");
- header("Status: ${code} $status[$code]");
+ header('HTTP/1.1 '.$code.' '.$status[$code]);
header("Location: $url");
$xo = new XMLOutputter();
@@ -796,24 +862,6 @@ function common_redirect($url, $code=307)
function common_broadcast_notice($notice, $remote=false)
{
-
- // Check to see if notice should go to Twitter
- $flink = Foreign_link::getByUserID($notice->profile_id, 1); // 1 == Twitter
- if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
-
- // If it's not a Twitter-style reply, or if the user WANTS to send replies...
-
- if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
- (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
-
- $result = common_twitter_broadcast($notice, $flink);
-
- if (!$result) {
- common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
- }
- }
- }
-
if (common_config('queue', 'enabled')) {
// Do it later!
return common_enqueue_notice($notice);
@@ -822,73 +870,11 @@ function common_broadcast_notice($notice, $remote=false)
}
}
-function common_twitter_broadcast($notice, $flink)
-{
- global $config;
- $success = true;
- $fuser = $flink->getForeignUser();
- $twitter_user = $fuser->nickname;
- $twitter_password = $flink->credentials;
- $uri = 'http://www.twitter.com/statuses/update.json';
-
- // XXX: Hack to get around PHP cURL's use of @ being a a meta character
- $statustxt = preg_replace('/^@/', ' @', $notice->content);
-
- $options = array(
- CURLOPT_USERPWD => "$twitter_user:$twitter_password",
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => array(
- 'status' => $statustxt,
- 'source' => $config['integration']['source']
- ),
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_FAILONERROR => true,
- CURLOPT_HEADER => false,
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_USERAGENT => "Laconica",
- CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
- CURLOPT_TIMEOUT => 120,
-
- # Twitter is strict about accepting invalid "Expect" headers
- CURLOPT_HTTPHEADER => array('Expect:')
- );
-
- $ch = curl_init($uri);
- curl_setopt_array($ch, $options);
- $data = curl_exec($ch);
- $errmsg = curl_error($ch);
-
- if ($errmsg) {
- common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
- __FILE__);
- $success = false;
- }
-
- curl_close($ch);
-
- if (!$data) {
- common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
- __FILE__);
- $success = false;
- }
-
- // Twitter should return a status
- $status = json_decode($data);
-
- if (!$status->id) {
- common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
- __FILE__);
- $success = false;
- }
-
- return $success;
-}
-
// Stick the notice on the queue
function common_enqueue_notice($notice)
{
- foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
+ foreach (array('jabber', 'omb', 'sms', 'public', 'twitter', 'facebook', 'ping') as $transport) {
$qi = new Queue_item();
$qi->notice_id = $notice->id;
$qi->transport = $transport;
@@ -935,6 +921,15 @@ function common_real_broadcast($notice, $remote=false)
common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
}
}
+ if ($success) {
+ $success = broadcast_twitter($notice);
+ if (!$success) {
+ common_log(LOG_ERR, 'Error in Twitter broadcast for notice ' . $notice->id);
+ }
+ }
+
+ // XXX: Do a real-time FB broadcast here?
+
// XXX: broadcast notices to other IM
return $success;
}
@@ -955,9 +950,9 @@ function common_profile_url($nickname)
// Should make up a reasonable root URL
-function common_root_url()
+function common_root_url($ssl=false)
{
- return common_path('');
+ return common_path('', $ssl);
}
// returns $bytes bytes of random data as a hexadecimal string
@@ -1016,8 +1011,7 @@ function common_ensure_syslog()
{
static $initialized = false;
if (!$initialized) {
- global $config;
- openlog($config['syslog']['appname'], 0, LOG_USER);
+ openlog(common_config('syslog', 'appname'), 0, LOG_USER);
$initialized = true;
}
}
@@ -1327,3 +1321,16 @@ function common_compatible_license($from, $to)
// XXX: better compatibility check needed here!
return ($from == $to);
}
+
+/**
+ * returns a quoted table name, if required according to config
+ */
+function common_database_tablename($tablename)
+{
+
+ if(common_config('db','quote_identifiers')) {
+ $tablename = '"'. $tablename .'"';
+ }
+ //table prefixes could be added here later
+ return $tablename;
+} \ No newline at end of file
diff --git a/lib/xmlstringer.php b/lib/xmlstringer.php
new file mode 100644
index 000000000..951b13b67
--- /dev/null
+++ b/lib/xmlstringer.php
@@ -0,0 +1,68 @@
+<?php
+/**
+ * Laconica, the distributed open-source microblogging tool
+ *
+ * Generator for in-memory XML
+ *
+ * PHP version 5
+ *
+ * LICENCE: This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ *
+ * @category Output
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @copyright 2009 Control Yourself, Inc.
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ */
+
+if (!defined('LACONICA')) {
+ exit(1);
+}
+
+/**
+ * Create in-memory XML
+ *
+ * @category Output
+ * @package Laconica
+ * @author Evan Prodromou <evan@controlyourself.ca>
+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
+ * @link http://laconi.ca/
+ * @see Action
+ * @see HTMLOutputter
+ */
+
+class XMLStringer extends XMLOutputter
+{
+ function __construct($indent=false)
+ {
+ $this->xw = new XMLWriter();
+ $this->xw->openMemory();
+ $this->xw->setIndent($indent);
+ }
+
+ function getString()
+ {
+ return $this->xw->outputMemory();
+ }
+
+ // utility for quickly creating XML-strings
+
+ static function estring($tag, $attrs=null, $content=null)
+ {
+ $xs = new XMLStringer();
+ $xs->element($tag, $attrs, $content);
+ return $xs->getString();
+ }
+} \ No newline at end of file