From d18c621bcf038f172141bd302911a313e6f5c30b Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Fri, 12 Dec 2008 12:11:35 -0500 Subject: more information in subscription notices darcs-hash:20081212171135-84dde-543176e3a8190699e44fc896ba90f6ea776057d4.gz --- lib/mail.php | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) (limited to 'lib') diff --git a/lib/mail.php b/lib/mail.php index a7cbab858..c90140d3c 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -112,16 +112,25 @@ function mail_subscribe_notify_profile($listenee, $other) { $recipients = $listenee->email; $headers['From'] = mail_notify_from(); $headers['To'] = $name . ' <' . $listenee->email . '>'; - $headers['Subject'] = sprintf(_('%1$s is now listening to your notices on %2$s.'), $other->getBestName(), + $headers['Subject'] = sprintf(_('%1$s is now listening to your notices on %2$s.'), + $other->getBestName(), common_config('site', 'name')); $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". "\t".'%3$s'."\n\n". - 'Faithfully yours,'."\n".'%4$s.'."\n"), - $long_name, - common_config('site', 'name'), - $other->profileurl, - common_config('site', 'name')); - + '%4$s'. + '%5$s'. + '%6$s'. + "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". + "----\n". + "Change your email address or notification options at %8$s"), + $long_name, + common_config('site', 'name'), + $other->profileurl, + ($other->location) ? sprintf(_("Location: %s\n"), $other->location) : '', + ($other->homepage) ? sprintf(_("Homepage: %s\n"), $other->homepage) : '', + ($other->bio) ? sprintf(_("Bio: %s\n\n"), $other->bio) : '', + common_config('site', 'name'), + common_local_url('emailsettings')); // reset localization common_init_locale(); mail_send($recipients, $headers, $body); -- cgit v1.2.3-54-g00ecf From ee4db3d21c17928913566d6a2b65cb36b677fa73 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sat, 20 Dec 2008 19:30:16 -0500 Subject: reformatting for phpcs in lib/util.php darcs-hash:20081221003016-84dde-0e80268e95235462e069d4d1e6b949bc891ccdbd.gz --- _darcs/inventory | 4 +- ...dde-0e80268e95235462e069d4d1e6b949bc891ccdbd.gz | Bin 0 -> 22612 bytes _darcs/pristine/lib/util.php | 3273 ++++++++++--------- _darcs/tentative_pristine | 3418 +++++++++++++++++++- lib/util.php | 3273 ++++++++++--------- 5 files changed, 6642 insertions(+), 3326 deletions(-) create mode 100644 _darcs/patches/20081221003016-84dde-0e80268e95235462e069d4d1e6b949bc891ccdbd.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 49dc7559d..83b5a479f 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -21,4 +21,6 @@ Sarven Capadisli **20081218003302 [more information in subscription notices Evan Prodromou **20081212171135] [first step of phpcs-cleanup of index.php -Evan Prodromou **20081221002332] \ No newline at end of file +Evan Prodromou **20081221002332] +[reformatting for phpcs in lib/util.php +Evan Prodromou **20081221003016] \ No newline at end of file diff --git a/_darcs/patches/20081221003016-84dde-0e80268e95235462e069d4d1e6b949bc891ccdbd.gz b/_darcs/patches/20081221003016-84dde-0e80268e95235462e069d4d1e6b949bc891ccdbd.gz new file mode 100644 index 000000000..344e0693f Binary files /dev/null and b/_darcs/patches/20081221003016-84dde-0e80268e95235462e069d4d1e6b949bc891ccdbd.gz differ diff --git a/_darcs/pristine/lib/util.php b/_darcs/pristine/lib/util.php index 8eeda1115..f0387ebe5 100644 --- a/_darcs/pristine/lib/util.php +++ b/_darcs/pristine/lib/util.php @@ -19,116 +19,116 @@ /* XXX: break up into separate modules (HTTP, HTML, user, files) */ -# Show a server error +// Show a server error function common_server_error($msg, $code=500) { - static $status = array(500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported'); - - if (!array_key_exists($code, $status)) { - $code = 500; - } + static $status = array(500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported'); + + if (!array_key_exists($code, $status)) { + $code = 500; + } - $status_string = $status[$code]; + $status_string = $status[$code]; - header('HTTP/1.1 '.$code.' '.$status_string); - header('Content-type: text/plain'); + header('HTTP/1.1 '.$code.' '.$status_string); + header('Content-type: text/plain'); - print $msg; - print "\n"; - exit(); + print $msg; + print "\n"; + exit(); } -# Show a user error +// Show a user error function common_user_error($msg, $code=400) { - static $status = array(400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed'); - - if (!array_key_exists($code, $status)) { - $code = 400; - } - - $status_string = $status[$code]; - - header('HTTP/1.1 '.$code.' '.$status_string); - - common_show_header('Error'); - common_element('div', array('class' => 'error'), $msg); - common_show_footer(); + static $status = array(400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed'); + + if (!array_key_exists($code, $status)) { + $code = 400; + } + + $status_string = $status[$code]; + + header('HTTP/1.1 '.$code.' '.$status_string); + + common_show_header('Error'); + common_element('div', array('class' => 'error'), $msg); + common_show_footer(); } $xw = null; -# Start an HTML element -function common_element_start($tag, $attrs=NULL) { - global $xw; - $xw->startElement($tag); - if (is_array($attrs)) { - foreach ($attrs as $name => $value) { - $xw->writeAttribute($name, $value); - } - } else if (is_string($attrs)) { - $xw->writeAttribute('class', $attrs); - } +// Start an HTML element +function common_element_start($tag, $attrs=null) { + global $xw; + $xw->startElement($tag); + if (is_array($attrs)) { + foreach ($attrs as $name => $value) { + $xw->writeAttribute($name, $value); + } + } else if (is_string($attrs)) { + $xw->writeAttribute('class', $attrs); + } } function common_element_end($tag) { - static $empty_tag = array('base', 'meta', 'link', 'hr', - 'br', 'param', 'img', 'area', - 'input', 'col'); - global $xw; - # XXX: check namespace - if (in_array($tag, $empty_tag)) { - $xw->endElement(); - } else { - $xw->fullEndElement(); - } -} - -function common_element($tag, $attrs=NULL, $content=NULL) { - common_element_start($tag, $attrs); - global $xw; - if (!is_null($content)) { - $xw->text($content); - } - common_element_end($tag); -} - -function common_start_xml($doc=NULL, $public=NULL, $system=NULL, $indent=true) { - global $xw; - $xw = new XMLWriter(); - $xw->openURI('php://output'); - $xw->setIndent($indent); - $xw->startDocument('1.0', 'UTF-8'); - if ($doc) { - $xw->writeDTD($doc, $public, $system); - } + static $empty_tag = array('base', 'meta', 'link', 'hr', + 'br', 'param', 'img', 'area', + 'input', 'col'); + global $xw; + // XXX: check namespace + if (in_array($tag, $empty_tag)) { + $xw->endElement(); + } else { + $xw->fullEndElement(); + } +} + +function common_element($tag, $attrs=null, $content=null) { + common_element_start($tag, $attrs); + global $xw; + if (!is_null($content)) { + $xw->text($content); + } + common_element_end($tag); +} + +function common_start_xml($doc=null, $public=null, $system=null, $indent=true) { + global $xw; + $xw = new XMLWriter(); + $xw->openURI('php://output'); + $xw->setIndent($indent); + $xw->startDocument('1.0', 'UTF-8'); + if ($doc) { + $xw->writeDTD($doc, $public, $system); + } } function common_end_xml() { - global $xw; - $xw->endDocument(); - $xw->flush(); + global $xw; + $xw->endDocument(); + $xw->flush(); } function common_init_locale($language=null) { @@ -138,433 +138,433 @@ function common_init_locale($language=null) { putenv('LANGUAGE='.$language); putenv('LANG='.$language); return setlocale(LC_ALL, $language . ".utf8", - $language . ".UTF8", - $language . ".utf-8", - $language . ".UTF-8", - $language); + $language . ".UTF8", + $language . ".utf-8", + $language . ".UTF-8", + $language); } function common_init_language() { - mb_internal_encoding('UTF-8'); - $language = common_language(); - # So we don't have to make people install the gettext locales - $locale_set = common_init_locale($language); - bindtextdomain("laconica", common_config('site','locale_path')); - bind_textdomain_codeset("laconica", "UTF-8"); - textdomain("laconica"); - setlocale(LC_CTYPE, 'C'); - if(!$locale_set) { - common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); - } + mb_internal_encoding('UTF-8'); + $language = common_language(); + // So we don't have to make people install the gettext locales + $locale_set = common_init_locale($language); + bindtextdomain("laconica", common_config('site','locale_path')); + bind_textdomain_codeset("laconica", "UTF-8"); + textdomain("laconica"); + setlocale(LC_CTYPE, 'C'); + if(!$locale_set) { + common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); + } } define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2'); -function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) { +function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null) { - global $config, $xw; + global $config, $xw; global $action; /* XXX: kind of cheating here. */ - common_start_html(); - - common_element_start('head'); - common_element('title', NULL, - $pagetitle . " - " . $config['site']['name']); - common_element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, - 'media' => 'screen, projection, tv')); - foreach (array(6,7) as $ver) { - if (file_exists(theme_file('ie'.$ver.'.css'))) { - # Yes, IE people should be put in jail. - $xw->writeComment('[if lte IE '.$ver.']> 'text/javascript', - 'src' => common_path('js/jquery.min.js')), - ' '); - common_element('script', array('type' => 'text/javascript', - 'src' => common_path('js/jquery.form.js')), - ' '); - common_element('script', array('type' => 'text/javascript', - 'src' => common_path('js/xbImportNode.js')), - ' '); - common_element('script', array('type' => 'text/javascript', - 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), - ' '); - common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', - 'href' => common_local_url('opensearch', array('type' => 'people')), - 'title' => common_config('site', 'name').' People Search')); - - common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', - 'href' => common_local_url('opensearch', array('type' => 'notice')), - 'title' => common_config('site', 'name').' Notice Search')); - - if ($callable) { - if ($data) { - call_user_func($callable, $data); - } else { - call_user_func($callable); - } - } - common_element_end('head'); - common_element_start('body', $action); - common_element_start('div', array('id' => 'wrap')); - common_element_start('div', array('id' => 'header')); - common_nav_menu(); - if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) - || file_exists(theme_file('logo.png'))) - { - common_element_start('a', array('href' => common_local_url('public'))); - common_element('img', array('src' => isset($config['site']['logo']) ? - ($config['site']['logo']) : theme_path('logo.png'), - 'alt' => $config['site']['name'], - 'id' => 'logo')); - common_element_end('a'); - } else { - common_element_start('p', array('id' => 'branding')); - common_element('a', array('href' => common_local_url('public')), - $config['site']['name']); - common_element_end('p'); - } - - common_element('h1', 'pagetitle', $pagetitle); - - if ($headercall) { - if ($data) { - call_user_func($headercall, $data); - } else { - call_user_func($headercall); - } - } - common_element_end('div'); - common_element_start('div', array('id' => 'content')); -} - -function common_start_html($type=NULL, $indent=true) { - - if (!$type) { - $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL; - - # XXX: allow content negotiation for RDF, RSS, or XRDS - - $type = common_negotiate_type(common_accept_to_prefs($httpaccept), - common_accept_to_prefs(PAGE_TYPE_PREFS)); - - if (!$type) { - common_user_error(_('This page is not available in a media type you accept'), 406); - exit(0); - } - } - - header('Content-Type: '.$type); - - common_start_xml('html', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); - - # FIXME: correct language for interface - - $language = common_language(); - - common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', - 'xml:lang' => $language, - 'lang' => $language)); + common_start_html(); + + common_element_start('head'); + common_element('title', null, + $pagetitle . " - " . $config['site']['name']); + common_element('link', array('rel' => 'stylesheet', + 'type' => 'text/css', + 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, + 'media' => 'screen, projection, tv')); + foreach (array(6,7) as $ver) { + if (file_exists(theme_file('ie'.$ver.'.css'))) { + // Yes, IE people should be put in jail. + $xw->writeComment('[if lte IE '.$ver.']> 'text/javascript', + 'src' => common_path('js/jquery.min.js')), + ' '); + common_element('script', array('type' => 'text/javascript', + 'src' => common_path('js/jquery.form.js')), + ' '); + common_element('script', array('type' => 'text/javascript', + 'src' => common_path('js/xbImportNode.js')), + ' '); + common_element('script', array('type' => 'text/javascript', + 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), + ' '); + common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', + 'href' => common_local_url('opensearch', array('type' => 'people')), + 'title' => common_config('site', 'name').' People Search')); + + common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', + 'href' => common_local_url('opensearch', array('type' => 'notice')), + 'title' => common_config('site', 'name').' Notice Search')); + + if ($callable) { + if ($data) { + call_user_func($callable, $data); + } else { + call_user_func($callable); + } + } + common_element_end('head'); + common_element_start('body', $action); + common_element_start('div', array('id' => 'wrap')); + common_element_start('div', array('id' => 'header')); + common_nav_menu(); + if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) + || file_exists(theme_file('logo.png'))) + { + common_element_start('a', array('href' => common_local_url('public'))); + common_element('img', array('src' => isset($config['site']['logo']) ? + ($config['site']['logo']) : theme_path('logo.png'), + 'alt' => $config['site']['name'], + 'id' => 'logo')); + common_element_end('a'); + } else { + common_element_start('p', array('id' => 'branding')); + common_element('a', array('href' => common_local_url('public')), + $config['site']['name']); + common_element_end('p'); + } + + common_element('h1', 'pagetitle', $pagetitle); + + if ($headercall) { + if ($data) { + call_user_func($headercall, $data); + } else { + call_user_func($headercall); + } + } + common_element_end('div'); + common_element_start('div', array('id' => 'content')); +} + +function common_start_html($type=null, $indent=true) { + + if (!$type) { + $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; + + // XXX: allow content negotiation for RDF, RSS, or XRDS + + $type = common_negotiate_type(common_accept_to_prefs($httpaccept), + common_accept_to_prefs(PAGE_TYPE_PREFS)); + + if (!$type) { + common_user_error(_('This page is not available in a media type you accept'), 406); + exit(0); + } + } + + header('Content-Type: '.$type); + + common_start_xml('html', + '-//W3C//DTD XHTML 1.0 Strict//EN', + 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); + + // FIXME: correct language for interface + + $language = common_language(); + + common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', + 'xml:lang' => $language, + 'lang' => $language)); } function common_show_footer() { - global $xw, $config; - common_element_end('div'); # content div - common_foot_menu(); - common_element_start('div', array('id' => 'footer')); - common_element_start('div', 'laconica'); - if (common_config('site', 'broughtby')) { - $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); - } else { - $instr = _('**%%site.name%%** is a microblogging service. '); - } - $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); + global $xw, $config; + common_element_end('div'); // content div + common_foot_menu(); + common_element_start('div', array('id' => 'footer')); + common_element_start('div', 'laconica'); + if (common_config('site', 'broughtby')) { + $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); + } else { + $instr = _('**%%site.name%%** is a microblogging service. '); + } + $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); $output = common_markup_to_html($instr); common_raw($output); - common_element_end('div'); - common_element('img', array('id' => 'cc', - 'src' => $config['license']['image'], - 'alt' => $config['license']['title'])); - common_element_start('p'); - common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); - common_element('a', array('class' => 'license', - 'rel' => 'license', - 'href' => $config['license']['url']), - $config['license']['title']); - common_text(_('. Contributors should be attributed by full name or nickname.')); - common_element_end('p'); - common_element_end('div'); - common_element_end('div'); - common_element_end('body'); - common_element_end('html'); - common_end_xml(); + common_element_end('div'); + common_element('img', array('id' => 'cc', + 'src' => $config['license']['image'], + 'alt' => $config['license']['title'])); + common_element_start('p'); + common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); + common_element('a', array('class' => 'license', + 'rel' => 'license', + 'href' => $config['license']['url']), + $config['license']['title']); + common_text(_('. Contributors should be attributed by full name or nickname.')); + common_element_end('p'); + common_element_end('div'); + common_element_end('div'); + common_element_end('body'); + common_element_end('html'); + common_end_xml(); } function common_text($txt) { - global $xw; - $xw->text($txt); + global $xw; + $xw->text($txt); } function common_raw($xml) { - global $xw; - $xw->writeRaw($xml); + global $xw; + $xw->writeRaw($xml); } function common_nav_menu() { - $user = common_current_user(); - common_element_start('ul', array('id' => 'nav')); - if ($user) { - common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), - _('Home')); - } - common_menu_item(common_local_url('peoplesearch'), _('Search')); - if ($user) { - common_menu_item(common_local_url('profilesettings'), - _('Settings')); - common_menu_item(common_local_url('invite'), - _('Invite')); - common_menu_item(common_local_url('logout'), - _('Logout')); - } else { - common_menu_item(common_local_url('login'), _('Login')); - if (!common_config('site', 'closed')) { - common_menu_item(common_local_url('register'), _('Register')); - } - common_menu_item(common_local_url('openidlogin'), _('OpenID')); - } - common_menu_item(common_local_url('doc', array('title' => 'help')), - _('Help')); - common_element_end('ul'); + $user = common_current_user(); + common_element_start('ul', array('id' => 'nav')); + if ($user) { + common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), + _('Home')); + } + common_menu_item(common_local_url('peoplesearch'), _('Search')); + if ($user) { + common_menu_item(common_local_url('profilesettings'), + _('Settings')); + common_menu_item(common_local_url('invite'), + _('Invite')); + common_menu_item(common_local_url('logout'), + _('Logout')); + } else { + common_menu_item(common_local_url('login'), _('Login')); + if (!common_config('site', 'closed')) { + common_menu_item(common_local_url('register'), _('Register')); + } + common_menu_item(common_local_url('openidlogin'), _('OpenID')); + } + common_menu_item(common_local_url('doc', array('title' => 'help')), + _('Help')); + common_element_end('ul'); } function common_foot_menu() { - common_element_start('ul', array('id' => 'nav_sub')); - common_menu_item(common_local_url('doc', array('title' => 'help')), - _('Help')); - common_menu_item(common_local_url('doc', array('title' => 'about')), - _('About')); - common_menu_item(common_local_url('doc', array('title' => 'faq')), - _('FAQ')); - common_menu_item(common_local_url('doc', array('title' => 'privacy')), - _('Privacy')); - common_menu_item(common_local_url('doc', array('title' => 'source')), - _('Source')); - common_menu_item(common_local_url('doc', array('title' => 'contact')), - _('Contact')); - common_element_end('ul'); -} - -function common_menu_item($url, $text, $title=NULL, $is_selected=false) { - $lattrs = array(); - if ($is_selected) { - $lattrs['class'] = 'current'; - } - common_element_start('li', $lattrs); - $attrs['href'] = $url; - if ($title) { - $attrs['title'] = $title; - } - common_element('a', $attrs, $text); - common_element_end('li'); -} - -function common_input($id, $label, $value=NULL,$instructions=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - $attrs = array('name' => $id, - 'type' => 'text', - 'class' => 'input_text', - 'id' => $id); - if ($value) { - $attrs['value'] = htmlspecialchars($value); - } - common_element('input', $attrs); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); -} - -function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false) + common_element_start('ul', array('id' => 'nav_sub')); + common_menu_item(common_local_url('doc', array('title' => 'help')), + _('Help')); + common_menu_item(common_local_url('doc', array('title' => 'about')), + _('About')); + common_menu_item(common_local_url('doc', array('title' => 'faq')), + _('FAQ')); + common_menu_item(common_local_url('doc', array('title' => 'privacy')), + _('Privacy')); + common_menu_item(common_local_url('doc', array('title' => 'source')), + _('Source')); + common_menu_item(common_local_url('doc', array('title' => 'contact')), + _('Contact')); + common_element_end('ul'); +} + +function common_menu_item($url, $text, $title=null, $is_selected=false) { + $lattrs = array(); + if ($is_selected) { + $lattrs['class'] = 'current'; + } + common_element_start('li', $lattrs); + $attrs['href'] = $url; + if ($title) { + $attrs['title'] = $title; + } + common_element('a', $attrs, $text); + common_element_end('li'); +} + +function common_input($id, $label, $value=null,$instructions=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + $attrs = array('name' => $id, + 'type' => 'text', + 'class' => 'input_text', + 'id' => $id); + if ($value) { + $attrs['value'] = htmlspecialchars($value); + } + common_element('input', $attrs); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); +} + +function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false) { - common_element_start('p'); - $attrs = array('name' => $id, - 'type' => 'checkbox', - 'class' => 'checkbox', - 'id' => $id); - if ($value) { - $attrs['value'] = htmlspecialchars($value); - } - if ($checked) { - $attrs['checked'] = 'checked'; - } - if ($disabled) { - $attrs['disabled'] = 'true'; - } - common_element('input', $attrs); - common_text(' '); - common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); - common_text(' '); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); -} - -function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - common_element_start('select', array('id' => $id, 'name' => $id)); - if ($blank_select) { - common_element('option', array('value' => '')); - } - foreach ($content as $value => $option) { - if ($value == $selected) { - common_element('option', array('value' => $value, 'selected' => $value), $option); - } else { - common_element('option', array('value' => $value), $option); - } - } - common_element_end('select'); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); + common_element_start('p'); + $attrs = array('name' => $id, + 'type' => 'checkbox', + 'class' => 'checkbox', + 'id' => $id); + if ($value) { + $attrs['value'] = htmlspecialchars($value); + } + if ($checked) { + $attrs['checked'] = 'checked'; + } + if ($disabled) { + $attrs['disabled'] = 'true'; + } + common_element('input', $attrs); + common_text(' '); + common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); + common_text(' '); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); +} + +function common_dropdown($id, $label, $content, $instructions=null, $blank_select=FALSE, $selected=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + common_element_start('select', array('id' => $id, 'name' => $id)); + if ($blank_select) { + common_element('option', array('value' => '')); + } + foreach ($content as $value => $option) { + if ($value == $selected) { + common_element('option', array('value' => $value, 'selected' => $value), $option); + } else { + common_element('option', array('value' => $value), $option); + } + } + common_element_end('select'); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); } function common_hidden($id, $value) { - common_element('input', array('name' => $id, - 'type' => 'hidden', - 'id' => $id, - 'value' => $value)); -} - -function common_password($id, $label, $instructions=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - $attrs = array('name' => $id, - 'type' => 'password', - 'class' => 'password', - 'id' => $id); - common_element('input', $attrs); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); + common_element('input', array('name' => $id, + 'type' => 'hidden', + 'id' => $id, + 'value' => $value)); +} + +function common_password($id, $label, $instructions=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + $attrs = array('name' => $id, + 'type' => 'password', + 'class' => 'password', + 'id' => $id); + common_element('input', $attrs); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); } function common_submit($id, $label, $cls='submit') { - global $xw; - common_element_start('p'); - common_element('input', array('type' => 'submit', - 'id' => $id, - 'name' => $id, - 'class' => $cls, - 'value' => $label)); - common_element_end('p'); -} - -function common_textarea($id, $label, $content=NULL, $instructions=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - common_element('textarea', array('rows' => 3, - 'cols' => 40, - 'name' => $id, - 'id' => $id), - ($content) ? $content : ''); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); + global $xw; + common_element_start('p'); + common_element('input', array('type' => 'submit', + 'id' => $id, + 'name' => $id, + 'class' => $cls, + 'value' => $label)); + common_element_end('p'); +} + +function common_textarea($id, $label, $content=null, $instructions=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + common_element('textarea', array('rows' => 3, + 'cols' => 40, + 'name' => $id, + 'id' => $id), + ($content) ? $content : ''); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); } function common_timezone() { - if (common_logged_in()) { - $user = common_current_user(); - if ($user->timezone) { - return $user->timezone; - } - } + if (common_logged_in()) { + $user = common_current_user(); + if ($user->timezone) { + return $user->timezone; + } + } - global $config; - return $config['site']['timezone']; + global $config; + return $config['site']['timezone']; } 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()) { - $user = common_current_user(); - $user_language = $user->language; - if ($user_language) - return $user_language; - } + // If there is a user logged in and they've set a language preference + // then return that one... + if (common_logged_in()) { + $user = common_current_user(); + $user_language = $user->language; + if ($user_language) + return $user_language; + } - // Otherwise, find the best match for the languages requested by the - // user's browser... - $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL; - if (!empty($httplang)) { - $language = client_prefered_language($httplang); - if ($language) - return $language; - } + // Otherwise, find the best match for the languages requested by the + // user's browser... + $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; + if (!empty($httplang)) { + $language = client_prefered_language($httplang); + if ($language) + return $language; + } - // Finally, if none of the above worked, use the site's default... - return common_config('site', 'language'); + // Finally, if none of the above worked, use the site's default... + return common_config('site', 'language'); } -# salted, hashed passwords are stored in the DB +// salted, hashed passwords are stored in the DB function common_munge_password($password, $id) { - return md5($password . $id); + return md5($password . $id); } -# check if a username exists and has matching password +// check if a username exists and has matching password function common_check_user($nickname, $password) { - # NEVER allow blank passwords, even if they match the DB - if (mb_strlen($password) == 0) { - return false; - } - $user = User::staticGet('nickname', $nickname); - if (is_null($user)) { - return false; - } else { - if (0 == strcmp(common_munge_password($password, $user->id), - $user->password)) { - return $user; - } else { - return false; - } - } -} - -# is the current user logged in? + // NEVER allow blank passwords, even if they match the DB + if (mb_strlen($password) == 0) { + return false; + } + $user = User::staticGet('nickname', $nickname); + if (is_null($user)) { + return false; + } else { + if (0 == strcmp(common_munge_password($password, $user->id), + $user->password)) { + return $user; + } else { + return false; + } + } +} + +// is the current user logged in? function common_logged_in() { - return (!is_null(common_current_user())); + return (!is_null(common_current_user())); } function common_have_session() { - return (0 != strcmp(session_id(), '')); + return (0 != strcmp(session_id(), '')); } function common_ensure_session() { - if (!common_have_session()) { - @session_start(); - } + if (!common_have_session()) { + @session_start(); + } } -# Three kinds of arguments: -# 1) a user object -# 2) a nickname -# 3) NULL to clear +// Three kinds of arguments: +// 1) a user object +// 2) a nickname +// 3) null to clear -# Initialize to false; set to NULL if none found +// Initialize to false; set to null if none found $_cur = false; @@ -572,92 +572,92 @@ function common_set_user($user) { global $_cur; - if (is_null($user) && common_have_session()) { - $_cur = NULL; - unset($_SESSION['userid']); - return true; - } else if (is_string($user)) { - $nickname = $user; - $user = User::staticGet('nickname', $nickname); - } else if (!($user instanceof User)) { - return false; - } - - if ($user) { - common_ensure_session(); - $_SESSION['userid'] = $user->id; + if (is_null($user) && common_have_session()) { + $_cur = null; + unset($_SESSION['userid']); + return true; + } else if (is_string($user)) { + $nickname = $user; + $user = User::staticGet('nickname', $nickname); + } else if (!($user instanceof User)) { + return false; + } + + if ($user) { + common_ensure_session(); + $_SESSION['userid'] = $user->id; $_cur = $user; - return $_cur; - } - return false; + return $_cur; + } + return false; } function common_set_cookie($key, $value, $expiration=0) { - $path = common_config('site', 'path'); - $server = common_config('site', 'server'); + $path = common_config('site', 'path'); + $server = common_config('site', 'server'); - if ($path && ($path != '/')) { - $cookiepath = '/' . $path . '/'; - } else { - $cookiepath = '/'; - } - return setcookie($key, - $value, - $expiration, - $cookiepath, - $server); + if ($path && ($path != '/')) { + $cookiepath = '/' . $path . '/'; + } else { + $cookiepath = '/'; + } + return setcookie($key, + $value, + $expiration, + $cookiepath, + $server); } define('REMEMBERME', 'rememberme'); -define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); # 30 days +define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days -function common_rememberme($user=NULL) { - if (!$user) { - $user = common_current_user(); - if (!$user) { - common_debug('No current user to remember', __FILE__); - return false; - } - } +function common_rememberme($user=null) { + if (!$user) { + $user = common_current_user(); + if (!$user) { + common_debug('No current user to remember', __FILE__); + return false; + } + } - $rm = new Remember_me(); + $rm = new Remember_me(); - $rm->code = common_good_rand(16); - $rm->user_id = $user->id; + $rm->code = common_good_rand(16); + $rm->user_id = $user->id; - # Wrap the insert in some good ol' fashioned transaction code + // Wrap the insert in some good ol' fashioned transaction code $rm->query('BEGIN'); - $result = $rm->insert(); + $result = $rm->insert(); - if (!$result) { - common_log_db_error($rm, 'INSERT', __FILE__); - common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); - return false; + if (!$result) { + common_log_db_error($rm, 'INSERT', __FILE__); + common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); + return false; } $rm->query('COMMIT'); - common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); + common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); $cookieval = $rm->user_id . ':' . $rm->code; - common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); + common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); - common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); + common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); - return true; + return true; } function common_remembered_user() { - $user = NULL; + $user = null; - $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : NULL; + $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null; - if (!$packed) { - return NULL; + if (!$packed) { + return null; } list($id, $code) = explode(':', $packed); @@ -665,7 +665,7 @@ function common_remembered_user() { if (!$id || !$code) { common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed); common_forgetme(); - return NULL; + return null; } $rm = Remember_me::staticGet($code); @@ -673,13 +673,13 @@ function common_remembered_user() { if (!$rm) { common_log(LOG_WARNING, 'No such remember code: ' . $code); common_forgetme(); - return NULL; + return null; } if ($rm->user_id != $id) { common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id); common_forgetme(); - return NULL; + return null; } $user = User::staticGet($rm->user_id); @@ -687,17 +687,17 @@ function common_remembered_user() { if (!$user) { common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id); common_forgetme(); - return NULL; + return null; } - # successful! + // successful! $result = $rm->delete(); if (!$result) { common_log_db_error($rm, 'DELETE', __FILE__); common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code); common_forgetme(); - return NULL; + return null; } common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code); @@ -705,21 +705,21 @@ function common_remembered_user() { common_set_user($user); common_real_login(false); - # We issue a new cookie, so they can log in - # automatically again after this session + // We issue a new cookie, so they can log in + // automatically again after this session common_rememberme($user); - return $user; + return $user; } -# must be called with a valid user! +// must be called with a valid user! function common_forgetme() { - common_set_cookie(REMEMBERME, '', 0); + common_set_cookie(REMEMBERME, '', 0); } -# who is the current user? +// who is the current user? function common_current_user() { global $_cur; @@ -734,99 +734,99 @@ function common_current_user() { } } - # that didn't work; try to remember; will init $_cur to NULL on failure + // that didn't work; try to remember; will init $_cur to null on failure $_cur = common_remembered_user(); if ($_cur) { common_debug("Got User " . $_cur->nickname); common_debug("Faking session on remembered user"); - # XXX: Is this necessary? + // XXX: Is this necessary? $_SESSION['userid'] = $_cur->id; } } - return $_cur; + return $_cur; } -# Logins that are 'remembered' aren't 'real' -- they're subject to -# cookie-stealing. So, we don't let them do certain things. New reg, -# OpenID, and password logins _are_ real. +// Logins that are 'remembered' aren't 'real' -- they're subject to +// cookie-stealing. So, we don't let them do certain things. New reg, +// OpenID, and password logins _are_ real. function common_real_login($real=true) { - common_ensure_session(); - $_SESSION['real_login'] = $real; + common_ensure_session(); + $_SESSION['real_login'] = $real; } function common_is_real_login() { - return common_logged_in() && $_SESSION['real_login']; + return common_logged_in() && $_SESSION['real_login']; } -# get canonical version of nickname for comparison +// get canonical version of nickname for comparison function common_canonical_nickname($nickname) { - # XXX: UTF-8 canonicalization (like combining chars) - return strtolower($nickname); + // XXX: UTF-8 canonicalization (like combining chars) + return strtolower($nickname); } -# get canonical version of email for comparison +// get canonical version of email for comparison function common_canonical_email($email) { - # XXX: canonicalize UTF-8 - # XXX: lcase the domain part - return $email; + // XXX: canonicalize UTF-8 + // XXX: lcase the domain part + return $email; } define('URL_REGEX', '^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))'); function common_render_content($text, $notice) { - $r = common_render_text($text); - $id = $notice->profile_id; - $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); - $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); - $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); - return $r; + $r = common_render_text($text); + $id = $notice->profile_id; + $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); + $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); + $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); + return $r; } function common_render_text($text) { - $r = htmlspecialchars($text); + $r = htmlspecialchars($text); - $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); - $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); - $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); - # XXX: machine tags - return $r; + $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); + $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); + $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); + // XXX: machine tags + return $r; } function common_render_uri_thingy($matches) { - $uri = $matches[0]; - $trailer = ''; - - # Some heuristics for extracting URIs from surrounding punctuation - # Strip from trailing text... - if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { - $uri = $matches[1]; - $trailer = $matches[2]; - } - - $pairs = array( - ']' => '[', # technically disallowed in URIs, but used in Java docs - ')' => '(', # far too frequent in Wikipedia and MSDN - ); - $final = substr($uri, -1, 1); - if (isset($pairs[$final])) { - $openers = substr_count($uri, $pairs[$final]); - $closers = substr_count($uri, $final); - if ($closers > $openers) { - // Assume the paren was opened outside the URI - $uri = substr($uri, 0, -1); - $trailer = $final . $trailer; - } - } - if ($longurl = common_longurl($uri)) { - $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); - $title = " title='$longurl'"; - } - else $title = ''; - - return '' . $uri . '' . $trailer; + $uri = $matches[0]; + $trailer = ''; + + // Some heuristics for extracting URIs from surrounding punctuation + // Strip from trailing text... + if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { + $uri = $matches[1]; + $trailer = $matches[2]; + } + + $pairs = array( + ']' => '[', // technically disallowed in URIs, but used in Java docs + ')' => '(', // far too frequent in Wikipedia and MSDN + ); + $final = substr($uri, -1, 1); + if (isset($pairs[$final])) { + $openers = substr_count($uri, $pairs[$final]); + $closers = substr_count($uri, $final); + if ($closers > $openers) { + // Assume the paren was opened outside the URI + $uri = substr($uri, 0, -1); + $trailer = $final . $trailer; + } + } + if ($longurl = common_longurl($uri)) { + $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); + $title = " title='$longurl'"; + } + else $title = ''; + + return '' . $uri . '' . $trailer; } function common_longurl($short_url) { @@ -836,10 +836,10 @@ function common_longurl($short_url) { } function common_longurl2($uri) { - $uri_e = urlencode($uri); - $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); - if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; - return stripslashes($longurl['long_url']); + $uri_e = urlencode($uri); + $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); + if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; + return stripslashes($longurl['long_url']); } function common_shorten_links($text) { @@ -847,465 +847,465 @@ function common_shorten_links($text) { static $cache = array(); if (isset($cache[$text])) return $cache[$text]; // \s = not a horizontal whitespace character (since PHP 5.2.4) - return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); + return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); } function common_shorten_link($url, $reverse = false) { - static $url_cache = array(); + static $url_cache = array(); if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url; - $user = common_current_user(); - - $curlh = curl_init(); - curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait - curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); - curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); - - switch($user->urlshorteningservice) { - case 'ur1.ca': - $short_url_service = new LilUrl; - $short_url = $short_url_service->shorten($url); - break; - - case '2tu.us': - $short_url_service = new TightUrl; - $short_url = $short_url_service->shorten($url); - break; - - case 'ptiturl.com': - $short_url_service = new PtitUrl; - $short_url = $short_url_service->shorten($url); - break; - - case 'bit.ly': - curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); - $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; - break; - - case 'is.gd': - curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - case 'snipr.com': - curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - case 'metamark.net': - curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - case 'tinyurl.com': - curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - default: - $short_url = false; - } - - curl_close($curlh); - - if ($short_url) { + $user = common_current_user(); + + $curlh = curl_init(); + curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait + curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); + curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); + + switch($user->urlshorteningservice) { + case 'ur1.ca': + $short_url_service = new LilUrl; + $short_url = $short_url_service->shorten($url); + break; + + case '2tu.us': + $short_url_service = new TightUrl; + $short_url = $short_url_service->shorten($url); + break; + + case 'ptiturl.com': + $short_url_service = new PtitUrl; + $short_url = $short_url_service->shorten($url); + break; + + case 'bit.ly': + curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); + $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; + break; + + case 'is.gd': + curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + case 'snipr.com': + curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + case 'metamark.net': + curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + case 'tinyurl.com': + curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + default: + $short_url = false; + } + + curl_close($curlh); + + if ($short_url) { $url_cache[(string)$short_url] = $url; - return (string)$short_url; - } - return $url; + return (string)$short_url; + } + return $url; } function common_xml_safe_str($str) { - $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8'); + $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); + // Replace control, formatting, and surrogate characters with '*', ala Twitter + return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str); } function common_tag_link($tag) { - $canonical = common_canonical_tag($tag); - $url = common_local_url('tag', array('tag' => $canonical)); - return ''; + $canonical = common_canonical_tag($tag); + $url = common_local_url('tag', array('tag' => $canonical)); + return ''; } function common_canonical_tag($tag) { - return strtolower(str_replace(array('-', '_', '.'), '', $tag)); + return strtolower(str_replace(array('-', '_', '.'), '', $tag)); } function common_valid_profile_tag($str) { - return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); + return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); } function common_at_link($sender_id, $nickname) { - $sender = Profile::staticGet($sender_id); - $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); - if ($recipient) { - return ''.$nickname.''; - } else { - return $nickname; - } + $sender = Profile::staticGet($sender_id); + $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); + if ($recipient) { + return ''.$nickname.''; + } else { + return $nickname; + } } function common_at_hash_link($sender_id, $tag) { - $user = User::staticGet($sender_id); - if (!$user) { - return $tag; - } - $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); - if ($tagged) { - $url = common_local_url('subscriptions', - array('nickname' => $user->nickname, - 'tag' => $tag)); - return ''.$tag.''; - } else { - return $tag; - } -} - -function common_relative_profile($sender, $nickname, $dt=NULL) { - # Try to find profiles this profile is subscribed to that have this nickname - $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'); - if ($recipient->find(TRUE)) { - # XXX: should probably differentiate between profiles with - # the same name by date of most recent update - return $recipient; - } - # Try to find profiles that listen to this profile and that have this nickname - $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'); - if ($recipient->find(TRUE)) { - # XXX: should probably differentiate between profiles with - # the same name by date of most recent update - return $recipient; - } - # If this is a local user, try to find a local user with that nickname. - $sender = User::staticGet($sender->id); - if ($sender) { - $recipient_user = User::staticGet('nickname', $nickname); - if ($recipient_user) { - return $recipient_user->getProfile(); - } - } - # Otherwise, no links. @messages from local users to remote users, - # or from remote users to other remote users, are just - # outside our ability to make intelligent guesses about - return NULL; + $user = User::staticGet($sender_id); + if (!$user) { + return $tag; + } + $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); + if ($tagged) { + $url = common_local_url('subscriptions', + array('nickname' => $user->nickname, + 'tag' => $tag)); + return ''.$tag.''; + } else { + return $tag; + } +} + +function common_relative_profile($sender, $nickname, $dt=null) { + // Try to find profiles this profile is subscribed to that have this nickname + $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'); + if ($recipient->find(TRUE)) { + // XXX: should probably differentiate between profiles with + // the same name by date of most recent update + return $recipient; + } + // Try to find profiles that listen to this profile and that have this nickname + $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'); + if ($recipient->find(TRUE)) { + // XXX: should probably differentiate between profiles with + // the same name by date of most recent update + return $recipient; + } + // If this is a local user, try to find a local user with that nickname. + $sender = User::staticGet($sender->id); + if ($sender) { + $recipient_user = User::staticGet('nickname', $nickname); + if ($recipient_user) { + return $recipient_user->getProfile(); + } + } + // Otherwise, no links. @messages from local users to remote users, + // or from remote users to other remote users, are just + // outside our ability to make intelligent guesses about + return null; } // where should the avatar go for this user? -function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) { - global $config; +function common_avatar_filename($id, $extension, $size=null, $extra=null) { + global $config; - if ($size) { - return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; - } else { - return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; - } + if ($size) { + return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; + } else { + return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; + } } function common_avatar_path($filename) { - global $config; - return INSTALLDIR . '/avatar/' . $filename; + global $config; + return INSTALLDIR . '/avatar/' . $filename; } function common_avatar_url($filename) { - return common_path('avatar/'.$filename); + return common_path('avatar/'.$filename); } function common_avatar_display_url($avatar) { - $server = common_config('avatar', 'server'); - if ($server) { - return 'http://'.$server.'/'.$avatar->filename; - } else { - return $avatar->url; - } + $server = common_config('avatar', 'server'); + if ($server) { + return 'http://'.$server.'/'.$avatar->filename; + } else { + return $avatar->url; + } } function common_default_avatar($size) { - static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', - AVATAR_STREAM_SIZE => 'stream', - AVATAR_MINI_SIZE => 'mini'); - return theme_path('default-avatar-'.$sizenames[$size].'.png'); -} - -function common_local_url($action, $args=NULL, $fragment=NULL) { - $url = NULL; - if (common_config('site','fancy')) { - $url = common_fancy_url($action, $args); - } else { - $url = common_simple_url($action, $args); - } - if (!is_null($fragment)) { - $url .= '#'.$fragment; - } - return $url; -} - -function common_fancy_url($action, $args=NULL) { - switch (strtolower($action)) { - case 'public': - if ($args && isset($args['page'])) { - return common_path('?page=' . $args['page']); - } else { - return common_path(''); - } - case 'featured': - if ($args && isset($args['page'])) { - return common_path('featured?page=' . $args['page']); - } else { - return common_path('featured'); - } - case 'favorited': - if ($args && isset($args['page'])) { - return common_path('favorited?page=' . $args['page']); - } else { - return common_path('favorited'); - } - case 'publicrss': - return common_path('rss'); - case 'publicatom': - return common_path("api/statuses/public_timeline.atom"); - case 'publicxrds': - return common_path('xrds'); - case 'featuredrss': - return common_path('featuredrss'); - case 'favoritedrss': - return common_path('favoritedrss'); - case 'opensearch': - if ($args && $args['type']) { - return common_path('opensearch/'.$args['type']); - } else { - return common_path('opensearch/people'); - } - case 'doc': - return common_path('doc/'.$args['title']); + static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', + AVATAR_STREAM_SIZE => 'stream', + AVATAR_MINI_SIZE => 'mini'); + return theme_path('default-avatar-'.$sizenames[$size].'.png'); +} + +function common_local_url($action, $args=null, $fragment=null) { + $url = null; + if (common_config('site','fancy')) { + $url = common_fancy_url($action, $args); + } else { + $url = common_simple_url($action, $args); + } + if (!is_null($fragment)) { + $url .= '#'.$fragment; + } + return $url; +} + +function common_fancy_url($action, $args=null) { + switch (strtolower($action)) { + case 'public': + if ($args && isset($args['page'])) { + return common_path('?page=' . $args['page']); + } else { + return common_path(''); + } + case 'featured': + if ($args && isset($args['page'])) { + return common_path('featured?page=' . $args['page']); + } else { + return common_path('featured'); + } + case 'favorited': + if ($args && isset($args['page'])) { + return common_path('favorited?page=' . $args['page']); + } else { + return common_path('favorited'); + } + case 'publicrss': + return common_path('rss'); + case 'publicatom': + return common_path("api/statuses/public_timeline.atom"); + case 'publicxrds': + return common_path('xrds'); + case 'featuredrss': + return common_path('featuredrss'); + case 'favoritedrss': + return common_path('favoritedrss'); + case 'opensearch': + if ($args && $args['type']) { + return common_path('opensearch/'.$args['type']); + } else { + return common_path('opensearch/people'); + } + case 'doc': + return common_path('doc/'.$args['title']); case 'block': - case 'login': - case 'logout': - case 'subscribe': - case 'unsubscribe': - case 'invite': - return common_path('main/'.$action); - case 'tagother': - return common_path('main/tagother?id='.$args['id']); - case 'register': - if ($args && $args['code']) { - return common_path('main/register/'.$args['code']); - } else { - return common_path('main/register'); - } - case 'remotesubscribe': - if ($args && $args['nickname']) { - return common_path('main/remote?nickname=' . $args['nickname']); - } else { - return common_path('main/remote'); - } - case 'nudge': - return common_path($args['nickname'].'/nudge'); - case 'openidlogin': - return common_path('main/openid'); - case 'profilesettings': - return common_path('settings/profile'); - case 'emailsettings': - return common_path('settings/email'); - case 'openidsettings': - return common_path('settings/openid'); - case 'smssettings': - return common_path('settings/sms'); - case 'twittersettings': - return common_path('settings/twitter'); - case 'othersettings': - return common_path('settings/other'); + case 'login': + case 'logout': + case 'subscribe': + case 'unsubscribe': + case 'invite': + return common_path('main/'.$action); + case 'tagother': + return common_path('main/tagother?id='.$args['id']); + case 'register': + if ($args && $args['code']) { + return common_path('main/register/'.$args['code']); + } else { + return common_path('main/register'); + } + case 'remotesubscribe': + if ($args && $args['nickname']) { + return common_path('main/remote?nickname=' . $args['nickname']); + } else { + return common_path('main/remote'); + } + case 'nudge': + return common_path($args['nickname'].'/nudge'); + case 'openidlogin': + return common_path('main/openid'); + case 'profilesettings': + return common_path('settings/profile'); + case 'emailsettings': + return common_path('settings/email'); + case 'openidsettings': + return common_path('settings/openid'); + case 'smssettings': + return common_path('settings/sms'); + case 'twittersettings': + return common_path('settings/twitter'); + case 'othersettings': + return common_path('settings/other'); case 'deleteprofile': return common_path('settings/delete'); - case 'newnotice': - if ($args && $args['replyto']) { - return common_path('notice/new?replyto='.$args['replyto']); - } else { - return common_path('notice/new'); - } - case 'shownotice': - return common_path('notice/'.$args['notice']); - case 'deletenotice': - if ($args && $args['notice']) { - return common_path('notice/delete/'.$args['notice']); - } else { - return common_path('notice/delete'); - } - case 'microsummary': - case 'xrds': - case 'foaf': - return common_path($args['nickname'].'/'.$action); - case 'all': - case 'replies': - case 'inbox': - case 'outbox': - if ($args && isset($args['page'])) { - return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); - } else { - return common_path($args['nickname'].'/'.$action); - } - case 'subscriptions': - case 'subscribers': - $nickname = $args['nickname']; - unset($args['nickname']); - if (isset($args['tag'])) { - $tag = $args['tag']; - unset($args['tag']); - } - $params = http_build_query($args); - if ($params) { - return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); - } else { - return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); - } - case 'allrss': - return common_path($args['nickname'].'/all/rss'); - case 'repliesrss': - return common_path($args['nickname'].'/replies/rss'); - case 'userrss': + case 'newnotice': + if ($args && $args['replyto']) { + return common_path('notice/new?replyto='.$args['replyto']); + } else { + return common_path('notice/new'); + } + case 'shownotice': + return common_path('notice/'.$args['notice']); + case 'deletenotice': + if ($args && $args['notice']) { + return common_path('notice/delete/'.$args['notice']); + } else { + return common_path('notice/delete'); + } + case 'microsummary': + case 'xrds': + case 'foaf': + return common_path($args['nickname'].'/'.$action); + case 'all': + case 'replies': + case 'inbox': + case 'outbox': + if ($args && isset($args['page'])) { + return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); + } else { + return common_path($args['nickname'].'/'.$action); + } + case 'subscriptions': + case 'subscribers': + $nickname = $args['nickname']; + unset($args['nickname']); + if (isset($args['tag'])) { + $tag = $args['tag']; + unset($args['tag']); + } + $params = http_build_query($args); + if ($params) { + return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); + } else { + return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); + } + case 'allrss': + return common_path($args['nickname'].'/all/rss'); + case 'repliesrss': + return common_path($args['nickname'].'/replies/rss'); + case 'userrss': if (isset($args['limit'])) - return common_path($args['nickname'].'/rss?limit=' . $args['limit']); - return common_path($args['nickname'].'/rss'); - case 'showstream': - if ($args && isset($args['page'])) { - return common_path($args['nickname'].'?page=' . $args['page']); - } else { - return common_path($args['nickname']); - } - - case 'usertimeline': - return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); - case 'confirmaddress': - return common_path('main/confirmaddress/'.$args['code']); - case 'userbyid': - return common_path('user/'.$args['id']); - case 'recoverpassword': - $path = 'main/recoverpassword'; - if ($args['code']) { - $path .= '/' . $args['code']; - } - return common_path($path); - case 'imsettings': - return common_path('settings/im'); - case 'peoplesearch': - return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'noticesearch': - return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'noticesearchrss': - return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'avatarbynickname': - return common_path($args['nickname'].'/avatar/'.$args['size']); - case 'tag': - if (isset($args['tag']) && $args['tag']) { - $path = 'tag/' . $args['tag']; - unset($args['tag']); - } else { - $path = 'tags'; - } - return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); - case 'peopletag': - $path = 'peopletag/' . $args['tag']; - unset($args['tag']); - return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); - case 'tags': - return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'favor': - return common_path('main/favor'); - case 'disfavor': - return common_path('main/disfavor'); - case 'showfavorites': - if ($args && isset($args['page'])) { - return common_path($args['nickname'].'/favorites?page=' . $args['page']); - } else { - return common_path($args['nickname'].'/favorites'); - } - case 'favoritesrss': - return common_path($args['nickname'].'/favorites/rss'); - case 'showmessage': - return common_path('message/' . $args['message']); - case 'newmessage': - return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'api': - # XXX: do fancy URLs for all the API methods - switch (strtolower($args['apiaction'])) { - case 'statuses': - switch (strtolower($args['method'])) { - case 'user_timeline.rss': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); - case 'user_timeline.atom': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); - case 'user_timeline.json': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); - case 'user_timeline.xml': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); - default: return common_simple_url($action, $args); - } - default: return common_simple_url($action, $args); - } - case 'sup': - if ($args && isset($args['seconds'])) { - return common_path('main/sup?seconds='.$args['seconds']); - } else { - return common_path('main/sup'); - } - default: - return common_simple_url($action, $args); - } -} - -function common_simple_url($action, $args=NULL) { - global $config; - /* XXX: pretty URLs */ - $extra = ''; - if ($args) { - foreach ($args as $key => $value) { - $extra .= "&${key}=${value}"; - } - } - return common_path("index.php?action=${action}${extra}"); + return common_path($args['nickname'].'/rss?limit=' . $args['limit']); + return common_path($args['nickname'].'/rss'); + case 'showstream': + if ($args && isset($args['page'])) { + return common_path($args['nickname'].'?page=' . $args['page']); + } else { + return common_path($args['nickname']); + } + + case 'usertimeline': + return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); + case 'confirmaddress': + return common_path('main/confirmaddress/'.$args['code']); + case 'userbyid': + return common_path('user/'.$args['id']); + case 'recoverpassword': + $path = 'main/recoverpassword'; + if ($args['code']) { + $path .= '/' . $args['code']; + } + return common_path($path); + case 'imsettings': + return common_path('settings/im'); + case 'peoplesearch': + return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'noticesearch': + return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'noticesearchrss': + return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'avatarbynickname': + return common_path($args['nickname'].'/avatar/'.$args['size']); + case 'tag': + if (isset($args['tag']) && $args['tag']) { + $path = 'tag/' . $args['tag']; + unset($args['tag']); + } else { + $path = 'tags'; + } + return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); + case 'peopletag': + $path = 'peopletag/' . $args['tag']; + unset($args['tag']); + return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); + case 'tags': + return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'favor': + return common_path('main/favor'); + case 'disfavor': + return common_path('main/disfavor'); + case 'showfavorites': + if ($args && isset($args['page'])) { + return common_path($args['nickname'].'/favorites?page=' . $args['page']); + } else { + return common_path($args['nickname'].'/favorites'); + } + case 'favoritesrss': + return common_path($args['nickname'].'/favorites/rss'); + case 'showmessage': + return common_path('message/' . $args['message']); + case 'newmessage': + return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'api': + // XXX: do fancy URLs for all the API methods + switch (strtolower($args['apiaction'])) { + case 'statuses': + switch (strtolower($args['method'])) { + case 'user_timeline.rss': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); + case 'user_timeline.atom': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); + case 'user_timeline.json': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); + case 'user_timeline.xml': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); + default: return common_simple_url($action, $args); + } + default: return common_simple_url($action, $args); + } + case 'sup': + if ($args && isset($args['seconds'])) { + return common_path('main/sup?seconds='.$args['seconds']); + } else { + return common_path('main/sup'); + } + default: + return common_simple_url($action, $args); + } +} + +function common_simple_url($action, $args=null) { + global $config; + /* XXX: pretty URLs */ + $extra = ''; + if ($args) { + foreach ($args as $key => $value) { + $extra .= "&${key}=${value}"; + } + } + return common_path("index.php?action=${action}${extra}"); } function common_path($relative) { - global $config; - $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; - return "http://".$config['site']['server'].'/'.$pathpart.$relative; + global $config; + $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; + return "http://".$config['site']['server'].'/'.$pathpart.$relative; } function common_date_string($dt) { - // XXX: do some sexy date formatting - // return date(DATE_RFC822, $dt); - $t = strtotime($dt); - $now = time(); - $diff = $now - $t; - - if ($now < $t) { # that shouldn't happen! - return common_exact_date($dt); - } else if ($diff < 60) { - return _('a few seconds ago'); - } else if ($diff < 92) { - return _('about a minute ago'); - } else if ($diff < 3300) { - return sprintf(_('about %d minutes ago'), round($diff/60)); - } else if ($diff < 5400) { - return _('about an hour ago'); - } else if ($diff < 22 * 3600) { - return sprintf(_('about %d hours ago'), round($diff/3600)); - } else if ($diff < 37 * 3600) { - return _('about a day ago'); - } else if ($diff < 24 * 24 * 3600) { - return sprintf(_('about %d days ago'), round($diff/(24*3600))); - } else if ($diff < 46 * 24 * 3600) { - return _('about a month ago'); - } else if ($diff < 330 * 24 * 3600) { - return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); - } else if ($diff < 480 * 24 * 3600) { - return _('about a year ago'); - } else { - return common_exact_date($dt); - } + // XXX: do some sexy date formatting + // return date(DATE_RFC822, $dt); + $t = strtotime($dt); + $now = time(); + $diff = $now - $t; + + if ($now < $t) { // that shouldn't happen! + return common_exact_date($dt); + } else if ($diff < 60) { + return _('a few seconds ago'); + } else if ($diff < 92) { + return _('about a minute ago'); + } else if ($diff < 3300) { + return sprintf(_('about %d minutes ago'), round($diff/60)); + } else if ($diff < 5400) { + return _('about an hour ago'); + } else if ($diff < 22 * 3600) { + return sprintf(_('about %d hours ago'), round($diff/3600)); + } else if ($diff < 37 * 3600) { + return _('about a day ago'); + } else if ($diff < 24 * 24 * 3600) { + return sprintf(_('about %d days ago'), round($diff/(24*3600))); + } else if ($diff < 46 * 24 * 3600) { + return _('about a month ago'); + } else if ($diff < 330 * 24 * 3600) { + return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); + } else if ($diff < 480 * 24 * 3600) { + return _('about a year ago'); + } else { + return common_exact_date($dt); + } } function common_exact_date($dt) { @@ -1317,885 +1317,885 @@ function common_exact_date($dt) { $_siteTz = new DateTimeZone(common_timezone()); } - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, $_utc); - $d->setTimezone($_siteTz); - return $d->format(DATE_RFC850); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, $_utc); + $d->setTimezone($_siteTz); + return $d->format(DATE_RFC850); } function common_date_w3dtf($dt) { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format(DATE_W3C); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format(DATE_W3C); } function common_date_rfc2822($dt) { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format('r'); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format('r'); } function common_date_iso8601($dt) { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format('c'); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format('c'); } function common_sql_now() { - return strftime('%Y-%m-%d %H:%M:%S', time()); + return strftime('%Y-%m-%d %H:%M:%S', time()); } function common_redirect($url, $code=307) { - static $status = array(301 => "Moved Permanently", - 302 => "Found", - 303 => "See Other", - 307 => "Temporary Redirect"); - header("Status: ${code} $status[$code]"); - header("Location: $url"); - - common_start_xml('a', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); - common_element('a', array('href' => $url), $url); - common_end_xml(); + static $status = array(301 => "Moved Permanently", + 302 => "Found", + 303 => "See Other", + 307 => "Temporary Redirect"); + header("Status: ${code} $status[$code]"); + header("Location: $url"); + + common_start_xml('a', + '-//W3C//DTD XHTML 1.0 Strict//EN', + 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + common_element('a', array('href' => $url), $url); + common_end_xml(); exit; } function common_save_replies($notice) { - # Alternative reply format - $tname = false; - if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { - $tname = $match[1]; - } - # extract all @messages - $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); - - $names = array(); - - if ($cnt || $tname) { - # XXX: is there another way to make an array copy? - $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); - } - - $sender = Profile::staticGet($notice->profile_id); - - $replied = array(); - - # store replied only for first @ (what user/notice what the reply directed, - # we assume first @ is it) - - for ($i=0; $icreated); - if (!$recipient) { - continue; - } - if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self - $reply_for = $recipient; - $recipient_notice = $reply_for->getCurrentNotice(); - if ($recipient_notice) { - $orig = clone($notice); - $notice->reply_to = $recipient_notice->id; - $notice->update($orig); - } - } - # Don't save replies from blocked profile to local user + // Alternative reply format + $tname = false; + if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { + $tname = $match[1]; + } + // extract all @messages + $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); + + $names = array(); + + if ($cnt || $tname) { + // XXX: is there another way to make an array copy? + $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); + } + + $sender = Profile::staticGet($notice->profile_id); + + $replied = array(); + + // store replied only for first @ (what user/notice what the reply directed, + // we assume first @ is it) + + for ($i=0; $icreated); + if (!$recipient) { + continue; + } + if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self + $reply_for = $recipient; + $recipient_notice = $reply_for->getCurrentNotice(); + if ($recipient_notice) { + $orig = clone($notice); + $notice->reply_to = $recipient_notice->id; + $notice->update($orig); + } + } + // Don't save replies from blocked profile to local user $recipient_user = User::staticGet('id', $recipient->id); if ($recipient_user && $recipient_user->hasBlocked($sender)) { continue; } - $reply = new Reply(); - $reply->notice_id = $notice->id; - $reply->profile_id = $recipient->id; - $id = $reply->insert(); - if (!$id) { - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); - common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); - return; - } else { - $replied[$recipient->id] = 1; - } - } - - # Hash format replies, too - $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); - if ($cnt) { - foreach ($match[1] as $tag) { - $tagged = Profile_tag::getTagged($sender->id, $tag); - foreach ($tagged as $t) { - if (!$replied[$t->id]) { - # Don't save replies from blocked profile to local user + $reply = new Reply(); + $reply->notice_id = $notice->id; + $reply->profile_id = $recipient->id; + $id = $reply->insert(); + if (!$id) { + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); + common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); + return; + } else { + $replied[$recipient->id] = 1; + } + } + + // Hash format replies, too + $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); + if ($cnt) { + foreach ($match[1] as $tag) { + $tagged = Profile_tag::getTagged($sender->id, $tag); + foreach ($tagged as $t) { + if (!$replied[$t->id]) { + // Don't save replies from blocked profile to local user $t_user = User::staticGet('id', $t->id); if ($t_user && $t_user->hasBlocked($sender)) { continue; } - $reply = new Reply(); - $reply->notice_id = $notice->id; - $reply->profile_id = $t->id; - $id = $reply->insert(); - if (!$id) { - common_log_db_error($reply, 'INSERT', __FILE__); - return; - } - } - } - } - } + $reply = new Reply(); + $reply->notice_id = $notice->id; + $reply->profile_id = $t->id; + $id = $reply->insert(); + if (!$id) { + common_log_db_error($reply, 'INSERT', __FILE__); + return; + } + } + } + } + } } 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) { + // 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 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)) { + 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); + $result = common_twitter_broadcast($notice, $flink); - if (!$result) { - common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__); - } - } - } + 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); - } else { - return common_real_broadcast($notice, $remote); - } + if (common_config('queue', 'enabled')) { + // Do it later! + return common_enqueue_notice($notice); + } else { + return common_real_broadcast($notice, $remote); + } } 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 - ); - - $ch = curl_init($uri); + 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 + ); + + $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; - } + if ($errmsg) { + common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", + __FILE__); + $success = false; + } - curl_close($ch); + curl_close($ch); - if (!$data) { - common_debug("No data returned by Twitter's API trying to send update for $twitter_user", - __FILE__); - $success = false; - } + 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); + // 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; - } + if (!$status->id) { + common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user", + __FILE__); + $success = false; + } - return $success; + return $success; } -# Stick the notice on the queue +// Stick the notice on the queue function common_enqueue_notice($notice) { - foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { - $qi = new Queue_item(); - $qi->notice_id = $notice->id; - $qi->transport = $transport; - $qi->created = $notice->created; + foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { + $qi = new Queue_item(); + $qi->notice_id = $notice->id; + $qi->transport = $transport; + $qi->created = $notice->created; $result = $qi->insert(); - if (!$result) { - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); - return false; - } - common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); - } - return $result; + if (!$result) { + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); + return false; + } + common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); + } + return $result; } function common_dequeue_notice($notice) { - $qi = Queue_item::staticGet($notice->id); - if ($qi) { - $result = $qi->delete(); - if (!$result) { - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); - return false; - } - common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); - return $result; - } else { + $qi = Queue_item::staticGet($notice->id); + if ($qi) { + $result = $qi->delete(); + if (!$result) { + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); return false; } + common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); + return $result; + } else { + return false; + } } function common_real_broadcast($notice, $remote=false) { - $success = true; - if (!$remote) { - # Make sure we have the OMB stuff - require_once(INSTALLDIR.'/lib/omb.php'); - $success = omb_broadcast_remote_subscribers($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); - } - } - if ($success) { - require_once(INSTALLDIR.'/lib/jabber.php'); - $success = jabber_broadcast_notice($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); - } - } - if ($success) { - require_once(INSTALLDIR.'/lib/mail.php'); - $success = mail_broadcast_notice_sms($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); - } - } - if ($success) { - $success = jabber_public_notice($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); - } - } - // XXX: broadcast notices to other IM - return $success; + $success = true; + if (!$remote) { + // Make sure we have the OMB stuff + require_once(INSTALLDIR.'/lib/omb.php'); + $success = omb_broadcast_remote_subscribers($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); + } + } + if ($success) { + require_once(INSTALLDIR.'/lib/jabber.php'); + $success = jabber_broadcast_notice($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); + } + } + if ($success) { + require_once(INSTALLDIR.'/lib/mail.php'); + $success = mail_broadcast_notice_sms($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); + } + } + if ($success) { + $success = jabber_public_notice($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); + } + } + // XXX: broadcast notices to other IM + return $success; } function common_broadcast_profile($profile) { - // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ - require_once(INSTALLDIR.'/lib/omb.php'); - omb_broadcast_profile($profile); - // XXX: Other broadcasts...? - return true; + // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ + require_once(INSTALLDIR.'/lib/omb.php'); + omb_broadcast_profile($profile); + // XXX: Other broadcasts...? + return true; } function common_profile_url($nickname) { - return common_local_url('showstream', array('nickname' => $nickname)); + return common_local_url('showstream', array('nickname' => $nickname)); } -# Don't call if nobody's logged in +// Don't call if nobody's logged in -function common_notice_form($action=NULL, $content=NULL) { - $user = common_current_user(); - assert(!is_null($user)); - common_element_start('form', array('id' => 'status_form', - 'method' => 'post', - 'action' => common_local_url('newnotice'))); - common_element_start('p'); - common_element('label', array('for' => 'status_textarea', - 'id' => 'status_label'), - sprintf(_('What\'s up, %s?'), $user->nickname)); +function common_notice_form($action=null, $content=null) { + $user = common_current_user(); + assert(!is_null($user)); + common_element_start('form', array('id' => 'status_form', + 'method' => 'post', + 'action' => common_local_url('newnotice'))); + common_element_start('p'); + common_element('label', array('for' => 'status_textarea', + 'id' => 'status_label'), + sprintf(_('What\'s up, %s?'), $user->nickname)); common_element('span', array('id' => 'counter', 'class' => 'counter'), '140'); - common_element('textarea', array('id' => 'status_textarea', - 'cols' => 60, - 'rows' => 3, - 'name' => 'status_textarea'), - ($content) ? $content : ''); - common_hidden('token', common_session_token()); - if ($action) { - common_hidden('returnto', $action); - } - # set by JavaScript - common_hidden('inreplyto', 'false'); - common_element('input', array('id' => 'status_submit', - 'name' => 'status_submit', - 'type' => 'submit', - 'value' => _('Send'))); - common_element_end('p'); - common_element_end('form'); -} - -# Should make up a reasonable root URL + common_element('textarea', array('id' => 'status_textarea', + 'cols' => 60, + 'rows' => 3, + 'name' => 'status_textarea'), + ($content) ? $content : ''); + common_hidden('token', common_session_token()); + if ($action) { + common_hidden('returnto', $action); + } + // set by JavaScript + common_hidden('inreplyto', 'false'); + common_element('input', array('id' => 'status_submit', + 'name' => 'status_submit', + 'type' => 'submit', + 'value' => _('Send'))); + common_element_end('p'); + common_element_end('form'); +} + +// Should make up a reasonable root URL function common_root_url() { - return common_path(''); + return common_path(''); } -# returns $bytes bytes of random data as a hexadecimal string -# "good" here is a goal and not a guarantee +// returns $bytes bytes of random data as a hexadecimal string +// "good" here is a goal and not a guarantee function common_good_rand($bytes) { - # XXX: use random.org...? - if (file_exists('/dev/urandom')) { - return common_urandom($bytes); - } else { # FIXME: this is probably not good enough - return common_mtrand($bytes); - } + // XXX: use random.org...? + if (file_exists('/dev/urandom')) { + return common_urandom($bytes); + } else { // FIXME: this is probably not good enough + return common_mtrand($bytes); + } } function common_urandom($bytes) { - $h = fopen('/dev/urandom', 'rb'); - # should not block - $src = fread($h, $bytes); - fclose($h); - $enc = ''; - for ($i = 0; $i < $bytes; $i++) { - $enc .= sprintf("%02x", (ord($src[$i]))); - } - return $enc; + $h = fopen('/dev/urandom', 'rb'); + // should not block + $src = fread($h, $bytes); + fclose($h); + $enc = ''; + for ($i = 0; $i < $bytes; $i++) { + $enc .= sprintf("%02x", (ord($src[$i]))); + } + return $enc; } function common_mtrand($bytes) { - $enc = ''; - for ($i = 0; $i < $bytes; $i++) { - $enc .= sprintf("%02x", mt_rand(0, 255)); - } - return $enc; + $enc = ''; + for ($i = 0; $i < $bytes; $i++) { + $enc .= sprintf("%02x", mt_rand(0, 255)); + } + return $enc; } function common_set_returnto($url) { - common_ensure_session(); - $_SESSION['returnto'] = $url; + common_ensure_session(); + $_SESSION['returnto'] = $url; } function common_get_returnto() { - common_ensure_session(); - return $_SESSION['returnto']; + common_ensure_session(); + return $_SESSION['returnto']; } function common_timestamp() { - return date('YmdHis'); + return date('YmdHis'); } function common_ensure_syslog() { - static $initialized = false; - if (!$initialized) { - global $config; - openlog($config['syslog']['appname'], 0, LOG_USER); - $initialized = true; - } -} - -function common_log($priority, $msg, $filename=NULL) { - $logfile = common_config('site', 'logfile'); - if ($logfile) { - $log = fopen($logfile, "a"); - if ($log) { - static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', - 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); - $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; - fwrite($log, $output); - fclose($log); - } - } else { - common_ensure_syslog(); - syslog($priority, $msg); - } -} - -function common_debug($msg, $filename=NULL) { - if ($filename) { - common_log(LOG_DEBUG, basename($filename).' - '.$msg); - } else { - common_log(LOG_DEBUG, $msg); - } -} - -function common_log_db_error(&$object, $verb, $filename=NULL) { - $objstr = common_log_objstring($object); - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); + static $initialized = false; + if (!$initialized) { + global $config; + openlog($config['syslog']['appname'], 0, LOG_USER); + $initialized = true; + } +} + +function common_log($priority, $msg, $filename=null) { + $logfile = common_config('site', 'logfile'); + if ($logfile) { + $log = fopen($logfile, "a"); + if ($log) { + static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', + 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); + $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; + fwrite($log, $output); + fclose($log); + } + } else { + common_ensure_syslog(); + syslog($priority, $msg); + } +} + +function common_debug($msg, $filename=null) { + if ($filename) { + common_log(LOG_DEBUG, basename($filename).' - '.$msg); + } else { + common_log(LOG_DEBUG, $msg); + } +} + +function common_log_db_error(&$object, $verb, $filename=null) { + $objstr = common_log_objstring($object); + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); } function common_log_objstring(&$object) { - if (is_null($object)) { - return "NULL"; - } - $arr = $object->toArray(); - $fields = array(); - foreach ($arr as $k => $v) { - $fields[] = "$k='$v'"; - } - $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; - return $objstring; + if (is_null($object)) { + return "null"; + } + $arr = $object->toArray(); + $fields = array(); + foreach ($arr as $k => $v) { + $fields[] = "$k='$v'"; + } + $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; + return $objstring; } function common_valid_http_url($url) { - return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); + return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); } function common_valid_tag($tag) { - if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { - return (Validate::email($matches[1]) || - preg_match('/^([\w-\.]+)$/', $matches[1])); - } - return false; + if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { + return (Validate::email($matches[1]) || + preg_match('/^([\w-\.]+)$/', $matches[1])); + } + return false; } -# Does a little before-after block for next/prev page +// Does a little before-after block for next/prev page -function common_pagination($have_before, $have_after, $page, $action, $args=NULL) { +function common_pagination($have_before, $have_after, $page, $action, $args=null) { - if ($have_before || $have_after) { - common_element_start('div', array('id' => 'pagination')); - common_element_start('ul', array('id' => 'nav_pagination')); - } + if ($have_before || $have_after) { + common_element_start('div', array('id' => 'pagination')); + common_element_start('ul', array('id' => 'nav_pagination')); + } - if ($have_before) { - $pargs = array('page' => $page-1); - $newargs = ($args) ? array_merge($args,$pargs) : $pargs; + if ($have_before) { + $pargs = array('page' => $page-1); + $newargs = ($args) ? array_merge($args,$pargs) : $pargs; - common_element_start('li', 'before'); - common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), - _('« After')); - common_element_end('li'); - } + common_element_start('li', 'before'); + common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), + _('« After')); + common_element_end('li'); + } - if ($have_after) { - $pargs = array('page' => $page+1); - $newargs = ($args) ? array_merge($args,$pargs) : $pargs; - common_element_start('li', 'after'); - common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), - _('Before »')); - common_element_end('li'); - } + if ($have_after) { + $pargs = array('page' => $page+1); + $newargs = ($args) ? array_merge($args,$pargs) : $pargs; + common_element_start('li', 'after'); + common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), + _('Before »')); + common_element_end('li'); + } - if ($have_before || $have_after) { - common_element_end('ul'); - common_element_end('div'); - } + if ($have_before || $have_after) { + common_element_end('ul'); + common_element_end('div'); + } } /* Following functions are copied from MediaWiki GlobalFunctions.php * and written by Evan Prodromou. */ function common_accept_to_prefs($accept, $def = '*/*') { - # No arg means accept anything (per HTTP spec) - if(!$accept) { - return array($def => 1); - } + // No arg means accept anything (per HTTP spec) + if(!$accept) { + return array($def => 1); + } - $prefs = array(); + $prefs = array(); - $parts = explode(',', $accept); + $parts = explode(',', $accept); - foreach($parts as $part) { - # FIXME: doesn't deal with params like 'text/html; level=1' - @list($value, $qpart) = explode(';', $part); - $match = array(); - if(!isset($qpart)) { - $prefs[$value] = 1; - } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { - $prefs[$value] = $match[1]; - } - } + foreach($parts as $part) { + // FIXME: doesn't deal with params like 'text/html; level=1' + @list($value, $qpart) = explode(';', $part); + $match = array(); + if(!isset($qpart)) { + $prefs[$value] = 1; + } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { + $prefs[$value] = $match[1]; + } + } - return $prefs; + return $prefs; } function common_mime_type_match($type, $avail) { - if(array_key_exists($type, $avail)) { - return $type; - } else { - $parts = explode('/', $type); - if(array_key_exists($parts[0] . '/*', $avail)) { - return $parts[0] . '/*'; - } elseif(array_key_exists('*/*', $avail)) { - return '*/*'; - } else { - return NULL; - } - } + if(array_key_exists($type, $avail)) { + return $type; + } else { + $parts = explode('/', $type); + if(array_key_exists($parts[0] . '/*', $avail)) { + return $parts[0] . '/*'; + } elseif(array_key_exists('*/*', $avail)) { + return '*/*'; + } else { + return null; + } + } } function common_negotiate_type($cprefs, $sprefs) { - $combine = array(); - - foreach(array_keys($sprefs) as $type) { - $parts = explode('/', $type); - if($parts[1] != '*') { - $ckey = common_mime_type_match($type, $cprefs); - if($ckey) { - $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; - } - } - } - - foreach(array_keys($cprefs) as $type) { - $parts = explode('/', $type); - if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { - $skey = common_mime_type_match($type, $sprefs); - if($skey) { - $combine[$type] = $sprefs[$skey] * $cprefs[$type]; - } - } - } - - $bestq = 0; - $besttype = "text/html"; - - foreach(array_keys($combine) as $type) { - if($combine[$type] > $bestq) { - $besttype = $type; - $bestq = $combine[$type]; - } - } - - return $besttype; + $combine = array(); + + foreach(array_keys($sprefs) as $type) { + $parts = explode('/', $type); + if($parts[1] != '*') { + $ckey = common_mime_type_match($type, $cprefs); + if($ckey) { + $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; + } + } + } + + foreach(array_keys($cprefs) as $type) { + $parts = explode('/', $type); + if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { + $skey = common_mime_type_match($type, $sprefs); + if($skey) { + $combine[$type] = $sprefs[$skey] * $cprefs[$type]; + } + } + } + + $bestq = 0; + $besttype = "text/html"; + + foreach(array_keys($combine) as $type) { + if($combine[$type] > $bestq) { + $besttype = $type; + $bestq = $combine[$type]; + } + } + + return $besttype; } function common_config($main, $sub) { - global $config; - return isset($config[$main][$sub]) ? $config[$main][$sub] : false; + global $config; + return isset($config[$main][$sub]) ? $config[$main][$sub] : false; } function common_copy_args($from) { - $to = array(); - $strip = get_magic_quotes_gpc(); - foreach ($from as $k => $v) { - $to[$k] = ($strip) ? stripslashes($v) : $v; - } - return $to; + $to = array(); + $strip = get_magic_quotes_gpc(); + foreach ($from as $k => $v) { + $to[$k] = ($strip) ? stripslashes($v) : $v; + } + return $to; } // Neutralise the evil effects of magic_quotes_gpc in the current request. // This is used before handing a request off to OAuthRequest::from_request. function common_remove_magic_from_request() { - if(get_magic_quotes_gpc()) { - $_POST=array_map('stripslashes',$_POST); - $_GET=array_map('stripslashes',$_GET); - } + if(get_magic_quotes_gpc()) { + $_POST=array_map('stripslashes',$_POST); + $_GET=array_map('stripslashes',$_GET); + } } function common_user_uri(&$user) { - return common_local_url('userbyid', array('id' => $user->id)); + return common_local_url('userbyid', array('id' => $user->id)); } function common_notice_uri(&$notice) { - return common_local_url('shownotice', - array('notice' => $notice->id)); + return common_local_url('shownotice', + array('notice' => $notice->id)); } -# 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits +// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits function common_confirmation_code($bits) { - # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits - static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; - $chars = ceil($bits/5); - $code = ''; - for ($i = 0; $i < $chars; $i++) { - # XXX: convert to string and back - $num = hexdec(common_good_rand(1)); - # XXX: randomness is too precious to throw away almost - # 40% of the bits we get! - $code .= $codechars[$num%32]; - } - return $code; -} - -# convert markup to HTML + // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits + static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; + $chars = ceil($bits/5); + $code = ''; + for ($i = 0; $i < $chars; $i++) { + // XXX: convert to string and back + $num = hexdec(common_good_rand(1)); + // XXX: randomness is too precious to throw away almost + // 40% of the bits we get! + $code .= $codechars[$num%32]; + } + return $code; +} + +// convert markup to HTML function common_markup_to_html($c) { - $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); - $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); - $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); - return Markdown($c); + $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); + $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); + $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); + return Markdown($c); } function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) { - $avatar = $profile->getAvatar($size); - if ($avatar) { - return common_avatar_display_url($avatar); - } else { - return common_default_avatar($size); - } + $avatar = $profile->getAvatar($size); + if ($avatar) { + return common_avatar_display_url($avatar); + } else { + return common_default_avatar($size); + } } function common_profile_uri($profile) { - if (!$profile) { - return NULL; - } - $user = User::staticGet($profile->id); - if ($user) { - return $user->uri; - } - - $remote = Remote_profile::staticGet($profile->id); - if ($remote) { - return $remote->uri; - } - # XXX: this is a very bad profile! - return NULL; + if (!$profile) { + return null; + } + $user = User::staticGet($profile->id); + if ($user) { + return $user->uri; + } + + $remote = Remote_profile::staticGet($profile->id); + if ($remote) { + return $remote->uri; + } + // XXX: this is a very bad profile! + return null; } function common_canonical_sms($sms) { - # strip non-digits - preg_replace('/\D/', '', $sms); - return $sms; + // strip non-digits + preg_replace('/\D/', '', $sms); + return $sms; } function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) { switch ($errno) { case E_USER_ERROR: - common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); - exit(1); - break; + common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); + exit(1); + break; - case E_USER_WARNING: - common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); - break; + case E_USER_WARNING: + common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); + break; case E_USER_NOTICE: - common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); - break; + common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); + break; } - # FIXME: show error page if we're on the Web + // FIXME: show error page if we're on the Web /* Don't execute PHP internal error handler */ return true; } function common_session_token() { - common_ensure_session(); - if (!array_key_exists('token', $_SESSION)) { - $_SESSION['token'] = common_good_rand(64); - } - return $_SESSION['token']; + common_ensure_session(); + if (!array_key_exists('token', $_SESSION)) { + $_SESSION['token'] = common_good_rand(64); + } + return $_SESSION['token']; } function common_disfavor_form($notice) { - common_element_start('form', array('id' => 'disfavor-' . $notice->id, - 'method' => 'post', - 'class' => 'disfavor', - 'action' => common_local_url('disfavor'))); - - common_element('input', array('type' => 'hidden', - 'name' => 'token-'. $notice->id, - 'id' => 'token-'. $notice->id, - 'class' => 'token', - 'value' => common_session_token())); - - common_element('input', array('type' => 'hidden', - 'name' => 'notice', - 'id' => 'notice-n'. $notice->id, - 'class' => 'notice', - 'value' => $notice->id)); - - common_element('input', array('type' => 'submit', - 'id' => 'disfavor-submit-' . $notice->id, - 'name' => 'disfavor-submit-' . $notice->id, - 'class' => 'disfavor', - 'value' => 'Disfavor favorite', - 'title' => 'Remove this message from favorites')); - common_element_end('form'); + common_element_start('form', array('id' => 'disfavor-' . $notice->id, + 'method' => 'post', + 'class' => 'disfavor', + 'action' => common_local_url('disfavor'))); + + common_element('input', array('type' => 'hidden', + 'name' => 'token-'. $notice->id, + 'id' => 'token-'. $notice->id, + 'class' => 'token', + 'value' => common_session_token())); + + common_element('input', array('type' => 'hidden', + 'name' => 'notice', + 'id' => 'notice-n'. $notice->id, + 'class' => 'notice', + 'value' => $notice->id)); + + common_element('input', array('type' => 'submit', + 'id' => 'disfavor-submit-' . $notice->id, + 'name' => 'disfavor-submit-' . $notice->id, + 'class' => 'disfavor', + 'value' => 'Disfavor favorite', + 'title' => 'Remove this message from favorites')); + common_element_end('form'); } function common_favor_form($notice) { - common_element_start('form', array('id' => 'favor-' . $notice->id, - 'method' => 'post', - 'class' => 'favor', - 'action' => common_local_url('favor'))); - - common_element('input', array('type' => 'hidden', - 'name' => 'token-'. $notice->id, - 'id' => 'token-'. $notice->id, - 'class' => 'token', - 'value' => common_session_token())); - - common_element('input', array('type' => 'hidden', - 'name' => 'notice', - 'id' => 'notice-n'. $notice->id, - 'class' => 'notice', - 'value' => $notice->id)); - - common_element('input', array('type' => 'submit', - 'id' => 'favor-submit-' . $notice->id, - 'name' => 'favor-submit-' . $notice->id, - 'class' => 'favor', - 'value' => 'Add to favorites', - 'title' => 'Add this message to favorites')); - common_element_end('form'); + common_element_start('form', array('id' => 'favor-' . $notice->id, + 'method' => 'post', + 'class' => 'favor', + 'action' => common_local_url('favor'))); + + common_element('input', array('type' => 'hidden', + 'name' => 'token-'. $notice->id, + 'id' => 'token-'. $notice->id, + 'class' => 'token', + 'value' => common_session_token())); + + common_element('input', array('type' => 'hidden', + 'name' => 'notice', + 'id' => 'notice-n'. $notice->id, + 'class' => 'notice', + 'value' => $notice->id)); + + common_element('input', array('type' => 'submit', + 'id' => 'favor-submit-' . $notice->id, + 'name' => 'favor-submit-' . $notice->id, + 'class' => 'favor', + 'value' => 'Add to favorites', + 'title' => 'Add this message to favorites')); + common_element_end('form'); } function common_nudge_form($profile) { - common_element_start('form', array('id' => 'nudge', 'method' => 'post', - 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); - common_hidden('token', common_session_token()); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Send a nudge'))); - common_element_end('form'); + common_element_start('form', array('id' => 'nudge', 'method' => 'post', + 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); + common_hidden('token', common_session_token()); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Send a nudge'))); + common_element_end('form'); } function common_nudge_response() { - common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); + common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); } function common_subscribe_form($profile) { - common_element_start('form', array('id' => 'subscribe-' . $profile->id, - 'method' => 'post', - 'class' => 'subscribe', - 'action' => common_local_url('subscribe'))); - common_hidden('token', common_session_token()); - common_element('input', array('id' => 'subscribeto-' . $profile->id, - 'name' => 'subscribeto', - 'type' => 'hidden', - 'value' => $profile->id)); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Subscribe'))); - common_element_end('form'); + common_element_start('form', array('id' => 'subscribe-' . $profile->id, + 'method' => 'post', + 'class' => 'subscribe', + 'action' => common_local_url('subscribe'))); + common_hidden('token', common_session_token()); + common_element('input', array('id' => 'subscribeto-' . $profile->id, + 'name' => 'subscribeto', + 'type' => 'hidden', + 'value' => $profile->id)); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Subscribe'))); + common_element_end('form'); } function common_unsubscribe_form($profile) { - common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, - 'method' => 'post', - 'class' => 'unsubscribe', - 'action' => common_local_url('unsubscribe'))); - common_hidden('token', common_session_token()); - common_element('input', array('id' => 'unsubscribeto-' . $profile->id, - 'name' => 'unsubscribeto', - 'type' => 'hidden', - 'value' => $profile->id)); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Unsubscribe'))); - common_element_end('form'); + common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, + 'method' => 'post', + 'class' => 'unsubscribe', + 'action' => common_local_url('unsubscribe'))); + common_hidden('token', common_session_token()); + common_element('input', array('id' => 'unsubscribeto-' . $profile->id, + 'name' => 'unsubscribeto', + 'type' => 'hidden', + 'value' => $profile->id)); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Unsubscribe'))); + common_element_end('form'); } // XXX: Refactor this code function common_profile_new_message_nudge ($cur, $profile) { - $user = User::staticGet('id', $profile->id); + $user = User::staticGet('id', $profile->id); - if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { + if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { common_element_start('li', array('id' => 'profile_send_a_new_message')); - common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), - _('Send a message')); + common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), + _('Send a message')); common_element_end('li'); - if ($user->email && $user->emailnotifynudge) { + if ($user->email && $user->emailnotifynudge) { common_element_start('li', array('id' => 'profile_nudge')); common_nudge_form($user); common_element_end('li'); } - } + } } function common_cache_key($extra) { - return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; + return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; } function common_keyize($str) { - $str = strtolower($str); - $str = preg_replace('/\s/', '_', $str); - return $str; + $str = strtolower($str); + $str = preg_replace('/\s/', '_', $str); + return $str; } function common_message_form($content, $user, $to) { - common_element_start('form', array('id' => 'message_form', - 'method' => 'post', - 'action' => common_local_url('newmessage'))); + common_element_start('form', array('id' => 'message_form', + 'method' => 'post', + 'action' => common_local_url('newmessage'))); - $mutual_users = $user->mutuallySubscribedUsers(); + $mutual_users = $user->mutuallySubscribedUsers(); - $mutual = array(); + $mutual = array(); - while ($mutual_users->fetch()) { - if ($mutual_users->id != $user->id) { - $mutual[$mutual_users->id] = $mutual_users->nickname; - } - } + while ($mutual_users->fetch()) { + if ($mutual_users->id != $user->id) { + $mutual[$mutual_users->id] = $mutual_users->nickname; + } + } - $mutual_users->free(); - unset($mutual_users); + $mutual_users->free(); + unset($mutual_users); - common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id); + common_dropdown('to', _('To'), $mutual, null, FALSE, $to->id); - common_element_start('p'); + common_element_start('p'); - common_element('textarea', array('id' => 'message_content', - 'cols' => 60, - 'rows' => 3, - 'name' => 'content'), - ($content) ? $content : ''); + common_element('textarea', array('id' => 'message_content', + 'cols' => 60, + 'rows' => 3, + 'name' => 'content'), + ($content) ? $content : ''); - common_element('input', array('id' => 'message_send', - 'name' => 'message_send', - 'type' => 'submit', - 'value' => _('Send'))); + common_element('input', array('id' => 'message_send', + 'name' => 'message_send', + 'type' => 'submit', + 'value' => _('Send'))); - common_hidden('token', common_session_token()); + common_hidden('token', common_session_token()); - common_element_end('p'); - common_element_end('form'); + common_element_end('p'); + common_element_end('form'); } function common_memcache() { - static $cache = NULL; - if (!common_config('memcached', 'enabled')) { - return NULL; - } else { - if (!$cache) { - $cache = new Memcache(); - $servers = common_config('memcached', 'server'); - if (is_array($servers)) { - foreach($servers as $server) { - $cache->addServer($server); - } - } else { - $cache->addServer($servers); - } - } - return $cache; - } + static $cache = null; + if (!common_config('memcached', 'enabled')) { + return null; + } else { + if (!$cache) { + $cache = new Memcache(); + $servers = common_config('memcached', 'server'); + if (is_array($servers)) { + foreach($servers as $server) { + $cache->addServer($server); + } + } else { + $cache->addServer($servers); + } + } + return $cache; + } } function common_compatible_license($from, $to) { - # XXX: better compatibility check needed here! - return ($from == $to); + // XXX: better compatibility check needed here! + return ($from == $to); } /* These are almost identical, so we use a helper function */ -function common_block_form($profile, $args=NULL) { +function common_block_form($profile, $args=null) { common_blocking_form('block', _('Block'), $profile, $args); } -function common_unblock_form($profile, $args=NULL) { +function common_unblock_form($profile, $args=null) { common_blocking_form('unblock', _('Unblock'), $profile, $args); } -function common_blocking_form($type, $label, $profile, $args=NULL) { +function common_blocking_form($type, $label, $profile, $args=null) { common_element_start('form', array('id' => $type . '-' . $profile->id, 'method' => 'post', 'class' => $type, @@ -2217,4 +2217,3 @@ function common_blocking_form($type, $label, $profile, $args=NULL) { common_element_end('form'); return; } - diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index fa3a0e58e..487d2bcdc 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,52 +1,3368 @@ -hunk ./index.php 2 --/* -+/** -hunk ./index.php 23 --require_once(INSTALLDIR . "/lib/common.php"); -+require_once INSTALLDIR . '/lib/common.php'; -hunk ./index.php 25 --# get and cache current user -+// get and cache current user -hunk ./index.php 29 --# initialize language env -+// initialize language env -hunk ./index.php 44 -- 'recoverpassword', 'api', 'doc', 'register'))) --{ -+ 'recoverpassword', 'api', 'doc', 'register'))) { -hunk ./index.php 51 -- require_once($actionfile); -- $action_class = ucfirst($action)."Action"; -+ -+ include_once $actionfile; -+ -+ $action_class = ucfirst($action).'Action'; -+ -hunk ./index.php 57 -- if ($config['db']['mirror'] && $action_obj->is_readonly()) { -- if (is_array($config['db']['mirror'])) { -- # "load balancing", ha ha -- $k = array_rand($config['db']['mirror']); -- $mirror = $config['db']['mirror'][$k]; -- } else { -- $mirror = $config['db']['mirror']; -- } -- $config['db']['database'] = $mirror; -- } -+ -+ if ($config['db']['mirror'] && $action_obj->is_readonly()) { -+ if (is_array($config['db']['mirror'])) { -+ // "load balancing", ha ha -+ $k = array_rand($config['db']['mirror']); -+ -+ $mirror = $config['db']['mirror'][$k]; -+ } else { -+ $mirror = $config['db']['mirror']; -+ } -+ $config['db']['database'] = $mirror; -+ } -hunk ./index.php 70 -- call_user_func(array($action_obj, 'handle'), $_REQUEST); -- } -+ call_user_func(array($action_obj, 'handle'), $_REQUEST); +hunk ./lib/util.php 22 +-# Show a server error ++// Show a server error +hunk ./lib/util.php 25 +- static $status = array(500 => 'Internal Server Error', +- 501 => 'Not Implemented', +- 502 => 'Bad Gateway', +- 503 => 'Service Unavailable', +- 504 => 'Gateway Timeout', +- 505 => 'HTTP Version Not Supported'); ++ static $status = array(500 => 'Internal Server Error', ++ 501 => 'Not Implemented', ++ 502 => 'Bad Gateway', ++ 503 => 'Service Unavailable', ++ 504 => 'Gateway Timeout', ++ 505 => 'HTTP Version Not Supported'); +hunk ./lib/util.php 32 +- if (!array_key_exists($code, $status)) { +- $code = 500; +- } ++ if (!array_key_exists($code, $status)) { ++ $code = 500; ++ } +hunk ./lib/util.php 36 +- $status_string = $status[$code]; ++ $status_string = $status[$code]; +hunk ./lib/util.php 38 +- header('HTTP/1.1 '.$code.' '.$status_string); +- header('Content-type: text/plain'); ++ header('HTTP/1.1 '.$code.' '.$status_string); ++ header('Content-type: text/plain'); +hunk ./lib/util.php 41 +- print $msg; +- print "\n"; +- exit(); ++ print $msg; ++ print "\n"; ++ exit(); +hunk ./lib/util.php 46 +-# Show a user error ++// Show a user error +hunk ./lib/util.php 48 +- static $status = array(400 => 'Bad Request', +- 401 => 'Unauthorized', +- 402 => 'Payment Required', +- 403 => 'Forbidden', +- 404 => 'Not Found', +- 405 => 'Method Not Allowed', +- 406 => 'Not Acceptable', +- 407 => 'Proxy Authentication Required', +- 408 => 'Request Timeout', +- 409 => 'Conflict', +- 410 => 'Gone', +- 411 => 'Length Required', +- 412 => 'Precondition Failed', +- 413 => 'Request Entity Too Large', +- 414 => 'Request-URI Too Long', +- 415 => 'Unsupported Media Type', +- 416 => 'Requested Range Not Satisfiable', +- 417 => 'Expectation Failed'); ++ static $status = array(400 => 'Bad Request', ++ 401 => 'Unauthorized', ++ 402 => 'Payment Required', ++ 403 => 'Forbidden', ++ 404 => 'Not Found', ++ 405 => 'Method Not Allowed', ++ 406 => 'Not Acceptable', ++ 407 => 'Proxy Authentication Required', ++ 408 => 'Request Timeout', ++ 409 => 'Conflict', ++ 410 => 'Gone', ++ 411 => 'Length Required', ++ 412 => 'Precondition Failed', ++ 413 => 'Request Entity Too Large', ++ 414 => 'Request-URI Too Long', ++ 415 => 'Unsupported Media Type', ++ 416 => 'Requested Range Not Satisfiable', ++ 417 => 'Expectation Failed'); +hunk ./lib/util.php 67 +- if (!array_key_exists($code, $status)) { +- $code = 400; +- } ++ if (!array_key_exists($code, $status)) { ++ $code = 400; ++ } +hunk ./lib/util.php 71 +- $status_string = $status[$code]; ++ $status_string = $status[$code]; +hunk ./lib/util.php 73 +- header('HTTP/1.1 '.$code.' '.$status_string); ++ header('HTTP/1.1 '.$code.' '.$status_string); +hunk ./lib/util.php 75 +- common_show_header('Error'); +- common_element('div', array('class' => 'error'), $msg); +- common_show_footer(); ++ common_show_header('Error'); ++ common_element('div', array('class' => 'error'), $msg); ++ common_show_footer(); +hunk ./lib/util.php 82 +-# Start an HTML element +-function common_element_start($tag, $attrs=NULL) { +- global $xw; +- $xw->startElement($tag); +- if (is_array($attrs)) { +- foreach ($attrs as $name => $value) { +- $xw->writeAttribute($name, $value); +- } +- } else if (is_string($attrs)) { +- $xw->writeAttribute('class', $attrs); +- } ++// Start an HTML element ++function common_element_start($tag, $attrs=null) { ++ global $xw; ++ $xw->startElement($tag); ++ if (is_array($attrs)) { ++ foreach ($attrs as $name => $value) { ++ $xw->writeAttribute($name, $value); ++ } ++ } else if (is_string($attrs)) { ++ $xw->writeAttribute('class', $attrs); ++ } +hunk ./lib/util.php 96 +- static $empty_tag = array('base', 'meta', 'link', 'hr', +- 'br', 'param', 'img', 'area', +- 'input', 'col'); +- global $xw; +- # XXX: check namespace +- if (in_array($tag, $empty_tag)) { +- $xw->endElement(); +- } else { +- $xw->fullEndElement(); +- } ++ static $empty_tag = array('base', 'meta', 'link', 'hr', ++ 'br', 'param', 'img', 'area', ++ 'input', 'col'); ++ global $xw; ++ // XXX: check namespace ++ if (in_array($tag, $empty_tag)) { ++ $xw->endElement(); ++ } else { ++ $xw->fullEndElement(); ++ } +hunk ./lib/util.php 108 +-function common_element($tag, $attrs=NULL, $content=NULL) { +- common_element_start($tag, $attrs); +- global $xw; +- if (!is_null($content)) { +- $xw->text($content); +- } +- common_element_end($tag); ++function common_element($tag, $attrs=null, $content=null) { ++ common_element_start($tag, $attrs); ++ global $xw; ++ if (!is_null($content)) { ++ $xw->text($content); ++ } ++ common_element_end($tag); +hunk ./lib/util.php 117 +-function common_start_xml($doc=NULL, $public=NULL, $system=NULL, $indent=true) { +- global $xw; +- $xw = new XMLWriter(); +- $xw->openURI('php://output'); +- $xw->setIndent($indent); +- $xw->startDocument('1.0', 'UTF-8'); +- if ($doc) { +- $xw->writeDTD($doc, $public, $system); +- } ++function common_start_xml($doc=null, $public=null, $system=null, $indent=true) { ++ global $xw; ++ $xw = new XMLWriter(); ++ $xw->openURI('php://output'); ++ $xw->setIndent($indent); ++ $xw->startDocument('1.0', 'UTF-8'); ++ if ($doc) { ++ $xw->writeDTD($doc, $public, $system); ++ } +hunk ./lib/util.php 129 +- global $xw; +- $xw->endDocument(); +- $xw->flush(); ++ global $xw; ++ $xw->endDocument(); ++ $xw->flush(); +hunk ./lib/util.php 141 +- $language . ".UTF8", +- $language . ".utf-8", +- $language . ".UTF-8", +- $language); ++ $language . ".UTF8", ++ $language . ".utf-8", ++ $language . ".UTF-8", ++ $language); +hunk ./lib/util.php 148 +- mb_internal_encoding('UTF-8'); +- $language = common_language(); +- # So we don't have to make people install the gettext locales +- $locale_set = common_init_locale($language); +- bindtextdomain("laconica", common_config('site','locale_path')); +- bind_textdomain_codeset("laconica", "UTF-8"); +- textdomain("laconica"); +- setlocale(LC_CTYPE, 'C'); +- if(!$locale_set) { +- common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); +- } ++ mb_internal_encoding('UTF-8'); ++ $language = common_language(); ++ // So we don't have to make people install the gettext locales ++ $locale_set = common_init_locale($language); ++ bindtextdomain("laconica", common_config('site','locale_path')); ++ bind_textdomain_codeset("laconica", "UTF-8"); ++ textdomain("laconica"); ++ setlocale(LC_CTYPE, 'C'); ++ if(!$locale_set) { ++ common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); ++ } +hunk ./lib/util.php 163 +-function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) { ++function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null) { +hunk ./lib/util.php 165 +- global $config, $xw; ++ global $config, $xw; +hunk ./lib/util.php 168 +- common_start_html(); ++ common_start_html(); +hunk ./lib/util.php 170 +- common_element_start('head'); +- common_element('title', NULL, +- $pagetitle . " - " . $config['site']['name']); +- common_element('link', array('rel' => 'stylesheet', +- 'type' => 'text/css', +- 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, +- 'media' => 'screen, projection, tv')); +- foreach (array(6,7) as $ver) { +- if (file_exists(theme_file('ie'.$ver.'.css'))) { +- # Yes, IE people should be put in jail. +- $xw->writeComment('[if lte IE '.$ver.']> 'stylesheet', ++ 'type' => 'text/css', ++ 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, ++ 'media' => 'screen, projection, tv')); ++ foreach (array(6,7) as $ver) { ++ if (file_exists(theme_file('ie'.$ver.'.css'))) { ++ // Yes, IE people should be put in jail. ++ $xw->writeComment('[if lte IE '.$ver.']> 'text/javascript', +- 'src' => common_path('js/jquery.min.js')), +- ' '); +- common_element('script', array('type' => 'text/javascript', +- 'src' => common_path('js/jquery.form.js')), +- ' '); +- common_element('script', array('type' => 'text/javascript', +- 'src' => common_path('js/xbImportNode.js')), +- ' '); +- common_element('script', array('type' => 'text/javascript', +- 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), +- ' '); +- common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', +- 'href' => common_local_url('opensearch', array('type' => 'people')), +- 'title' => common_config('site', 'name').' People Search')); ++ common_element('script', array('type' => 'text/javascript', ++ 'src' => common_path('js/jquery.min.js')), ++ ' '); ++ common_element('script', array('type' => 'text/javascript', ++ 'src' => common_path('js/jquery.form.js')), ++ ' '); ++ common_element('script', array('type' => 'text/javascript', ++ 'src' => common_path('js/xbImportNode.js')), ++ ' '); ++ common_element('script', array('type' => 'text/javascript', ++ 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), ++ ' '); ++ common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', ++ 'href' => common_local_url('opensearch', array('type' => 'people')), ++ 'title' => common_config('site', 'name').' People Search')); +hunk ./lib/util.php 201 +- common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', +- 'href' => common_local_url('opensearch', array('type' => 'notice')), +- 'title' => common_config('site', 'name').' Notice Search')); ++ common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', ++ 'href' => common_local_url('opensearch', array('type' => 'notice')), ++ 'title' => common_config('site', 'name').' Notice Search')); +hunk ./lib/util.php 205 +- if ($callable) { +- if ($data) { +- call_user_func($callable, $data); +- } else { +- call_user_func($callable); +- } +- } +- common_element_end('head'); +- common_element_start('body', $action); +- common_element_start('div', array('id' => 'wrap')); +- common_element_start('div', array('id' => 'header')); +- common_nav_menu(); +- if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) +- || file_exists(theme_file('logo.png'))) +- { +- common_element_start('a', array('href' => common_local_url('public'))); +- common_element('img', array('src' => isset($config['site']['logo']) ? +- ($config['site']['logo']) : theme_path('logo.png'), +- 'alt' => $config['site']['name'], +- 'id' => 'logo')); +- common_element_end('a'); +- } else { +- common_element_start('p', array('id' => 'branding')); +- common_element('a', array('href' => common_local_url('public')), +- $config['site']['name']); +- common_element_end('p'); +- } ++ if ($callable) { ++ if ($data) { ++ call_user_func($callable, $data); ++ } else { ++ call_user_func($callable); ++ } ++ } ++ common_element_end('head'); ++ common_element_start('body', $action); ++ common_element_start('div', array('id' => 'wrap')); ++ common_element_start('div', array('id' => 'header')); ++ common_nav_menu(); ++ if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) ++ || file_exists(theme_file('logo.png'))) ++ { ++ common_element_start('a', array('href' => common_local_url('public'))); ++ common_element('img', array('src' => isset($config['site']['logo']) ? ++ ($config['site']['logo']) : theme_path('logo.png'), ++ 'alt' => $config['site']['name'], ++ 'id' => 'logo')); ++ common_element_end('a'); ++ } else { ++ common_element_start('p', array('id' => 'branding')); ++ common_element('a', array('href' => common_local_url('public')), ++ $config['site']['name']); ++ common_element_end('p'); ++ } +hunk ./lib/util.php 233 +- common_element('h1', 'pagetitle', $pagetitle); ++ common_element('h1', 'pagetitle', $pagetitle); +hunk ./lib/util.php 235 +- if ($headercall) { +- if ($data) { +- call_user_func($headercall, $data); +- } else { +- call_user_func($headercall); +- } +- } +- common_element_end('div'); +- common_element_start('div', array('id' => 'content')); ++ if ($headercall) { ++ if ($data) { ++ call_user_func($headercall, $data); ++ } else { ++ call_user_func($headercall); ++ } ++ } ++ common_element_end('div'); ++ common_element_start('div', array('id' => 'content')); +hunk ./lib/util.php 246 +-function common_start_html($type=NULL, $indent=true) { ++function common_start_html($type=null, $indent=true) { +hunk ./lib/util.php 248 +- if (!$type) { +- $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL; ++ if (!$type) { ++ $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; +hunk ./lib/util.php 251 +- # XXX: allow content negotiation for RDF, RSS, or XRDS ++ // XXX: allow content negotiation for RDF, RSS, or XRDS +hunk ./lib/util.php 253 +- $type = common_negotiate_type(common_accept_to_prefs($httpaccept), +- common_accept_to_prefs(PAGE_TYPE_PREFS)); ++ $type = common_negotiate_type(common_accept_to_prefs($httpaccept), ++ common_accept_to_prefs(PAGE_TYPE_PREFS)); +hunk ./lib/util.php 256 +- if (!$type) { +- common_user_error(_('This page is not available in a media type you accept'), 406); +- exit(0); +- } +- } ++ if (!$type) { ++ common_user_error(_('This page is not available in a media type you accept'), 406); ++ exit(0); ++ } ++ } +hunk ./lib/util.php 262 +- header('Content-Type: '.$type); ++ header('Content-Type: '.$type); +hunk ./lib/util.php 264 +- common_start_xml('html', +- '-//W3C//DTD XHTML 1.0 Strict//EN', +- 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); ++ common_start_xml('html', ++ '-//W3C//DTD XHTML 1.0 Strict//EN', ++ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); +hunk ./lib/util.php 268 +- # FIXME: correct language for interface ++ // FIXME: correct language for interface +hunk ./lib/util.php 270 +- $language = common_language(); ++ $language = common_language(); +hunk ./lib/util.php 272 +- common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', +- 'xml:lang' => $language, +- 'lang' => $language)); ++ common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', ++ 'xml:lang' => $language, ++ 'lang' => $language)); +hunk ./lib/util.php 278 +- global $xw, $config; +- common_element_end('div'); # content div +- common_foot_menu(); +- common_element_start('div', array('id' => 'footer')); +- common_element_start('div', 'laconica'); +- if (common_config('site', 'broughtby')) { +- $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); +- } else { +- $instr = _('**%%site.name%%** is a microblogging service. '); +- } +- $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); ++ global $xw, $config; ++ common_element_end('div'); // content div ++ common_foot_menu(); ++ common_element_start('div', array('id' => 'footer')); ++ common_element_start('div', 'laconica'); ++ if (common_config('site', 'broughtby')) { ++ $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); ++ } else { ++ $instr = _('**%%site.name%%** is a microblogging service. '); ++ } ++ $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); +hunk ./lib/util.php 291 +- common_element_end('div'); +- common_element('img', array('id' => 'cc', +- 'src' => $config['license']['image'], +- 'alt' => $config['license']['title'])); +- common_element_start('p'); +- common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); +- common_element('a', array('class' => 'license', +- 'rel' => 'license', +- 'href' => $config['license']['url']), +- $config['license']['title']); +- common_text(_('. Contributors should be attributed by full name or nickname.')); +- common_element_end('p'); +- common_element_end('div'); +- common_element_end('div'); +- common_element_end('body'); +- common_element_end('html'); +- common_end_xml(); ++ common_element_end('div'); ++ common_element('img', array('id' => 'cc', ++ 'src' => $config['license']['image'], ++ 'alt' => $config['license']['title'])); ++ common_element_start('p'); ++ common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); ++ common_element('a', array('class' => 'license', ++ 'rel' => 'license', ++ 'href' => $config['license']['url']), ++ $config['license']['title']); ++ common_text(_('. Contributors should be attributed by full name or nickname.')); ++ common_element_end('p'); ++ common_element_end('div'); ++ common_element_end('div'); ++ common_element_end('body'); ++ common_element_end('html'); ++ common_end_xml(); +hunk ./lib/util.php 311 +- global $xw; +- $xw->text($txt); ++ global $xw; ++ $xw->text($txt); +hunk ./lib/util.php 316 +- global $xw; +- $xw->writeRaw($xml); ++ global $xw; ++ $xw->writeRaw($xml); +hunk ./lib/util.php 321 +- $user = common_current_user(); +- common_element_start('ul', array('id' => 'nav')); +- if ($user) { +- common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), +- _('Home')); +- } +- common_menu_item(common_local_url('peoplesearch'), _('Search')); +- if ($user) { +- common_menu_item(common_local_url('profilesettings'), +- _('Settings')); +- common_menu_item(common_local_url('invite'), +- _('Invite')); +- common_menu_item(common_local_url('logout'), +- _('Logout')); +- } else { +- common_menu_item(common_local_url('login'), _('Login')); +- if (!common_config('site', 'closed')) { +- common_menu_item(common_local_url('register'), _('Register')); +- } +- common_menu_item(common_local_url('openidlogin'), _('OpenID')); +- } +- common_menu_item(common_local_url('doc', array('title' => 'help')), +- _('Help')); +- common_element_end('ul'); ++ $user = common_current_user(); ++ common_element_start('ul', array('id' => 'nav')); ++ if ($user) { ++ common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), ++ _('Home')); ++ } ++ common_menu_item(common_local_url('peoplesearch'), _('Search')); ++ if ($user) { ++ common_menu_item(common_local_url('profilesettings'), ++ _('Settings')); ++ common_menu_item(common_local_url('invite'), ++ _('Invite')); ++ common_menu_item(common_local_url('logout'), ++ _('Logout')); ++ } else { ++ common_menu_item(common_local_url('login'), _('Login')); ++ if (!common_config('site', 'closed')) { ++ common_menu_item(common_local_url('register'), _('Register')); ++ } ++ common_menu_item(common_local_url('openidlogin'), _('OpenID')); ++ } ++ common_menu_item(common_local_url('doc', array('title' => 'help')), ++ _('Help')); ++ common_element_end('ul'); +hunk ./lib/util.php 348 +- common_element_start('ul', array('id' => 'nav_sub')); +- common_menu_item(common_local_url('doc', array('title' => 'help')), +- _('Help')); +- common_menu_item(common_local_url('doc', array('title' => 'about')), +- _('About')); +- common_menu_item(common_local_url('doc', array('title' => 'faq')), +- _('FAQ')); +- common_menu_item(common_local_url('doc', array('title' => 'privacy')), +- _('Privacy')); +- common_menu_item(common_local_url('doc', array('title' => 'source')), +- _('Source')); +- common_menu_item(common_local_url('doc', array('title' => 'contact')), +- _('Contact')); +- common_element_end('ul'); ++ common_element_start('ul', array('id' => 'nav_sub')); ++ common_menu_item(common_local_url('doc', array('title' => 'help')), ++ _('Help')); ++ common_menu_item(common_local_url('doc', array('title' => 'about')), ++ _('About')); ++ common_menu_item(common_local_url('doc', array('title' => 'faq')), ++ _('FAQ')); ++ common_menu_item(common_local_url('doc', array('title' => 'privacy')), ++ _('Privacy')); ++ common_menu_item(common_local_url('doc', array('title' => 'source')), ++ _('Source')); ++ common_menu_item(common_local_url('doc', array('title' => 'contact')), ++ _('Contact')); ++ common_element_end('ul'); +hunk ./lib/util.php 364 +-function common_menu_item($url, $text, $title=NULL, $is_selected=false) { +- $lattrs = array(); +- if ($is_selected) { +- $lattrs['class'] = 'current'; +- } +- common_element_start('li', $lattrs); +- $attrs['href'] = $url; +- if ($title) { +- $attrs['title'] = $title; +- } +- common_element('a', $attrs, $text); +- common_element_end('li'); ++function common_menu_item($url, $text, $title=null, $is_selected=false) { ++ $lattrs = array(); ++ if ($is_selected) { ++ $lattrs['class'] = 'current'; ++ } ++ common_element_start('li', $lattrs); ++ $attrs['href'] = $url; ++ if ($title) { ++ $attrs['title'] = $title; ++ } ++ common_element('a', $attrs, $text); ++ common_element_end('li'); +hunk ./lib/util.php 378 +-function common_input($id, $label, $value=NULL,$instructions=NULL) { +- common_element_start('p'); +- common_element('label', array('for' => $id), $label); +- $attrs = array('name' => $id, +- 'type' => 'text', +- 'class' => 'input_text', +- 'id' => $id); +- if ($value) { +- $attrs['value'] = htmlspecialchars($value); +- } +- common_element('input', $attrs); +- if ($instructions) { +- common_element('span', 'input_instructions', $instructions); +- } +- common_element_end('p'); ++function common_input($id, $label, $value=null,$instructions=null) { ++ common_element_start('p'); ++ common_element('label', array('for' => $id), $label); ++ $attrs = array('name' => $id, ++ 'type' => 'text', ++ 'class' => 'input_text', ++ 'id' => $id); ++ if ($value) { ++ $attrs['value'] = htmlspecialchars($value); ++ } ++ common_element('input', $attrs); ++ if ($instructions) { ++ common_element('span', 'input_instructions', $instructions); ++ } ++ common_element_end('p'); +hunk ./lib/util.php 395 +-function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false) ++function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false) +hunk ./lib/util.php 397 +- common_element_start('p'); +- $attrs = array('name' => $id, +- 'type' => 'checkbox', +- 'class' => 'checkbox', +- 'id' => $id); +- if ($value) { +- $attrs['value'] = htmlspecialchars($value); +- } +- if ($checked) { +- $attrs['checked'] = 'checked'; +- } +- if ($disabled) { +- $attrs['disabled'] = 'true'; +- } +- common_element('input', $attrs); +- common_text(' '); +- common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); +- common_text(' '); +- if ($instructions) { +- common_element('span', 'input_instructions', $instructions); +- } +- common_element_end('p'); ++ common_element_start('p'); ++ $attrs = array('name' => $id, ++ 'type' => 'checkbox', ++ 'class' => 'checkbox', ++ 'id' => $id); ++ if ($value) { ++ $attrs['value'] = htmlspecialchars($value); ++ } ++ if ($checked) { ++ $attrs['checked'] = 'checked'; ++ } ++ if ($disabled) { ++ $attrs['disabled'] = 'true'; ++ } ++ common_element('input', $attrs); ++ common_text(' '); ++ common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); ++ common_text(' '); ++ if ($instructions) { ++ common_element('span', 'input_instructions', $instructions); ++ } ++ common_element_end('p'); +hunk ./lib/util.php 421 +-function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) { +- common_element_start('p'); +- common_element('label', array('for' => $id), $label); +- common_element_start('select', array('id' => $id, 'name' => $id)); +- if ($blank_select) { +- common_element('option', array('value' => '')); +- } +- foreach ($content as $value => $option) { +- if ($value == $selected) { +- common_element('option', array('value' => $value, 'selected' => $value), $option); +- } else { +- common_element('option', array('value' => $value), $option); +- } +- } +- common_element_end('select'); +- if ($instructions) { +- common_element('span', 'input_instructions', $instructions); +- } +- common_element_end('p'); ++function common_dropdown($id, $label, $content, $instructions=null, $blank_select=FALSE, $selected=null) { ++ common_element_start('p'); ++ common_element('label', array('for' => $id), $label); ++ common_element_start('select', array('id' => $id, 'name' => $id)); ++ if ($blank_select) { ++ common_element('option', array('value' => '')); ++ } ++ foreach ($content as $value => $option) { ++ if ($value == $selected) { ++ common_element('option', array('value' => $value, 'selected' => $value), $option); ++ } else { ++ common_element('option', array('value' => $value), $option); ++ } ++ } ++ common_element_end('select'); ++ if ($instructions) { ++ common_element('span', 'input_instructions', $instructions); ++ } ++ common_element_end('p'); +hunk ./lib/util.php 442 +- common_element('input', array('name' => $id, +- 'type' => 'hidden', +- 'id' => $id, +- 'value' => $value)); ++ common_element('input', array('name' => $id, ++ 'type' => 'hidden', ++ 'id' => $id, ++ 'value' => $value)); +hunk ./lib/util.php 448 +-function common_password($id, $label, $instructions=NULL) { +- common_element_start('p'); +- common_element('label', array('for' => $id), $label); +- $attrs = array('name' => $id, +- 'type' => 'password', +- 'class' => 'password', +- 'id' => $id); +- common_element('input', $attrs); +- if ($instructions) { +- common_element('span', 'input_instructions', $instructions); +- } +- common_element_end('p'); ++function common_password($id, $label, $instructions=null) { ++ common_element_start('p'); ++ common_element('label', array('for' => $id), $label); ++ $attrs = array('name' => $id, ++ 'type' => 'password', ++ 'class' => 'password', ++ 'id' => $id); ++ common_element('input', $attrs); ++ if ($instructions) { ++ common_element('span', 'input_instructions', $instructions); ++ } ++ common_element_end('p'); +hunk ./lib/util.php 463 +- global $xw; +- common_element_start('p'); +- common_element('input', array('type' => 'submit', +- 'id' => $id, +- 'name' => $id, +- 'class' => $cls, +- 'value' => $label)); +- common_element_end('p'); ++ global $xw; ++ common_element_start('p'); ++ common_element('input', array('type' => 'submit', ++ 'id' => $id, ++ 'name' => $id, ++ 'class' => $cls, ++ 'value' => $label)); ++ common_element_end('p'); +hunk ./lib/util.php 473 +-function common_textarea($id, $label, $content=NULL, $instructions=NULL) { +- common_element_start('p'); +- common_element('label', array('for' => $id), $label); +- common_element('textarea', array('rows' => 3, +- 'cols' => 40, +- 'name' => $id, +- 'id' => $id), +- ($content) ? $content : ''); +- if ($instructions) { +- common_element('span', 'input_instructions', $instructions); +- } +- common_element_end('p'); ++function common_textarea($id, $label, $content=null, $instructions=null) { ++ common_element_start('p'); ++ common_element('label', array('for' => $id), $label); ++ common_element('textarea', array('rows' => 3, ++ 'cols' => 40, ++ 'name' => $id, ++ 'id' => $id), ++ ($content) ? $content : ''); ++ if ($instructions) { ++ common_element('span', 'input_instructions', $instructions); ++ } ++ common_element_end('p'); +hunk ./lib/util.php 488 +- if (common_logged_in()) { +- $user = common_current_user(); +- if ($user->timezone) { +- return $user->timezone; +- } +- } ++ if (common_logged_in()) { ++ $user = common_current_user(); ++ if ($user->timezone) { ++ return $user->timezone; ++ } ++ } +hunk ./lib/util.php 495 +- global $config; +- return $config['site']['timezone']; ++ global $config; ++ return $config['site']['timezone']; +hunk ./lib/util.php 501 +- // If there is a user logged in and they've set a language preference +- // then return that one... +- if (common_logged_in()) { +- $user = common_current_user(); +- $user_language = $user->language; +- if ($user_language) +- return $user_language; +- } ++ // If there is a user logged in and they've set a language preference ++ // then return that one... ++ if (common_logged_in()) { ++ $user = common_current_user(); ++ $user_language = $user->language; ++ if ($user_language) ++ return $user_language; ++ } +hunk ./lib/util.php 510 +- // Otherwise, find the best match for the languages requested by the +- // user's browser... +- $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL; +- if (!empty($httplang)) { +- $language = client_prefered_language($httplang); +- if ($language) +- return $language; +- } ++ // Otherwise, find the best match for the languages requested by the ++ // user's browser... ++ $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; ++ if (!empty($httplang)) { ++ $language = client_prefered_language($httplang); ++ if ($language) ++ return $language; ++ } +hunk ./lib/util.php 519 +- // Finally, if none of the above worked, use the site's default... +- return common_config('site', 'language'); ++ // Finally, if none of the above worked, use the site's default... ++ return common_config('site', 'language'); +hunk ./lib/util.php 522 +-# salted, hashed passwords are stored in the DB ++// salted, hashed passwords are stored in the DB +hunk ./lib/util.php 525 +- return md5($password . $id); ++ return md5($password . $id); +hunk ./lib/util.php 528 +-# check if a username exists and has matching password ++// check if a username exists and has matching password +hunk ./lib/util.php 530 +- # NEVER allow blank passwords, even if they match the DB +- if (mb_strlen($password) == 0) { +- return false; +- } +- $user = User::staticGet('nickname', $nickname); +- if (is_null($user)) { +- return false; +- } else { +- if (0 == strcmp(common_munge_password($password, $user->id), +- $user->password)) { +- return $user; +- } else { +- return false; +- } +- } ++ // NEVER allow blank passwords, even if they match the DB ++ if (mb_strlen($password) == 0) { ++ return false; ++ } ++ $user = User::staticGet('nickname', $nickname); ++ if (is_null($user)) { ++ return false; ++ } else { ++ if (0 == strcmp(common_munge_password($password, $user->id), ++ $user->password)) { ++ return $user; ++ } else { ++ return false; ++ } ++ } +hunk ./lib/util.php 547 +-# is the current user logged in? ++// is the current user logged in? +hunk ./lib/util.php 549 +- return (!is_null(common_current_user())); ++ return (!is_null(common_current_user())); +hunk ./lib/util.php 553 +- return (0 != strcmp(session_id(), '')); ++ return (0 != strcmp(session_id(), '')); +hunk ./lib/util.php 557 +- if (!common_have_session()) { +- @session_start(); +- } ++ if (!common_have_session()) { ++ @session_start(); ++ } +hunk ./lib/util.php 562 +-# Three kinds of arguments: +-# 1) a user object +-# 2) a nickname +-# 3) NULL to clear ++// Three kinds of arguments: ++// 1) a user object ++// 2) a nickname ++// 3) null to clear +hunk ./lib/util.php 567 +-# Initialize to false; set to NULL if none found ++// Initialize to false; set to null if none found +hunk ./lib/util.php 575 +- if (is_null($user) && common_have_session()) { +- $_cur = NULL; +- unset($_SESSION['userid']); +- return true; +- } else if (is_string($user)) { +- $nickname = $user; +- $user = User::staticGet('nickname', $nickname); +- } else if (!($user instanceof User)) { +- return false; +- } ++ if (is_null($user) && common_have_session()) { ++ $_cur = null; ++ unset($_SESSION['userid']); ++ return true; ++ } else if (is_string($user)) { ++ $nickname = $user; ++ $user = User::staticGet('nickname', $nickname); ++ } else if (!($user instanceof User)) { ++ return false; ++ } +hunk ./lib/util.php 586 +- if ($user) { +- common_ensure_session(); +- $_SESSION['userid'] = $user->id; ++ if ($user) { ++ common_ensure_session(); ++ $_SESSION['userid'] = $user->id; +hunk ./lib/util.php 590 +- return $_cur; +- } +- return false; ++ return $_cur; ++ } ++ return false; +hunk ./lib/util.php 596 +- $path = common_config('site', 'path'); +- $server = common_config('site', 'server'); ++ $path = common_config('site', 'path'); ++ $server = common_config('site', 'server'); +hunk ./lib/util.php 599 +- if ($path && ($path != '/')) { +- $cookiepath = '/' . $path . '/'; +- } else { +- $cookiepath = '/'; +- } +- return setcookie($key, +- $value, +- $expiration, +- $cookiepath, +- $server); ++ if ($path && ($path != '/')) { ++ $cookiepath = '/' . $path . '/'; ++ } else { ++ $cookiepath = '/'; ++ } ++ return setcookie($key, ++ $value, ++ $expiration, ++ $cookiepath, ++ $server); +hunk ./lib/util.php 612 +-define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); # 30 days ++define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days +hunk ./lib/util.php 614 +-function common_rememberme($user=NULL) { +- if (!$user) { +- $user = common_current_user(); +- if (!$user) { +- common_debug('No current user to remember', __FILE__); +- return false; +- } +- } ++function common_rememberme($user=null) { ++ if (!$user) { ++ $user = common_current_user(); ++ if (!$user) { ++ common_debug('No current user to remember', __FILE__); ++ return false; ++ } ++ } +hunk ./lib/util.php 623 +- $rm = new Remember_me(); ++ $rm = new Remember_me(); +hunk ./lib/util.php 625 +- $rm->code = common_good_rand(16); +- $rm->user_id = $user->id; ++ $rm->code = common_good_rand(16); ++ $rm->user_id = $user->id; +hunk ./lib/util.php 628 +- # Wrap the insert in some good ol' fashioned transaction code ++ // Wrap the insert in some good ol' fashioned transaction code +hunk ./lib/util.php 632 +- $result = $rm->insert(); ++ $result = $rm->insert(); +hunk ./lib/util.php 634 +- if (!$result) { +- common_log_db_error($rm, 'INSERT', __FILE__); +- common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); +- return false; ++ if (!$result) { ++ common_log_db_error($rm, 'INSERT', __FILE__); ++ common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); ++ return false; +hunk ./lib/util.php 642 +- common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); ++ common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); +hunk ./lib/util.php 646 +- common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); ++ common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); +hunk ./lib/util.php 648 +- common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); ++ common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); +hunk ./lib/util.php 650 +- return true; ++ return true; +hunk ./lib/util.php 655 +- $user = NULL; ++ $user = null; +hunk ./lib/util.php 657 +- $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : NULL; ++ $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null; +hunk ./lib/util.php 659 +- if (!$packed) { +- return NULL; ++ if (!$packed) { ++ return null; +hunk ./lib/util.php 668 +- return NULL; ++ return null; +hunk ./lib/util.php 676 +- return NULL; ++ return null; +hunk ./lib/util.php 682 +- return NULL; ++ return null; +hunk ./lib/util.php 690 +- return NULL; ++ return null; +hunk ./lib/util.php 693 +- # successful! ++ // successful! +hunk ./lib/util.php 700 +- return NULL; ++ return null; +hunk ./lib/util.php 708 +- # We issue a new cookie, so they can log in +- # automatically again after this session ++ // We issue a new cookie, so they can log in ++ // automatically again after this session +hunk ./lib/util.php 713 +- return $user; ++ return $user; +hunk ./lib/util.php 716 +-# must be called with a valid user! ++// must be called with a valid user! +hunk ./lib/util.php 719 +- common_set_cookie(REMEMBERME, '', 0); ++ common_set_cookie(REMEMBERME, '', 0); +hunk ./lib/util.php 722 +-# who is the current user? ++// who is the current user? +hunk ./lib/util.php 737 +- # that didn't work; try to remember; will init $_cur to NULL on failure ++ // that didn't work; try to remember; will init $_cur to null on failure +hunk ./lib/util.php 743 +- # XXX: Is this necessary? ++ // XXX: Is this necessary? +hunk ./lib/util.php 748 +- return $_cur; ++ return $_cur; +hunk ./lib/util.php 751 +-# Logins that are 'remembered' aren't 'real' -- they're subject to +-# cookie-stealing. So, we don't let them do certain things. New reg, +-# OpenID, and password logins _are_ real. ++// Logins that are 'remembered' aren't 'real' -- they're subject to ++// cookie-stealing. So, we don't let them do certain things. New reg, ++// OpenID, and password logins _are_ real. +hunk ./lib/util.php 756 +- common_ensure_session(); +- $_SESSION['real_login'] = $real; ++ common_ensure_session(); ++ $_SESSION['real_login'] = $real; +hunk ./lib/util.php 761 +- return common_logged_in() && $_SESSION['real_login']; ++ return common_logged_in() && $_SESSION['real_login']; +hunk ./lib/util.php 764 +-# get canonical version of nickname for comparison ++// get canonical version of nickname for comparison +hunk ./lib/util.php 766 +- # XXX: UTF-8 canonicalization (like combining chars) +- return strtolower($nickname); ++ // XXX: UTF-8 canonicalization (like combining chars) ++ return strtolower($nickname); +hunk ./lib/util.php 770 +-# get canonical version of email for comparison ++// get canonical version of email for comparison +hunk ./lib/util.php 772 +- # XXX: canonicalize UTF-8 +- # XXX: lcase the domain part +- return $email; ++ // XXX: canonicalize UTF-8 ++ // XXX: lcase the domain part ++ return $email; +hunk ./lib/util.php 780 +- $r = common_render_text($text); +- $id = $notice->profile_id; +- $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); +- $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); +- $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); +- return $r; ++ $r = common_render_text($text); ++ $id = $notice->profile_id; ++ $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); ++ $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); ++ $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); ++ return $r; +hunk ./lib/util.php 789 +- $r = htmlspecialchars($text); ++ $r = htmlspecialchars($text); +hunk ./lib/util.php 791 +- $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); +- $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); +- $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); +- # XXX: machine tags +- return $r; ++ $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); ++ $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); ++ $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); ++ // XXX: machine tags ++ return $r; +hunk ./lib/util.php 799 +- $uri = $matches[0]; +- $trailer = ''; ++ $uri = $matches[0]; ++ $trailer = ''; +hunk ./lib/util.php 802 +- # Some heuristics for extracting URIs from surrounding punctuation +- # Strip from trailing text... +- if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { +- $uri = $matches[1]; +- $trailer = $matches[2]; +- } ++ // Some heuristics for extracting URIs from surrounding punctuation ++ // Strip from trailing text... ++ if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { ++ $uri = $matches[1]; ++ $trailer = $matches[2]; ++ } +hunk ./lib/util.php 809 +- $pairs = array( +- ']' => '[', # technically disallowed in URIs, but used in Java docs +- ')' => '(', # far too frequent in Wikipedia and MSDN +- ); +- $final = substr($uri, -1, 1); +- if (isset($pairs[$final])) { +- $openers = substr_count($uri, $pairs[$final]); +- $closers = substr_count($uri, $final); +- if ($closers > $openers) { +- // Assume the paren was opened outside the URI +- $uri = substr($uri, 0, -1); +- $trailer = $final . $trailer; +- } +- } +- if ($longurl = common_longurl($uri)) { +- $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); +- $title = " title='$longurl'"; +- } +- else $title = ''; ++ $pairs = array( ++ ']' => '[', // technically disallowed in URIs, but used in Java docs ++ ')' => '(', // far too frequent in Wikipedia and MSDN ++ ); ++ $final = substr($uri, -1, 1); ++ if (isset($pairs[$final])) { ++ $openers = substr_count($uri, $pairs[$final]); ++ $closers = substr_count($uri, $final); ++ if ($closers > $openers) { ++ // Assume the paren was opened outside the URI ++ $uri = substr($uri, 0, -1); ++ $trailer = $final . $trailer; ++ } ++ } ++ if ($longurl = common_longurl($uri)) { ++ $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); ++ $title = " title='$longurl'"; ++ } ++ else $title = ''; +hunk ./lib/util.php 829 +- return '' . $uri . '' . $trailer; ++ return '' . $uri . '' . $trailer; +hunk ./lib/util.php 839 +- $uri_e = urlencode($uri); +- $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); +- if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; +- return stripslashes($longurl['long_url']); ++ $uri_e = urlencode($uri); ++ $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); ++ if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; ++ return stripslashes($longurl['long_url']); +hunk ./lib/util.php 850 +- return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); ++ return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); +hunk ./lib/util.php 854 +- static $url_cache = array(); ++ static $url_cache = array(); +hunk ./lib/util.php 857 +- $user = common_current_user(); ++ $user = common_current_user(); +hunk ./lib/util.php 859 +- $curlh = curl_init(); +- curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait +- curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); +- curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); ++ $curlh = curl_init(); ++ curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait ++ curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); ++ curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); +hunk ./lib/util.php 864 +- switch($user->urlshorteningservice) { +- case 'ur1.ca': +- $short_url_service = new LilUrl; +- $short_url = $short_url_service->shorten($url); +- break; ++ switch($user->urlshorteningservice) { ++ case 'ur1.ca': ++ $short_url_service = new LilUrl; ++ $short_url = $short_url_service->shorten($url); ++ break; +hunk ./lib/util.php 870 +- case '2tu.us': +- $short_url_service = new TightUrl; +- $short_url = $short_url_service->shorten($url); +- break; ++ case '2tu.us': ++ $short_url_service = new TightUrl; ++ $short_url = $short_url_service->shorten($url); ++ break; +hunk ./lib/util.php 875 +- case 'ptiturl.com': +- $short_url_service = new PtitUrl; +- $short_url = $short_url_service->shorten($url); +- break; ++ case 'ptiturl.com': ++ $short_url_service = new PtitUrl; ++ $short_url = $short_url_service->shorten($url); ++ break; +hunk ./lib/util.php 880 +- case 'bit.ly': +- curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); +- $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; +- break; ++ case 'bit.ly': ++ curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); ++ $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; ++ break; +hunk ./lib/util.php 885 +- case 'is.gd': +- curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); +- $short_url = curl_exec($curlh); +- break; +- case 'snipr.com': +- curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); +- $short_url = curl_exec($curlh); +- break; +- case 'metamark.net': +- curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); +- $short_url = curl_exec($curlh); +- break; +- case 'tinyurl.com': +- curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); +- $short_url = curl_exec($curlh); +- break; +- default: +- $short_url = false; +- } ++ case 'is.gd': ++ curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); ++ $short_url = curl_exec($curlh); ++ break; ++ case 'snipr.com': ++ curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); ++ $short_url = curl_exec($curlh); ++ break; ++ case 'metamark.net': ++ curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); ++ $short_url = curl_exec($curlh); ++ break; ++ case 'tinyurl.com': ++ curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); ++ $short_url = curl_exec($curlh); ++ break; ++ default: ++ $short_url = false; ++ } +hunk ./lib/util.php 905 +- curl_close($curlh); ++ curl_close($curlh); +hunk ./lib/util.php 907 +- if ($short_url) { ++ if ($short_url) { +hunk ./lib/util.php 909 +- return (string)$short_url; +- } +- return $url; ++ return (string)$short_url; ++ } ++ return $url; +hunk ./lib/util.php 915 +- $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8'); ++ $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8'); +hunk ./lib/util.php 917 +- // Replace control, formatting, and surrogate characters with '*', ala Twitter +- return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str); ++ // Replace control, formatting, and surrogate characters with '*', ala Twitter ++ return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str); +hunk ./lib/util.php 922 +- $canonical = common_canonical_tag($tag); +- $url = common_local_url('tag', array('tag' => $canonical)); +- return ''; ++ $canonical = common_canonical_tag($tag); ++ $url = common_local_url('tag', array('tag' => $canonical)); ++ return ''; +hunk ./lib/util.php 928 +- return strtolower(str_replace(array('-', '_', '.'), '', $tag)); ++ return strtolower(str_replace(array('-', '_', '.'), '', $tag)); +hunk ./lib/util.php 932 +- return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); ++ return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); +hunk ./lib/util.php 936 +- $sender = Profile::staticGet($sender_id); +- $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); +- if ($recipient) { +- return ''.$nickname.''; +- } else { +- return $nickname; +- } ++ $sender = Profile::staticGet($sender_id); ++ $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); ++ if ($recipient) { ++ return ''.$nickname.''; ++ } else { ++ return $nickname; ++ } +hunk ./lib/util.php 946 +- $user = User::staticGet($sender_id); +- if (!$user) { +- return $tag; +- } +- $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); +- if ($tagged) { +- $url = common_local_url('subscriptions', +- array('nickname' => $user->nickname, +- 'tag' => $tag)); +- return ''.$tag.''; +- } else { +- return $tag; +- } ++ $user = User::staticGet($sender_id); ++ if (!$user) { ++ return $tag; ++ } ++ $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); ++ if ($tagged) { ++ $url = common_local_url('subscriptions', ++ array('nickname' => $user->nickname, ++ 'tag' => $tag)); ++ return ''.$tag.''; ++ } else { ++ return $tag; ++ } +hunk ./lib/util.php 961 +-function common_relative_profile($sender, $nickname, $dt=NULL) { +- # Try to find profiles this profile is subscribed to that have this nickname +- $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'); +- if ($recipient->find(TRUE)) { +- # XXX: should probably differentiate between profiles with +- # the same name by date of most recent update +- return $recipient; +- } +- # Try to find profiles that listen to this profile and that have this nickname +- $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'); +- if ($recipient->find(TRUE)) { +- # XXX: should probably differentiate between profiles with +- # the same name by date of most recent update +- return $recipient; +- } +- # If this is a local user, try to find a local user with that nickname. +- $sender = User::staticGet($sender->id); +- if ($sender) { +- $recipient_user = User::staticGet('nickname', $nickname); +- if ($recipient_user) { +- return $recipient_user->getProfile(); +- } +- } +- # Otherwise, no links. @messages from local users to remote users, +- # or from remote users to other remote users, are just +- # outside our ability to make intelligent guesses about +- return NULL; ++function common_relative_profile($sender, $nickname, $dt=null) { ++ // Try to find profiles this profile is subscribed to that have this nickname ++ $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'); ++ if ($recipient->find(TRUE)) { ++ // XXX: should probably differentiate between profiles with ++ // the same name by date of most recent update ++ return $recipient; ++ } ++ // Try to find profiles that listen to this profile and that have this nickname ++ $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'); ++ if ($recipient->find(TRUE)) { ++ // XXX: should probably differentiate between profiles with ++ // the same name by date of most recent update ++ return $recipient; ++ } ++ // If this is a local user, try to find a local user with that nickname. ++ $sender = User::staticGet($sender->id); ++ if ($sender) { ++ $recipient_user = User::staticGet('nickname', $nickname); ++ if ($recipient_user) { ++ return $recipient_user->getProfile(); ++ } ++ } ++ // Otherwise, no links. @messages from local users to remote users, ++ // or from remote users to other remote users, are just ++ // outside our ability to make intelligent guesses about ++ return null; +hunk ./lib/util.php 998 +-function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) { +- global $config; ++function common_avatar_filename($id, $extension, $size=null, $extra=null) { ++ global $config; +hunk ./lib/util.php 1001 +- if ($size) { +- return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; +- } else { +- return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; +- } ++ if ($size) { ++ return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; ++ } else { ++ return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; ++ } +hunk ./lib/util.php 1009 +- global $config; +- return INSTALLDIR . '/avatar/' . $filename; ++ global $config; ++ return INSTALLDIR . '/avatar/' . $filename; +hunk ./lib/util.php 1014 +- return common_path('avatar/'.$filename); ++ return common_path('avatar/'.$filename); +hunk ./lib/util.php 1018 +- $server = common_config('avatar', 'server'); +- if ($server) { +- return 'http://'.$server.'/'.$avatar->filename; +- } else { +- return $avatar->url; +- } ++ $server = common_config('avatar', 'server'); ++ if ($server) { ++ return 'http://'.$server.'/'.$avatar->filename; ++ } else { ++ return $avatar->url; ++ } +hunk ./lib/util.php 1027 +- static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', +- AVATAR_STREAM_SIZE => 'stream', +- AVATAR_MINI_SIZE => 'mini'); +- return theme_path('default-avatar-'.$sizenames[$size].'.png'); ++ static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', ++ AVATAR_STREAM_SIZE => 'stream', ++ AVATAR_MINI_SIZE => 'mini'); ++ return theme_path('default-avatar-'.$sizenames[$size].'.png'); +hunk ./lib/util.php 1033 +-function common_local_url($action, $args=NULL, $fragment=NULL) { +- $url = NULL; +- if (common_config('site','fancy')) { +- $url = common_fancy_url($action, $args); +- } else { +- $url = common_simple_url($action, $args); +- } +- if (!is_null($fragment)) { +- $url .= '#'.$fragment; +- } +- return $url; ++function common_local_url($action, $args=null, $fragment=null) { ++ $url = null; ++ if (common_config('site','fancy')) { ++ $url = common_fancy_url($action, $args); ++ } else { ++ $url = common_simple_url($action, $args); ++ } ++ if (!is_null($fragment)) { ++ $url .= '#'.$fragment; ++ } ++ return $url; +hunk ./lib/util.php 1046 +-function common_fancy_url($action, $args=NULL) { +- switch (strtolower($action)) { +- case 'public': +- if ($args && isset($args['page'])) { +- return common_path('?page=' . $args['page']); +- } else { +- return common_path(''); +- } +- case 'featured': +- if ($args && isset($args['page'])) { +- return common_path('featured?page=' . $args['page']); +- } else { +- return common_path('featured'); +- } +- case 'favorited': +- if ($args && isset($args['page'])) { +- return common_path('favorited?page=' . $args['page']); +- } else { +- return common_path('favorited'); +- } +- case 'publicrss': +- return common_path('rss'); +- case 'publicatom': +- return common_path("api/statuses/public_timeline.atom"); +- case 'publicxrds': +- return common_path('xrds'); +- case 'featuredrss': +- return common_path('featuredrss'); +- case 'favoritedrss': +- return common_path('favoritedrss'); +- case 'opensearch': +- if ($args && $args['type']) { +- return common_path('opensearch/'.$args['type']); +- } else { +- return common_path('opensearch/people'); +- } +- case 'doc': +- return common_path('doc/'.$args['title']); ++function common_fancy_url($action, $args=null) { ++ switch (strtolower($action)) { ++ case 'public': ++ if ($args && isset($args['page'])) { ++ return common_path('?page=' . $args['page']); ++ } else { ++ return common_path(''); ++ } ++ case 'featured': ++ if ($args && isset($args['page'])) { ++ return common_path('featured?page=' . $args['page']); ++ } else { ++ return common_path('featured'); ++ } ++ case 'favorited': ++ if ($args && isset($args['page'])) { ++ return common_path('favorited?page=' . $args['page']); ++ } else { ++ return common_path('favorited'); ++ } ++ case 'publicrss': ++ return common_path('rss'); ++ case 'publicatom': ++ return common_path("api/statuses/public_timeline.atom"); ++ case 'publicxrds': ++ return common_path('xrds'); ++ case 'featuredrss': ++ return common_path('featuredrss'); ++ case 'favoritedrss': ++ return common_path('favoritedrss'); ++ case 'opensearch': ++ if ($args && $args['type']) { ++ return common_path('opensearch/'.$args['type']); ++ } else { ++ return common_path('opensearch/people'); ++ } ++ case 'doc': ++ return common_path('doc/'.$args['title']); +hunk ./lib/util.php 1085 +- case 'login': +- case 'logout': +- case 'subscribe': +- case 'unsubscribe': +- case 'invite': +- return common_path('main/'.$action); +- case 'tagother': +- return common_path('main/tagother?id='.$args['id']); +- case 'register': +- if ($args && $args['code']) { +- return common_path('main/register/'.$args['code']); +- } else { +- return common_path('main/register'); +- } +- case 'remotesubscribe': +- if ($args && $args['nickname']) { +- return common_path('main/remote?nickname=' . $args['nickname']); +- } else { +- return common_path('main/remote'); +- } +- case 'nudge': +- return common_path($args['nickname'].'/nudge'); +- case 'openidlogin': +- return common_path('main/openid'); +- case 'profilesettings': +- return common_path('settings/profile'); +- case 'emailsettings': +- return common_path('settings/email'); +- case 'openidsettings': +- return common_path('settings/openid'); +- case 'smssettings': +- return common_path('settings/sms'); +- case 'twittersettings': +- return common_path('settings/twitter'); +- case 'othersettings': +- return common_path('settings/other'); ++ case 'login': ++ case 'logout': ++ case 'subscribe': ++ case 'unsubscribe': ++ case 'invite': ++ return common_path('main/'.$action); ++ case 'tagother': ++ return common_path('main/tagother?id='.$args['id']); ++ case 'register': ++ if ($args && $args['code']) { ++ return common_path('main/register/'.$args['code']); ++ } else { ++ return common_path('main/register'); ++ } ++ case 'remotesubscribe': ++ if ($args && $args['nickname']) { ++ return common_path('main/remote?nickname=' . $args['nickname']); ++ } else { ++ return common_path('main/remote'); ++ } ++ case 'nudge': ++ return common_path($args['nickname'].'/nudge'); ++ case 'openidlogin': ++ return common_path('main/openid'); ++ case 'profilesettings': ++ return common_path('settings/profile'); ++ case 'emailsettings': ++ return common_path('settings/email'); ++ case 'openidsettings': ++ return common_path('settings/openid'); ++ case 'smssettings': ++ return common_path('settings/sms'); ++ case 'twittersettings': ++ return common_path('settings/twitter'); ++ case 'othersettings': ++ return common_path('settings/other'); +hunk ./lib/util.php 1123 +- case 'newnotice': +- if ($args && $args['replyto']) { +- return common_path('notice/new?replyto='.$args['replyto']); +- } else { +- return common_path('notice/new'); +- } +- case 'shownotice': +- return common_path('notice/'.$args['notice']); +- case 'deletenotice': +- if ($args && $args['notice']) { +- return common_path('notice/delete/'.$args['notice']); +- } else { +- return common_path('notice/delete'); +- } +- case 'microsummary': +- case 'xrds': +- case 'foaf': +- return common_path($args['nickname'].'/'.$action); +- case 'all': +- case 'replies': +- case 'inbox': +- case 'outbox': +- if ($args && isset($args['page'])) { +- return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); +- } else { +- return common_path($args['nickname'].'/'.$action); +- } +- case 'subscriptions': +- case 'subscribers': +- $nickname = $args['nickname']; +- unset($args['nickname']); +- if (isset($args['tag'])) { +- $tag = $args['tag']; +- unset($args['tag']); +- } +- $params = http_build_query($args); +- if ($params) { +- return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); +- } else { +- return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); +- } +- case 'allrss': +- return common_path($args['nickname'].'/all/rss'); +- case 'repliesrss': +- return common_path($args['nickname'].'/replies/rss'); +- case 'userrss': ++ case 'newnotice': ++ if ($args && $args['replyto']) { ++ return common_path('notice/new?replyto='.$args['replyto']); ++ } else { ++ return common_path('notice/new'); ++ } ++ case 'shownotice': ++ return common_path('notice/'.$args['notice']); ++ case 'deletenotice': ++ if ($args && $args['notice']) { ++ return common_path('notice/delete/'.$args['notice']); ++ } else { ++ return common_path('notice/delete'); ++ } ++ case 'microsummary': ++ case 'xrds': ++ case 'foaf': ++ return common_path($args['nickname'].'/'.$action); ++ case 'all': ++ case 'replies': ++ case 'inbox': ++ case 'outbox': ++ if ($args && isset($args['page'])) { ++ return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); ++ } else { ++ return common_path($args['nickname'].'/'.$action); ++ } ++ case 'subscriptions': ++ case 'subscribers': ++ $nickname = $args['nickname']; ++ unset($args['nickname']); ++ if (isset($args['tag'])) { ++ $tag = $args['tag']; ++ unset($args['tag']); ++ } ++ $params = http_build_query($args); ++ if ($params) { ++ return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); ++ } else { ++ return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); ++ } ++ case 'allrss': ++ return common_path($args['nickname'].'/all/rss'); ++ case 'repliesrss': ++ return common_path($args['nickname'].'/replies/rss'); ++ case 'userrss': +hunk ./lib/util.php 1170 +- return common_path($args['nickname'].'/rss?limit=' . $args['limit']); +- return common_path($args['nickname'].'/rss'); +- case 'showstream': +- if ($args && isset($args['page'])) { +- return common_path($args['nickname'].'?page=' . $args['page']); +- } else { +- return common_path($args['nickname']); +- } ++ return common_path($args['nickname'].'/rss?limit=' . $args['limit']); ++ return common_path($args['nickname'].'/rss'); ++ case 'showstream': ++ if ($args && isset($args['page'])) { ++ return common_path($args['nickname'].'?page=' . $args['page']); ++ } else { ++ return common_path($args['nickname']); ++ } +hunk ./lib/util.php 1179 +- case 'usertimeline': +- return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); +- case 'confirmaddress': +- return common_path('main/confirmaddress/'.$args['code']); +- case 'userbyid': +- return common_path('user/'.$args['id']); +- case 'recoverpassword': +- $path = 'main/recoverpassword'; +- if ($args['code']) { +- $path .= '/' . $args['code']; +- } +- return common_path($path); +- case 'imsettings': +- return common_path('settings/im'); +- case 'peoplesearch': +- return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'noticesearch': +- return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'noticesearchrss': +- return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'avatarbynickname': +- return common_path($args['nickname'].'/avatar/'.$args['size']); +- case 'tag': +- if (isset($args['tag']) && $args['tag']) { +- $path = 'tag/' . $args['tag']; +- unset($args['tag']); +- } else { +- $path = 'tags'; +- } +- return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'peopletag': +- $path = 'peopletag/' . $args['tag']; +- unset($args['tag']); +- return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'tags': +- return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'favor': +- return common_path('main/favor'); +- case 'disfavor': +- return common_path('main/disfavor'); +- case 'showfavorites': +- if ($args && isset($args['page'])) { +- return common_path($args['nickname'].'/favorites?page=' . $args['page']); +- } else { +- return common_path($args['nickname'].'/favorites'); +- } +- case 'favoritesrss': +- return common_path($args['nickname'].'/favorites/rss'); +- case 'showmessage': +- return common_path('message/' . $args['message']); +- case 'newmessage': +- return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); +- case 'api': +- # XXX: do fancy URLs for all the API methods +- switch (strtolower($args['apiaction'])) { +- case 'statuses': +- switch (strtolower($args['method'])) { +- case 'user_timeline.rss': +- return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); +- case 'user_timeline.atom': +- return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); +- case 'user_timeline.json': +- return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); +- case 'user_timeline.xml': +- return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); +- default: return common_simple_url($action, $args); +- } +- default: return common_simple_url($action, $args); +- } +- case 'sup': +- if ($args && isset($args['seconds'])) { +- return common_path('main/sup?seconds='.$args['seconds']); +- } else { +- return common_path('main/sup'); +- } +- default: +- return common_simple_url($action, $args); +- } ++ case 'usertimeline': ++ return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); ++ case 'confirmaddress': ++ return common_path('main/confirmaddress/'.$args['code']); ++ case 'userbyid': ++ return common_path('user/'.$args['id']); ++ case 'recoverpassword': ++ $path = 'main/recoverpassword'; ++ if ($args['code']) { ++ $path .= '/' . $args['code']; ++ } ++ return common_path($path); ++ case 'imsettings': ++ return common_path('settings/im'); ++ case 'peoplesearch': ++ return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'noticesearch': ++ return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'noticesearchrss': ++ return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'avatarbynickname': ++ return common_path($args['nickname'].'/avatar/'.$args['size']); ++ case 'tag': ++ if (isset($args['tag']) && $args['tag']) { ++ $path = 'tag/' . $args['tag']; ++ unset($args['tag']); ++ } else { ++ $path = 'tags'; ++ } ++ return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'peopletag': ++ $path = 'peopletag/' . $args['tag']; ++ unset($args['tag']); ++ return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'tags': ++ return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'favor': ++ return common_path('main/favor'); ++ case 'disfavor': ++ return common_path('main/disfavor'); ++ case 'showfavorites': ++ if ($args && isset($args['page'])) { ++ return common_path($args['nickname'].'/favorites?page=' . $args['page']); ++ } else { ++ return common_path($args['nickname'].'/favorites'); ++ } ++ case 'favoritesrss': ++ return common_path($args['nickname'].'/favorites/rss'); ++ case 'showmessage': ++ return common_path('message/' . $args['message']); ++ case 'newmessage': ++ return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); ++ case 'api': ++ // XXX: do fancy URLs for all the API methods ++ switch (strtolower($args['apiaction'])) { ++ case 'statuses': ++ switch (strtolower($args['method'])) { ++ case 'user_timeline.rss': ++ return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); ++ case 'user_timeline.atom': ++ return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); ++ case 'user_timeline.json': ++ return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); ++ case 'user_timeline.xml': ++ return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); ++ default: return common_simple_url($action, $args); ++ } ++ default: return common_simple_url($action, $args); ++ } ++ case 'sup': ++ if ($args && isset($args['seconds'])) { ++ return common_path('main/sup?seconds='.$args['seconds']); ++ } else { ++ return common_path('main/sup'); ++ } ++ default: ++ return common_simple_url($action, $args); ++ } +hunk ./lib/util.php 1259 +-function common_simple_url($action, $args=NULL) { +- global $config; +- /* XXX: pretty URLs */ +- $extra = ''; +- if ($args) { +- foreach ($args as $key => $value) { +- $extra .= "&${key}=${value}"; +- } +- } +- return common_path("index.php?action=${action}${extra}"); ++function common_simple_url($action, $args=null) { ++ global $config; ++ /* XXX: pretty URLs */ ++ $extra = ''; ++ if ($args) { ++ foreach ($args as $key => $value) { ++ $extra .= "&${key}=${value}"; ++ } ++ } ++ return common_path("index.php?action=${action}${extra}"); +hunk ./lib/util.php 1272 +- global $config; +- $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; +- return "http://".$config['site']['server'].'/'.$pathpart.$relative; ++ global $config; ++ $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; ++ return "http://".$config['site']['server'].'/'.$pathpart.$relative; +hunk ./lib/util.php 1278 +- // XXX: do some sexy date formatting +- // return date(DATE_RFC822, $dt); +- $t = strtotime($dt); +- $now = time(); +- $diff = $now - $t; ++ // XXX: do some sexy date formatting ++ // return date(DATE_RFC822, $dt); ++ $t = strtotime($dt); ++ $now = time(); ++ $diff = $now - $t; +hunk ./lib/util.php 1284 +- if ($now < $t) { # that shouldn't happen! +- return common_exact_date($dt); +- } else if ($diff < 60) { +- return _('a few seconds ago'); +- } else if ($diff < 92) { +- return _('about a minute ago'); +- } else if ($diff < 3300) { +- return sprintf(_('about %d minutes ago'), round($diff/60)); +- } else if ($diff < 5400) { +- return _('about an hour ago'); +- } else if ($diff < 22 * 3600) { +- return sprintf(_('about %d hours ago'), round($diff/3600)); +- } else if ($diff < 37 * 3600) { +- return _('about a day ago'); +- } else if ($diff < 24 * 24 * 3600) { +- return sprintf(_('about %d days ago'), round($diff/(24*3600))); +- } else if ($diff < 46 * 24 * 3600) { +- return _('about a month ago'); +- } else if ($diff < 330 * 24 * 3600) { +- return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); +- } else if ($diff < 480 * 24 * 3600) { +- return _('about a year ago'); +- } else { +- return common_exact_date($dt); +- } ++ if ($now < $t) { // that shouldn't happen! ++ return common_exact_date($dt); ++ } else if ($diff < 60) { ++ return _('a few seconds ago'); ++ } else if ($diff < 92) { ++ return _('about a minute ago'); ++ } else if ($diff < 3300) { ++ return sprintf(_('about %d minutes ago'), round($diff/60)); ++ } else if ($diff < 5400) { ++ return _('about an hour ago'); ++ } else if ($diff < 22 * 3600) { ++ return sprintf(_('about %d hours ago'), round($diff/3600)); ++ } else if ($diff < 37 * 3600) { ++ return _('about a day ago'); ++ } else if ($diff < 24 * 24 * 3600) { ++ return sprintf(_('about %d days ago'), round($diff/(24*3600))); ++ } else if ($diff < 46 * 24 * 3600) { ++ return _('about a month ago'); ++ } else if ($diff < 330 * 24 * 3600) { ++ return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); ++ } else if ($diff < 480 * 24 * 3600) { ++ return _('about a year ago'); ++ } else { ++ return common_exact_date($dt); ++ } +hunk ./lib/util.php 1320 +- $dateStr = date('d F Y H:i:s', strtotime($dt)); +- $d = new DateTime($dateStr, $_utc); +- $d->setTimezone($_siteTz); +- return $d->format(DATE_RFC850); ++ $dateStr = date('d F Y H:i:s', strtotime($dt)); ++ $d = new DateTime($dateStr, $_utc); ++ $d->setTimezone($_siteTz); ++ return $d->format(DATE_RFC850); +hunk ./lib/util.php 1327 +- $dateStr = date('d F Y H:i:s', strtotime($dt)); +- $d = new DateTime($dateStr, new DateTimeZone('UTC')); +- $d->setTimezone(new DateTimeZone(common_timezone())); +- return $d->format(DATE_W3C); ++ $dateStr = date('d F Y H:i:s', strtotime($dt)); ++ $d = new DateTime($dateStr, new DateTimeZone('UTC')); ++ $d->setTimezone(new DateTimeZone(common_timezone())); ++ return $d->format(DATE_W3C); +hunk ./lib/util.php 1334 +- $dateStr = date('d F Y H:i:s', strtotime($dt)); +- $d = new DateTime($dateStr, new DateTimeZone('UTC')); +- $d->setTimezone(new DateTimeZone(common_timezone())); +- return $d->format('r'); ++ $dateStr = date('d F Y H:i:s', strtotime($dt)); ++ $d = new DateTime($dateStr, new DateTimeZone('UTC')); ++ $d->setTimezone(new DateTimeZone(common_timezone())); ++ return $d->format('r'); +hunk ./lib/util.php 1341 +- $dateStr = date('d F Y H:i:s', strtotime($dt)); +- $d = new DateTime($dateStr, new DateTimeZone('UTC')); +- $d->setTimezone(new DateTimeZone(common_timezone())); +- return $d->format('c'); ++ $dateStr = date('d F Y H:i:s', strtotime($dt)); ++ $d = new DateTime($dateStr, new DateTimeZone('UTC')); ++ $d->setTimezone(new DateTimeZone(common_timezone())); ++ return $d->format('c'); +hunk ./lib/util.php 1348 +- return strftime('%Y-%m-%d %H:%M:%S', time()); ++ return strftime('%Y-%m-%d %H:%M:%S', time()); +hunk ./lib/util.php 1352 +- static $status = array(301 => "Moved Permanently", +- 302 => "Found", +- 303 => "See Other", +- 307 => "Temporary Redirect"); +- header("Status: ${code} $status[$code]"); +- header("Location: $url"); ++ static $status = array(301 => "Moved Permanently", ++ 302 => "Found", ++ 303 => "See Other", ++ 307 => "Temporary Redirect"); ++ header("Status: ${code} $status[$code]"); ++ header("Location: $url"); +hunk ./lib/util.php 1359 +- common_start_xml('a', +- '-//W3C//DTD XHTML 1.0 Strict//EN', +- 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); +- common_element('a', array('href' => $url), $url); +- common_end_xml(); ++ common_start_xml('a', ++ '-//W3C//DTD XHTML 1.0 Strict//EN', ++ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); ++ common_element('a', array('href' => $url), $url); ++ common_end_xml(); +hunk ./lib/util.php 1368 +- # Alternative reply format +- $tname = false; +- if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { +- $tname = $match[1]; +- } +- # extract all @messages +- $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); ++ // Alternative reply format ++ $tname = false; ++ if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { ++ $tname = $match[1]; ++ } ++ // extract all @messages ++ $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); +hunk ./lib/util.php 1376 +- $names = array(); ++ $names = array(); +hunk ./lib/util.php 1378 +- if ($cnt || $tname) { +- # XXX: is there another way to make an array copy? +- $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); +- } ++ if ($cnt || $tname) { ++ // XXX: is there another way to make an array copy? ++ $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); ++ } +hunk ./lib/util.php 1383 +- $sender = Profile::staticGet($notice->profile_id); ++ $sender = Profile::staticGet($notice->profile_id); +hunk ./lib/util.php 1385 +- $replied = array(); ++ $replied = array(); +hunk ./lib/util.php 1387 +- # store replied only for first @ (what user/notice what the reply directed, +- # we assume first @ is it) ++ // store replied only for first @ (what user/notice what the reply directed, ++ // we assume first @ is it) +hunk ./lib/util.php 1390 +- for ($i=0; $icreated); +- if (!$recipient) { +- continue; +- } +- if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self +- $reply_for = $recipient; +- $recipient_notice = $reply_for->getCurrentNotice(); +- if ($recipient_notice) { +- $orig = clone($notice); +- $notice->reply_to = $recipient_notice->id; +- $notice->update($orig); +- } +- } +- # Don't save replies from blocked profile to local user ++ for ($i=0; $icreated); ++ if (!$recipient) { ++ continue; ++ } ++ if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self ++ $reply_for = $recipient; ++ $recipient_notice = $reply_for->getCurrentNotice(); ++ if ($recipient_notice) { ++ $orig = clone($notice); ++ $notice->reply_to = $recipient_notice->id; ++ $notice->update($orig); ++ } ++ } ++ // Don't save replies from blocked profile to local user +hunk ./lib/util.php 1410 +- $reply = new Reply(); +- $reply->notice_id = $notice->id; +- $reply->profile_id = $recipient->id; +- $id = $reply->insert(); +- if (!$id) { +- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); +- common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); +- common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); +- return; +- } else { +- $replied[$recipient->id] = 1; +- } +- } ++ $reply = new Reply(); ++ $reply->notice_id = $notice->id; ++ $reply->profile_id = $recipient->id; ++ $id = $reply->insert(); ++ if (!$id) { ++ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); ++ common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); ++ common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); ++ return; ++ } else { ++ $replied[$recipient->id] = 1; ++ } ++ } +hunk ./lib/util.php 1424 +- # Hash format replies, too +- $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); +- if ($cnt) { +- foreach ($match[1] as $tag) { +- $tagged = Profile_tag::getTagged($sender->id, $tag); +- foreach ($tagged as $t) { +- if (!$replied[$t->id]) { +- # Don't save replies from blocked profile to local user ++ // Hash format replies, too ++ $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); ++ if ($cnt) { ++ foreach ($match[1] as $tag) { ++ $tagged = Profile_tag::getTagged($sender->id, $tag); ++ foreach ($tagged as $t) { ++ if (!$replied[$t->id]) { ++ // Don't save replies from blocked profile to local user +hunk ./lib/util.php 1436 +- $reply = new Reply(); +- $reply->notice_id = $notice->id; +- $reply->profile_id = $t->id; +- $id = $reply->insert(); +- if (!$id) { +- common_log_db_error($reply, 'INSERT', __FILE__); +- return; +- } +- } +- } +- } +- } ++ $reply = new Reply(); ++ $reply->notice_id = $notice->id; ++ $reply->profile_id = $t->id; ++ $id = $reply->insert(); ++ if (!$id) { ++ common_log_db_error($reply, 'INSERT', __FILE__); ++ return; ++ } ++ } ++ } ++ } ++ } +hunk ./lib/util.php 1452 +- // 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) { ++ // 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) { +hunk ./lib/util.php 1456 +- // If it's not a Twitter-style reply, or if the user WANTS to send replies... ++ // If it's not a Twitter-style reply, or if the user WANTS to send replies... +hunk ./lib/util.php 1458 +- if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) || +- (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) { ++ if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) || ++ (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) { +hunk ./lib/util.php 1461 +- $result = common_twitter_broadcast($notice, $flink); ++ $result = common_twitter_broadcast($notice, $flink); +hunk ./lib/util.php 1463 +- if (!$result) { +- common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__); +- } +- } +- } ++ if (!$result) { ++ common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__); ++ } ++ } ++ } +hunk ./lib/util.php 1469 +- if (common_config('queue', 'enabled')) { +- # Do it later! +- return common_enqueue_notice($notice); +- } else { +- return common_real_broadcast($notice, $remote); +- } ++ if (common_config('queue', 'enabled')) { ++ // Do it later! ++ return common_enqueue_notice($notice); ++ } else { ++ return common_real_broadcast($notice, $remote); ++ } +hunk ./lib/util.php 1478 +- global $config; +- $success = true; +- $fuser = $flink->getForeignUser(); +- $twitter_user = $fuser->nickname; +- $twitter_password = $flink->credentials; +- $uri = 'http://www.twitter.com/statuses/update.json'; ++ global $config; ++ $success = true; ++ $fuser = $flink->getForeignUser(); ++ $twitter_user = $fuser->nickname; ++ $twitter_password = $flink->credentials; ++ $uri = 'http://www.twitter.com/statuses/update.json'; +hunk ./lib/util.php 1485 +- // XXX: Hack to get around PHP cURL's use of @ being a a meta character +- $statustxt = preg_replace('/^@/', ' @', $notice->content); ++ // XXX: Hack to get around PHP cURL's use of @ being a a meta character ++ $statustxt = preg_replace('/^@/', ' @', $notice->content); +hunk ./lib/util.php 1488 +- $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 +- ); ++ $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 ++ ); +hunk ./lib/util.php 1504 +- $ch = curl_init($uri); ++ $ch = curl_init($uri); +hunk ./lib/util.php 1509 +- if ($errmsg) { +- common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", +- __FILE__); +- $success = false; +- } ++ if ($errmsg) { ++ common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", ++ __FILE__); ++ $success = false; ++ } +hunk ./lib/util.php 1515 +- curl_close($ch); ++ curl_close($ch); +hunk ./lib/util.php 1517 +- if (!$data) { +- common_debug("No data returned by Twitter's API trying to send update for $twitter_user", +- __FILE__); +- $success = false; +- } ++ if (!$data) { ++ common_debug("No data returned by Twitter's API trying to send update for $twitter_user", ++ __FILE__); ++ $success = false; ++ } +hunk ./lib/util.php 1523 +- // Twitter should return a status +- $status = json_decode($data); ++ // Twitter should return a status ++ $status = json_decode($data); +hunk ./lib/util.php 1526 +- if (!$status->id) { +- common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user", +- __FILE__); +- $success = false; +- } ++ if (!$status->id) { ++ common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user", ++ __FILE__); ++ $success = false; ++ } +hunk ./lib/util.php 1532 +- return $success; ++ return $success; +hunk ./lib/util.php 1535 +-# Stick the notice on the queue ++// Stick the notice on the queue +hunk ./lib/util.php 1538 +- foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { +- $qi = new Queue_item(); +- $qi->notice_id = $notice->id; +- $qi->transport = $transport; +- $qi->created = $notice->created; ++ foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { ++ $qi = new Queue_item(); ++ $qi->notice_id = $notice->id; ++ $qi->transport = $transport; ++ $qi->created = $notice->created; +hunk ./lib/util.php 1544 +- if (!$result) { +- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); +- common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); +- return false; +- } +- common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); +- } +- return $result; ++ if (!$result) { ++ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); ++ common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); ++ return false; ++ } ++ common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); ++ } ++ return $result; +hunk ./lib/util.php 1555 +- $qi = Queue_item::staticGet($notice->id); +- if ($qi) { +- $result = $qi->delete(); +- if (!$result) { +- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); +- common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); +- return false; +- } +- common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); +- return $result; +- } else { ++ $qi = Queue_item::staticGet($notice->id); ++ if ($qi) { ++ $result = $qi->delete(); ++ if (!$result) { ++ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); ++ common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); +hunk ./lib/util.php 1563 ++ common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); ++ return $result; ++ } else { ++ return false; ++ } +hunk ./lib/util.php 1571 +- $success = true; +- if (!$remote) { +- # Make sure we have the OMB stuff +- require_once(INSTALLDIR.'/lib/omb.php'); +- $success = omb_broadcast_remote_subscribers($notice); +- if (!$success) { +- common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); +- } +- } +- if ($success) { +- require_once(INSTALLDIR.'/lib/jabber.php'); +- $success = jabber_broadcast_notice($notice); +- if (!$success) { +- common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); +- } +- } +- if ($success) { +- require_once(INSTALLDIR.'/lib/mail.php'); +- $success = mail_broadcast_notice_sms($notice); +- if (!$success) { +- common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); +- } +- } +- if ($success) { +- $success = jabber_public_notice($notice); +- if (!$success) { +- common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); +- } +- } +- // XXX: broadcast notices to other IM +- return $success; ++ $success = true; ++ if (!$remote) { ++ // Make sure we have the OMB stuff ++ require_once(INSTALLDIR.'/lib/omb.php'); ++ $success = omb_broadcast_remote_subscribers($notice); ++ if (!$success) { ++ common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); ++ } ++ } ++ if ($success) { ++ require_once(INSTALLDIR.'/lib/jabber.php'); ++ $success = jabber_broadcast_notice($notice); ++ if (!$success) { ++ common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); ++ } ++ } ++ if ($success) { ++ require_once(INSTALLDIR.'/lib/mail.php'); ++ $success = mail_broadcast_notice_sms($notice); ++ if (!$success) { ++ common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); ++ } ++ } ++ if ($success) { ++ $success = jabber_public_notice($notice); ++ if (!$success) { ++ common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); ++ } ++ } ++ // XXX: broadcast notices to other IM ++ return $success; +hunk ./lib/util.php 1605 +- // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ +- require_once(INSTALLDIR.'/lib/omb.php'); +- omb_broadcast_profile($profile); +- // XXX: Other broadcasts...? +- return true; ++ // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ ++ require_once(INSTALLDIR.'/lib/omb.php'); ++ omb_broadcast_profile($profile); ++ // XXX: Other broadcasts...? ++ return true; +hunk ./lib/util.php 1613 +- return common_local_url('showstream', array('nickname' => $nickname)); ++ return common_local_url('showstream', array('nickname' => $nickname)); +hunk ./lib/util.php 1616 +-# Don't call if nobody's logged in ++// Don't call if nobody's logged in +hunk ./lib/util.php 1618 +-function common_notice_form($action=NULL, $content=NULL) { +- $user = common_current_user(); +- assert(!is_null($user)); +- common_element_start('form', array('id' => 'status_form', +- 'method' => 'post', +- 'action' => common_local_url('newnotice'))); +- common_element_start('p'); +- common_element('label', array('for' => 'status_textarea', +- 'id' => 'status_label'), +- sprintf(_('What\'s up, %s?'), $user->nickname)); ++function common_notice_form($action=null, $content=null) { ++ $user = common_current_user(); ++ assert(!is_null($user)); ++ common_element_start('form', array('id' => 'status_form', ++ 'method' => 'post', ++ 'action' => common_local_url('newnotice'))); ++ common_element_start('p'); ++ common_element('label', array('for' => 'status_textarea', ++ 'id' => 'status_label'), ++ sprintf(_('What\'s up, %s?'), $user->nickname)); +hunk ./lib/util.php 1629 +- common_element('textarea', array('id' => 'status_textarea', +- 'cols' => 60, +- 'rows' => 3, +- 'name' => 'status_textarea'), +- ($content) ? $content : ''); +- common_hidden('token', common_session_token()); +- if ($action) { +- common_hidden('returnto', $action); +- } +- # set by JavaScript +- common_hidden('inreplyto', 'false'); +- common_element('input', array('id' => 'status_submit', +- 'name' => 'status_submit', +- 'type' => 'submit', +- 'value' => _('Send'))); +- common_element_end('p'); +- common_element_end('form'); ++ common_element('textarea', array('id' => 'status_textarea', ++ 'cols' => 60, ++ 'rows' => 3, ++ 'name' => 'status_textarea'), ++ ($content) ? $content : ''); ++ common_hidden('token', common_session_token()); ++ if ($action) { ++ common_hidden('returnto', $action); ++ } ++ // set by JavaScript ++ common_hidden('inreplyto', 'false'); ++ common_element('input', array('id' => 'status_submit', ++ 'name' => 'status_submit', ++ 'type' => 'submit', ++ 'value' => _('Send'))); ++ common_element_end('p'); ++ common_element_end('form'); +hunk ./lib/util.php 1648 +-# Should make up a reasonable root URL ++// Should make up a reasonable root URL +hunk ./lib/util.php 1651 +- return common_path(''); ++ return common_path(''); +hunk ./lib/util.php 1654 +-# returns $bytes bytes of random data as a hexadecimal string +-# "good" here is a goal and not a guarantee ++// returns $bytes bytes of random data as a hexadecimal string ++// "good" here is a goal and not a guarantee +hunk ./lib/util.php 1658 +- # XXX: use random.org...? +- if (file_exists('/dev/urandom')) { +- return common_urandom($bytes); +- } else { # FIXME: this is probably not good enough +- return common_mtrand($bytes); +- } ++ // XXX: use random.org...? ++ if (file_exists('/dev/urandom')) { ++ return common_urandom($bytes); ++ } else { // FIXME: this is probably not good enough ++ return common_mtrand($bytes); ++ } +hunk ./lib/util.php 1667 +- $h = fopen('/dev/urandom', 'rb'); +- # should not block +- $src = fread($h, $bytes); +- fclose($h); +- $enc = ''; +- for ($i = 0; $i < $bytes; $i++) { +- $enc .= sprintf("%02x", (ord($src[$i]))); +- } +- return $enc; ++ $h = fopen('/dev/urandom', 'rb'); ++ // should not block ++ $src = fread($h, $bytes); ++ fclose($h); ++ $enc = ''; ++ for ($i = 0; $i < $bytes; $i++) { ++ $enc .= sprintf("%02x", (ord($src[$i]))); ++ } ++ return $enc; +hunk ./lib/util.php 1679 +- $enc = ''; +- for ($i = 0; $i < $bytes; $i++) { +- $enc .= sprintf("%02x", mt_rand(0, 255)); +- } +- return $enc; ++ $enc = ''; ++ for ($i = 0; $i < $bytes; $i++) { ++ $enc .= sprintf("%02x", mt_rand(0, 255)); ++ } ++ return $enc; +hunk ./lib/util.php 1687 +- common_ensure_session(); +- $_SESSION['returnto'] = $url; ++ common_ensure_session(); ++ $_SESSION['returnto'] = $url; +hunk ./lib/util.php 1692 +- common_ensure_session(); +- return $_SESSION['returnto']; ++ common_ensure_session(); ++ return $_SESSION['returnto']; +hunk ./lib/util.php 1697 +- return date('YmdHis'); ++ return date('YmdHis'); +hunk ./lib/util.php 1701 +- static $initialized = false; +- if (!$initialized) { +- global $config; +- openlog($config['syslog']['appname'], 0, LOG_USER); +- $initialized = true; +- } ++ static $initialized = false; ++ if (!$initialized) { ++ global $config; ++ openlog($config['syslog']['appname'], 0, LOG_USER); ++ $initialized = true; ++ } +hunk ./lib/util.php 1709 +-function common_log($priority, $msg, $filename=NULL) { +- $logfile = common_config('site', 'logfile'); +- if ($logfile) { +- $log = fopen($logfile, "a"); +- if ($log) { +- static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', +- 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); +- $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; +- fwrite($log, $output); +- fclose($log); +- } +- } else { +- common_ensure_syslog(); +- syslog($priority, $msg); +- } ++function common_log($priority, $msg, $filename=null) { ++ $logfile = common_config('site', 'logfile'); ++ if ($logfile) { ++ $log = fopen($logfile, "a"); ++ if ($log) { ++ static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', ++ 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); ++ $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; ++ fwrite($log, $output); ++ fclose($log); ++ } ++ } else { ++ common_ensure_syslog(); ++ syslog($priority, $msg); ++ } +hunk ./lib/util.php 1726 +-function common_debug($msg, $filename=NULL) { +- if ($filename) { +- common_log(LOG_DEBUG, basename($filename).' - '.$msg); +- } else { +- common_log(LOG_DEBUG, $msg); +- } ++function common_debug($msg, $filename=null) { ++ if ($filename) { ++ common_log(LOG_DEBUG, basename($filename).' - '.$msg); ++ } else { ++ common_log(LOG_DEBUG, $msg); ++ } +hunk ./lib/util.php 1734 +-function common_log_db_error(&$object, $verb, $filename=NULL) { +- $objstr = common_log_objstring($object); +- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); +- common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); ++function common_log_db_error(&$object, $verb, $filename=null) { ++ $objstr = common_log_objstring($object); ++ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); ++ common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); +hunk ./lib/util.php 1741 +- if (is_null($object)) { +- return "NULL"; +- } +- $arr = $object->toArray(); +- $fields = array(); +- foreach ($arr as $k => $v) { +- $fields[] = "$k='$v'"; +- } +- $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; +- return $objstring; ++ if (is_null($object)) { ++ return "null"; ++ } ++ $arr = $object->toArray(); ++ $fields = array(); ++ foreach ($arr as $k => $v) { ++ $fields[] = "$k='$v'"; ++ } ++ $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; ++ return $objstring; +hunk ./lib/util.php 1754 +- return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); ++ return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); +hunk ./lib/util.php 1758 +- if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { +- return (Validate::email($matches[1]) || +- preg_match('/^([\w-\.]+)$/', $matches[1])); +- } +- return false; ++ if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { ++ return (Validate::email($matches[1]) || ++ preg_match('/^([\w-\.]+)$/', $matches[1])); ++ } ++ return false; +hunk ./lib/util.php 1765 +-# Does a little before-after block for next/prev page ++// Does a little before-after block for next/prev page +hunk ./lib/util.php 1767 +-function common_pagination($have_before, $have_after, $page, $action, $args=NULL) { ++function common_pagination($have_before, $have_after, $page, $action, $args=null) { +hunk ./lib/util.php 1769 +- if ($have_before || $have_after) { +- common_element_start('div', array('id' => 'pagination')); +- common_element_start('ul', array('id' => 'nav_pagination')); +- } ++ if ($have_before || $have_after) { ++ common_element_start('div', array('id' => 'pagination')); ++ common_element_start('ul', array('id' => 'nav_pagination')); ++ } +hunk ./lib/util.php 1774 +- if ($have_before) { +- $pargs = array('page' => $page-1); +- $newargs = ($args) ? array_merge($args,$pargs) : $pargs; ++ if ($have_before) { ++ $pargs = array('page' => $page-1); ++ $newargs = ($args) ? array_merge($args,$pargs) : $pargs; +hunk ./lib/util.php 1778 +- common_element_start('li', 'before'); +- common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), +- _('« After')); +- common_element_end('li'); +- } ++ common_element_start('li', 'before'); ++ common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), ++ _('« After')); ++ common_element_end('li'); ++ } +hunk ./lib/util.php 1784 +- if ($have_after) { +- $pargs = array('page' => $page+1); +- $newargs = ($args) ? array_merge($args,$pargs) : $pargs; +- common_element_start('li', 'after'); +- common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), +- _('Before »')); +- common_element_end('li'); +- } ++ if ($have_after) { ++ $pargs = array('page' => $page+1); ++ $newargs = ($args) ? array_merge($args,$pargs) : $pargs; ++ common_element_start('li', 'after'); ++ common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), ++ _('Before »')); ++ common_element_end('li'); ++ } +hunk ./lib/util.php 1793 +- if ($have_before || $have_after) { +- common_element_end('ul'); +- common_element_end('div'); +- } ++ if ($have_before || $have_after) { ++ common_element_end('ul'); ++ common_element_end('div'); ++ } +hunk ./lib/util.php 1803 +- # No arg means accept anything (per HTTP spec) +- if(!$accept) { +- return array($def => 1); +- } ++ // No arg means accept anything (per HTTP spec) ++ if(!$accept) { ++ return array($def => 1); ++ } +hunk ./lib/util.php 1808 +- $prefs = array(); ++ $prefs = array(); +hunk ./lib/util.php 1810 +- $parts = explode(',', $accept); ++ $parts = explode(',', $accept); +hunk ./lib/util.php 1812 +- foreach($parts as $part) { +- # FIXME: doesn't deal with params like 'text/html; level=1' +- @list($value, $qpart) = explode(';', $part); +- $match = array(); +- if(!isset($qpart)) { +- $prefs[$value] = 1; +- } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { +- $prefs[$value] = $match[1]; +- } +- } ++ foreach($parts as $part) { ++ // FIXME: doesn't deal with params like 'text/html; level=1' ++ @list($value, $qpart) = explode(';', $part); ++ $match = array(); ++ if(!isset($qpart)) { ++ $prefs[$value] = 1; ++ } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { ++ $prefs[$value] = $match[1]; ++ } ++ } +hunk ./lib/util.php 1823 +- return $prefs; ++ return $prefs; +hunk ./lib/util.php 1827 +- if(array_key_exists($type, $avail)) { +- return $type; +- } else { +- $parts = explode('/', $type); +- if(array_key_exists($parts[0] . '/*', $avail)) { +- return $parts[0] . '/*'; +- } elseif(array_key_exists('*/*', $avail)) { +- return '*/*'; +- } else { +- return NULL; +- } +- } ++ if(array_key_exists($type, $avail)) { ++ return $type; ++ } else { ++ $parts = explode('/', $type); ++ if(array_key_exists($parts[0] . '/*', $avail)) { ++ return $parts[0] . '/*'; ++ } elseif(array_key_exists('*/*', $avail)) { ++ return '*/*'; ++ } else { ++ return null; ++ } ++ } +hunk ./lib/util.php 1842 +- $combine = array(); ++ $combine = array(); +hunk ./lib/util.php 1844 +- foreach(array_keys($sprefs) as $type) { +- $parts = explode('/', $type); +- if($parts[1] != '*') { +- $ckey = common_mime_type_match($type, $cprefs); +- if($ckey) { +- $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; +- } +- } +- } ++ foreach(array_keys($sprefs) as $type) { ++ $parts = explode('/', $type); ++ if($parts[1] != '*') { ++ $ckey = common_mime_type_match($type, $cprefs); ++ if($ckey) { ++ $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; ++ } ++ } ++ } +hunk ./lib/util.php 1854 +- foreach(array_keys($cprefs) as $type) { +- $parts = explode('/', $type); +- if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { +- $skey = common_mime_type_match($type, $sprefs); +- if($skey) { +- $combine[$type] = $sprefs[$skey] * $cprefs[$type]; +- } +- } +- } ++ foreach(array_keys($cprefs) as $type) { ++ $parts = explode('/', $type); ++ if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { ++ $skey = common_mime_type_match($type, $sprefs); ++ if($skey) { ++ $combine[$type] = $sprefs[$skey] * $cprefs[$type]; ++ } ++ } ++ } +hunk ./lib/util.php 1864 +- $bestq = 0; +- $besttype = "text/html"; ++ $bestq = 0; ++ $besttype = "text/html"; +hunk ./lib/util.php 1867 +- foreach(array_keys($combine) as $type) { +- if($combine[$type] > $bestq) { +- $besttype = $type; +- $bestq = $combine[$type]; +- } +- } ++ foreach(array_keys($combine) as $type) { ++ if($combine[$type] > $bestq) { ++ $besttype = $type; ++ $bestq = $combine[$type]; ++ } ++ } +hunk ./lib/util.php 1874 +- return $besttype; ++ return $besttype; +hunk ./lib/util.php 1878 +- global $config; +- return isset($config[$main][$sub]) ? $config[$main][$sub] : false; ++ global $config; ++ return isset($config[$main][$sub]) ? $config[$main][$sub] : false; +hunk ./lib/util.php 1883 +- $to = array(); +- $strip = get_magic_quotes_gpc(); +- foreach ($from as $k => $v) { +- $to[$k] = ($strip) ? stripslashes($v) : $v; +- } +- return $to; ++ $to = array(); ++ $strip = get_magic_quotes_gpc(); ++ foreach ($from as $k => $v) { ++ $to[$k] = ($strip) ? stripslashes($v) : $v; ++ } ++ return $to; +hunk ./lib/util.php 1894 +- if(get_magic_quotes_gpc()) { +- $_POST=array_map('stripslashes',$_POST); +- $_GET=array_map('stripslashes',$_GET); +- } ++ if(get_magic_quotes_gpc()) { ++ $_POST=array_map('stripslashes',$_POST); ++ $_GET=array_map('stripslashes',$_GET); ++ } +hunk ./lib/util.php 1901 +- return common_local_url('userbyid', array('id' => $user->id)); ++ return common_local_url('userbyid', array('id' => $user->id)); +hunk ./lib/util.php 1905 +- return common_local_url('shownotice', +- array('notice' => $notice->id)); ++ return common_local_url('shownotice', ++ array('notice' => $notice->id)); +hunk ./lib/util.php 1909 +-# 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits ++// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits +hunk ./lib/util.php 1912 +- # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits +- static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; +- $chars = ceil($bits/5); +- $code = ''; +- for ($i = 0; $i < $chars; $i++) { +- # XXX: convert to string and back +- $num = hexdec(common_good_rand(1)); +- # XXX: randomness is too precious to throw away almost +- # 40% of the bits we get! +- $code .= $codechars[$num%32]; +- } +- return $code; ++ // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits ++ static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; ++ $chars = ceil($bits/5); ++ $code = ''; ++ for ($i = 0; $i < $chars; $i++) { ++ // XXX: convert to string and back ++ $num = hexdec(common_good_rand(1)); ++ // XXX: randomness is too precious to throw away almost ++ // 40% of the bits we get! ++ $code .= $codechars[$num%32]; ++ } ++ return $code; +hunk ./lib/util.php 1926 +-# convert markup to HTML ++// convert markup to HTML +hunk ./lib/util.php 1929 +- $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); +- $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); +- $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); +- return Markdown($c); ++ $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); ++ $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); ++ $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); ++ return Markdown($c); +hunk ./lib/util.php 1936 +- $avatar = $profile->getAvatar($size); +- if ($avatar) { +- return common_avatar_display_url($avatar); +- } else { +- return common_default_avatar($size); +- } ++ $avatar = $profile->getAvatar($size); ++ if ($avatar) { ++ return common_avatar_display_url($avatar); ++ } else { ++ return common_default_avatar($size); ++ } +hunk ./lib/util.php 1945 +- if (!$profile) { +- return NULL; +- } +- $user = User::staticGet($profile->id); +- if ($user) { +- return $user->uri; +- } ++ if (!$profile) { ++ return null; ++ } ++ $user = User::staticGet($profile->id); ++ if ($user) { ++ return $user->uri; ++ } +hunk ./lib/util.php 1953 +- $remote = Remote_profile::staticGet($profile->id); +- if ($remote) { +- return $remote->uri; +- } +- # XXX: this is a very bad profile! +- return NULL; ++ $remote = Remote_profile::staticGet($profile->id); ++ if ($remote) { ++ return $remote->uri; ++ } ++ // XXX: this is a very bad profile! ++ return null; +hunk ./lib/util.php 1962 +- # strip non-digits +- preg_replace('/\D/', '', $sms); +- return $sms; ++ // strip non-digits ++ preg_replace('/\D/', '', $sms); ++ return $sms; +hunk ./lib/util.php 1970 +- common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); +- exit(1); +- break; ++ common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); ++ exit(1); ++ break; +hunk ./lib/util.php 1974 +- case E_USER_WARNING: +- common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); +- break; ++ case E_USER_WARNING: ++ common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); ++ break; +hunk ./lib/util.php 1979 +- common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); +- break; ++ common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); ++ break; +hunk ./lib/util.php 1983 +- # FIXME: show error page if we're on the Web ++ // FIXME: show error page if we're on the Web +hunk ./lib/util.php 1989 +- common_ensure_session(); +- if (!array_key_exists('token', $_SESSION)) { +- $_SESSION['token'] = common_good_rand(64); +- } +- return $_SESSION['token']; ++ common_ensure_session(); ++ if (!array_key_exists('token', $_SESSION)) { ++ $_SESSION['token'] = common_good_rand(64); ++ } ++ return $_SESSION['token']; +hunk ./lib/util.php 1997 +- common_element_start('form', array('id' => 'disfavor-' . $notice->id, +- 'method' => 'post', +- 'class' => 'disfavor', +- 'action' => common_local_url('disfavor'))); ++ common_element_start('form', array('id' => 'disfavor-' . $notice->id, ++ 'method' => 'post', ++ 'class' => 'disfavor', ++ 'action' => common_local_url('disfavor'))); +hunk ./lib/util.php 2002 +- common_element('input', array('type' => 'hidden', +- 'name' => 'token-'. $notice->id, +- 'id' => 'token-'. $notice->id, +- 'class' => 'token', +- 'value' => common_session_token())); ++ common_element('input', array('type' => 'hidden', ++ 'name' => 'token-'. $notice->id, ++ 'id' => 'token-'. $notice->id, ++ 'class' => 'token', ++ 'value' => common_session_token())); +hunk ./lib/util.php 2008 +- common_element('input', array('type' => 'hidden', +- 'name' => 'notice', +- 'id' => 'notice-n'. $notice->id, +- 'class' => 'notice', +- 'value' => $notice->id)); ++ common_element('input', array('type' => 'hidden', ++ 'name' => 'notice', ++ 'id' => 'notice-n'. $notice->id, ++ 'class' => 'notice', ++ 'value' => $notice->id)); +hunk ./lib/util.php 2014 +- common_element('input', array('type' => 'submit', +- 'id' => 'disfavor-submit-' . $notice->id, +- 'name' => 'disfavor-submit-' . $notice->id, +- 'class' => 'disfavor', +- 'value' => 'Disfavor favorite', +- 'title' => 'Remove this message from favorites')); +- common_element_end('form'); ++ common_element('input', array('type' => 'submit', ++ 'id' => 'disfavor-submit-' . $notice->id, ++ 'name' => 'disfavor-submit-' . $notice->id, ++ 'class' => 'disfavor', ++ 'value' => 'Disfavor favorite', ++ 'title' => 'Remove this message from favorites')); ++ common_element_end('form'); +hunk ./lib/util.php 2024 +- common_element_start('form', array('id' => 'favor-' . $notice->id, +- 'method' => 'post', +- 'class' => 'favor', +- 'action' => common_local_url('favor'))); ++ common_element_start('form', array('id' => 'favor-' . $notice->id, ++ 'method' => 'post', ++ 'class' => 'favor', ++ 'action' => common_local_url('favor'))); +hunk ./lib/util.php 2029 +- common_element('input', array('type' => 'hidden', +- 'name' => 'token-'. $notice->id, +- 'id' => 'token-'. $notice->id, +- 'class' => 'token', +- 'value' => common_session_token())); ++ common_element('input', array('type' => 'hidden', ++ 'name' => 'token-'. $notice->id, ++ 'id' => 'token-'. $notice->id, ++ 'class' => 'token', ++ 'value' => common_session_token())); +hunk ./lib/util.php 2035 +- common_element('input', array('type' => 'hidden', +- 'name' => 'notice', +- 'id' => 'notice-n'. $notice->id, +- 'class' => 'notice', +- 'value' => $notice->id)); ++ common_element('input', array('type' => 'hidden', ++ 'name' => 'notice', ++ 'id' => 'notice-n'. $notice->id, ++ 'class' => 'notice', ++ 'value' => $notice->id)); +hunk ./lib/util.php 2041 +- common_element('input', array('type' => 'submit', +- 'id' => 'favor-submit-' . $notice->id, +- 'name' => 'favor-submit-' . $notice->id, +- 'class' => 'favor', +- 'value' => 'Add to favorites', +- 'title' => 'Add this message to favorites')); +- common_element_end('form'); ++ common_element('input', array('type' => 'submit', ++ 'id' => 'favor-submit-' . $notice->id, ++ 'name' => 'favor-submit-' . $notice->id, ++ 'class' => 'favor', ++ 'value' => 'Add to favorites', ++ 'title' => 'Add this message to favorites')); ++ common_element_end('form'); +hunk ./lib/util.php 2051 +- common_element_start('form', array('id' => 'nudge', 'method' => 'post', +- 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); +- common_hidden('token', common_session_token()); +- common_element('input', array('type' => 'submit', +- 'class' => 'submit', +- 'value' => _('Send a nudge'))); +- common_element_end('form'); ++ common_element_start('form', array('id' => 'nudge', 'method' => 'post', ++ 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); ++ common_hidden('token', common_session_token()); ++ common_element('input', array('type' => 'submit', ++ 'class' => 'submit', ++ 'value' => _('Send a nudge'))); ++ common_element_end('form'); +hunk ./lib/util.php 2060 +- common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); ++ common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); +hunk ./lib/util.php 2064 +- common_element_start('form', array('id' => 'subscribe-' . $profile->id, +- 'method' => 'post', +- 'class' => 'subscribe', +- 'action' => common_local_url('subscribe'))); +- common_hidden('token', common_session_token()); +- common_element('input', array('id' => 'subscribeto-' . $profile->id, +- 'name' => 'subscribeto', +- 'type' => 'hidden', +- 'value' => $profile->id)); +- common_element('input', array('type' => 'submit', +- 'class' => 'submit', +- 'value' => _('Subscribe'))); +- common_element_end('form'); ++ common_element_start('form', array('id' => 'subscribe-' . $profile->id, ++ 'method' => 'post', ++ 'class' => 'subscribe', ++ 'action' => common_local_url('subscribe'))); ++ common_hidden('token', common_session_token()); ++ common_element('input', array('id' => 'subscribeto-' . $profile->id, ++ 'name' => 'subscribeto', ++ 'type' => 'hidden', ++ 'value' => $profile->id)); ++ common_element('input', array('type' => 'submit', ++ 'class' => 'submit', ++ 'value' => _('Subscribe'))); ++ common_element_end('form'); +hunk ./lib/util.php 2080 +- common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, +- 'method' => 'post', +- 'class' => 'unsubscribe', +- 'action' => common_local_url('unsubscribe'))); +- common_hidden('token', common_session_token()); +- common_element('input', array('id' => 'unsubscribeto-' . $profile->id, +- 'name' => 'unsubscribeto', +- 'type' => 'hidden', +- 'value' => $profile->id)); +- common_element('input', array('type' => 'submit', +- 'class' => 'submit', +- 'value' => _('Unsubscribe'))); +- common_element_end('form'); ++ common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, ++ 'method' => 'post', ++ 'class' => 'unsubscribe', ++ 'action' => common_local_url('unsubscribe'))); ++ common_hidden('token', common_session_token()); ++ common_element('input', array('id' => 'unsubscribeto-' . $profile->id, ++ 'name' => 'unsubscribeto', ++ 'type' => 'hidden', ++ 'value' => $profile->id)); ++ common_element('input', array('type' => 'submit', ++ 'class' => 'submit', ++ 'value' => _('Unsubscribe'))); ++ common_element_end('form'); +hunk ./lib/util.php 2097 +- $user = User::staticGet('id', $profile->id); ++ $user = User::staticGet('id', $profile->id); +hunk ./lib/util.php 2099 +- if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { ++ if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { +hunk ./lib/util.php 2101 +- common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), +- _('Send a message')); ++ common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), ++ _('Send a message')); +hunk ./lib/util.php 2105 +- if ($user->email && $user->emailnotifynudge) { ++ if ($user->email && $user->emailnotifynudge) { +hunk ./lib/util.php 2110 +- } ++ } +hunk ./lib/util.php 2114 +- return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; ++ return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; +hunk ./lib/util.php 2118 +- $str = strtolower($str); +- $str = preg_replace('/\s/', '_', $str); +- return $str; ++ $str = strtolower($str); ++ $str = preg_replace('/\s/', '_', $str); ++ return $str; +hunk ./lib/util.php 2125 +- common_element_start('form', array('id' => 'message_form', +- 'method' => 'post', +- 'action' => common_local_url('newmessage'))); ++ common_element_start('form', array('id' => 'message_form', ++ 'method' => 'post', ++ 'action' => common_local_url('newmessage'))); +hunk ./lib/util.php 2129 +- $mutual_users = $user->mutuallySubscribedUsers(); ++ $mutual_users = $user->mutuallySubscribedUsers(); +hunk ./lib/util.php 2131 +- $mutual = array(); ++ $mutual = array(); +hunk ./lib/util.php 2133 +- while ($mutual_users->fetch()) { +- if ($mutual_users->id != $user->id) { +- $mutual[$mutual_users->id] = $mutual_users->nickname; +- } +- } ++ while ($mutual_users->fetch()) { ++ if ($mutual_users->id != $user->id) { ++ $mutual[$mutual_users->id] = $mutual_users->nickname; ++ } ++ } +hunk ./lib/util.php 2139 +- $mutual_users->free(); +- unset($mutual_users); ++ $mutual_users->free(); ++ unset($mutual_users); +hunk ./lib/util.php 2142 +- common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id); ++ common_dropdown('to', _('To'), $mutual, null, FALSE, $to->id); +hunk ./lib/util.php 2144 +- common_element_start('p'); ++ common_element_start('p'); +hunk ./lib/util.php 2146 +- common_element('textarea', array('id' => 'message_content', +- 'cols' => 60, +- 'rows' => 3, +- 'name' => 'content'), +- ($content) ? $content : ''); ++ common_element('textarea', array('id' => 'message_content', ++ 'cols' => 60, ++ 'rows' => 3, ++ 'name' => 'content'), ++ ($content) ? $content : ''); +hunk ./lib/util.php 2152 +- common_element('input', array('id' => 'message_send', +- 'name' => 'message_send', +- 'type' => 'submit', +- 'value' => _('Send'))); ++ common_element('input', array('id' => 'message_send', ++ 'name' => 'message_send', ++ 'type' => 'submit', ++ 'value' => _('Send'))); +hunk ./lib/util.php 2157 +- common_hidden('token', common_session_token()); ++ common_hidden('token', common_session_token()); +hunk ./lib/util.php 2159 +- common_element_end('p'); +- common_element_end('form'); ++ common_element_end('p'); ++ common_element_end('form'); +hunk ./lib/util.php 2164 +- static $cache = NULL; +- if (!common_config('memcached', 'enabled')) { +- return NULL; +- } else { +- if (!$cache) { +- $cache = new Memcache(); +- $servers = common_config('memcached', 'server'); +- if (is_array($servers)) { +- foreach($servers as $server) { +- $cache->addServer($server); +- } +- } else { +- $cache->addServer($servers); +- } +- } +- return $cache; +- } ++ static $cache = null; ++ if (!common_config('memcached', 'enabled')) { ++ return null; ++ } else { ++ if (!$cache) { ++ $cache = new Memcache(); ++ $servers = common_config('memcached', 'server'); ++ if (is_array($servers)) { ++ foreach($servers as $server) { ++ $cache->addServer($server); ++ } ++ } else { ++ $cache->addServer($servers); ++ } ++ } ++ return $cache; + } +hunk ./lib/util.php 2184 +- # XXX: better compatibility check needed here! +- return ($from == $to); ++ // XXX: better compatibility check needed here! ++ return ($from == $to); +hunk ./lib/util.php 2190 +-function common_block_form($profile, $args=NULL) { ++function common_block_form($profile, $args=null) { +hunk ./lib/util.php 2194 +-function common_unblock_form($profile, $args=NULL) { ++function common_unblock_form($profile, $args=null) { +hunk ./lib/util.php 2198 +-function common_blocking_form($type, $label, $profile, $args=NULL) { ++function common_blocking_form($type, $label, $profile, $args=null) { +hunk ./lib/util.php 2220 +- diff --git a/lib/util.php b/lib/util.php index 8eeda1115..f0387ebe5 100644 --- a/lib/util.php +++ b/lib/util.php @@ -19,116 +19,116 @@ /* XXX: break up into separate modules (HTTP, HTML, user, files) */ -# Show a server error +// Show a server error function common_server_error($msg, $code=500) { - static $status = array(500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported'); - - if (!array_key_exists($code, $status)) { - $code = 500; - } + static $status = array(500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported'); + + if (!array_key_exists($code, $status)) { + $code = 500; + } - $status_string = $status[$code]; + $status_string = $status[$code]; - header('HTTP/1.1 '.$code.' '.$status_string); - header('Content-type: text/plain'); + header('HTTP/1.1 '.$code.' '.$status_string); + header('Content-type: text/plain'); - print $msg; - print "\n"; - exit(); + print $msg; + print "\n"; + exit(); } -# Show a user error +// Show a user error function common_user_error($msg, $code=400) { - static $status = array(400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed'); - - if (!array_key_exists($code, $status)) { - $code = 400; - } - - $status_string = $status[$code]; - - header('HTTP/1.1 '.$code.' '.$status_string); - - common_show_header('Error'); - common_element('div', array('class' => 'error'), $msg); - common_show_footer(); + static $status = array(400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed'); + + if (!array_key_exists($code, $status)) { + $code = 400; + } + + $status_string = $status[$code]; + + header('HTTP/1.1 '.$code.' '.$status_string); + + common_show_header('Error'); + common_element('div', array('class' => 'error'), $msg); + common_show_footer(); } $xw = null; -# Start an HTML element -function common_element_start($tag, $attrs=NULL) { - global $xw; - $xw->startElement($tag); - if (is_array($attrs)) { - foreach ($attrs as $name => $value) { - $xw->writeAttribute($name, $value); - } - } else if (is_string($attrs)) { - $xw->writeAttribute('class', $attrs); - } +// Start an HTML element +function common_element_start($tag, $attrs=null) { + global $xw; + $xw->startElement($tag); + if (is_array($attrs)) { + foreach ($attrs as $name => $value) { + $xw->writeAttribute($name, $value); + } + } else if (is_string($attrs)) { + $xw->writeAttribute('class', $attrs); + } } function common_element_end($tag) { - static $empty_tag = array('base', 'meta', 'link', 'hr', - 'br', 'param', 'img', 'area', - 'input', 'col'); - global $xw; - # XXX: check namespace - if (in_array($tag, $empty_tag)) { - $xw->endElement(); - } else { - $xw->fullEndElement(); - } -} - -function common_element($tag, $attrs=NULL, $content=NULL) { - common_element_start($tag, $attrs); - global $xw; - if (!is_null($content)) { - $xw->text($content); - } - common_element_end($tag); -} - -function common_start_xml($doc=NULL, $public=NULL, $system=NULL, $indent=true) { - global $xw; - $xw = new XMLWriter(); - $xw->openURI('php://output'); - $xw->setIndent($indent); - $xw->startDocument('1.0', 'UTF-8'); - if ($doc) { - $xw->writeDTD($doc, $public, $system); - } + static $empty_tag = array('base', 'meta', 'link', 'hr', + 'br', 'param', 'img', 'area', + 'input', 'col'); + global $xw; + // XXX: check namespace + if (in_array($tag, $empty_tag)) { + $xw->endElement(); + } else { + $xw->fullEndElement(); + } +} + +function common_element($tag, $attrs=null, $content=null) { + common_element_start($tag, $attrs); + global $xw; + if (!is_null($content)) { + $xw->text($content); + } + common_element_end($tag); +} + +function common_start_xml($doc=null, $public=null, $system=null, $indent=true) { + global $xw; + $xw = new XMLWriter(); + $xw->openURI('php://output'); + $xw->setIndent($indent); + $xw->startDocument('1.0', 'UTF-8'); + if ($doc) { + $xw->writeDTD($doc, $public, $system); + } } function common_end_xml() { - global $xw; - $xw->endDocument(); - $xw->flush(); + global $xw; + $xw->endDocument(); + $xw->flush(); } function common_init_locale($language=null) { @@ -138,433 +138,433 @@ function common_init_locale($language=null) { putenv('LANGUAGE='.$language); putenv('LANG='.$language); return setlocale(LC_ALL, $language . ".utf8", - $language . ".UTF8", - $language . ".utf-8", - $language . ".UTF-8", - $language); + $language . ".UTF8", + $language . ".utf-8", + $language . ".UTF-8", + $language); } function common_init_language() { - mb_internal_encoding('UTF-8'); - $language = common_language(); - # So we don't have to make people install the gettext locales - $locale_set = common_init_locale($language); - bindtextdomain("laconica", common_config('site','locale_path')); - bind_textdomain_codeset("laconica", "UTF-8"); - textdomain("laconica"); - setlocale(LC_CTYPE, 'C'); - if(!$locale_set) { - common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); - } + mb_internal_encoding('UTF-8'); + $language = common_language(); + // So we don't have to make people install the gettext locales + $locale_set = common_init_locale($language); + bindtextdomain("laconica", common_config('site','locale_path')); + bind_textdomain_codeset("laconica", "UTF-8"); + textdomain("laconica"); + setlocale(LC_CTYPE, 'C'); + if(!$locale_set) { + common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); + } } define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2'); -function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) { +function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null) { - global $config, $xw; + global $config, $xw; global $action; /* XXX: kind of cheating here. */ - common_start_html(); - - common_element_start('head'); - common_element('title', NULL, - $pagetitle . " - " . $config['site']['name']); - common_element('link', array('rel' => 'stylesheet', - 'type' => 'text/css', - 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, - 'media' => 'screen, projection, tv')); - foreach (array(6,7) as $ver) { - if (file_exists(theme_file('ie'.$ver.'.css'))) { - # Yes, IE people should be put in jail. - $xw->writeComment('[if lte IE '.$ver.']> 'text/javascript', - 'src' => common_path('js/jquery.min.js')), - ' '); - common_element('script', array('type' => 'text/javascript', - 'src' => common_path('js/jquery.form.js')), - ' '); - common_element('script', array('type' => 'text/javascript', - 'src' => common_path('js/xbImportNode.js')), - ' '); - common_element('script', array('type' => 'text/javascript', - 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), - ' '); - common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', - 'href' => common_local_url('opensearch', array('type' => 'people')), - 'title' => common_config('site', 'name').' People Search')); - - common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', - 'href' => common_local_url('opensearch', array('type' => 'notice')), - 'title' => common_config('site', 'name').' Notice Search')); - - if ($callable) { - if ($data) { - call_user_func($callable, $data); - } else { - call_user_func($callable); - } - } - common_element_end('head'); - common_element_start('body', $action); - common_element_start('div', array('id' => 'wrap')); - common_element_start('div', array('id' => 'header')); - common_nav_menu(); - if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) - || file_exists(theme_file('logo.png'))) - { - common_element_start('a', array('href' => common_local_url('public'))); - common_element('img', array('src' => isset($config['site']['logo']) ? - ($config['site']['logo']) : theme_path('logo.png'), - 'alt' => $config['site']['name'], - 'id' => 'logo')); - common_element_end('a'); - } else { - common_element_start('p', array('id' => 'branding')); - common_element('a', array('href' => common_local_url('public')), - $config['site']['name']); - common_element_end('p'); - } - - common_element('h1', 'pagetitle', $pagetitle); - - if ($headercall) { - if ($data) { - call_user_func($headercall, $data); - } else { - call_user_func($headercall); - } - } - common_element_end('div'); - common_element_start('div', array('id' => 'content')); -} - -function common_start_html($type=NULL, $indent=true) { - - if (!$type) { - $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL; - - # XXX: allow content negotiation for RDF, RSS, or XRDS - - $type = common_negotiate_type(common_accept_to_prefs($httpaccept), - common_accept_to_prefs(PAGE_TYPE_PREFS)); - - if (!$type) { - common_user_error(_('This page is not available in a media type you accept'), 406); - exit(0); - } - } - - header('Content-Type: '.$type); - - common_start_xml('html', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); - - # FIXME: correct language for interface - - $language = common_language(); - - common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', - 'xml:lang' => $language, - 'lang' => $language)); + common_start_html(); + + common_element_start('head'); + common_element('title', null, + $pagetitle . " - " . $config['site']['name']); + common_element('link', array('rel' => 'stylesheet', + 'type' => 'text/css', + 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, + 'media' => 'screen, projection, tv')); + foreach (array(6,7) as $ver) { + if (file_exists(theme_file('ie'.$ver.'.css'))) { + // Yes, IE people should be put in jail. + $xw->writeComment('[if lte IE '.$ver.']> 'text/javascript', + 'src' => common_path('js/jquery.min.js')), + ' '); + common_element('script', array('type' => 'text/javascript', + 'src' => common_path('js/jquery.form.js')), + ' '); + common_element('script', array('type' => 'text/javascript', + 'src' => common_path('js/xbImportNode.js')), + ' '); + common_element('script', array('type' => 'text/javascript', + 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), + ' '); + common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', + 'href' => common_local_url('opensearch', array('type' => 'people')), + 'title' => common_config('site', 'name').' People Search')); + + common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', + 'href' => common_local_url('opensearch', array('type' => 'notice')), + 'title' => common_config('site', 'name').' Notice Search')); + + if ($callable) { + if ($data) { + call_user_func($callable, $data); + } else { + call_user_func($callable); + } + } + common_element_end('head'); + common_element_start('body', $action); + common_element_start('div', array('id' => 'wrap')); + common_element_start('div', array('id' => 'header')); + common_nav_menu(); + if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) + || file_exists(theme_file('logo.png'))) + { + common_element_start('a', array('href' => common_local_url('public'))); + common_element('img', array('src' => isset($config['site']['logo']) ? + ($config['site']['logo']) : theme_path('logo.png'), + 'alt' => $config['site']['name'], + 'id' => 'logo')); + common_element_end('a'); + } else { + common_element_start('p', array('id' => 'branding')); + common_element('a', array('href' => common_local_url('public')), + $config['site']['name']); + common_element_end('p'); + } + + common_element('h1', 'pagetitle', $pagetitle); + + if ($headercall) { + if ($data) { + call_user_func($headercall, $data); + } else { + call_user_func($headercall); + } + } + common_element_end('div'); + common_element_start('div', array('id' => 'content')); +} + +function common_start_html($type=null, $indent=true) { + + if (!$type) { + $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; + + // XXX: allow content negotiation for RDF, RSS, or XRDS + + $type = common_negotiate_type(common_accept_to_prefs($httpaccept), + common_accept_to_prefs(PAGE_TYPE_PREFS)); + + if (!$type) { + common_user_error(_('This page is not available in a media type you accept'), 406); + exit(0); + } + } + + header('Content-Type: '.$type); + + common_start_xml('html', + '-//W3C//DTD XHTML 1.0 Strict//EN', + 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); + + // FIXME: correct language for interface + + $language = common_language(); + + common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', + 'xml:lang' => $language, + 'lang' => $language)); } function common_show_footer() { - global $xw, $config; - common_element_end('div'); # content div - common_foot_menu(); - common_element_start('div', array('id' => 'footer')); - common_element_start('div', 'laconica'); - if (common_config('site', 'broughtby')) { - $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); - } else { - $instr = _('**%%site.name%%** is a microblogging service. '); - } - $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); + global $xw, $config; + common_element_end('div'); // content div + common_foot_menu(); + common_element_start('div', array('id' => 'footer')); + common_element_start('div', 'laconica'); + if (common_config('site', 'broughtby')) { + $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); + } else { + $instr = _('**%%site.name%%** is a microblogging service. '); + } + $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); $output = common_markup_to_html($instr); common_raw($output); - common_element_end('div'); - common_element('img', array('id' => 'cc', - 'src' => $config['license']['image'], - 'alt' => $config['license']['title'])); - common_element_start('p'); - common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); - common_element('a', array('class' => 'license', - 'rel' => 'license', - 'href' => $config['license']['url']), - $config['license']['title']); - common_text(_('. Contributors should be attributed by full name or nickname.')); - common_element_end('p'); - common_element_end('div'); - common_element_end('div'); - common_element_end('body'); - common_element_end('html'); - common_end_xml(); + common_element_end('div'); + common_element('img', array('id' => 'cc', + 'src' => $config['license']['image'], + 'alt' => $config['license']['title'])); + common_element_start('p'); + common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); + common_element('a', array('class' => 'license', + 'rel' => 'license', + 'href' => $config['license']['url']), + $config['license']['title']); + common_text(_('. Contributors should be attributed by full name or nickname.')); + common_element_end('p'); + common_element_end('div'); + common_element_end('div'); + common_element_end('body'); + common_element_end('html'); + common_end_xml(); } function common_text($txt) { - global $xw; - $xw->text($txt); + global $xw; + $xw->text($txt); } function common_raw($xml) { - global $xw; - $xw->writeRaw($xml); + global $xw; + $xw->writeRaw($xml); } function common_nav_menu() { - $user = common_current_user(); - common_element_start('ul', array('id' => 'nav')); - if ($user) { - common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), - _('Home')); - } - common_menu_item(common_local_url('peoplesearch'), _('Search')); - if ($user) { - common_menu_item(common_local_url('profilesettings'), - _('Settings')); - common_menu_item(common_local_url('invite'), - _('Invite')); - common_menu_item(common_local_url('logout'), - _('Logout')); - } else { - common_menu_item(common_local_url('login'), _('Login')); - if (!common_config('site', 'closed')) { - common_menu_item(common_local_url('register'), _('Register')); - } - common_menu_item(common_local_url('openidlogin'), _('OpenID')); - } - common_menu_item(common_local_url('doc', array('title' => 'help')), - _('Help')); - common_element_end('ul'); + $user = common_current_user(); + common_element_start('ul', array('id' => 'nav')); + if ($user) { + common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), + _('Home')); + } + common_menu_item(common_local_url('peoplesearch'), _('Search')); + if ($user) { + common_menu_item(common_local_url('profilesettings'), + _('Settings')); + common_menu_item(common_local_url('invite'), + _('Invite')); + common_menu_item(common_local_url('logout'), + _('Logout')); + } else { + common_menu_item(common_local_url('login'), _('Login')); + if (!common_config('site', 'closed')) { + common_menu_item(common_local_url('register'), _('Register')); + } + common_menu_item(common_local_url('openidlogin'), _('OpenID')); + } + common_menu_item(common_local_url('doc', array('title' => 'help')), + _('Help')); + common_element_end('ul'); } function common_foot_menu() { - common_element_start('ul', array('id' => 'nav_sub')); - common_menu_item(common_local_url('doc', array('title' => 'help')), - _('Help')); - common_menu_item(common_local_url('doc', array('title' => 'about')), - _('About')); - common_menu_item(common_local_url('doc', array('title' => 'faq')), - _('FAQ')); - common_menu_item(common_local_url('doc', array('title' => 'privacy')), - _('Privacy')); - common_menu_item(common_local_url('doc', array('title' => 'source')), - _('Source')); - common_menu_item(common_local_url('doc', array('title' => 'contact')), - _('Contact')); - common_element_end('ul'); -} - -function common_menu_item($url, $text, $title=NULL, $is_selected=false) { - $lattrs = array(); - if ($is_selected) { - $lattrs['class'] = 'current'; - } - common_element_start('li', $lattrs); - $attrs['href'] = $url; - if ($title) { - $attrs['title'] = $title; - } - common_element('a', $attrs, $text); - common_element_end('li'); -} - -function common_input($id, $label, $value=NULL,$instructions=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - $attrs = array('name' => $id, - 'type' => 'text', - 'class' => 'input_text', - 'id' => $id); - if ($value) { - $attrs['value'] = htmlspecialchars($value); - } - common_element('input', $attrs); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); -} - -function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false) + common_element_start('ul', array('id' => 'nav_sub')); + common_menu_item(common_local_url('doc', array('title' => 'help')), + _('Help')); + common_menu_item(common_local_url('doc', array('title' => 'about')), + _('About')); + common_menu_item(common_local_url('doc', array('title' => 'faq')), + _('FAQ')); + common_menu_item(common_local_url('doc', array('title' => 'privacy')), + _('Privacy')); + common_menu_item(common_local_url('doc', array('title' => 'source')), + _('Source')); + common_menu_item(common_local_url('doc', array('title' => 'contact')), + _('Contact')); + common_element_end('ul'); +} + +function common_menu_item($url, $text, $title=null, $is_selected=false) { + $lattrs = array(); + if ($is_selected) { + $lattrs['class'] = 'current'; + } + common_element_start('li', $lattrs); + $attrs['href'] = $url; + if ($title) { + $attrs['title'] = $title; + } + common_element('a', $attrs, $text); + common_element_end('li'); +} + +function common_input($id, $label, $value=null,$instructions=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + $attrs = array('name' => $id, + 'type' => 'text', + 'class' => 'input_text', + 'id' => $id); + if ($value) { + $attrs['value'] = htmlspecialchars($value); + } + common_element('input', $attrs); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); +} + +function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false) { - common_element_start('p'); - $attrs = array('name' => $id, - 'type' => 'checkbox', - 'class' => 'checkbox', - 'id' => $id); - if ($value) { - $attrs['value'] = htmlspecialchars($value); - } - if ($checked) { - $attrs['checked'] = 'checked'; - } - if ($disabled) { - $attrs['disabled'] = 'true'; - } - common_element('input', $attrs); - common_text(' '); - common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); - common_text(' '); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); -} - -function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - common_element_start('select', array('id' => $id, 'name' => $id)); - if ($blank_select) { - common_element('option', array('value' => '')); - } - foreach ($content as $value => $option) { - if ($value == $selected) { - common_element('option', array('value' => $value, 'selected' => $value), $option); - } else { - common_element('option', array('value' => $value), $option); - } - } - common_element_end('select'); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); + common_element_start('p'); + $attrs = array('name' => $id, + 'type' => 'checkbox', + 'class' => 'checkbox', + 'id' => $id); + if ($value) { + $attrs['value'] = htmlspecialchars($value); + } + if ($checked) { + $attrs['checked'] = 'checked'; + } + if ($disabled) { + $attrs['disabled'] = 'true'; + } + common_element('input', $attrs); + common_text(' '); + common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); + common_text(' '); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); +} + +function common_dropdown($id, $label, $content, $instructions=null, $blank_select=FALSE, $selected=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + common_element_start('select', array('id' => $id, 'name' => $id)); + if ($blank_select) { + common_element('option', array('value' => '')); + } + foreach ($content as $value => $option) { + if ($value == $selected) { + common_element('option', array('value' => $value, 'selected' => $value), $option); + } else { + common_element('option', array('value' => $value), $option); + } + } + common_element_end('select'); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); } function common_hidden($id, $value) { - common_element('input', array('name' => $id, - 'type' => 'hidden', - 'id' => $id, - 'value' => $value)); -} - -function common_password($id, $label, $instructions=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - $attrs = array('name' => $id, - 'type' => 'password', - 'class' => 'password', - 'id' => $id); - common_element('input', $attrs); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); + common_element('input', array('name' => $id, + 'type' => 'hidden', + 'id' => $id, + 'value' => $value)); +} + +function common_password($id, $label, $instructions=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + $attrs = array('name' => $id, + 'type' => 'password', + 'class' => 'password', + 'id' => $id); + common_element('input', $attrs); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); } function common_submit($id, $label, $cls='submit') { - global $xw; - common_element_start('p'); - common_element('input', array('type' => 'submit', - 'id' => $id, - 'name' => $id, - 'class' => $cls, - 'value' => $label)); - common_element_end('p'); -} - -function common_textarea($id, $label, $content=NULL, $instructions=NULL) { - common_element_start('p'); - common_element('label', array('for' => $id), $label); - common_element('textarea', array('rows' => 3, - 'cols' => 40, - 'name' => $id, - 'id' => $id), - ($content) ? $content : ''); - if ($instructions) { - common_element('span', 'input_instructions', $instructions); - } - common_element_end('p'); + global $xw; + common_element_start('p'); + common_element('input', array('type' => 'submit', + 'id' => $id, + 'name' => $id, + 'class' => $cls, + 'value' => $label)); + common_element_end('p'); +} + +function common_textarea($id, $label, $content=null, $instructions=null) { + common_element_start('p'); + common_element('label', array('for' => $id), $label); + common_element('textarea', array('rows' => 3, + 'cols' => 40, + 'name' => $id, + 'id' => $id), + ($content) ? $content : ''); + if ($instructions) { + common_element('span', 'input_instructions', $instructions); + } + common_element_end('p'); } function common_timezone() { - if (common_logged_in()) { - $user = common_current_user(); - if ($user->timezone) { - return $user->timezone; - } - } + if (common_logged_in()) { + $user = common_current_user(); + if ($user->timezone) { + return $user->timezone; + } + } - global $config; - return $config['site']['timezone']; + global $config; + return $config['site']['timezone']; } 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()) { - $user = common_current_user(); - $user_language = $user->language; - if ($user_language) - return $user_language; - } + // If there is a user logged in and they've set a language preference + // then return that one... + if (common_logged_in()) { + $user = common_current_user(); + $user_language = $user->language; + if ($user_language) + return $user_language; + } - // Otherwise, find the best match for the languages requested by the - // user's browser... - $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL; - if (!empty($httplang)) { - $language = client_prefered_language($httplang); - if ($language) - return $language; - } + // Otherwise, find the best match for the languages requested by the + // user's browser... + $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; + if (!empty($httplang)) { + $language = client_prefered_language($httplang); + if ($language) + return $language; + } - // Finally, if none of the above worked, use the site's default... - return common_config('site', 'language'); + // Finally, if none of the above worked, use the site's default... + return common_config('site', 'language'); } -# salted, hashed passwords are stored in the DB +// salted, hashed passwords are stored in the DB function common_munge_password($password, $id) { - return md5($password . $id); + return md5($password . $id); } -# check if a username exists and has matching password +// check if a username exists and has matching password function common_check_user($nickname, $password) { - # NEVER allow blank passwords, even if they match the DB - if (mb_strlen($password) == 0) { - return false; - } - $user = User::staticGet('nickname', $nickname); - if (is_null($user)) { - return false; - } else { - if (0 == strcmp(common_munge_password($password, $user->id), - $user->password)) { - return $user; - } else { - return false; - } - } -} - -# is the current user logged in? + // NEVER allow blank passwords, even if they match the DB + if (mb_strlen($password) == 0) { + return false; + } + $user = User::staticGet('nickname', $nickname); + if (is_null($user)) { + return false; + } else { + if (0 == strcmp(common_munge_password($password, $user->id), + $user->password)) { + return $user; + } else { + return false; + } + } +} + +// is the current user logged in? function common_logged_in() { - return (!is_null(common_current_user())); + return (!is_null(common_current_user())); } function common_have_session() { - return (0 != strcmp(session_id(), '')); + return (0 != strcmp(session_id(), '')); } function common_ensure_session() { - if (!common_have_session()) { - @session_start(); - } + if (!common_have_session()) { + @session_start(); + } } -# Three kinds of arguments: -# 1) a user object -# 2) a nickname -# 3) NULL to clear +// Three kinds of arguments: +// 1) a user object +// 2) a nickname +// 3) null to clear -# Initialize to false; set to NULL if none found +// Initialize to false; set to null if none found $_cur = false; @@ -572,92 +572,92 @@ function common_set_user($user) { global $_cur; - if (is_null($user) && common_have_session()) { - $_cur = NULL; - unset($_SESSION['userid']); - return true; - } else if (is_string($user)) { - $nickname = $user; - $user = User::staticGet('nickname', $nickname); - } else if (!($user instanceof User)) { - return false; - } - - if ($user) { - common_ensure_session(); - $_SESSION['userid'] = $user->id; + if (is_null($user) && common_have_session()) { + $_cur = null; + unset($_SESSION['userid']); + return true; + } else if (is_string($user)) { + $nickname = $user; + $user = User::staticGet('nickname', $nickname); + } else if (!($user instanceof User)) { + return false; + } + + if ($user) { + common_ensure_session(); + $_SESSION['userid'] = $user->id; $_cur = $user; - return $_cur; - } - return false; + return $_cur; + } + return false; } function common_set_cookie($key, $value, $expiration=0) { - $path = common_config('site', 'path'); - $server = common_config('site', 'server'); + $path = common_config('site', 'path'); + $server = common_config('site', 'server'); - if ($path && ($path != '/')) { - $cookiepath = '/' . $path . '/'; - } else { - $cookiepath = '/'; - } - return setcookie($key, - $value, - $expiration, - $cookiepath, - $server); + if ($path && ($path != '/')) { + $cookiepath = '/' . $path . '/'; + } else { + $cookiepath = '/'; + } + return setcookie($key, + $value, + $expiration, + $cookiepath, + $server); } define('REMEMBERME', 'rememberme'); -define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); # 30 days +define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days -function common_rememberme($user=NULL) { - if (!$user) { - $user = common_current_user(); - if (!$user) { - common_debug('No current user to remember', __FILE__); - return false; - } - } +function common_rememberme($user=null) { + if (!$user) { + $user = common_current_user(); + if (!$user) { + common_debug('No current user to remember', __FILE__); + return false; + } + } - $rm = new Remember_me(); + $rm = new Remember_me(); - $rm->code = common_good_rand(16); - $rm->user_id = $user->id; + $rm->code = common_good_rand(16); + $rm->user_id = $user->id; - # Wrap the insert in some good ol' fashioned transaction code + // Wrap the insert in some good ol' fashioned transaction code $rm->query('BEGIN'); - $result = $rm->insert(); + $result = $rm->insert(); - if (!$result) { - common_log_db_error($rm, 'INSERT', __FILE__); - common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); - return false; + if (!$result) { + common_log_db_error($rm, 'INSERT', __FILE__); + common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); + return false; } $rm->query('COMMIT'); - common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); + common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); $cookieval = $rm->user_id . ':' . $rm->code; - common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); + common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); - common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); + common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); - return true; + return true; } function common_remembered_user() { - $user = NULL; + $user = null; - $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : NULL; + $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null; - if (!$packed) { - return NULL; + if (!$packed) { + return null; } list($id, $code) = explode(':', $packed); @@ -665,7 +665,7 @@ function common_remembered_user() { if (!$id || !$code) { common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed); common_forgetme(); - return NULL; + return null; } $rm = Remember_me::staticGet($code); @@ -673,13 +673,13 @@ function common_remembered_user() { if (!$rm) { common_log(LOG_WARNING, 'No such remember code: ' . $code); common_forgetme(); - return NULL; + return null; } if ($rm->user_id != $id) { common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id); common_forgetme(); - return NULL; + return null; } $user = User::staticGet($rm->user_id); @@ -687,17 +687,17 @@ function common_remembered_user() { if (!$user) { common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id); common_forgetme(); - return NULL; + return null; } - # successful! + // successful! $result = $rm->delete(); if (!$result) { common_log_db_error($rm, 'DELETE', __FILE__); common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code); common_forgetme(); - return NULL; + return null; } common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code); @@ -705,21 +705,21 @@ function common_remembered_user() { common_set_user($user); common_real_login(false); - # We issue a new cookie, so they can log in - # automatically again after this session + // We issue a new cookie, so they can log in + // automatically again after this session common_rememberme($user); - return $user; + return $user; } -# must be called with a valid user! +// must be called with a valid user! function common_forgetme() { - common_set_cookie(REMEMBERME, '', 0); + common_set_cookie(REMEMBERME, '', 0); } -# who is the current user? +// who is the current user? function common_current_user() { global $_cur; @@ -734,99 +734,99 @@ function common_current_user() { } } - # that didn't work; try to remember; will init $_cur to NULL on failure + // that didn't work; try to remember; will init $_cur to null on failure $_cur = common_remembered_user(); if ($_cur) { common_debug("Got User " . $_cur->nickname); common_debug("Faking session on remembered user"); - # XXX: Is this necessary? + // XXX: Is this necessary? $_SESSION['userid'] = $_cur->id; } } - return $_cur; + return $_cur; } -# Logins that are 'remembered' aren't 'real' -- they're subject to -# cookie-stealing. So, we don't let them do certain things. New reg, -# OpenID, and password logins _are_ real. +// Logins that are 'remembered' aren't 'real' -- they're subject to +// cookie-stealing. So, we don't let them do certain things. New reg, +// OpenID, and password logins _are_ real. function common_real_login($real=true) { - common_ensure_session(); - $_SESSION['real_login'] = $real; + common_ensure_session(); + $_SESSION['real_login'] = $real; } function common_is_real_login() { - return common_logged_in() && $_SESSION['real_login']; + return common_logged_in() && $_SESSION['real_login']; } -# get canonical version of nickname for comparison +// get canonical version of nickname for comparison function common_canonical_nickname($nickname) { - # XXX: UTF-8 canonicalization (like combining chars) - return strtolower($nickname); + // XXX: UTF-8 canonicalization (like combining chars) + return strtolower($nickname); } -# get canonical version of email for comparison +// get canonical version of email for comparison function common_canonical_email($email) { - # XXX: canonicalize UTF-8 - # XXX: lcase the domain part - return $email; + // XXX: canonicalize UTF-8 + // XXX: lcase the domain part + return $email; } define('URL_REGEX', '^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))'); function common_render_content($text, $notice) { - $r = common_render_text($text); - $id = $notice->profile_id; - $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); - $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); - $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); - return $r; + $r = common_render_text($text); + $id = $notice->profile_id; + $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); + $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); + $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); + return $r; } function common_render_text($text) { - $r = htmlspecialchars($text); + $r = htmlspecialchars($text); - $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); - $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); - $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); - # XXX: machine tags - return $r; + $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); + $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); + $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); + // XXX: machine tags + return $r; } function common_render_uri_thingy($matches) { - $uri = $matches[0]; - $trailer = ''; - - # Some heuristics for extracting URIs from surrounding punctuation - # Strip from trailing text... - if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { - $uri = $matches[1]; - $trailer = $matches[2]; - } - - $pairs = array( - ']' => '[', # technically disallowed in URIs, but used in Java docs - ')' => '(', # far too frequent in Wikipedia and MSDN - ); - $final = substr($uri, -1, 1); - if (isset($pairs[$final])) { - $openers = substr_count($uri, $pairs[$final]); - $closers = substr_count($uri, $final); - if ($closers > $openers) { - // Assume the paren was opened outside the URI - $uri = substr($uri, 0, -1); - $trailer = $final . $trailer; - } - } - if ($longurl = common_longurl($uri)) { - $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); - $title = " title='$longurl'"; - } - else $title = ''; - - return '' . $uri . '' . $trailer; + $uri = $matches[0]; + $trailer = ''; + + // Some heuristics for extracting URIs from surrounding punctuation + // Strip from trailing text... + if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { + $uri = $matches[1]; + $trailer = $matches[2]; + } + + $pairs = array( + ']' => '[', // technically disallowed in URIs, but used in Java docs + ')' => '(', // far too frequent in Wikipedia and MSDN + ); + $final = substr($uri, -1, 1); + if (isset($pairs[$final])) { + $openers = substr_count($uri, $pairs[$final]); + $closers = substr_count($uri, $final); + if ($closers > $openers) { + // Assume the paren was opened outside the URI + $uri = substr($uri, 0, -1); + $trailer = $final . $trailer; + } + } + if ($longurl = common_longurl($uri)) { + $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); + $title = " title='$longurl'"; + } + else $title = ''; + + return '' . $uri . '' . $trailer; } function common_longurl($short_url) { @@ -836,10 +836,10 @@ function common_longurl($short_url) { } function common_longurl2($uri) { - $uri_e = urlencode($uri); - $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); - if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; - return stripslashes($longurl['long_url']); + $uri_e = urlencode($uri); + $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); + if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; + return stripslashes($longurl['long_url']); } function common_shorten_links($text) { @@ -847,465 +847,465 @@ function common_shorten_links($text) { static $cache = array(); if (isset($cache[$text])) return $cache[$text]; // \s = not a horizontal whitespace character (since PHP 5.2.4) - return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); + return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); } function common_shorten_link($url, $reverse = false) { - static $url_cache = array(); + static $url_cache = array(); if ($reverse) return isset($url_cache[$url]) ? $url_cache[$url] : $url; - $user = common_current_user(); - - $curlh = curl_init(); - curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait - curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); - curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); - - switch($user->urlshorteningservice) { - case 'ur1.ca': - $short_url_service = new LilUrl; - $short_url = $short_url_service->shorten($url); - break; - - case '2tu.us': - $short_url_service = new TightUrl; - $short_url = $short_url_service->shorten($url); - break; - - case 'ptiturl.com': - $short_url_service = new PtitUrl; - $short_url = $short_url_service->shorten($url); - break; - - case 'bit.ly': - curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); - $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; - break; - - case 'is.gd': - curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - case 'snipr.com': - curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - case 'metamark.net': - curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - case 'tinyurl.com': - curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); - $short_url = curl_exec($curlh); - break; - default: - $short_url = false; - } - - curl_close($curlh); - - if ($short_url) { + $user = common_current_user(); + + $curlh = curl_init(); + curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait + curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); + curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); + + switch($user->urlshorteningservice) { + case 'ur1.ca': + $short_url_service = new LilUrl; + $short_url = $short_url_service->shorten($url); + break; + + case '2tu.us': + $short_url_service = new TightUrl; + $short_url = $short_url_service->shorten($url); + break; + + case 'ptiturl.com': + $short_url_service = new PtitUrl; + $short_url = $short_url_service->shorten($url); + break; + + case 'bit.ly': + curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); + $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; + break; + + case 'is.gd': + curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + case 'snipr.com': + curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + case 'metamark.net': + curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + case 'tinyurl.com': + curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); + $short_url = curl_exec($curlh); + break; + default: + $short_url = false; + } + + curl_close($curlh); + + if ($short_url) { $url_cache[(string)$short_url] = $url; - return (string)$short_url; - } - return $url; + return (string)$short_url; + } + return $url; } function common_xml_safe_str($str) { - $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8'); + $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); + // Replace control, formatting, and surrogate characters with '*', ala Twitter + return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str); } function common_tag_link($tag) { - $canonical = common_canonical_tag($tag); - $url = common_local_url('tag', array('tag' => $canonical)); - return ''; + $canonical = common_canonical_tag($tag); + $url = common_local_url('tag', array('tag' => $canonical)); + return ''; } function common_canonical_tag($tag) { - return strtolower(str_replace(array('-', '_', '.'), '', $tag)); + return strtolower(str_replace(array('-', '_', '.'), '', $tag)); } function common_valid_profile_tag($str) { - return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); + return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); } function common_at_link($sender_id, $nickname) { - $sender = Profile::staticGet($sender_id); - $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); - if ($recipient) { - return ''.$nickname.''; - } else { - return $nickname; - } + $sender = Profile::staticGet($sender_id); + $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); + if ($recipient) { + return ''.$nickname.''; + } else { + return $nickname; + } } function common_at_hash_link($sender_id, $tag) { - $user = User::staticGet($sender_id); - if (!$user) { - return $tag; - } - $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); - if ($tagged) { - $url = common_local_url('subscriptions', - array('nickname' => $user->nickname, - 'tag' => $tag)); - return ''.$tag.''; - } else { - return $tag; - } -} - -function common_relative_profile($sender, $nickname, $dt=NULL) { - # Try to find profiles this profile is subscribed to that have this nickname - $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'); - if ($recipient->find(TRUE)) { - # XXX: should probably differentiate between profiles with - # the same name by date of most recent update - return $recipient; - } - # Try to find profiles that listen to this profile and that have this nickname - $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'); - if ($recipient->find(TRUE)) { - # XXX: should probably differentiate between profiles with - # the same name by date of most recent update - return $recipient; - } - # If this is a local user, try to find a local user with that nickname. - $sender = User::staticGet($sender->id); - if ($sender) { - $recipient_user = User::staticGet('nickname', $nickname); - if ($recipient_user) { - return $recipient_user->getProfile(); - } - } - # Otherwise, no links. @messages from local users to remote users, - # or from remote users to other remote users, are just - # outside our ability to make intelligent guesses about - return NULL; + $user = User::staticGet($sender_id); + if (!$user) { + return $tag; + } + $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); + if ($tagged) { + $url = common_local_url('subscriptions', + array('nickname' => $user->nickname, + 'tag' => $tag)); + return ''.$tag.''; + } else { + return $tag; + } +} + +function common_relative_profile($sender, $nickname, $dt=null) { + // Try to find profiles this profile is subscribed to that have this nickname + $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'); + if ($recipient->find(TRUE)) { + // XXX: should probably differentiate between profiles with + // the same name by date of most recent update + return $recipient; + } + // Try to find profiles that listen to this profile and that have this nickname + $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'); + if ($recipient->find(TRUE)) { + // XXX: should probably differentiate between profiles with + // the same name by date of most recent update + return $recipient; + } + // If this is a local user, try to find a local user with that nickname. + $sender = User::staticGet($sender->id); + if ($sender) { + $recipient_user = User::staticGet('nickname', $nickname); + if ($recipient_user) { + return $recipient_user->getProfile(); + } + } + // Otherwise, no links. @messages from local users to remote users, + // or from remote users to other remote users, are just + // outside our ability to make intelligent guesses about + return null; } // where should the avatar go for this user? -function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) { - global $config; +function common_avatar_filename($id, $extension, $size=null, $extra=null) { + global $config; - if ($size) { - return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; - } else { - return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; - } + if ($size) { + return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; + } else { + return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; + } } function common_avatar_path($filename) { - global $config; - return INSTALLDIR . '/avatar/' . $filename; + global $config; + return INSTALLDIR . '/avatar/' . $filename; } function common_avatar_url($filename) { - return common_path('avatar/'.$filename); + return common_path('avatar/'.$filename); } function common_avatar_display_url($avatar) { - $server = common_config('avatar', 'server'); - if ($server) { - return 'http://'.$server.'/'.$avatar->filename; - } else { - return $avatar->url; - } + $server = common_config('avatar', 'server'); + if ($server) { + return 'http://'.$server.'/'.$avatar->filename; + } else { + return $avatar->url; + } } function common_default_avatar($size) { - static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', - AVATAR_STREAM_SIZE => 'stream', - AVATAR_MINI_SIZE => 'mini'); - return theme_path('default-avatar-'.$sizenames[$size].'.png'); -} - -function common_local_url($action, $args=NULL, $fragment=NULL) { - $url = NULL; - if (common_config('site','fancy')) { - $url = common_fancy_url($action, $args); - } else { - $url = common_simple_url($action, $args); - } - if (!is_null($fragment)) { - $url .= '#'.$fragment; - } - return $url; -} - -function common_fancy_url($action, $args=NULL) { - switch (strtolower($action)) { - case 'public': - if ($args && isset($args['page'])) { - return common_path('?page=' . $args['page']); - } else { - return common_path(''); - } - case 'featured': - if ($args && isset($args['page'])) { - return common_path('featured?page=' . $args['page']); - } else { - return common_path('featured'); - } - case 'favorited': - if ($args && isset($args['page'])) { - return common_path('favorited?page=' . $args['page']); - } else { - return common_path('favorited'); - } - case 'publicrss': - return common_path('rss'); - case 'publicatom': - return common_path("api/statuses/public_timeline.atom"); - case 'publicxrds': - return common_path('xrds'); - case 'featuredrss': - return common_path('featuredrss'); - case 'favoritedrss': - return common_path('favoritedrss'); - case 'opensearch': - if ($args && $args['type']) { - return common_path('opensearch/'.$args['type']); - } else { - return common_path('opensearch/people'); - } - case 'doc': - return common_path('doc/'.$args['title']); + static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', + AVATAR_STREAM_SIZE => 'stream', + AVATAR_MINI_SIZE => 'mini'); + return theme_path('default-avatar-'.$sizenames[$size].'.png'); +} + +function common_local_url($action, $args=null, $fragment=null) { + $url = null; + if (common_config('site','fancy')) { + $url = common_fancy_url($action, $args); + } else { + $url = common_simple_url($action, $args); + } + if (!is_null($fragment)) { + $url .= '#'.$fragment; + } + return $url; +} + +function common_fancy_url($action, $args=null) { + switch (strtolower($action)) { + case 'public': + if ($args && isset($args['page'])) { + return common_path('?page=' . $args['page']); + } else { + return common_path(''); + } + case 'featured': + if ($args && isset($args['page'])) { + return common_path('featured?page=' . $args['page']); + } else { + return common_path('featured'); + } + case 'favorited': + if ($args && isset($args['page'])) { + return common_path('favorited?page=' . $args['page']); + } else { + return common_path('favorited'); + } + case 'publicrss': + return common_path('rss'); + case 'publicatom': + return common_path("api/statuses/public_timeline.atom"); + case 'publicxrds': + return common_path('xrds'); + case 'featuredrss': + return common_path('featuredrss'); + case 'favoritedrss': + return common_path('favoritedrss'); + case 'opensearch': + if ($args && $args['type']) { + return common_path('opensearch/'.$args['type']); + } else { + return common_path('opensearch/people'); + } + case 'doc': + return common_path('doc/'.$args['title']); case 'block': - case 'login': - case 'logout': - case 'subscribe': - case 'unsubscribe': - case 'invite': - return common_path('main/'.$action); - case 'tagother': - return common_path('main/tagother?id='.$args['id']); - case 'register': - if ($args && $args['code']) { - return common_path('main/register/'.$args['code']); - } else { - return common_path('main/register'); - } - case 'remotesubscribe': - if ($args && $args['nickname']) { - return common_path('main/remote?nickname=' . $args['nickname']); - } else { - return common_path('main/remote'); - } - case 'nudge': - return common_path($args['nickname'].'/nudge'); - case 'openidlogin': - return common_path('main/openid'); - case 'profilesettings': - return common_path('settings/profile'); - case 'emailsettings': - return common_path('settings/email'); - case 'openidsettings': - return common_path('settings/openid'); - case 'smssettings': - return common_path('settings/sms'); - case 'twittersettings': - return common_path('settings/twitter'); - case 'othersettings': - return common_path('settings/other'); + case 'login': + case 'logout': + case 'subscribe': + case 'unsubscribe': + case 'invite': + return common_path('main/'.$action); + case 'tagother': + return common_path('main/tagother?id='.$args['id']); + case 'register': + if ($args && $args['code']) { + return common_path('main/register/'.$args['code']); + } else { + return common_path('main/register'); + } + case 'remotesubscribe': + if ($args && $args['nickname']) { + return common_path('main/remote?nickname=' . $args['nickname']); + } else { + return common_path('main/remote'); + } + case 'nudge': + return common_path($args['nickname'].'/nudge'); + case 'openidlogin': + return common_path('main/openid'); + case 'profilesettings': + return common_path('settings/profile'); + case 'emailsettings': + return common_path('settings/email'); + case 'openidsettings': + return common_path('settings/openid'); + case 'smssettings': + return common_path('settings/sms'); + case 'twittersettings': + return common_path('settings/twitter'); + case 'othersettings': + return common_path('settings/other'); case 'deleteprofile': return common_path('settings/delete'); - case 'newnotice': - if ($args && $args['replyto']) { - return common_path('notice/new?replyto='.$args['replyto']); - } else { - return common_path('notice/new'); - } - case 'shownotice': - return common_path('notice/'.$args['notice']); - case 'deletenotice': - if ($args && $args['notice']) { - return common_path('notice/delete/'.$args['notice']); - } else { - return common_path('notice/delete'); - } - case 'microsummary': - case 'xrds': - case 'foaf': - return common_path($args['nickname'].'/'.$action); - case 'all': - case 'replies': - case 'inbox': - case 'outbox': - if ($args && isset($args['page'])) { - return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); - } else { - return common_path($args['nickname'].'/'.$action); - } - case 'subscriptions': - case 'subscribers': - $nickname = $args['nickname']; - unset($args['nickname']); - if (isset($args['tag'])) { - $tag = $args['tag']; - unset($args['tag']); - } - $params = http_build_query($args); - if ($params) { - return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); - } else { - return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); - } - case 'allrss': - return common_path($args['nickname'].'/all/rss'); - case 'repliesrss': - return common_path($args['nickname'].'/replies/rss'); - case 'userrss': + case 'newnotice': + if ($args && $args['replyto']) { + return common_path('notice/new?replyto='.$args['replyto']); + } else { + return common_path('notice/new'); + } + case 'shownotice': + return common_path('notice/'.$args['notice']); + case 'deletenotice': + if ($args && $args['notice']) { + return common_path('notice/delete/'.$args['notice']); + } else { + return common_path('notice/delete'); + } + case 'microsummary': + case 'xrds': + case 'foaf': + return common_path($args['nickname'].'/'.$action); + case 'all': + case 'replies': + case 'inbox': + case 'outbox': + if ($args && isset($args['page'])) { + return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); + } else { + return common_path($args['nickname'].'/'.$action); + } + case 'subscriptions': + case 'subscribers': + $nickname = $args['nickname']; + unset($args['nickname']); + if (isset($args['tag'])) { + $tag = $args['tag']; + unset($args['tag']); + } + $params = http_build_query($args); + if ($params) { + return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); + } else { + return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); + } + case 'allrss': + return common_path($args['nickname'].'/all/rss'); + case 'repliesrss': + return common_path($args['nickname'].'/replies/rss'); + case 'userrss': if (isset($args['limit'])) - return common_path($args['nickname'].'/rss?limit=' . $args['limit']); - return common_path($args['nickname'].'/rss'); - case 'showstream': - if ($args && isset($args['page'])) { - return common_path($args['nickname'].'?page=' . $args['page']); - } else { - return common_path($args['nickname']); - } - - case 'usertimeline': - return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); - case 'confirmaddress': - return common_path('main/confirmaddress/'.$args['code']); - case 'userbyid': - return common_path('user/'.$args['id']); - case 'recoverpassword': - $path = 'main/recoverpassword'; - if ($args['code']) { - $path .= '/' . $args['code']; - } - return common_path($path); - case 'imsettings': - return common_path('settings/im'); - case 'peoplesearch': - return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'noticesearch': - return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'noticesearchrss': - return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'avatarbynickname': - return common_path($args['nickname'].'/avatar/'.$args['size']); - case 'tag': - if (isset($args['tag']) && $args['tag']) { - $path = 'tag/' . $args['tag']; - unset($args['tag']); - } else { - $path = 'tags'; - } - return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); - case 'peopletag': - $path = 'peopletag/' . $args['tag']; - unset($args['tag']); - return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); - case 'tags': - return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'favor': - return common_path('main/favor'); - case 'disfavor': - return common_path('main/disfavor'); - case 'showfavorites': - if ($args && isset($args['page'])) { - return common_path($args['nickname'].'/favorites?page=' . $args['page']); - } else { - return common_path($args['nickname'].'/favorites'); - } - case 'favoritesrss': - return common_path($args['nickname'].'/favorites/rss'); - case 'showmessage': - return common_path('message/' . $args['message']); - case 'newmessage': - return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); - case 'api': - # XXX: do fancy URLs for all the API methods - switch (strtolower($args['apiaction'])) { - case 'statuses': - switch (strtolower($args['method'])) { - case 'user_timeline.rss': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); - case 'user_timeline.atom': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); - case 'user_timeline.json': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); - case 'user_timeline.xml': - return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); - default: return common_simple_url($action, $args); - } - default: return common_simple_url($action, $args); - } - case 'sup': - if ($args && isset($args['seconds'])) { - return common_path('main/sup?seconds='.$args['seconds']); - } else { - return common_path('main/sup'); - } - default: - return common_simple_url($action, $args); - } -} - -function common_simple_url($action, $args=NULL) { - global $config; - /* XXX: pretty URLs */ - $extra = ''; - if ($args) { - foreach ($args as $key => $value) { - $extra .= "&${key}=${value}"; - } - } - return common_path("index.php?action=${action}${extra}"); + return common_path($args['nickname'].'/rss?limit=' . $args['limit']); + return common_path($args['nickname'].'/rss'); + case 'showstream': + if ($args && isset($args['page'])) { + return common_path($args['nickname'].'?page=' . $args['page']); + } else { + return common_path($args['nickname']); + } + + case 'usertimeline': + return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); + case 'confirmaddress': + return common_path('main/confirmaddress/'.$args['code']); + case 'userbyid': + return common_path('user/'.$args['id']); + case 'recoverpassword': + $path = 'main/recoverpassword'; + if ($args['code']) { + $path .= '/' . $args['code']; + } + return common_path($path); + case 'imsettings': + return common_path('settings/im'); + case 'peoplesearch': + return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'noticesearch': + return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'noticesearchrss': + return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'avatarbynickname': + return common_path($args['nickname'].'/avatar/'.$args['size']); + case 'tag': + if (isset($args['tag']) && $args['tag']) { + $path = 'tag/' . $args['tag']; + unset($args['tag']); + } else { + $path = 'tags'; + } + return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); + case 'peopletag': + $path = 'peopletag/' . $args['tag']; + unset($args['tag']); + return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); + case 'tags': + return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'favor': + return common_path('main/favor'); + case 'disfavor': + return common_path('main/disfavor'); + case 'showfavorites': + if ($args && isset($args['page'])) { + return common_path($args['nickname'].'/favorites?page=' . $args['page']); + } else { + return common_path($args['nickname'].'/favorites'); + } + case 'favoritesrss': + return common_path($args['nickname'].'/favorites/rss'); + case 'showmessage': + return common_path('message/' . $args['message']); + case 'newmessage': + return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); + case 'api': + // XXX: do fancy URLs for all the API methods + switch (strtolower($args['apiaction'])) { + case 'statuses': + switch (strtolower($args['method'])) { + case 'user_timeline.rss': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); + case 'user_timeline.atom': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); + case 'user_timeline.json': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); + case 'user_timeline.xml': + return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); + default: return common_simple_url($action, $args); + } + default: return common_simple_url($action, $args); + } + case 'sup': + if ($args && isset($args['seconds'])) { + return common_path('main/sup?seconds='.$args['seconds']); + } else { + return common_path('main/sup'); + } + default: + return common_simple_url($action, $args); + } +} + +function common_simple_url($action, $args=null) { + global $config; + /* XXX: pretty URLs */ + $extra = ''; + if ($args) { + foreach ($args as $key => $value) { + $extra .= "&${key}=${value}"; + } + } + return common_path("index.php?action=${action}${extra}"); } function common_path($relative) { - global $config; - $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; - return "http://".$config['site']['server'].'/'.$pathpart.$relative; + global $config; + $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; + return "http://".$config['site']['server'].'/'.$pathpart.$relative; } function common_date_string($dt) { - // XXX: do some sexy date formatting - // return date(DATE_RFC822, $dt); - $t = strtotime($dt); - $now = time(); - $diff = $now - $t; - - if ($now < $t) { # that shouldn't happen! - return common_exact_date($dt); - } else if ($diff < 60) { - return _('a few seconds ago'); - } else if ($diff < 92) { - return _('about a minute ago'); - } else if ($diff < 3300) { - return sprintf(_('about %d minutes ago'), round($diff/60)); - } else if ($diff < 5400) { - return _('about an hour ago'); - } else if ($diff < 22 * 3600) { - return sprintf(_('about %d hours ago'), round($diff/3600)); - } else if ($diff < 37 * 3600) { - return _('about a day ago'); - } else if ($diff < 24 * 24 * 3600) { - return sprintf(_('about %d days ago'), round($diff/(24*3600))); - } else if ($diff < 46 * 24 * 3600) { - return _('about a month ago'); - } else if ($diff < 330 * 24 * 3600) { - return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); - } else if ($diff < 480 * 24 * 3600) { - return _('about a year ago'); - } else { - return common_exact_date($dt); - } + // XXX: do some sexy date formatting + // return date(DATE_RFC822, $dt); + $t = strtotime($dt); + $now = time(); + $diff = $now - $t; + + if ($now < $t) { // that shouldn't happen! + return common_exact_date($dt); + } else if ($diff < 60) { + return _('a few seconds ago'); + } else if ($diff < 92) { + return _('about a minute ago'); + } else if ($diff < 3300) { + return sprintf(_('about %d minutes ago'), round($diff/60)); + } else if ($diff < 5400) { + return _('about an hour ago'); + } else if ($diff < 22 * 3600) { + return sprintf(_('about %d hours ago'), round($diff/3600)); + } else if ($diff < 37 * 3600) { + return _('about a day ago'); + } else if ($diff < 24 * 24 * 3600) { + return sprintf(_('about %d days ago'), round($diff/(24*3600))); + } else if ($diff < 46 * 24 * 3600) { + return _('about a month ago'); + } else if ($diff < 330 * 24 * 3600) { + return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); + } else if ($diff < 480 * 24 * 3600) { + return _('about a year ago'); + } else { + return common_exact_date($dt); + } } function common_exact_date($dt) { @@ -1317,885 +1317,885 @@ function common_exact_date($dt) { $_siteTz = new DateTimeZone(common_timezone()); } - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, $_utc); - $d->setTimezone($_siteTz); - return $d->format(DATE_RFC850); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, $_utc); + $d->setTimezone($_siteTz); + return $d->format(DATE_RFC850); } function common_date_w3dtf($dt) { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format(DATE_W3C); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format(DATE_W3C); } function common_date_rfc2822($dt) { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format('r'); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format('r'); } function common_date_iso8601($dt) { - $dateStr = date('d F Y H:i:s', strtotime($dt)); - $d = new DateTime($dateStr, new DateTimeZone('UTC')); - $d->setTimezone(new DateTimeZone(common_timezone())); - return $d->format('c'); + $dateStr = date('d F Y H:i:s', strtotime($dt)); + $d = new DateTime($dateStr, new DateTimeZone('UTC')); + $d->setTimezone(new DateTimeZone(common_timezone())); + return $d->format('c'); } function common_sql_now() { - return strftime('%Y-%m-%d %H:%M:%S', time()); + return strftime('%Y-%m-%d %H:%M:%S', time()); } function common_redirect($url, $code=307) { - static $status = array(301 => "Moved Permanently", - 302 => "Found", - 303 => "See Other", - 307 => "Temporary Redirect"); - header("Status: ${code} $status[$code]"); - header("Location: $url"); - - common_start_xml('a', - '-//W3C//DTD XHTML 1.0 Strict//EN', - 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); - common_element('a', array('href' => $url), $url); - common_end_xml(); + static $status = array(301 => "Moved Permanently", + 302 => "Found", + 303 => "See Other", + 307 => "Temporary Redirect"); + header("Status: ${code} $status[$code]"); + header("Location: $url"); + + common_start_xml('a', + '-//W3C//DTD XHTML 1.0 Strict//EN', + 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); + common_element('a', array('href' => $url), $url); + common_end_xml(); exit; } function common_save_replies($notice) { - # Alternative reply format - $tname = false; - if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { - $tname = $match[1]; - } - # extract all @messages - $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); - - $names = array(); - - if ($cnt || $tname) { - # XXX: is there another way to make an array copy? - $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); - } - - $sender = Profile::staticGet($notice->profile_id); - - $replied = array(); - - # store replied only for first @ (what user/notice what the reply directed, - # we assume first @ is it) - - for ($i=0; $icreated); - if (!$recipient) { - continue; - } - if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self - $reply_for = $recipient; - $recipient_notice = $reply_for->getCurrentNotice(); - if ($recipient_notice) { - $orig = clone($notice); - $notice->reply_to = $recipient_notice->id; - $notice->update($orig); - } - } - # Don't save replies from blocked profile to local user + // Alternative reply format + $tname = false; + if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { + $tname = $match[1]; + } + // extract all @messages + $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); + + $names = array(); + + if ($cnt || $tname) { + // XXX: is there another way to make an array copy? + $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); + } + + $sender = Profile::staticGet($notice->profile_id); + + $replied = array(); + + // store replied only for first @ (what user/notice what the reply directed, + // we assume first @ is it) + + for ($i=0; $icreated); + if (!$recipient) { + continue; + } + if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self + $reply_for = $recipient; + $recipient_notice = $reply_for->getCurrentNotice(); + if ($recipient_notice) { + $orig = clone($notice); + $notice->reply_to = $recipient_notice->id; + $notice->update($orig); + } + } + // Don't save replies from blocked profile to local user $recipient_user = User::staticGet('id', $recipient->id); if ($recipient_user && $recipient_user->hasBlocked($sender)) { continue; } - $reply = new Reply(); - $reply->notice_id = $notice->id; - $reply->profile_id = $recipient->id; - $id = $reply->insert(); - if (!$id) { - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); - common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); - return; - } else { - $replied[$recipient->id] = 1; - } - } - - # Hash format replies, too - $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); - if ($cnt) { - foreach ($match[1] as $tag) { - $tagged = Profile_tag::getTagged($sender->id, $tag); - foreach ($tagged as $t) { - if (!$replied[$t->id]) { - # Don't save replies from blocked profile to local user + $reply = new Reply(); + $reply->notice_id = $notice->id; + $reply->profile_id = $recipient->id; + $id = $reply->insert(); + if (!$id) { + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); + common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); + return; + } else { + $replied[$recipient->id] = 1; + } + } + + // Hash format replies, too + $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); + if ($cnt) { + foreach ($match[1] as $tag) { + $tagged = Profile_tag::getTagged($sender->id, $tag); + foreach ($tagged as $t) { + if (!$replied[$t->id]) { + // Don't save replies from blocked profile to local user $t_user = User::staticGet('id', $t->id); if ($t_user && $t_user->hasBlocked($sender)) { continue; } - $reply = new Reply(); - $reply->notice_id = $notice->id; - $reply->profile_id = $t->id; - $id = $reply->insert(); - if (!$id) { - common_log_db_error($reply, 'INSERT', __FILE__); - return; - } - } - } - } - } + $reply = new Reply(); + $reply->notice_id = $notice->id; + $reply->profile_id = $t->id; + $id = $reply->insert(); + if (!$id) { + common_log_db_error($reply, 'INSERT', __FILE__); + return; + } + } + } + } + } } 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) { + // 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 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)) { + 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); + $result = common_twitter_broadcast($notice, $flink); - if (!$result) { - common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__); - } - } - } + 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); - } else { - return common_real_broadcast($notice, $remote); - } + if (common_config('queue', 'enabled')) { + // Do it later! + return common_enqueue_notice($notice); + } else { + return common_real_broadcast($notice, $remote); + } } 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 - ); - - $ch = curl_init($uri); + 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 + ); + + $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; - } + if ($errmsg) { + common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", + __FILE__); + $success = false; + } - curl_close($ch); + curl_close($ch); - if (!$data) { - common_debug("No data returned by Twitter's API trying to send update for $twitter_user", - __FILE__); - $success = false; - } + 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); + // 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; - } + if (!$status->id) { + common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user", + __FILE__); + $success = false; + } - return $success; + return $success; } -# Stick the notice on the queue +// Stick the notice on the queue function common_enqueue_notice($notice) { - foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { - $qi = new Queue_item(); - $qi->notice_id = $notice->id; - $qi->transport = $transport; - $qi->created = $notice->created; + foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { + $qi = new Queue_item(); + $qi->notice_id = $notice->id; + $qi->transport = $transport; + $qi->created = $notice->created; $result = $qi->insert(); - if (!$result) { - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); - return false; - } - common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); - } - return $result; + if (!$result) { + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); + return false; + } + common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); + } + return $result; } function common_dequeue_notice($notice) { - $qi = Queue_item::staticGet($notice->id); - if ($qi) { - $result = $qi->delete(); - if (!$result) { - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); - return false; - } - common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); - return $result; - } else { + $qi = Queue_item::staticGet($notice->id); + if ($qi) { + $result = $qi->delete(); + if (!$result) { + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); return false; } + common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); + return $result; + } else { + return false; + } } function common_real_broadcast($notice, $remote=false) { - $success = true; - if (!$remote) { - # Make sure we have the OMB stuff - require_once(INSTALLDIR.'/lib/omb.php'); - $success = omb_broadcast_remote_subscribers($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); - } - } - if ($success) { - require_once(INSTALLDIR.'/lib/jabber.php'); - $success = jabber_broadcast_notice($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); - } - } - if ($success) { - require_once(INSTALLDIR.'/lib/mail.php'); - $success = mail_broadcast_notice_sms($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); - } - } - if ($success) { - $success = jabber_public_notice($notice); - if (!$success) { - common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); - } - } - // XXX: broadcast notices to other IM - return $success; + $success = true; + if (!$remote) { + // Make sure we have the OMB stuff + require_once(INSTALLDIR.'/lib/omb.php'); + $success = omb_broadcast_remote_subscribers($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); + } + } + if ($success) { + require_once(INSTALLDIR.'/lib/jabber.php'); + $success = jabber_broadcast_notice($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); + } + } + if ($success) { + require_once(INSTALLDIR.'/lib/mail.php'); + $success = mail_broadcast_notice_sms($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); + } + } + if ($success) { + $success = jabber_public_notice($notice); + if (!$success) { + common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); + } + } + // XXX: broadcast notices to other IM + return $success; } function common_broadcast_profile($profile) { - // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ - require_once(INSTALLDIR.'/lib/omb.php'); - omb_broadcast_profile($profile); - // XXX: Other broadcasts...? - return true; + // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ + require_once(INSTALLDIR.'/lib/omb.php'); + omb_broadcast_profile($profile); + // XXX: Other broadcasts...? + return true; } function common_profile_url($nickname) { - return common_local_url('showstream', array('nickname' => $nickname)); + return common_local_url('showstream', array('nickname' => $nickname)); } -# Don't call if nobody's logged in +// Don't call if nobody's logged in -function common_notice_form($action=NULL, $content=NULL) { - $user = common_current_user(); - assert(!is_null($user)); - common_element_start('form', array('id' => 'status_form', - 'method' => 'post', - 'action' => common_local_url('newnotice'))); - common_element_start('p'); - common_element('label', array('for' => 'status_textarea', - 'id' => 'status_label'), - sprintf(_('What\'s up, %s?'), $user->nickname)); +function common_notice_form($action=null, $content=null) { + $user = common_current_user(); + assert(!is_null($user)); + common_element_start('form', array('id' => 'status_form', + 'method' => 'post', + 'action' => common_local_url('newnotice'))); + common_element_start('p'); + common_element('label', array('for' => 'status_textarea', + 'id' => 'status_label'), + sprintf(_('What\'s up, %s?'), $user->nickname)); common_element('span', array('id' => 'counter', 'class' => 'counter'), '140'); - common_element('textarea', array('id' => 'status_textarea', - 'cols' => 60, - 'rows' => 3, - 'name' => 'status_textarea'), - ($content) ? $content : ''); - common_hidden('token', common_session_token()); - if ($action) { - common_hidden('returnto', $action); - } - # set by JavaScript - common_hidden('inreplyto', 'false'); - common_element('input', array('id' => 'status_submit', - 'name' => 'status_submit', - 'type' => 'submit', - 'value' => _('Send'))); - common_element_end('p'); - common_element_end('form'); -} - -# Should make up a reasonable root URL + common_element('textarea', array('id' => 'status_textarea', + 'cols' => 60, + 'rows' => 3, + 'name' => 'status_textarea'), + ($content) ? $content : ''); + common_hidden('token', common_session_token()); + if ($action) { + common_hidden('returnto', $action); + } + // set by JavaScript + common_hidden('inreplyto', 'false'); + common_element('input', array('id' => 'status_submit', + 'name' => 'status_submit', + 'type' => 'submit', + 'value' => _('Send'))); + common_element_end('p'); + common_element_end('form'); +} + +// Should make up a reasonable root URL function common_root_url() { - return common_path(''); + return common_path(''); } -# returns $bytes bytes of random data as a hexadecimal string -# "good" here is a goal and not a guarantee +// returns $bytes bytes of random data as a hexadecimal string +// "good" here is a goal and not a guarantee function common_good_rand($bytes) { - # XXX: use random.org...? - if (file_exists('/dev/urandom')) { - return common_urandom($bytes); - } else { # FIXME: this is probably not good enough - return common_mtrand($bytes); - } + // XXX: use random.org...? + if (file_exists('/dev/urandom')) { + return common_urandom($bytes); + } else { // FIXME: this is probably not good enough + return common_mtrand($bytes); + } } function common_urandom($bytes) { - $h = fopen('/dev/urandom', 'rb'); - # should not block - $src = fread($h, $bytes); - fclose($h); - $enc = ''; - for ($i = 0; $i < $bytes; $i++) { - $enc .= sprintf("%02x", (ord($src[$i]))); - } - return $enc; + $h = fopen('/dev/urandom', 'rb'); + // should not block + $src = fread($h, $bytes); + fclose($h); + $enc = ''; + for ($i = 0; $i < $bytes; $i++) { + $enc .= sprintf("%02x", (ord($src[$i]))); + } + return $enc; } function common_mtrand($bytes) { - $enc = ''; - for ($i = 0; $i < $bytes; $i++) { - $enc .= sprintf("%02x", mt_rand(0, 255)); - } - return $enc; + $enc = ''; + for ($i = 0; $i < $bytes; $i++) { + $enc .= sprintf("%02x", mt_rand(0, 255)); + } + return $enc; } function common_set_returnto($url) { - common_ensure_session(); - $_SESSION['returnto'] = $url; + common_ensure_session(); + $_SESSION['returnto'] = $url; } function common_get_returnto() { - common_ensure_session(); - return $_SESSION['returnto']; + common_ensure_session(); + return $_SESSION['returnto']; } function common_timestamp() { - return date('YmdHis'); + return date('YmdHis'); } function common_ensure_syslog() { - static $initialized = false; - if (!$initialized) { - global $config; - openlog($config['syslog']['appname'], 0, LOG_USER); - $initialized = true; - } -} - -function common_log($priority, $msg, $filename=NULL) { - $logfile = common_config('site', 'logfile'); - if ($logfile) { - $log = fopen($logfile, "a"); - if ($log) { - static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', - 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); - $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; - fwrite($log, $output); - fclose($log); - } - } else { - common_ensure_syslog(); - syslog($priority, $msg); - } -} - -function common_debug($msg, $filename=NULL) { - if ($filename) { - common_log(LOG_DEBUG, basename($filename).' - '.$msg); - } else { - common_log(LOG_DEBUG, $msg); - } -} - -function common_log_db_error(&$object, $verb, $filename=NULL) { - $objstr = common_log_objstring($object); - $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); + static $initialized = false; + if (!$initialized) { + global $config; + openlog($config['syslog']['appname'], 0, LOG_USER); + $initialized = true; + } +} + +function common_log($priority, $msg, $filename=null) { + $logfile = common_config('site', 'logfile'); + if ($logfile) { + $log = fopen($logfile, "a"); + if ($log) { + static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', + 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); + $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; + fwrite($log, $output); + fclose($log); + } + } else { + common_ensure_syslog(); + syslog($priority, $msg); + } +} + +function common_debug($msg, $filename=null) { + if ($filename) { + common_log(LOG_DEBUG, basename($filename).' - '.$msg); + } else { + common_log(LOG_DEBUG, $msg); + } +} + +function common_log_db_error(&$object, $verb, $filename=null) { + $objstr = common_log_objstring($object); + $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); } function common_log_objstring(&$object) { - if (is_null($object)) { - return "NULL"; - } - $arr = $object->toArray(); - $fields = array(); - foreach ($arr as $k => $v) { - $fields[] = "$k='$v'"; - } - $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; - return $objstring; + if (is_null($object)) { + return "null"; + } + $arr = $object->toArray(); + $fields = array(); + foreach ($arr as $k => $v) { + $fields[] = "$k='$v'"; + } + $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; + return $objstring; } function common_valid_http_url($url) { - return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); + return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); } function common_valid_tag($tag) { - if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { - return (Validate::email($matches[1]) || - preg_match('/^([\w-\.]+)$/', $matches[1])); - } - return false; + if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { + return (Validate::email($matches[1]) || + preg_match('/^([\w-\.]+)$/', $matches[1])); + } + return false; } -# Does a little before-after block for next/prev page +// Does a little before-after block for next/prev page -function common_pagination($have_before, $have_after, $page, $action, $args=NULL) { +function common_pagination($have_before, $have_after, $page, $action, $args=null) { - if ($have_before || $have_after) { - common_element_start('div', array('id' => 'pagination')); - common_element_start('ul', array('id' => 'nav_pagination')); - } + if ($have_before || $have_after) { + common_element_start('div', array('id' => 'pagination')); + common_element_start('ul', array('id' => 'nav_pagination')); + } - if ($have_before) { - $pargs = array('page' => $page-1); - $newargs = ($args) ? array_merge($args,$pargs) : $pargs; + if ($have_before) { + $pargs = array('page' => $page-1); + $newargs = ($args) ? array_merge($args,$pargs) : $pargs; - common_element_start('li', 'before'); - common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), - _('« After')); - common_element_end('li'); - } + common_element_start('li', 'before'); + common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), + _('« After')); + common_element_end('li'); + } - if ($have_after) { - $pargs = array('page' => $page+1); - $newargs = ($args) ? array_merge($args,$pargs) : $pargs; - common_element_start('li', 'after'); - common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), - _('Before »')); - common_element_end('li'); - } + if ($have_after) { + $pargs = array('page' => $page+1); + $newargs = ($args) ? array_merge($args,$pargs) : $pargs; + common_element_start('li', 'after'); + common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), + _('Before »')); + common_element_end('li'); + } - if ($have_before || $have_after) { - common_element_end('ul'); - common_element_end('div'); - } + if ($have_before || $have_after) { + common_element_end('ul'); + common_element_end('div'); + } } /* Following functions are copied from MediaWiki GlobalFunctions.php * and written by Evan Prodromou. */ function common_accept_to_prefs($accept, $def = '*/*') { - # No arg means accept anything (per HTTP spec) - if(!$accept) { - return array($def => 1); - } + // No arg means accept anything (per HTTP spec) + if(!$accept) { + return array($def => 1); + } - $prefs = array(); + $prefs = array(); - $parts = explode(',', $accept); + $parts = explode(',', $accept); - foreach($parts as $part) { - # FIXME: doesn't deal with params like 'text/html; level=1' - @list($value, $qpart) = explode(';', $part); - $match = array(); - if(!isset($qpart)) { - $prefs[$value] = 1; - } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { - $prefs[$value] = $match[1]; - } - } + foreach($parts as $part) { + // FIXME: doesn't deal with params like 'text/html; level=1' + @list($value, $qpart) = explode(';', $part); + $match = array(); + if(!isset($qpart)) { + $prefs[$value] = 1; + } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { + $prefs[$value] = $match[1]; + } + } - return $prefs; + return $prefs; } function common_mime_type_match($type, $avail) { - if(array_key_exists($type, $avail)) { - return $type; - } else { - $parts = explode('/', $type); - if(array_key_exists($parts[0] . '/*', $avail)) { - return $parts[0] . '/*'; - } elseif(array_key_exists('*/*', $avail)) { - return '*/*'; - } else { - return NULL; - } - } + if(array_key_exists($type, $avail)) { + return $type; + } else { + $parts = explode('/', $type); + if(array_key_exists($parts[0] . '/*', $avail)) { + return $parts[0] . '/*'; + } elseif(array_key_exists('*/*', $avail)) { + return '*/*'; + } else { + return null; + } + } } function common_negotiate_type($cprefs, $sprefs) { - $combine = array(); - - foreach(array_keys($sprefs) as $type) { - $parts = explode('/', $type); - if($parts[1] != '*') { - $ckey = common_mime_type_match($type, $cprefs); - if($ckey) { - $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; - } - } - } - - foreach(array_keys($cprefs) as $type) { - $parts = explode('/', $type); - if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { - $skey = common_mime_type_match($type, $sprefs); - if($skey) { - $combine[$type] = $sprefs[$skey] * $cprefs[$type]; - } - } - } - - $bestq = 0; - $besttype = "text/html"; - - foreach(array_keys($combine) as $type) { - if($combine[$type] > $bestq) { - $besttype = $type; - $bestq = $combine[$type]; - } - } - - return $besttype; + $combine = array(); + + foreach(array_keys($sprefs) as $type) { + $parts = explode('/', $type); + if($parts[1] != '*') { + $ckey = common_mime_type_match($type, $cprefs); + if($ckey) { + $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; + } + } + } + + foreach(array_keys($cprefs) as $type) { + $parts = explode('/', $type); + if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { + $skey = common_mime_type_match($type, $sprefs); + if($skey) { + $combine[$type] = $sprefs[$skey] * $cprefs[$type]; + } + } + } + + $bestq = 0; + $besttype = "text/html"; + + foreach(array_keys($combine) as $type) { + if($combine[$type] > $bestq) { + $besttype = $type; + $bestq = $combine[$type]; + } + } + + return $besttype; } function common_config($main, $sub) { - global $config; - return isset($config[$main][$sub]) ? $config[$main][$sub] : false; + global $config; + return isset($config[$main][$sub]) ? $config[$main][$sub] : false; } function common_copy_args($from) { - $to = array(); - $strip = get_magic_quotes_gpc(); - foreach ($from as $k => $v) { - $to[$k] = ($strip) ? stripslashes($v) : $v; - } - return $to; + $to = array(); + $strip = get_magic_quotes_gpc(); + foreach ($from as $k => $v) { + $to[$k] = ($strip) ? stripslashes($v) : $v; + } + return $to; } // Neutralise the evil effects of magic_quotes_gpc in the current request. // This is used before handing a request off to OAuthRequest::from_request. function common_remove_magic_from_request() { - if(get_magic_quotes_gpc()) { - $_POST=array_map('stripslashes',$_POST); - $_GET=array_map('stripslashes',$_GET); - } + if(get_magic_quotes_gpc()) { + $_POST=array_map('stripslashes',$_POST); + $_GET=array_map('stripslashes',$_GET); + } } function common_user_uri(&$user) { - return common_local_url('userbyid', array('id' => $user->id)); + return common_local_url('userbyid', array('id' => $user->id)); } function common_notice_uri(&$notice) { - return common_local_url('shownotice', - array('notice' => $notice->id)); + return common_local_url('shownotice', + array('notice' => $notice->id)); } -# 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits +// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits function common_confirmation_code($bits) { - # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits - static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; - $chars = ceil($bits/5); - $code = ''; - for ($i = 0; $i < $chars; $i++) { - # XXX: convert to string and back - $num = hexdec(common_good_rand(1)); - # XXX: randomness is too precious to throw away almost - # 40% of the bits we get! - $code .= $codechars[$num%32]; - } - return $code; -} - -# convert markup to HTML + // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits + static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; + $chars = ceil($bits/5); + $code = ''; + for ($i = 0; $i < $chars; $i++) { + // XXX: convert to string and back + $num = hexdec(common_good_rand(1)); + // XXX: randomness is too precious to throw away almost + // 40% of the bits we get! + $code .= $codechars[$num%32]; + } + return $code; +} + +// convert markup to HTML function common_markup_to_html($c) { - $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); - $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); - $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); - return Markdown($c); + $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); + $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); + $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); + return Markdown($c); } function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) { - $avatar = $profile->getAvatar($size); - if ($avatar) { - return common_avatar_display_url($avatar); - } else { - return common_default_avatar($size); - } + $avatar = $profile->getAvatar($size); + if ($avatar) { + return common_avatar_display_url($avatar); + } else { + return common_default_avatar($size); + } } function common_profile_uri($profile) { - if (!$profile) { - return NULL; - } - $user = User::staticGet($profile->id); - if ($user) { - return $user->uri; - } - - $remote = Remote_profile::staticGet($profile->id); - if ($remote) { - return $remote->uri; - } - # XXX: this is a very bad profile! - return NULL; + if (!$profile) { + return null; + } + $user = User::staticGet($profile->id); + if ($user) { + return $user->uri; + } + + $remote = Remote_profile::staticGet($profile->id); + if ($remote) { + return $remote->uri; + } + // XXX: this is a very bad profile! + return null; } function common_canonical_sms($sms) { - # strip non-digits - preg_replace('/\D/', '', $sms); - return $sms; + // strip non-digits + preg_replace('/\D/', '', $sms); + return $sms; } function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) { switch ($errno) { case E_USER_ERROR: - common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); - exit(1); - break; + common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); + exit(1); + break; - case E_USER_WARNING: - common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); - break; + case E_USER_WARNING: + common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); + break; case E_USER_NOTICE: - common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); - break; + common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); + break; } - # FIXME: show error page if we're on the Web + // FIXME: show error page if we're on the Web /* Don't execute PHP internal error handler */ return true; } function common_session_token() { - common_ensure_session(); - if (!array_key_exists('token', $_SESSION)) { - $_SESSION['token'] = common_good_rand(64); - } - return $_SESSION['token']; + common_ensure_session(); + if (!array_key_exists('token', $_SESSION)) { + $_SESSION['token'] = common_good_rand(64); + } + return $_SESSION['token']; } function common_disfavor_form($notice) { - common_element_start('form', array('id' => 'disfavor-' . $notice->id, - 'method' => 'post', - 'class' => 'disfavor', - 'action' => common_local_url('disfavor'))); - - common_element('input', array('type' => 'hidden', - 'name' => 'token-'. $notice->id, - 'id' => 'token-'. $notice->id, - 'class' => 'token', - 'value' => common_session_token())); - - common_element('input', array('type' => 'hidden', - 'name' => 'notice', - 'id' => 'notice-n'. $notice->id, - 'class' => 'notice', - 'value' => $notice->id)); - - common_element('input', array('type' => 'submit', - 'id' => 'disfavor-submit-' . $notice->id, - 'name' => 'disfavor-submit-' . $notice->id, - 'class' => 'disfavor', - 'value' => 'Disfavor favorite', - 'title' => 'Remove this message from favorites')); - common_element_end('form'); + common_element_start('form', array('id' => 'disfavor-' . $notice->id, + 'method' => 'post', + 'class' => 'disfavor', + 'action' => common_local_url('disfavor'))); + + common_element('input', array('type' => 'hidden', + 'name' => 'token-'. $notice->id, + 'id' => 'token-'. $notice->id, + 'class' => 'token', + 'value' => common_session_token())); + + common_element('input', array('type' => 'hidden', + 'name' => 'notice', + 'id' => 'notice-n'. $notice->id, + 'class' => 'notice', + 'value' => $notice->id)); + + common_element('input', array('type' => 'submit', + 'id' => 'disfavor-submit-' . $notice->id, + 'name' => 'disfavor-submit-' . $notice->id, + 'class' => 'disfavor', + 'value' => 'Disfavor favorite', + 'title' => 'Remove this message from favorites')); + common_element_end('form'); } function common_favor_form($notice) { - common_element_start('form', array('id' => 'favor-' . $notice->id, - 'method' => 'post', - 'class' => 'favor', - 'action' => common_local_url('favor'))); - - common_element('input', array('type' => 'hidden', - 'name' => 'token-'. $notice->id, - 'id' => 'token-'. $notice->id, - 'class' => 'token', - 'value' => common_session_token())); - - common_element('input', array('type' => 'hidden', - 'name' => 'notice', - 'id' => 'notice-n'. $notice->id, - 'class' => 'notice', - 'value' => $notice->id)); - - common_element('input', array('type' => 'submit', - 'id' => 'favor-submit-' . $notice->id, - 'name' => 'favor-submit-' . $notice->id, - 'class' => 'favor', - 'value' => 'Add to favorites', - 'title' => 'Add this message to favorites')); - common_element_end('form'); + common_element_start('form', array('id' => 'favor-' . $notice->id, + 'method' => 'post', + 'class' => 'favor', + 'action' => common_local_url('favor'))); + + common_element('input', array('type' => 'hidden', + 'name' => 'token-'. $notice->id, + 'id' => 'token-'. $notice->id, + 'class' => 'token', + 'value' => common_session_token())); + + common_element('input', array('type' => 'hidden', + 'name' => 'notice', + 'id' => 'notice-n'. $notice->id, + 'class' => 'notice', + 'value' => $notice->id)); + + common_element('input', array('type' => 'submit', + 'id' => 'favor-submit-' . $notice->id, + 'name' => 'favor-submit-' . $notice->id, + 'class' => 'favor', + 'value' => 'Add to favorites', + 'title' => 'Add this message to favorites')); + common_element_end('form'); } function common_nudge_form($profile) { - common_element_start('form', array('id' => 'nudge', 'method' => 'post', - 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); - common_hidden('token', common_session_token()); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Send a nudge'))); - common_element_end('form'); + common_element_start('form', array('id' => 'nudge', 'method' => 'post', + 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); + common_hidden('token', common_session_token()); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Send a nudge'))); + common_element_end('form'); } function common_nudge_response() { - common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); + common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); } function common_subscribe_form($profile) { - common_element_start('form', array('id' => 'subscribe-' . $profile->id, - 'method' => 'post', - 'class' => 'subscribe', - 'action' => common_local_url('subscribe'))); - common_hidden('token', common_session_token()); - common_element('input', array('id' => 'subscribeto-' . $profile->id, - 'name' => 'subscribeto', - 'type' => 'hidden', - 'value' => $profile->id)); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Subscribe'))); - common_element_end('form'); + common_element_start('form', array('id' => 'subscribe-' . $profile->id, + 'method' => 'post', + 'class' => 'subscribe', + 'action' => common_local_url('subscribe'))); + common_hidden('token', common_session_token()); + common_element('input', array('id' => 'subscribeto-' . $profile->id, + 'name' => 'subscribeto', + 'type' => 'hidden', + 'value' => $profile->id)); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Subscribe'))); + common_element_end('form'); } function common_unsubscribe_form($profile) { - common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, - 'method' => 'post', - 'class' => 'unsubscribe', - 'action' => common_local_url('unsubscribe'))); - common_hidden('token', common_session_token()); - common_element('input', array('id' => 'unsubscribeto-' . $profile->id, - 'name' => 'unsubscribeto', - 'type' => 'hidden', - 'value' => $profile->id)); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Unsubscribe'))); - common_element_end('form'); + common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, + 'method' => 'post', + 'class' => 'unsubscribe', + 'action' => common_local_url('unsubscribe'))); + common_hidden('token', common_session_token()); + common_element('input', array('id' => 'unsubscribeto-' . $profile->id, + 'name' => 'unsubscribeto', + 'type' => 'hidden', + 'value' => $profile->id)); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Unsubscribe'))); + common_element_end('form'); } // XXX: Refactor this code function common_profile_new_message_nudge ($cur, $profile) { - $user = User::staticGet('id', $profile->id); + $user = User::staticGet('id', $profile->id); - if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { + if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { common_element_start('li', array('id' => 'profile_send_a_new_message')); - common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), - _('Send a message')); + common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), + _('Send a message')); common_element_end('li'); - if ($user->email && $user->emailnotifynudge) { + if ($user->email && $user->emailnotifynudge) { common_element_start('li', array('id' => 'profile_nudge')); common_nudge_form($user); common_element_end('li'); } - } + } } function common_cache_key($extra) { - return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; + return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; } function common_keyize($str) { - $str = strtolower($str); - $str = preg_replace('/\s/', '_', $str); - return $str; + $str = strtolower($str); + $str = preg_replace('/\s/', '_', $str); + return $str; } function common_message_form($content, $user, $to) { - common_element_start('form', array('id' => 'message_form', - 'method' => 'post', - 'action' => common_local_url('newmessage'))); + common_element_start('form', array('id' => 'message_form', + 'method' => 'post', + 'action' => common_local_url('newmessage'))); - $mutual_users = $user->mutuallySubscribedUsers(); + $mutual_users = $user->mutuallySubscribedUsers(); - $mutual = array(); + $mutual = array(); - while ($mutual_users->fetch()) { - if ($mutual_users->id != $user->id) { - $mutual[$mutual_users->id] = $mutual_users->nickname; - } - } + while ($mutual_users->fetch()) { + if ($mutual_users->id != $user->id) { + $mutual[$mutual_users->id] = $mutual_users->nickname; + } + } - $mutual_users->free(); - unset($mutual_users); + $mutual_users->free(); + unset($mutual_users); - common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id); + common_dropdown('to', _('To'), $mutual, null, FALSE, $to->id); - common_element_start('p'); + common_element_start('p'); - common_element('textarea', array('id' => 'message_content', - 'cols' => 60, - 'rows' => 3, - 'name' => 'content'), - ($content) ? $content : ''); + common_element('textarea', array('id' => 'message_content', + 'cols' => 60, + 'rows' => 3, + 'name' => 'content'), + ($content) ? $content : ''); - common_element('input', array('id' => 'message_send', - 'name' => 'message_send', - 'type' => 'submit', - 'value' => _('Send'))); + common_element('input', array('id' => 'message_send', + 'name' => 'message_send', + 'type' => 'submit', + 'value' => _('Send'))); - common_hidden('token', common_session_token()); + common_hidden('token', common_session_token()); - common_element_end('p'); - common_element_end('form'); + common_element_end('p'); + common_element_end('form'); } function common_memcache() { - static $cache = NULL; - if (!common_config('memcached', 'enabled')) { - return NULL; - } else { - if (!$cache) { - $cache = new Memcache(); - $servers = common_config('memcached', 'server'); - if (is_array($servers)) { - foreach($servers as $server) { - $cache->addServer($server); - } - } else { - $cache->addServer($servers); - } - } - return $cache; - } + static $cache = null; + if (!common_config('memcached', 'enabled')) { + return null; + } else { + if (!$cache) { + $cache = new Memcache(); + $servers = common_config('memcached', 'server'); + if (is_array($servers)) { + foreach($servers as $server) { + $cache->addServer($server); + } + } else { + $cache->addServer($servers); + } + } + return $cache; + } } function common_compatible_license($from, $to) { - # XXX: better compatibility check needed here! - return ($from == $to); + // XXX: better compatibility check needed here! + return ($from == $to); } /* These are almost identical, so we use a helper function */ -function common_block_form($profile, $args=NULL) { +function common_block_form($profile, $args=null) { common_blocking_form('block', _('Block'), $profile, $args); } -function common_unblock_form($profile, $args=NULL) { +function common_unblock_form($profile, $args=null) { common_blocking_form('unblock', _('Unblock'), $profile, $args); } -function common_blocking_form($type, $label, $profile, $args=NULL) { +function common_blocking_form($type, $label, $profile, $args=null) { common_element_start('form', array('id' => $type . '-' . $profile->id, 'method' => 'post', 'class' => $type, @@ -2217,4 +2217,3 @@ function common_blocking_form($type, $label, $profile, $args=NULL) { common_element_end('form'); return; } - -- cgit v1.2.3-54-g00ecf From 01a548a9fb078476be5f54b54cfcba4035faea5b Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sat, 20 Dec 2008 19:39:55 -0500 Subject: some modifications to assuage phpcs darcs-hash:20081221003955-84dde-d6e8067a579f70dcb707f4525e588920a2375f5c.gz --- _darcs/inventory | 4 +- ...dde-d6e8067a579f70dcb707f4525e588920a2375f5c.gz | Bin 0 -> 1601 bytes _darcs/pristine/lib/action.php | 255 +- _darcs/tentative_pristine | 3506 ++------------------ lib/action.php | 255 +- 5 files changed, 464 insertions(+), 3556 deletions(-) create mode 100644 _darcs/patches/20081221003955-84dde-d6e8067a579f70dcb707f4525e588920a2375f5c.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 83b5a479f..0328b73d1 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -23,4 +23,6 @@ Evan Prodromou **20081212171135] [first step of phpcs-cleanup of index.php Evan Prodromou **20081221002332] [reformatting for phpcs in lib/util.php -Evan Prodromou **20081221003016] \ No newline at end of file +Evan Prodromou **20081221003016] +[some modifications to assuage phpcs +Evan Prodromou **20081221003955] \ No newline at end of file diff --git a/_darcs/patches/20081221003955-84dde-d6e8067a579f70dcb707f4525e588920a2375f5c.gz b/_darcs/patches/20081221003955-84dde-d6e8067a579f70dcb707f4525e588920a2375f5c.gz new file mode 100644 index 000000000..c3d9f2070 Binary files /dev/null and b/_darcs/patches/20081221003955-84dde-d6e8067a579f70dcb707f4525e588920a2375f5c.gz differ diff --git a/_darcs/pristine/lib/action.php b/_darcs/pristine/lib/action.php index 7a2461bb5..486b40387 100644 --- a/_darcs/pristine/lib/action.php +++ b/_darcs/pristine/lib/action.php @@ -1,5 +1,5 @@ . */ -if (!defined('LACONICA')) { exit(1); } - -class Action { // lawsuit - - var $args; - - function Action() { - } - - # For initializing members of the class - - function prepare($argarray) { - $this->args =& common_copy_args($argarray); - return true; - } - - # For comparison with If-Last-Modified - # If not applicable, return NULL - - function last_modified() { - return NULL; - } - - function etag() { - return NULL; - } - - function is_readonly() { - return false; - } - - function arg($key, $def=NULL) { - if (array_key_exists($key, $this->args)) { - return $this->args[$key]; - } else { - return $def; - } - } - - function trimmed($key, $def=NULL) { - $arg = $this->arg($key, $def); - return (is_string($arg)) ? trim($arg) : $arg; - } - - # Note: argarray ignored, since it's now passed in in prepare() - - function handle($argarray=NULL) { - - $lm = $this->last_modified(); - $etag = $this->etag(); - - if ($etag) { - header('ETag: ' . $etag); - } - - 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 ($lm <= $ims) { - if (!$etag || $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { - header('HTTP/1.1 304 Not Modified'); - # Better way to do this? - exit(0); - } - } - } - } - } - - function _has_etag($etag, $if_none_match) { - return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); - } - - function boolean($key, $def=false) { - $arg = strtolower($this->trimmed($key)); - - if (is_null($arg)) { - return $def; - } else if (in_array($arg, array('true', 'yes', '1'))) { - return true; - } else if (in_array($arg, array('false', 'no', '0'))) { - return false; - } else { - return $def; - } - } - - function server_error($msg, $code=500) { - $action = $this->trimmed('action'); - common_debug("Server error '$code' on '$action': $msg", __FILE__); - common_server_error($msg, $code); - } - - function client_error($msg, $code=400) { - $action = $this->trimmed('action'); - common_debug("User error '$code' on '$action': $msg", __FILE__); - common_user_error($msg, $code); - } - - function self_url() { - $action = $this->trimmed('action'); - $args = $this->args; - unset($args['action']); - foreach (array_keys($_COOKIE) as $cookie) { - unset($args[$cookie]); - } - return common_local_url($action, $args); - } - - function nav_menu($menu) { +if (!defined('LACONICA')) { + exit(1); +} + +class Action // lawsuit +{ + + var $args; + + function Action() + { + } + + // For initializing members of the class + + function prepare($argarray) + { + $this->args =& common_copy_args($argarray); + return true; + } + + // For comparison with If-Last-Modified + // If not applicable, return null + + function last_modified() + { + return null; + } + + function etag() + { + return null; + } + + function is_readonly() + { + return false; + } + + function arg($key, $def=null) + { + if (array_key_exists($key, $this->args)) { + return $this->args[$key]; + } else { + return $def; + } + } + + function trimmed($key, $def=null) + { + $arg = $this->arg($key, $def); + return (is_string($arg)) ? trim($arg) : $arg; + } + + // Note: argarray ignored, since it's now passed in in prepare() + + function handle($argarray=null) + { + + $lm = $this->last_modified(); + $etag = $this->etag(); + + if ($etag) { + header('ETag: ' . $etag); + } + + 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 ($lm <= $ims) { + if (!$etag || + $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { + header('HTTP/1.1 304 Not Modified'); + // Better way to do this? + exit(0); + } + } + } + } + } + + function _has_etag($etag, $if_none_match) + { + return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); + } + + function boolean($key, $def=false) + { + $arg = strtolower($this->trimmed($key)); + + if (is_null($arg)) { + return $def; + } else if (in_array($arg, array('true', 'yes', '1'))) { + return true; + } else if (in_array($arg, array('false', 'no', '0'))) { + return false; + } else { + return $def; + } + } + + function server_error($msg, $code=500) + { + $action = $this->trimmed('action'); + common_debug("Server error '$code' on '$action': $msg", __FILE__); + common_server_error($msg, $code); + } + + function client_error($msg, $code=400) + { + $action = $this->trimmed('action'); + common_debug("User error '$code' on '$action': $msg", __FILE__); + common_user_error($msg, $code); + } + + function self_url() + { + $action = $this->trimmed('action'); + $args = $this->args; + unset($args['action']); + foreach (array_keys($_COOKIE) as $cookie) { + unset($args[$cookie]); + } + return common_local_url($action, $args); + } + + function nav_menu($menu) + { $action = $this->trimmed('action'); common_element_start('ul', array('id' => 'nav_views')); foreach ($menu as $menuaction => $menudesc) { - common_menu_item(common_local_url($menuaction, isset($menudesc[2]) ? $menudesc[2] : NULL), - $menudesc[0], - $menudesc[1], - $action == $menuaction); + common_menu_item(common_local_url($menuaction, + isset($menudesc[2]) ? $menudesc[2] : null), + $menudesc[0], + $menudesc[1], + $action == $menuaction); } common_element_end('ul'); - } + } } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 487d2bcdc..529be5f2c 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,3368 +1,236 @@ -hunk ./lib/util.php 22 --# Show a server error -+// Show a server error -hunk ./lib/util.php 25 -- static $status = array(500 => 'Internal Server Error', -- 501 => 'Not Implemented', -- 502 => 'Bad Gateway', -- 503 => 'Service Unavailable', -- 504 => 'Gateway Timeout', -- 505 => 'HTTP Version Not Supported'); -+ static $status = array(500 => 'Internal Server Error', -+ 501 => 'Not Implemented', -+ 502 => 'Bad Gateway', -+ 503 => 'Service Unavailable', -+ 504 => 'Gateway Timeout', -+ 505 => 'HTTP Version Not Supported'); -hunk ./lib/util.php 32 -- if (!array_key_exists($code, $status)) { -- $code = 500; -- } -+ if (!array_key_exists($code, $status)) { -+ $code = 500; -+ } -hunk ./lib/util.php 36 -- $status_string = $status[$code]; -+ $status_string = $status[$code]; -hunk ./lib/util.php 38 -- header('HTTP/1.1 '.$code.' '.$status_string); -- header('Content-type: text/plain'); -+ header('HTTP/1.1 '.$code.' '.$status_string); -+ header('Content-type: text/plain'); -hunk ./lib/util.php 41 -- print $msg; -- print "\n"; -- exit(); -+ print $msg; -+ print "\n"; -+ exit(); -hunk ./lib/util.php 46 --# Show a user error -+// Show a user error -hunk ./lib/util.php 48 -- static $status = array(400 => 'Bad Request', -- 401 => 'Unauthorized', -- 402 => 'Payment Required', -- 403 => 'Forbidden', -- 404 => 'Not Found', -- 405 => 'Method Not Allowed', -- 406 => 'Not Acceptable', -- 407 => 'Proxy Authentication Required', -- 408 => 'Request Timeout', -- 409 => 'Conflict', -- 410 => 'Gone', -- 411 => 'Length Required', -- 412 => 'Precondition Failed', -- 413 => 'Request Entity Too Large', -- 414 => 'Request-URI Too Long', -- 415 => 'Unsupported Media Type', -- 416 => 'Requested Range Not Satisfiable', -- 417 => 'Expectation Failed'); -+ static $status = array(400 => 'Bad Request', -+ 401 => 'Unauthorized', -+ 402 => 'Payment Required', -+ 403 => 'Forbidden', -+ 404 => 'Not Found', -+ 405 => 'Method Not Allowed', -+ 406 => 'Not Acceptable', -+ 407 => 'Proxy Authentication Required', -+ 408 => 'Request Timeout', -+ 409 => 'Conflict', -+ 410 => 'Gone', -+ 411 => 'Length Required', -+ 412 => 'Precondition Failed', -+ 413 => 'Request Entity Too Large', -+ 414 => 'Request-URI Too Long', -+ 415 => 'Unsupported Media Type', -+ 416 => 'Requested Range Not Satisfiable', -+ 417 => 'Expectation Failed'); -hunk ./lib/util.php 67 -- if (!array_key_exists($code, $status)) { -- $code = 400; -- } -+ if (!array_key_exists($code, $status)) { -+ $code = 400; -+ } -hunk ./lib/util.php 71 -- $status_string = $status[$code]; -+ $status_string = $status[$code]; -hunk ./lib/util.php 73 -- header('HTTP/1.1 '.$code.' '.$status_string); -+ header('HTTP/1.1 '.$code.' '.$status_string); -hunk ./lib/util.php 75 -- common_show_header('Error'); -- common_element('div', array('class' => 'error'), $msg); -- common_show_footer(); -+ common_show_header('Error'); -+ common_element('div', array('class' => 'error'), $msg); -+ common_show_footer(); -hunk ./lib/util.php 82 --# Start an HTML element --function common_element_start($tag, $attrs=NULL) { -- global $xw; -- $xw->startElement($tag); -- if (is_array($attrs)) { -- foreach ($attrs as $name => $value) { -- $xw->writeAttribute($name, $value); -- } -- } else if (is_string($attrs)) { -- $xw->writeAttribute('class', $attrs); -- } -+// Start an HTML element -+function common_element_start($tag, $attrs=null) { -+ global $xw; -+ $xw->startElement($tag); -+ if (is_array($attrs)) { -+ foreach ($attrs as $name => $value) { -+ $xw->writeAttribute($name, $value); -+ } -+ } else if (is_string($attrs)) { -+ $xw->writeAttribute('class', $attrs); -+ } -hunk ./lib/util.php 96 -- static $empty_tag = array('base', 'meta', 'link', 'hr', -- 'br', 'param', 'img', 'area', -- 'input', 'col'); -- global $xw; -- # XXX: check namespace -- if (in_array($tag, $empty_tag)) { -- $xw->endElement(); -- } else { -- $xw->fullEndElement(); -- } -+ static $empty_tag = array('base', 'meta', 'link', 'hr', -+ 'br', 'param', 'img', 'area', -+ 'input', 'col'); -+ global $xw; -+ // XXX: check namespace -+ if (in_array($tag, $empty_tag)) { -+ $xw->endElement(); -+ } else { -+ $xw->fullEndElement(); -+ } -hunk ./lib/util.php 108 --function common_element($tag, $attrs=NULL, $content=NULL) { -- common_element_start($tag, $attrs); -- global $xw; -- if (!is_null($content)) { -- $xw->text($content); -- } -- common_element_end($tag); -+function common_element($tag, $attrs=null, $content=null) { -+ common_element_start($tag, $attrs); -+ global $xw; -+ if (!is_null($content)) { -+ $xw->text($content); -+ } -+ common_element_end($tag); -hunk ./lib/util.php 117 --function common_start_xml($doc=NULL, $public=NULL, $system=NULL, $indent=true) { -- global $xw; -- $xw = new XMLWriter(); -- $xw->openURI('php://output'); -- $xw->setIndent($indent); -- $xw->startDocument('1.0', 'UTF-8'); -- if ($doc) { -- $xw->writeDTD($doc, $public, $system); -- } -+function common_start_xml($doc=null, $public=null, $system=null, $indent=true) { -+ global $xw; -+ $xw = new XMLWriter(); -+ $xw->openURI('php://output'); -+ $xw->setIndent($indent); -+ $xw->startDocument('1.0', 'UTF-8'); -+ if ($doc) { -+ $xw->writeDTD($doc, $public, $system); -+ } -hunk ./lib/util.php 129 -- global $xw; -- $xw->endDocument(); -- $xw->flush(); -+ global $xw; -+ $xw->endDocument(); -+ $xw->flush(); -hunk ./lib/util.php 141 -- $language . ".UTF8", -- $language . ".utf-8", -- $language . ".UTF-8", -- $language); -+ $language . ".UTF8", -+ $language . ".utf-8", -+ $language . ".UTF-8", -+ $language); -hunk ./lib/util.php 148 -- mb_internal_encoding('UTF-8'); -- $language = common_language(); -- # So we don't have to make people install the gettext locales -- $locale_set = common_init_locale($language); -- bindtextdomain("laconica", common_config('site','locale_path')); -- bind_textdomain_codeset("laconica", "UTF-8"); -- textdomain("laconica"); -- setlocale(LC_CTYPE, 'C'); -- if(!$locale_set) { -- common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); -- } -+ mb_internal_encoding('UTF-8'); -+ $language = common_language(); -+ // So we don't have to make people install the gettext locales -+ $locale_set = common_init_locale($language); -+ bindtextdomain("laconica", common_config('site','locale_path')); -+ bind_textdomain_codeset("laconica", "UTF-8"); -+ textdomain("laconica"); -+ setlocale(LC_CTYPE, 'C'); -+ if(!$locale_set) { -+ common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__); -+ } -hunk ./lib/util.php 163 --function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) { -+function common_show_header($pagetitle, $callable=null, $data=null, $headercall=null) { -hunk ./lib/util.php 165 -- global $config, $xw; -+ global $config, $xw; -hunk ./lib/util.php 168 -- common_start_html(); -+ common_start_html(); -hunk ./lib/util.php 170 -- common_element_start('head'); -- common_element('title', NULL, -- $pagetitle . " - " . $config['site']['name']); -- common_element('link', array('rel' => 'stylesheet', -- 'type' => 'text/css', -- 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, -- 'media' => 'screen, projection, tv')); -- foreach (array(6,7) as $ver) { -- if (file_exists(theme_file('ie'.$ver.'.css'))) { -- # Yes, IE people should be put in jail. -- $xw->writeComment('[if lte IE '.$ver.']> 'stylesheet', -+ 'type' => 'text/css', -+ 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION, -+ 'media' => 'screen, projection, tv')); -+ foreach (array(6,7) as $ver) { -+ if (file_exists(theme_file('ie'.$ver.'.css'))) { -+ // Yes, IE people should be put in jail. -+ $xw->writeComment('[if lte IE '.$ver.']> 'text/javascript', -- 'src' => common_path('js/jquery.min.js')), -- ' '); -- common_element('script', array('type' => 'text/javascript', -- 'src' => common_path('js/jquery.form.js')), -- ' '); -- common_element('script', array('type' => 'text/javascript', -- 'src' => common_path('js/xbImportNode.js')), -- ' '); -- common_element('script', array('type' => 'text/javascript', -- 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), -- ' '); -- common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', -- 'href' => common_local_url('opensearch', array('type' => 'people')), -- 'title' => common_config('site', 'name').' People Search')); -+ common_element('script', array('type' => 'text/javascript', -+ 'src' => common_path('js/jquery.min.js')), -+ ' '); -+ common_element('script', array('type' => 'text/javascript', -+ 'src' => common_path('js/jquery.form.js')), -+ ' '); -+ common_element('script', array('type' => 'text/javascript', -+ 'src' => common_path('js/xbImportNode.js')), -+ ' '); -+ common_element('script', array('type' => 'text/javascript', -+ 'src' => common_path('js/util.js?version='.LACONICA_VERSION)), -+ ' '); -+ common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', -+ 'href' => common_local_url('opensearch', array('type' => 'people')), -+ 'title' => common_config('site', 'name').' People Search')); -hunk ./lib/util.php 201 -- common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', -- 'href' => common_local_url('opensearch', array('type' => 'notice')), -- 'title' => common_config('site', 'name').' Notice Search')); -+ common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml', -+ 'href' => common_local_url('opensearch', array('type' => 'notice')), -+ 'title' => common_config('site', 'name').' Notice Search')); -hunk ./lib/util.php 205 -- if ($callable) { -- if ($data) { -- call_user_func($callable, $data); -- } else { -- call_user_func($callable); -- } -- } -- common_element_end('head'); -- common_element_start('body', $action); -- common_element_start('div', array('id' => 'wrap')); -- common_element_start('div', array('id' => 'header')); -- common_nav_menu(); -- if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) -- || file_exists(theme_file('logo.png'))) -- { -- common_element_start('a', array('href' => common_local_url('public'))); -- common_element('img', array('src' => isset($config['site']['logo']) ? -- ($config['site']['logo']) : theme_path('logo.png'), -- 'alt' => $config['site']['name'], -- 'id' => 'logo')); -- common_element_end('a'); -- } else { -- common_element_start('p', array('id' => 'branding')); -- common_element('a', array('href' => common_local_url('public')), -- $config['site']['name']); -- common_element_end('p'); -- } -+ if ($callable) { -+ if ($data) { -+ call_user_func($callable, $data); -+ } else { -+ call_user_func($callable); -+ } -+ } -+ common_element_end('head'); -+ common_element_start('body', $action); -+ common_element_start('div', array('id' => 'wrap')); -+ common_element_start('div', array('id' => 'header')); -+ common_nav_menu(); -+ if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0)) -+ || file_exists(theme_file('logo.png'))) +hunk ./lib/action.php 2 +-/* ++/** +hunk ./lib/action.php 20 +-if (!defined('LACONICA')) { exit(1); } ++if (!defined('LACONICA')) { ++ exit(1); ++} +hunk ./lib/action.php 24 +-class Action { // lawsuit ++class Action // lawsuit ++{ +hunk ./lib/action.php 27 +- var $args; ++ var $args; +hunk ./lib/action.php 29 +- function Action() { +- } ++ function Action() + { -+ common_element_start('a', array('href' => common_local_url('public'))); -+ common_element('img', array('src' => isset($config['site']['logo']) ? -+ ($config['site']['logo']) : theme_path('logo.png'), -+ 'alt' => $config['site']['name'], -+ 'id' => 'logo')); -+ common_element_end('a'); -+ } else { -+ common_element_start('p', array('id' => 'branding')); -+ common_element('a', array('href' => common_local_url('public')), -+ $config['site']['name']); -+ common_element_end('p'); -+ } -hunk ./lib/util.php 233 -- common_element('h1', 'pagetitle', $pagetitle); -+ common_element('h1', 'pagetitle', $pagetitle); -hunk ./lib/util.php 235 -- if ($headercall) { -- if ($data) { -- call_user_func($headercall, $data); -- } else { -- call_user_func($headercall); -- } -- } -- common_element_end('div'); -- common_element_start('div', array('id' => 'content')); -+ if ($headercall) { -+ if ($data) { -+ call_user_func($headercall, $data); -+ } else { -+ call_user_func($headercall); -+ } -+ } -+ common_element_end('div'); -+ common_element_start('div', array('id' => 'content')); -hunk ./lib/util.php 246 --function common_start_html($type=NULL, $indent=true) { -+function common_start_html($type=null, $indent=true) { -hunk ./lib/util.php 248 -- if (!$type) { -- $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL; -+ if (!$type) { -+ $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; -hunk ./lib/util.php 251 -- # XXX: allow content negotiation for RDF, RSS, or XRDS -+ // XXX: allow content negotiation for RDF, RSS, or XRDS -hunk ./lib/util.php 253 -- $type = common_negotiate_type(common_accept_to_prefs($httpaccept), -- common_accept_to_prefs(PAGE_TYPE_PREFS)); -+ $type = common_negotiate_type(common_accept_to_prefs($httpaccept), -+ common_accept_to_prefs(PAGE_TYPE_PREFS)); -hunk ./lib/util.php 256 -- if (!$type) { -- common_user_error(_('This page is not available in a media type you accept'), 406); -- exit(0); -- } -- } -+ if (!$type) { -+ common_user_error(_('This page is not available in a media type you accept'), 406); -+ exit(0); -+ } -+ } -hunk ./lib/util.php 262 -- header('Content-Type: '.$type); -+ header('Content-Type: '.$type); -hunk ./lib/util.php 264 -- common_start_xml('html', -- '-//W3C//DTD XHTML 1.0 Strict//EN', -- 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); -+ common_start_xml('html', -+ '-//W3C//DTD XHTML 1.0 Strict//EN', -+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', $indent); -hunk ./lib/util.php 268 -- # FIXME: correct language for interface -+ // FIXME: correct language for interface -hunk ./lib/util.php 270 -- $language = common_language(); -+ $language = common_language(); -hunk ./lib/util.php 272 -- common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', -- 'xml:lang' => $language, -- 'lang' => $language)); -+ common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml', -+ 'xml:lang' => $language, -+ 'lang' => $language)); -hunk ./lib/util.php 278 -- global $xw, $config; -- common_element_end('div'); # content div -- common_foot_menu(); -- common_element_start('div', array('id' => 'footer')); -- common_element_start('div', 'laconica'); -- if (common_config('site', 'broughtby')) { -- $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); -- } else { -- $instr = _('**%%site.name%%** is a microblogging service. '); -- } -- $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); -+ global $xw, $config; -+ common_element_end('div'); // content div -+ common_foot_menu(); -+ common_element_start('div', array('id' => 'footer')); -+ common_element_start('div', 'laconica'); -+ if (common_config('site', 'broughtby')) { -+ $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). '); -+ } else { -+ $instr = _('**%%site.name%%** is a microblogging service. '); -+ } -+ $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION); -hunk ./lib/util.php 291 -- common_element_end('div'); -- common_element('img', array('id' => 'cc', -- 'src' => $config['license']['image'], -- 'alt' => $config['license']['title'])); -- common_element_start('p'); -- common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); -- common_element('a', array('class' => 'license', -- 'rel' => 'license', -- 'href' => $config['license']['url']), -- $config['license']['title']); -- common_text(_('. Contributors should be attributed by full name or nickname.')); -- common_element_end('p'); -- common_element_end('div'); -- common_element_end('div'); -- common_element_end('body'); -- common_element_end('html'); -- common_end_xml(); -+ common_element_end('div'); -+ common_element('img', array('id' => 'cc', -+ 'src' => $config['license']['image'], -+ 'alt' => $config['license']['title'])); -+ common_element_start('p'); -+ common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the ')); -+ common_element('a', array('class' => 'license', -+ 'rel' => 'license', -+ 'href' => $config['license']['url']), -+ $config['license']['title']); -+ common_text(_('. Contributors should be attributed by full name or nickname.')); -+ common_element_end('p'); -+ common_element_end('div'); -+ common_element_end('div'); -+ common_element_end('body'); -+ common_element_end('html'); -+ common_end_xml(); -hunk ./lib/util.php 311 -- global $xw; -- $xw->text($txt); -+ global $xw; -+ $xw->text($txt); -hunk ./lib/util.php 316 -- global $xw; -- $xw->writeRaw($xml); -+ global $xw; -+ $xw->writeRaw($xml); -hunk ./lib/util.php 321 -- $user = common_current_user(); -- common_element_start('ul', array('id' => 'nav')); -- if ($user) { -- common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), -- _('Home')); -- } -- common_menu_item(common_local_url('peoplesearch'), _('Search')); -- if ($user) { -- common_menu_item(common_local_url('profilesettings'), -- _('Settings')); -- common_menu_item(common_local_url('invite'), -- _('Invite')); -- common_menu_item(common_local_url('logout'), -- _('Logout')); -- } else { -- common_menu_item(common_local_url('login'), _('Login')); -- if (!common_config('site', 'closed')) { -- common_menu_item(common_local_url('register'), _('Register')); -- } -- common_menu_item(common_local_url('openidlogin'), _('OpenID')); -- } -- common_menu_item(common_local_url('doc', array('title' => 'help')), -- _('Help')); -- common_element_end('ul'); -+ $user = common_current_user(); -+ common_element_start('ul', array('id' => 'nav')); -+ if ($user) { -+ common_menu_item(common_local_url('all', array('nickname' => $user->nickname)), -+ _('Home')); -+ } -+ common_menu_item(common_local_url('peoplesearch'), _('Search')); -+ if ($user) { -+ common_menu_item(common_local_url('profilesettings'), -+ _('Settings')); -+ common_menu_item(common_local_url('invite'), -+ _('Invite')); -+ common_menu_item(common_local_url('logout'), -+ _('Logout')); -+ } else { -+ common_menu_item(common_local_url('login'), _('Login')); -+ if (!common_config('site', 'closed')) { -+ common_menu_item(common_local_url('register'), _('Register')); -+ } -+ common_menu_item(common_local_url('openidlogin'), _('OpenID')); -+ } -+ common_menu_item(common_local_url('doc', array('title' => 'help')), -+ _('Help')); -+ common_element_end('ul'); -hunk ./lib/util.php 348 -- common_element_start('ul', array('id' => 'nav_sub')); -- common_menu_item(common_local_url('doc', array('title' => 'help')), -- _('Help')); -- common_menu_item(common_local_url('doc', array('title' => 'about')), -- _('About')); -- common_menu_item(common_local_url('doc', array('title' => 'faq')), -- _('FAQ')); -- common_menu_item(common_local_url('doc', array('title' => 'privacy')), -- _('Privacy')); -- common_menu_item(common_local_url('doc', array('title' => 'source')), -- _('Source')); -- common_menu_item(common_local_url('doc', array('title' => 'contact')), -- _('Contact')); -- common_element_end('ul'); -+ common_element_start('ul', array('id' => 'nav_sub')); -+ common_menu_item(common_local_url('doc', array('title' => 'help')), -+ _('Help')); -+ common_menu_item(common_local_url('doc', array('title' => 'about')), -+ _('About')); -+ common_menu_item(common_local_url('doc', array('title' => 'faq')), -+ _('FAQ')); -+ common_menu_item(common_local_url('doc', array('title' => 'privacy')), -+ _('Privacy')); -+ common_menu_item(common_local_url('doc', array('title' => 'source')), -+ _('Source')); -+ common_menu_item(common_local_url('doc', array('title' => 'contact')), -+ _('Contact')); -+ common_element_end('ul'); -hunk ./lib/util.php 364 --function common_menu_item($url, $text, $title=NULL, $is_selected=false) { -- $lattrs = array(); -- if ($is_selected) { -- $lattrs['class'] = 'current'; -- } -- common_element_start('li', $lattrs); -- $attrs['href'] = $url; -- if ($title) { -- $attrs['title'] = $title; -- } -- common_element('a', $attrs, $text); -- common_element_end('li'); -+function common_menu_item($url, $text, $title=null, $is_selected=false) { -+ $lattrs = array(); -+ if ($is_selected) { -+ $lattrs['class'] = 'current'; -+ } -+ common_element_start('li', $lattrs); -+ $attrs['href'] = $url; -+ if ($title) { -+ $attrs['title'] = $title; -+ } -+ common_element('a', $attrs, $text); -+ common_element_end('li'); -hunk ./lib/util.php 378 --function common_input($id, $label, $value=NULL,$instructions=NULL) { -- common_element_start('p'); -- common_element('label', array('for' => $id), $label); -- $attrs = array('name' => $id, -- 'type' => 'text', -- 'class' => 'input_text', -- 'id' => $id); -- if ($value) { -- $attrs['value'] = htmlspecialchars($value); -- } -- common_element('input', $attrs); -- if ($instructions) { -- common_element('span', 'input_instructions', $instructions); -- } -- common_element_end('p'); -+function common_input($id, $label, $value=null,$instructions=null) { -+ common_element_start('p'); -+ common_element('label', array('for' => $id), $label); -+ $attrs = array('name' => $id, -+ 'type' => 'text', -+ 'class' => 'input_text', -+ 'id' => $id); -+ if ($value) { -+ $attrs['value'] = htmlspecialchars($value); -+ } -+ common_element('input', $attrs); -+ if ($instructions) { -+ common_element('span', 'input_instructions', $instructions); -+ } -+ common_element_end('p'); -hunk ./lib/util.php 395 --function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false) -+function common_checkbox($id, $label, $checked=false, $instructions=null, $value='true', $disabled=false) -hunk ./lib/util.php 397 -- common_element_start('p'); -- $attrs = array('name' => $id, -- 'type' => 'checkbox', -- 'class' => 'checkbox', -- 'id' => $id); -- if ($value) { -- $attrs['value'] = htmlspecialchars($value); -- } -- if ($checked) { -- $attrs['checked'] = 'checked'; -- } -- if ($disabled) { -- $attrs['disabled'] = 'true'; -- } -- common_element('input', $attrs); -- common_text(' '); -- common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); -- common_text(' '); -- if ($instructions) { -- common_element('span', 'input_instructions', $instructions); -- } -- common_element_end('p'); -+ common_element_start('p'); -+ $attrs = array('name' => $id, -+ 'type' => 'checkbox', -+ 'class' => 'checkbox', -+ 'id' => $id); -+ if ($value) { -+ $attrs['value'] = htmlspecialchars($value); -+ } -+ if ($checked) { -+ $attrs['checked'] = 'checked'; -+ } -+ if ($disabled) { -+ $attrs['disabled'] = 'true'; -+ } -+ common_element('input', $attrs); -+ common_text(' '); -+ common_element('label', array('class' => 'checkbox_label', 'for' => $id), $label); -+ common_text(' '); -+ if ($instructions) { -+ common_element('span', 'input_instructions', $instructions); -+ } -+ common_element_end('p'); -hunk ./lib/util.php 421 --function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) { -- common_element_start('p'); -- common_element('label', array('for' => $id), $label); -- common_element_start('select', array('id' => $id, 'name' => $id)); -- if ($blank_select) { -- common_element('option', array('value' => '')); -- } -- foreach ($content as $value => $option) { -- if ($value == $selected) { -- common_element('option', array('value' => $value, 'selected' => $value), $option); -- } else { -- common_element('option', array('value' => $value), $option); -- } -- } -- common_element_end('select'); -- if ($instructions) { -- common_element('span', 'input_instructions', $instructions); -- } -- common_element_end('p'); -+function common_dropdown($id, $label, $content, $instructions=null, $blank_select=FALSE, $selected=null) { -+ common_element_start('p'); -+ common_element('label', array('for' => $id), $label); -+ common_element_start('select', array('id' => $id, 'name' => $id)); -+ if ($blank_select) { -+ common_element('option', array('value' => '')); -+ } -+ foreach ($content as $value => $option) { -+ if ($value == $selected) { -+ common_element('option', array('value' => $value, 'selected' => $value), $option); -+ } else { -+ common_element('option', array('value' => $value), $option); -+ } -+ } -+ common_element_end('select'); -+ if ($instructions) { -+ common_element('span', 'input_instructions', $instructions); -+ } -+ common_element_end('p'); -hunk ./lib/util.php 442 -- common_element('input', array('name' => $id, -- 'type' => 'hidden', -- 'id' => $id, -- 'value' => $value)); -+ common_element('input', array('name' => $id, -+ 'type' => 'hidden', -+ 'id' => $id, -+ 'value' => $value)); -hunk ./lib/util.php 448 --function common_password($id, $label, $instructions=NULL) { -- common_element_start('p'); -- common_element('label', array('for' => $id), $label); -- $attrs = array('name' => $id, -- 'type' => 'password', -- 'class' => 'password', -- 'id' => $id); -- common_element('input', $attrs); -- if ($instructions) { -- common_element('span', 'input_instructions', $instructions); -- } -- common_element_end('p'); -+function common_password($id, $label, $instructions=null) { -+ common_element_start('p'); -+ common_element('label', array('for' => $id), $label); -+ $attrs = array('name' => $id, -+ 'type' => 'password', -+ 'class' => 'password', -+ 'id' => $id); -+ common_element('input', $attrs); -+ if ($instructions) { -+ common_element('span', 'input_instructions', $instructions); -+ } -+ common_element_end('p'); -hunk ./lib/util.php 463 -- global $xw; -- common_element_start('p'); -- common_element('input', array('type' => 'submit', -- 'id' => $id, -- 'name' => $id, -- 'class' => $cls, -- 'value' => $label)); -- common_element_end('p'); -+ global $xw; -+ common_element_start('p'); -+ common_element('input', array('type' => 'submit', -+ 'id' => $id, -+ 'name' => $id, -+ 'class' => $cls, -+ 'value' => $label)); -+ common_element_end('p'); -hunk ./lib/util.php 473 --function common_textarea($id, $label, $content=NULL, $instructions=NULL) { -- common_element_start('p'); -- common_element('label', array('for' => $id), $label); -- common_element('textarea', array('rows' => 3, -- 'cols' => 40, -- 'name' => $id, -- 'id' => $id), -- ($content) ? $content : ''); -- if ($instructions) { -- common_element('span', 'input_instructions', $instructions); -- } -- common_element_end('p'); -+function common_textarea($id, $label, $content=null, $instructions=null) { -+ common_element_start('p'); -+ common_element('label', array('for' => $id), $label); -+ common_element('textarea', array('rows' => 3, -+ 'cols' => 40, -+ 'name' => $id, -+ 'id' => $id), -+ ($content) ? $content : ''); -+ if ($instructions) { -+ common_element('span', 'input_instructions', $instructions); -+ } -+ common_element_end('p'); -hunk ./lib/util.php 488 -- if (common_logged_in()) { -- $user = common_current_user(); -- if ($user->timezone) { -- return $user->timezone; -- } -- } -+ if (common_logged_in()) { -+ $user = common_current_user(); -+ if ($user->timezone) { -+ return $user->timezone; -+ } -+ } -hunk ./lib/util.php 495 -- global $config; -- return $config['site']['timezone']; -+ global $config; -+ return $config['site']['timezone']; -hunk ./lib/util.php 501 -- // If there is a user logged in and they've set a language preference -- // then return that one... -- if (common_logged_in()) { -- $user = common_current_user(); -- $user_language = $user->language; -- if ($user_language) -- return $user_language; -- } -+ // If there is a user logged in and they've set a language preference -+ // then return that one... -+ if (common_logged_in()) { -+ $user = common_current_user(); -+ $user_language = $user->language; -+ if ($user_language) -+ return $user_language; -+ } -hunk ./lib/util.php 510 -- // Otherwise, find the best match for the languages requested by the -- // user's browser... -- $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL; -- if (!empty($httplang)) { -- $language = client_prefered_language($httplang); -- if ($language) -- return $language; -- } -+ // Otherwise, find the best match for the languages requested by the -+ // user's browser... -+ $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; -+ if (!empty($httplang)) { -+ $language = client_prefered_language($httplang); -+ if ($language) -+ return $language; -+ } -hunk ./lib/util.php 519 -- // Finally, if none of the above worked, use the site's default... -- return common_config('site', 'language'); -+ // Finally, if none of the above worked, use the site's default... -+ return common_config('site', 'language'); -hunk ./lib/util.php 522 --# salted, hashed passwords are stored in the DB -+// salted, hashed passwords are stored in the DB -hunk ./lib/util.php 525 -- return md5($password . $id); -+ return md5($password . $id); -hunk ./lib/util.php 528 --# check if a username exists and has matching password -+// check if a username exists and has matching password -hunk ./lib/util.php 530 -- # NEVER allow blank passwords, even if they match the DB -- if (mb_strlen($password) == 0) { -- return false; -- } -- $user = User::staticGet('nickname', $nickname); -- if (is_null($user)) { -- return false; -- } else { -- if (0 == strcmp(common_munge_password($password, $user->id), -- $user->password)) { -- return $user; -- } else { -- return false; -- } -- } -+ // NEVER allow blank passwords, even if they match the DB -+ if (mb_strlen($password) == 0) { -+ return false; + } -+ $user = User::staticGet('nickname', $nickname); -+ if (is_null($user)) { -+ return false; -+ } else { -+ if (0 == strcmp(common_munge_password($password, $user->id), -+ $user->password)) { -+ return $user; -+ } else { -+ return false; -+ } -+ } -hunk ./lib/util.php 547 --# is the current user logged in? -+// is the current user logged in? -hunk ./lib/util.php 549 -- return (!is_null(common_current_user())); -+ return (!is_null(common_current_user())); -hunk ./lib/util.php 553 -- return (0 != strcmp(session_id(), '')); -+ return (0 != strcmp(session_id(), '')); -hunk ./lib/util.php 557 -- if (!common_have_session()) { -- @session_start(); -- } -+ if (!common_have_session()) { -+ @session_start(); -+ } -hunk ./lib/util.php 562 --# Three kinds of arguments: --# 1) a user object --# 2) a nickname --# 3) NULL to clear -+// Three kinds of arguments: -+// 1) a user object -+// 2) a nickname -+// 3) null to clear -hunk ./lib/util.php 567 --# Initialize to false; set to NULL if none found -+// Initialize to false; set to null if none found -hunk ./lib/util.php 575 -- if (is_null($user) && common_have_session()) { -- $_cur = NULL; -- unset($_SESSION['userid']); +hunk ./lib/action.php 33 +- # For initializing members of the class ++ // For initializing members of the class +hunk ./lib/action.php 35 +- function prepare($argarray) { +- $this->args =& common_copy_args($argarray); - return true; -- } else if (is_string($user)) { -- $nickname = $user; -- $user = User::staticGet('nickname', $nickname); -- } else if (!($user instanceof User)) { -- return false; - } -+ if (is_null($user) && common_have_session()) { -+ $_cur = null; -+ unset($_SESSION['userid']); ++ function prepare($argarray) ++ { ++ $this->args =& common_copy_args($argarray); + return true; -+ } else if (is_string($user)) { -+ $nickname = $user; -+ $user = User::staticGet('nickname', $nickname); -+ } else if (!($user instanceof User)) { -+ return false; -+ } -hunk ./lib/util.php 586 -- if ($user) { -- common_ensure_session(); -- $_SESSION['userid'] = $user->id; -+ if ($user) { -+ common_ensure_session(); -+ $_SESSION['userid'] = $user->id; -hunk ./lib/util.php 590 -- return $_cur; -- } -- return false; -+ return $_cur; -+ } -+ return false; -hunk ./lib/util.php 596 -- $path = common_config('site', 'path'); -- $server = common_config('site', 'server'); -+ $path = common_config('site', 'path'); -+ $server = common_config('site', 'server'); -hunk ./lib/util.php 599 -- if ($path && ($path != '/')) { -- $cookiepath = '/' . $path . '/'; -- } else { -- $cookiepath = '/'; -- } -- return setcookie($key, -- $value, -- $expiration, -- $cookiepath, -- $server); -+ if ($path && ($path != '/')) { -+ $cookiepath = '/' . $path . '/'; -+ } else { -+ $cookiepath = '/'; + } -+ return setcookie($key, -+ $value, -+ $expiration, -+ $cookiepath, -+ $server); -hunk ./lib/util.php 612 --define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); # 30 days -+define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days -hunk ./lib/util.php 614 --function common_rememberme($user=NULL) { -- if (!$user) { -- $user = common_current_user(); -- if (!$user) { -- common_debug('No current user to remember', __FILE__); -- return false; -- } +hunk ./lib/action.php 41 +- # For comparison with If-Last-Modified +- # If not applicable, return NULL ++ // For comparison with If-Last-Modified ++ // If not applicable, return null +hunk ./lib/action.php 44 +- function last_modified() { +- return NULL; - } -+function common_rememberme($user=null) { -+ if (!$user) { -+ $user = common_current_user(); -+ if (!$user) { -+ common_debug('No current user to remember', __FILE__); -+ return false; -+ } -+ } -hunk ./lib/util.php 623 -- $rm = new Remember_me(); -+ $rm = new Remember_me(); -hunk ./lib/util.php 625 -- $rm->code = common_good_rand(16); -- $rm->user_id = $user->id; -+ $rm->code = common_good_rand(16); -+ $rm->user_id = $user->id; -hunk ./lib/util.php 628 -- # Wrap the insert in some good ol' fashioned transaction code -+ // Wrap the insert in some good ol' fashioned transaction code -hunk ./lib/util.php 632 -- $result = $rm->insert(); -+ $result = $rm->insert(); -hunk ./lib/util.php 634 -- if (!$result) { -- common_log_db_error($rm, 'INSERT', __FILE__); -- common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); -- return false; -+ if (!$result) { -+ common_log_db_error($rm, 'INSERT', __FILE__); -+ common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); -+ return false; -hunk ./lib/util.php 642 -- common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); -+ common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); -hunk ./lib/util.php 646 -- common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); -+ common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); -hunk ./lib/util.php 648 -- common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); -+ common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY); -hunk ./lib/util.php 650 -- return true; -+ return true; -hunk ./lib/util.php 655 -- $user = NULL; -+ $user = null; -hunk ./lib/util.php 657 -- $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : NULL; -+ $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null; -hunk ./lib/util.php 659 -- if (!$packed) { -- return NULL; -+ if (!$packed) { -+ return null; -hunk ./lib/util.php 668 -- return NULL; -+ return null; -hunk ./lib/util.php 676 -- return NULL; -+ return null; -hunk ./lib/util.php 682 -- return NULL; -+ return null; -hunk ./lib/util.php 690 -- return NULL; -+ return null; -hunk ./lib/util.php 693 -- # successful! -+ // successful! -hunk ./lib/util.php 700 -- return NULL; ++ function last_modified() ++ { + return null; -hunk ./lib/util.php 708 -- # We issue a new cookie, so they can log in -- # automatically again after this session -+ // We issue a new cookie, so they can log in -+ // automatically again after this session -hunk ./lib/util.php 713 -- return $user; -+ return $user; -hunk ./lib/util.php 716 --# must be called with a valid user! -+// must be called with a valid user! -hunk ./lib/util.php 719 -- common_set_cookie(REMEMBERME, '', 0); -+ common_set_cookie(REMEMBERME, '', 0); -hunk ./lib/util.php 722 --# who is the current user? -+// who is the current user? -hunk ./lib/util.php 737 -- # that didn't work; try to remember; will init $_cur to NULL on failure -+ // that didn't work; try to remember; will init $_cur to null on failure -hunk ./lib/util.php 743 -- # XXX: Is this necessary? -+ // XXX: Is this necessary? -hunk ./lib/util.php 748 -- return $_cur; -+ return $_cur; -hunk ./lib/util.php 751 --# Logins that are 'remembered' aren't 'real' -- they're subject to --# cookie-stealing. So, we don't let them do certain things. New reg, --# OpenID, and password logins _are_ real. -+// Logins that are 'remembered' aren't 'real' -- they're subject to -+// cookie-stealing. So, we don't let them do certain things. New reg, -+// OpenID, and password logins _are_ real. -hunk ./lib/util.php 756 -- common_ensure_session(); -- $_SESSION['real_login'] = $real; -+ common_ensure_session(); -+ $_SESSION['real_login'] = $real; -hunk ./lib/util.php 761 -- return common_logged_in() && $_SESSION['real_login']; -+ return common_logged_in() && $_SESSION['real_login']; -hunk ./lib/util.php 764 --# get canonical version of nickname for comparison -+// get canonical version of nickname for comparison -hunk ./lib/util.php 766 -- # XXX: UTF-8 canonicalization (like combining chars) -- return strtolower($nickname); -+ // XXX: UTF-8 canonicalization (like combining chars) -+ return strtolower($nickname); -hunk ./lib/util.php 770 --# get canonical version of email for comparison -+// get canonical version of email for comparison -hunk ./lib/util.php 772 -- # XXX: canonicalize UTF-8 -- # XXX: lcase the domain part -- return $email; -+ // XXX: canonicalize UTF-8 -+ // XXX: lcase the domain part -+ return $email; -hunk ./lib/util.php 780 -- $r = common_render_text($text); -- $id = $notice->profile_id; -- $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); -- $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); -- $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); -- return $r; -+ $r = common_render_text($text); -+ $id = $notice->profile_id; -+ $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); -+ $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); -+ $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); -+ return $r; -hunk ./lib/util.php 789 -- $r = htmlspecialchars($text); -+ $r = htmlspecialchars($text); -hunk ./lib/util.php 791 -- $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); -- $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); -- $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); -- # XXX: machine tags -- return $r; -+ $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r); -+ $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r); -+ $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r); -+ // XXX: machine tags -+ return $r; -hunk ./lib/util.php 799 -- $uri = $matches[0]; -- $trailer = ''; -+ $uri = $matches[0]; -+ $trailer = ''; -hunk ./lib/util.php 802 -- # Some heuristics for extracting URIs from surrounding punctuation -- # Strip from trailing text... -- if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { -- $uri = $matches[1]; -- $trailer = $matches[2]; -- } -+ // Some heuristics for extracting URIs from surrounding punctuation -+ // Strip from trailing text... -+ if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) { -+ $uri = $matches[1]; -+ $trailer = $matches[2]; -+ } -hunk ./lib/util.php 809 -- $pairs = array( -- ']' => '[', # technically disallowed in URIs, but used in Java docs -- ')' => '(', # far too frequent in Wikipedia and MSDN -- ); -- $final = substr($uri, -1, 1); -- if (isset($pairs[$final])) { -- $openers = substr_count($uri, $pairs[$final]); -- $closers = substr_count($uri, $final); -- if ($closers > $openers) { -- // Assume the paren was opened outside the URI -- $uri = substr($uri, 0, -1); -- $trailer = $final . $trailer; -- } -- } -- if ($longurl = common_longurl($uri)) { -- $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); -- $title = " title='$longurl'"; -- } -- else $title = ''; -+ $pairs = array( -+ ']' => '[', // technically disallowed in URIs, but used in Java docs -+ ')' => '(', // far too frequent in Wikipedia and MSDN -+ ); -+ $final = substr($uri, -1, 1); -+ if (isset($pairs[$final])) { -+ $openers = substr_count($uri, $pairs[$final]); -+ $closers = substr_count($uri, $final); -+ if ($closers > $openers) { -+ // Assume the paren was opened outside the URI -+ $uri = substr($uri, 0, -1); -+ $trailer = $final . $trailer; -+ } -+ } -+ if ($longurl = common_longurl($uri)) { -+ $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8'); -+ $title = " title='$longurl'"; -+ } -+ else $title = ''; -hunk ./lib/util.php 829 -- return '' . $uri . '' . $trailer; -+ return '' . $uri . '' . $trailer; -hunk ./lib/util.php 839 -- $uri_e = urlencode($uri); -- $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); -- if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; -- return stripslashes($longurl['long_url']); -+ $uri_e = urlencode($uri); -+ $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e")); -+ if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false; -+ return stripslashes($longurl['long_url']); -hunk ./lib/util.php 850 -- return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); -+ return $cache[$text] = preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text); -hunk ./lib/util.php 854 -- static $url_cache = array(); -+ static $url_cache = array(); -hunk ./lib/util.php 857 -- $user = common_current_user(); -+ $user = common_current_user(); -hunk ./lib/util.php 859 -- $curlh = curl_init(); -- curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait -- curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); -- curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); -+ $curlh = curl_init(); -+ curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait -+ curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica'); -+ curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true); -hunk ./lib/util.php 864 -- switch($user->urlshorteningservice) { -- case 'ur1.ca': -- $short_url_service = new LilUrl; -- $short_url = $short_url_service->shorten($url); -- break; -+ switch($user->urlshorteningservice) { -+ case 'ur1.ca': -+ $short_url_service = new LilUrl; -+ $short_url = $short_url_service->shorten($url); -+ break; -hunk ./lib/util.php 870 -- case '2tu.us': -- $short_url_service = new TightUrl; -- $short_url = $short_url_service->shorten($url); -- break; -+ case '2tu.us': -+ $short_url_service = new TightUrl; -+ $short_url = $short_url_service->shorten($url); -+ break; -hunk ./lib/util.php 875 -- case 'ptiturl.com': -- $short_url_service = new PtitUrl; -- $short_url = $short_url_service->shorten($url); -- break; -+ case 'ptiturl.com': -+ $short_url_service = new PtitUrl; -+ $short_url = $short_url_service->shorten($url); -+ break; -hunk ./lib/util.php 880 -- case 'bit.ly': -- curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); -- $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; -- break; -+ case 'bit.ly': -+ curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($url)); -+ $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl; -+ break; -hunk ./lib/util.php 885 -- case 'is.gd': -- curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); -- $short_url = curl_exec($curlh); -- break; -- case 'snipr.com': -- curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); -- $short_url = curl_exec($curlh); -- break; -- case 'metamark.net': -- curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); -- $short_url = curl_exec($curlh); -- break; -- case 'tinyurl.com': -- curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); -- $short_url = curl_exec($curlh); -- break; -- default: -- $short_url = false; -- } -+ case 'is.gd': -+ curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($url)); -+ $short_url = curl_exec($curlh); -+ break; -+ case 'snipr.com': -+ curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($url)); -+ $short_url = curl_exec($curlh); -+ break; -+ case 'metamark.net': -+ curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($url)); -+ $short_url = curl_exec($curlh); -+ break; -+ case 'tinyurl.com': -+ curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($url)); -+ $short_url = curl_exec($curlh); -+ break; -+ default: -+ $short_url = false; -+ } -hunk ./lib/util.php 905 -- curl_close($curlh); -+ curl_close($curlh); -hunk ./lib/util.php 907 -- if ($short_url) { -+ if ($short_url) { -hunk ./lib/util.php 909 -- return (string)$short_url; -- } -- return $url; -+ return (string)$short_url; -+ } -+ return $url; -hunk ./lib/util.php 915 -- $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8'); -+ $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8'); -hunk ./lib/util.php 917 -- // Replace control, formatting, and surrogate characters with '*', ala Twitter -- return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str); -+ // Replace control, formatting, and surrogate characters with '*', ala Twitter -+ return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str); -hunk ./lib/util.php 922 -- $canonical = common_canonical_tag($tag); -- $url = common_local_url('tag', array('tag' => $canonical)); -- return ''; -+ $canonical = common_canonical_tag($tag); -+ $url = common_local_url('tag', array('tag' => $canonical)); -+ return ''; -hunk ./lib/util.php 928 -- return strtolower(str_replace(array('-', '_', '.'), '', $tag)); -+ return strtolower(str_replace(array('-', '_', '.'), '', $tag)); -hunk ./lib/util.php 932 -- return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); -+ return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); -hunk ./lib/util.php 936 -- $sender = Profile::staticGet($sender_id); -- $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); -- if ($recipient) { -- return ''.$nickname.''; -- } else { -- return $nickname; -- } -+ $sender = Profile::staticGet($sender_id); -+ $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); -+ if ($recipient) { -+ return ''.$nickname.''; -+ } else { -+ return $nickname; + } -hunk ./lib/util.php 946 -- $user = User::staticGet($sender_id); -- if (!$user) { -- return $tag; -- } -- $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); -- if ($tagged) { -- $url = common_local_url('subscriptions', -- array('nickname' => $user->nickname, -- 'tag' => $tag)); -- return ''.$tag.''; -- } else { -- return $tag; -- } -+ $user = User::staticGet($sender_id); -+ if (!$user) { -+ return $tag; -+ } -+ $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); -+ if ($tagged) { -+ $url = common_local_url('subscriptions', -+ array('nickname' => $user->nickname, -+ 'tag' => $tag)); -+ return ''.$tag.''; -+ } else { -+ return $tag; -+ } -hunk ./lib/util.php 961 --function common_relative_profile($sender, $nickname, $dt=NULL) { -- # Try to find profiles this profile is subscribed to that have this nickname -- $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'); -- if ($recipient->find(TRUE)) { -- # XXX: should probably differentiate between profiles with -- # the same name by date of most recent update -- return $recipient; -- } -- # Try to find profiles that listen to this profile and that have this nickname -- $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'); -- if ($recipient->find(TRUE)) { -- # XXX: should probably differentiate between profiles with -- # the same name by date of most recent update -- return $recipient; -- } -- # If this is a local user, try to find a local user with that nickname. -- $sender = User::staticGet($sender->id); -- if ($sender) { -- $recipient_user = User::staticGet('nickname', $nickname); -- if ($recipient_user) { -- return $recipient_user->getProfile(); -- } -- } -- # Otherwise, no links. @messages from local users to remote users, -- # or from remote users to other remote users, are just -- # outside our ability to make intelligent guesses about -- return NULL; -+function common_relative_profile($sender, $nickname, $dt=null) { -+ // Try to find profiles this profile is subscribed to that have this nickname -+ $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'); -+ if ($recipient->find(TRUE)) { -+ // XXX: should probably differentiate between profiles with -+ // the same name by date of most recent update -+ return $recipient; -+ } -+ // Try to find profiles that listen to this profile and that have this nickname -+ $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'); -+ if ($recipient->find(TRUE)) { -+ // XXX: should probably differentiate between profiles with -+ // the same name by date of most recent update -+ return $recipient; -+ } -+ // If this is a local user, try to find a local user with that nickname. -+ $sender = User::staticGet($sender->id); -+ if ($sender) { -+ $recipient_user = User::staticGet('nickname', $nickname); -+ if ($recipient_user) { -+ return $recipient_user->getProfile(); -+ } -+ } -+ // Otherwise, no links. @messages from local users to remote users, -+ // or from remote users to other remote users, are just -+ // outside our ability to make intelligent guesses about -+ return null; -hunk ./lib/util.php 998 --function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) { -- global $config; -+function common_avatar_filename($id, $extension, $size=null, $extra=null) { -+ global $config; -hunk ./lib/util.php 1001 -- if ($size) { -- return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; -- } else { -- return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; -- } -+ if ($size) { -+ return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension; -+ } else { -+ return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension; -+ } -hunk ./lib/util.php 1009 -- global $config; -- return INSTALLDIR . '/avatar/' . $filename; -+ global $config; -+ return INSTALLDIR . '/avatar/' . $filename; -hunk ./lib/util.php 1014 -- return common_path('avatar/'.$filename); -+ return common_path('avatar/'.$filename); -hunk ./lib/util.php 1018 -- $server = common_config('avatar', 'server'); -- if ($server) { -- return 'http://'.$server.'/'.$avatar->filename; -- } else { -- return $avatar->url; +hunk ./lib/action.php 49 +- function etag() { +- return NULL; - } -+ $server = common_config('avatar', 'server'); -+ if ($server) { -+ return 'http://'.$server.'/'.$avatar->filename; -+ } else { -+ return $avatar->url; ++ function etag() ++ { ++ return null; + } -hunk ./lib/util.php 1027 -- static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', -- AVATAR_STREAM_SIZE => 'stream', -- AVATAR_MINI_SIZE => 'mini'); -- return theme_path('default-avatar-'.$sizenames[$size].'.png'); -+ static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile', -+ AVATAR_STREAM_SIZE => 'stream', -+ AVATAR_MINI_SIZE => 'mini'); -+ return theme_path('default-avatar-'.$sizenames[$size].'.png'); -hunk ./lib/util.php 1033 --function common_local_url($action, $args=NULL, $fragment=NULL) { -- $url = NULL; -- if (common_config('site','fancy')) { -- $url = common_fancy_url($action, $args); -- } else { -- $url = common_simple_url($action, $args); -- } -- if (!is_null($fragment)) { -- $url .= '#'.$fragment; +hunk ./lib/action.php 54 +- function is_readonly() { +- return false; - } -- return $url; -+function common_local_url($action, $args=null, $fragment=null) { -+ $url = null; -+ if (common_config('site','fancy')) { -+ $url = common_fancy_url($action, $args); -+ } else { -+ $url = common_simple_url($action, $args); -+ } -+ if (!is_null($fragment)) { -+ $url .= '#'.$fragment; ++ function is_readonly() ++ { ++ return false; + } -+ return $url; -hunk ./lib/util.php 1046 --function common_fancy_url($action, $args=NULL) { -- switch (strtolower($action)) { -- case 'public': -- if ($args && isset($args['page'])) { -- return common_path('?page=' . $args['page']); -- } else { -- return common_path(''); -- } -- case 'featured': -- if ($args && isset($args['page'])) { -- return common_path('featured?page=' . $args['page']); -- } else { -- return common_path('featured'); -- } -- case 'favorited': -- if ($args && isset($args['page'])) { -- return common_path('favorited?page=' . $args['page']); -- } else { -- return common_path('favorited'); -- } -- case 'publicrss': -- return common_path('rss'); -- case 'publicatom': -- return common_path("api/statuses/public_timeline.atom"); -- case 'publicxrds': -- return common_path('xrds'); -- case 'featuredrss': -- return common_path('featuredrss'); -- case 'favoritedrss': -- return common_path('favoritedrss'); -- case 'opensearch': -- if ($args && $args['type']) { -- return common_path('opensearch/'.$args['type']); -- } else { -- return common_path('opensearch/people'); -- } -- case 'doc': -- return common_path('doc/'.$args['title']); -+function common_fancy_url($action, $args=null) { -+ switch (strtolower($action)) { -+ case 'public': -+ if ($args && isset($args['page'])) { -+ return common_path('?page=' . $args['page']); -+ } else { -+ return common_path(''); -+ } -+ case 'featured': -+ if ($args && isset($args['page'])) { -+ return common_path('featured?page=' . $args['page']); -+ } else { -+ return common_path('featured'); -+ } -+ case 'favorited': -+ if ($args && isset($args['page'])) { -+ return common_path('favorited?page=' . $args['page']); -+ } else { -+ return common_path('favorited'); -+ } -+ case 'publicrss': -+ return common_path('rss'); -+ case 'publicatom': -+ return common_path("api/statuses/public_timeline.atom"); -+ case 'publicxrds': -+ return common_path('xrds'); -+ case 'featuredrss': -+ return common_path('featuredrss'); -+ case 'favoritedrss': -+ return common_path('favoritedrss'); -+ case 'opensearch': -+ if ($args && $args['type']) { -+ return common_path('opensearch/'.$args['type']); -+ } else { -+ return common_path('opensearch/people'); -+ } -+ case 'doc': -+ return common_path('doc/'.$args['title']); -hunk ./lib/util.php 1085 -- case 'login': -- case 'logout': -- case 'subscribe': -- case 'unsubscribe': -- case 'invite': -- return common_path('main/'.$action); -- case 'tagother': -- return common_path('main/tagother?id='.$args['id']); -- case 'register': -- if ($args && $args['code']) { -- return common_path('main/register/'.$args['code']); -- } else { -- return common_path('main/register'); -- } -- case 'remotesubscribe': -- if ($args && $args['nickname']) { -- return common_path('main/remote?nickname=' . $args['nickname']); -- } else { -- return common_path('main/remote'); -- } -- case 'nudge': -- return common_path($args['nickname'].'/nudge'); -- case 'openidlogin': -- return common_path('main/openid'); -- case 'profilesettings': -- return common_path('settings/profile'); -- case 'emailsettings': -- return common_path('settings/email'); -- case 'openidsettings': -- return common_path('settings/openid'); -- case 'smssettings': -- return common_path('settings/sms'); -- case 'twittersettings': -- return common_path('settings/twitter'); -- case 'othersettings': -- return common_path('settings/other'); -+ case 'login': -+ case 'logout': -+ case 'subscribe': -+ case 'unsubscribe': -+ case 'invite': -+ return common_path('main/'.$action); -+ case 'tagother': -+ return common_path('main/tagother?id='.$args['id']); -+ case 'register': -+ if ($args && $args['code']) { -+ return common_path('main/register/'.$args['code']); -+ } else { -+ return common_path('main/register'); -+ } -+ case 'remotesubscribe': -+ if ($args && $args['nickname']) { -+ return common_path('main/remote?nickname=' . $args['nickname']); -+ } else { -+ return common_path('main/remote'); -+ } -+ case 'nudge': -+ return common_path($args['nickname'].'/nudge'); -+ case 'openidlogin': -+ return common_path('main/openid'); -+ case 'profilesettings': -+ return common_path('settings/profile'); -+ case 'emailsettings': -+ return common_path('settings/email'); -+ case 'openidsettings': -+ return common_path('settings/openid'); -+ case 'smssettings': -+ return common_path('settings/sms'); -+ case 'twittersettings': -+ return common_path('settings/twitter'); -+ case 'othersettings': -+ return common_path('settings/other'); -hunk ./lib/util.php 1123 -- case 'newnotice': -- if ($args && $args['replyto']) { -- return common_path('notice/new?replyto='.$args['replyto']); +hunk ./lib/action.php 59 +- function arg($key, $def=NULL) { +- if (array_key_exists($key, $this->args)) { +- return $this->args[$key]; - } else { -- return common_path('notice/new'); +- return $def; - } -- case 'shownotice': -- return common_path('notice/'.$args['notice']); -- case 'deletenotice': -- if ($args && $args['notice']) { -- return common_path('notice/delete/'.$args['notice']); -- } else { -- return common_path('notice/delete'); -- } -- case 'microsummary': -- case 'xrds': -- case 'foaf': -- return common_path($args['nickname'].'/'.$action); -- case 'all': -- case 'replies': -- case 'inbox': -- case 'outbox': -- if ($args && isset($args['page'])) { -- return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); -- } else { -- return common_path($args['nickname'].'/'.$action); -- } -- case 'subscriptions': -- case 'subscribers': -- $nickname = $args['nickname']; -- unset($args['nickname']); -- if (isset($args['tag'])) { -- $tag = $args['tag']; -- unset($args['tag']); -- } -- $params = http_build_query($args); -- if ($params) { -- return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); -- } else { -- return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); -- } -- case 'allrss': -- return common_path($args['nickname'].'/all/rss'); -- case 'repliesrss': -- return common_path($args['nickname'].'/replies/rss'); -- case 'userrss': -+ case 'newnotice': -+ if ($args && $args['replyto']) { -+ return common_path('notice/new?replyto='.$args['replyto']); -+ } else { -+ return common_path('notice/new'); -+ } -+ case 'shownotice': -+ return common_path('notice/'.$args['notice']); -+ case 'deletenotice': -+ if ($args && $args['notice']) { -+ return common_path('notice/delete/'.$args['notice']); -+ } else { -+ return common_path('notice/delete'); -+ } -+ case 'microsummary': -+ case 'xrds': -+ case 'foaf': -+ return common_path($args['nickname'].'/'.$action); -+ case 'all': -+ case 'replies': -+ case 'inbox': -+ case 'outbox': -+ if ($args && isset($args['page'])) { -+ return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']); -+ } else { -+ return common_path($args['nickname'].'/'.$action); -+ } -+ case 'subscriptions': -+ case 'subscribers': -+ $nickname = $args['nickname']; -+ unset($args['nickname']); -+ if (isset($args['tag'])) { -+ $tag = $args['tag']; -+ unset($args['tag']); -+ } -+ $params = http_build_query($args); -+ if ($params) { -+ return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '') . '?' . $params); -+ } else { -+ return common_path($nickname.'/'.$action . (($tag) ? '/' . $tag : '')); -+ } -+ case 'allrss': -+ return common_path($args['nickname'].'/all/rss'); -+ case 'repliesrss': -+ return common_path($args['nickname'].'/replies/rss'); -+ case 'userrss': -hunk ./lib/util.php 1170 -- return common_path($args['nickname'].'/rss?limit=' . $args['limit']); -- return common_path($args['nickname'].'/rss'); -- case 'showstream': -- if ($args && isset($args['page'])) { -- return common_path($args['nickname'].'?page=' . $args['page']); -- } else { -- return common_path($args['nickname']); -- } -+ return common_path($args['nickname'].'/rss?limit=' . $args['limit']); -+ return common_path($args['nickname'].'/rss'); -+ case 'showstream': -+ if ($args && isset($args['page'])) { -+ return common_path($args['nickname'].'?page=' . $args['page']); -+ } else { -+ return common_path($args['nickname']); -+ } -hunk ./lib/util.php 1179 -- case 'usertimeline': -- return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); -- case 'confirmaddress': -- return common_path('main/confirmaddress/'.$args['code']); -- case 'userbyid': -- return common_path('user/'.$args['id']); -- case 'recoverpassword': -- $path = 'main/recoverpassword'; -- if ($args['code']) { -- $path .= '/' . $args['code']; -- } -- return common_path($path); -- case 'imsettings': -- return common_path('settings/im'); -- case 'peoplesearch': -- return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'noticesearch': -- return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'noticesearchrss': -- return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'avatarbynickname': -- return common_path($args['nickname'].'/avatar/'.$args['size']); -- case 'tag': -- if (isset($args['tag']) && $args['tag']) { -- $path = 'tag/' . $args['tag']; -- unset($args['tag']); -- } else { -- $path = 'tags'; -- } -- return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'peopletag': -- $path = 'peopletag/' . $args['tag']; -- unset($args['tag']); -- return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'tags': -- return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'favor': -- return common_path('main/favor'); -- case 'disfavor': -- return common_path('main/disfavor'); -- case 'showfavorites': -- if ($args && isset($args['page'])) { -- return common_path($args['nickname'].'/favorites?page=' . $args['page']); -- } else { -- return common_path($args['nickname'].'/favorites'); -- } -- case 'favoritesrss': -- return common_path($args['nickname'].'/favorites/rss'); -- case 'showmessage': -- return common_path('message/' . $args['message']); -- case 'newmessage': -- return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); -- case 'api': -- # XXX: do fancy URLs for all the API methods -- switch (strtolower($args['apiaction'])) { -- case 'statuses': -- switch (strtolower($args['method'])) { -- case 'user_timeline.rss': -- return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); -- case 'user_timeline.atom': -- return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); -- case 'user_timeline.json': -- return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); -- case 'user_timeline.xml': -- return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); -- default: return common_simple_url($action, $args); -- } -- default: return common_simple_url($action, $args); -- } -- case 'sup': -- if ($args && isset($args['seconds'])) { -- return common_path('main/sup?seconds='.$args['seconds']); -- } else { -- return common_path('main/sup'); -- } -- default: -- return common_simple_url($action, $args); - } -+ case 'usertimeline': -+ return common_path("api/statuses/user_timeline/".$args['nickname'].".atom"); -+ case 'confirmaddress': -+ return common_path('main/confirmaddress/'.$args['code']); -+ case 'userbyid': -+ return common_path('user/'.$args['id']); -+ case 'recoverpassword': -+ $path = 'main/recoverpassword'; -+ if ($args['code']) { -+ $path .= '/' . $args['code']; -+ } -+ return common_path($path); -+ case 'imsettings': -+ return common_path('settings/im'); -+ case 'peoplesearch': -+ return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'noticesearch': -+ return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'noticesearchrss': -+ return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'avatarbynickname': -+ return common_path($args['nickname'].'/avatar/'.$args['size']); -+ case 'tag': -+ if (isset($args['tag']) && $args['tag']) { -+ $path = 'tag/' . $args['tag']; -+ unset($args['tag']); -+ } else { -+ $path = 'tags'; -+ } -+ return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'peopletag': -+ $path = 'peopletag/' . $args['tag']; -+ unset($args['tag']); -+ return common_path($path . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'tags': -+ return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'favor': -+ return common_path('main/favor'); -+ case 'disfavor': -+ return common_path('main/disfavor'); -+ case 'showfavorites': -+ if ($args && isset($args['page'])) { -+ return common_path($args['nickname'].'/favorites?page=' . $args['page']); -+ } else { -+ return common_path($args['nickname'].'/favorites'); -+ } -+ case 'favoritesrss': -+ return common_path($args['nickname'].'/favorites/rss'); -+ case 'showmessage': -+ return common_path('message/' . $args['message']); -+ case 'newmessage': -+ return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : '')); -+ case 'api': -+ // XXX: do fancy URLs for all the API methods -+ switch (strtolower($args['apiaction'])) { -+ case 'statuses': -+ switch (strtolower($args['method'])) { -+ case 'user_timeline.rss': -+ return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss'); -+ case 'user_timeline.atom': -+ return common_path('api/statuses/user_timeline/'.$args['argument'].'.atom'); -+ case 'user_timeline.json': -+ return common_path('api/statuses/user_timeline/'.$args['argument'].'.json'); -+ case 'user_timeline.xml': -+ return common_path('api/statuses/user_timeline/'.$args['argument'].'.xml'); -+ default: return common_simple_url($action, $args); -+ } -+ default: return common_simple_url($action, $args); -+ } -+ case 'sup': -+ if ($args && isset($args['seconds'])) { -+ return common_path('main/sup?seconds='.$args['seconds']); ++ function arg($key, $def=null) ++ { ++ if (array_key_exists($key, $this->args)) { ++ return $this->args[$key]; + } else { -+ return common_path('main/sup'); -+ } -+ default: -+ return common_simple_url($action, $args); -+ } -hunk ./lib/util.php 1259 --function common_simple_url($action, $args=NULL) { -- global $config; -- /* XXX: pretty URLs */ -- $extra = ''; -- if ($args) { -- foreach ($args as $key => $value) { -- $extra .= "&${key}=${value}"; -- } -- } -- return common_path("index.php?action=${action}${extra}"); -+function common_simple_url($action, $args=null) { -+ global $config; -+ /* XXX: pretty URLs */ -+ $extra = ''; -+ if ($args) { -+ foreach ($args as $key => $value) { -+ $extra .= "&${key}=${value}"; ++ return $def; + } + } -+ return common_path("index.php?action=${action}${extra}"); -hunk ./lib/util.php 1272 -- global $config; -- $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; -- return "http://".$config['site']['server'].'/'.$pathpart.$relative; -+ global $config; -+ $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : ''; -+ return "http://".$config['site']['server'].'/'.$pathpart.$relative; -hunk ./lib/util.php 1278 -- // XXX: do some sexy date formatting -- // return date(DATE_RFC822, $dt); -- $t = strtotime($dt); -- $now = time(); -- $diff = $now - $t; -+ // XXX: do some sexy date formatting -+ // return date(DATE_RFC822, $dt); -+ $t = strtotime($dt); -+ $now = time(); -+ $diff = $now - $t; -hunk ./lib/util.php 1284 -- if ($now < $t) { # that shouldn't happen! -- return common_exact_date($dt); -- } else if ($diff < 60) { -- return _('a few seconds ago'); -- } else if ($diff < 92) { -- return _('about a minute ago'); -- } else if ($diff < 3300) { -- return sprintf(_('about %d minutes ago'), round($diff/60)); -- } else if ($diff < 5400) { -- return _('about an hour ago'); -- } else if ($diff < 22 * 3600) { -- return sprintf(_('about %d hours ago'), round($diff/3600)); -- } else if ($diff < 37 * 3600) { -- return _('about a day ago'); -- } else if ($diff < 24 * 24 * 3600) { -- return sprintf(_('about %d days ago'), round($diff/(24*3600))); -- } else if ($diff < 46 * 24 * 3600) { -- return _('about a month ago'); -- } else if ($diff < 330 * 24 * 3600) { -- return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); -- } else if ($diff < 480 * 24 * 3600) { -- return _('about a year ago'); -- } else { -- return common_exact_date($dt); -- } -+ if ($now < $t) { // that shouldn't happen! -+ return common_exact_date($dt); -+ } else if ($diff < 60) { -+ return _('a few seconds ago'); -+ } else if ($diff < 92) { -+ return _('about a minute ago'); -+ } else if ($diff < 3300) { -+ return sprintf(_('about %d minutes ago'), round($diff/60)); -+ } else if ($diff < 5400) { -+ return _('about an hour ago'); -+ } else if ($diff < 22 * 3600) { -+ return sprintf(_('about %d hours ago'), round($diff/3600)); -+ } else if ($diff < 37 * 3600) { -+ return _('about a day ago'); -+ } else if ($diff < 24 * 24 * 3600) { -+ return sprintf(_('about %d days ago'), round($diff/(24*3600))); -+ } else if ($diff < 46 * 24 * 3600) { -+ return _('about a month ago'); -+ } else if ($diff < 330 * 24 * 3600) { -+ return sprintf(_('about %d months ago'), round($diff/(30*24*3600))); -+ } else if ($diff < 480 * 24 * 3600) { -+ return _('about a year ago'); -+ } else { -+ return common_exact_date($dt); -+ } -hunk ./lib/util.php 1320 -- $dateStr = date('d F Y H:i:s', strtotime($dt)); -- $d = new DateTime($dateStr, $_utc); -- $d->setTimezone($_siteTz); -- return $d->format(DATE_RFC850); -+ $dateStr = date('d F Y H:i:s', strtotime($dt)); -+ $d = new DateTime($dateStr, $_utc); -+ $d->setTimezone($_siteTz); -+ return $d->format(DATE_RFC850); -hunk ./lib/util.php 1327 -- $dateStr = date('d F Y H:i:s', strtotime($dt)); -- $d = new DateTime($dateStr, new DateTimeZone('UTC')); -- $d->setTimezone(new DateTimeZone(common_timezone())); -- return $d->format(DATE_W3C); -+ $dateStr = date('d F Y H:i:s', strtotime($dt)); -+ $d = new DateTime($dateStr, new DateTimeZone('UTC')); -+ $d->setTimezone(new DateTimeZone(common_timezone())); -+ return $d->format(DATE_W3C); -hunk ./lib/util.php 1334 -- $dateStr = date('d F Y H:i:s', strtotime($dt)); -- $d = new DateTime($dateStr, new DateTimeZone('UTC')); -- $d->setTimezone(new DateTimeZone(common_timezone())); -- return $d->format('r'); -+ $dateStr = date('d F Y H:i:s', strtotime($dt)); -+ $d = new DateTime($dateStr, new DateTimeZone('UTC')); -+ $d->setTimezone(new DateTimeZone(common_timezone())); -+ return $d->format('r'); -hunk ./lib/util.php 1341 -- $dateStr = date('d F Y H:i:s', strtotime($dt)); -- $d = new DateTime($dateStr, new DateTimeZone('UTC')); -- $d->setTimezone(new DateTimeZone(common_timezone())); -- return $d->format('c'); -+ $dateStr = date('d F Y H:i:s', strtotime($dt)); -+ $d = new DateTime($dateStr, new DateTimeZone('UTC')); -+ $d->setTimezone(new DateTimeZone(common_timezone())); -+ return $d->format('c'); -hunk ./lib/util.php 1348 -- return strftime('%Y-%m-%d %H:%M:%S', time()); -+ return strftime('%Y-%m-%d %H:%M:%S', time()); -hunk ./lib/util.php 1352 -- static $status = array(301 => "Moved Permanently", -- 302 => "Found", -- 303 => "See Other", -- 307 => "Temporary Redirect"); -- header("Status: ${code} $status[$code]"); -- header("Location: $url"); -+ static $status = array(301 => "Moved Permanently", -+ 302 => "Found", -+ 303 => "See Other", -+ 307 => "Temporary Redirect"); -+ header("Status: ${code} $status[$code]"); -+ header("Location: $url"); -hunk ./lib/util.php 1359 -- common_start_xml('a', -- '-//W3C//DTD XHTML 1.0 Strict//EN', -- 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); -- common_element('a', array('href' => $url), $url); -- common_end_xml(); -+ common_start_xml('a', -+ '-//W3C//DTD XHTML 1.0 Strict//EN', -+ 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); -+ common_element('a', array('href' => $url), $url); -+ common_end_xml(); -hunk ./lib/util.php 1368 -- # Alternative reply format -- $tname = false; -- if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { -- $tname = $match[1]; -- } -- # extract all @messages -- $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); -+ // Alternative reply format -+ $tname = false; -+ if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) { -+ $tname = $match[1]; -+ } -+ // extract all @messages -+ $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match); -hunk ./lib/util.php 1376 -- $names = array(); -+ $names = array(); -hunk ./lib/util.php 1378 -- if ($cnt || $tname) { -- # XXX: is there another way to make an array copy? -- $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); -- } -+ if ($cnt || $tname) { -+ // XXX: is there another way to make an array copy? -+ $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]); -+ } -hunk ./lib/util.php 1383 -- $sender = Profile::staticGet($notice->profile_id); -+ $sender = Profile::staticGet($notice->profile_id); -hunk ./lib/util.php 1385 -- $replied = array(); -+ $replied = array(); -hunk ./lib/util.php 1387 -- # store replied only for first @ (what user/notice what the reply directed, -- # we assume first @ is it) -+ // store replied only for first @ (what user/notice what the reply directed, -+ // we assume first @ is it) -hunk ./lib/util.php 1390 -- for ($i=0; $icreated); -- if (!$recipient) { -- continue; -- } -- if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self -- $reply_for = $recipient; -- $recipient_notice = $reply_for->getCurrentNotice(); -- if ($recipient_notice) { -- $orig = clone($notice); -- $notice->reply_to = $recipient_notice->id; -- $notice->update($orig); -- } -- } -- # Don't save replies from blocked profile to local user -+ for ($i=0; $icreated); -+ if (!$recipient) { -+ continue; -+ } -+ if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { // Don't save reply to self -+ $reply_for = $recipient; -+ $recipient_notice = $reply_for->getCurrentNotice(); -+ if ($recipient_notice) { -+ $orig = clone($notice); -+ $notice->reply_to = $recipient_notice->id; -+ $notice->update($orig); -+ } -+ } -+ // Don't save replies from blocked profile to local user -hunk ./lib/util.php 1410 -- $reply = new Reply(); -- $reply->notice_id = $notice->id; -- $reply->profile_id = $recipient->id; -- $id = $reply->insert(); -- if (!$id) { -- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -- common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); -- common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); -- return; -- } else { -- $replied[$recipient->id] = 1; -- } +hunk ./lib/action.php 68 +- function trimmed($key, $def=NULL) { +- $arg = $this->arg($key, $def); +- return (is_string($arg)) ? trim($arg) : $arg; - } -+ $reply = new Reply(); -+ $reply->notice_id = $notice->id; -+ $reply->profile_id = $recipient->id; -+ $id = $reply->insert(); -+ if (!$id) { -+ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -+ common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message); -+ common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message)); -+ return; -+ } else { -+ $replied[$recipient->id] = 1; -+ } -+ } -hunk ./lib/util.php 1424 -- # Hash format replies, too -- $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); -- if ($cnt) { -- foreach ($match[1] as $tag) { -- $tagged = Profile_tag::getTagged($sender->id, $tag); -- foreach ($tagged as $t) { -- if (!$replied[$t->id]) { -- # Don't save replies from blocked profile to local user -+ // Hash format replies, too -+ $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $notice->content, $match); -+ if ($cnt) { -+ foreach ($match[1] as $tag) { -+ $tagged = Profile_tag::getTagged($sender->id, $tag); -+ foreach ($tagged as $t) { -+ if (!$replied[$t->id]) { -+ // Don't save replies from blocked profile to local user -hunk ./lib/util.php 1436 -- $reply = new Reply(); -- $reply->notice_id = $notice->id; -- $reply->profile_id = $t->id; -- $id = $reply->insert(); -- if (!$id) { -- common_log_db_error($reply, 'INSERT', __FILE__); -- return; ++ function trimmed($key, $def=null) ++ { ++ $arg = $this->arg($key, $def); ++ return (is_string($arg)) ? trim($arg) : $arg; ++ } +hunk ./lib/action.php 74 +- # Note: argarray ignored, since it's now passed in in prepare() ++ // Note: argarray ignored, since it's now passed in in prepare() +hunk ./lib/action.php 76 +- function handle($argarray=NULL) { ++ function handle($argarray=null) ++ { +hunk ./lib/action.php 79 +- $lm = $this->last_modified(); +- $etag = $this->etag(); ++ $lm = $this->last_modified(); ++ $etag = $this->etag(); +hunk ./lib/action.php 82 +- if ($etag) { +- header('ETag: ' . $etag); +- } ++ if ($etag) { ++ header('ETag: ' . $etag); ++ } +hunk ./lib/action.php 86 +- 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 ($lm <= $ims) { +- if (!$etag || $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { +- header('HTTP/1.1 304 Not Modified'); +- # Better way to do this? +- exit(0); - } - } - } - } - } -+ $reply = new Reply(); -+ $reply->notice_id = $notice->id; -+ $reply->profile_id = $t->id; -+ $id = $reply->insert(); -+ if (!$id) { -+ common_log_db_error($reply, 'INSERT', __FILE__); -+ return; ++ 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 ($lm <= $ims) { ++ if (!$etag || ++ $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { ++ header('HTTP/1.1 304 Not Modified'); ++ // Better way to do this? ++ exit(0); + } + } + } + } + } -hunk ./lib/util.php 1452 -- // 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) { -+ // 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) { -hunk ./lib/util.php 1456 -- // If it's not a Twitter-style reply, or if the user WANTS to send replies... -+ // If it's not a Twitter-style reply, or if the user WANTS to send replies... -hunk ./lib/util.php 1458 -- if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) || -- (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) { -+ if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) || -+ (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) { -hunk ./lib/util.php 1461 -- $result = common_twitter_broadcast($notice, $flink); -+ $result = common_twitter_broadcast($notice, $flink); -hunk ./lib/util.php 1463 -- if (!$result) { -- common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__); -- } -- } -- } -+ if (!$result) { -+ common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__); -+ } -+ } -+ } -hunk ./lib/util.php 1469 -- if (common_config('queue', 'enabled')) { -- # Do it later! -- return common_enqueue_notice($notice); -- } else { -- return common_real_broadcast($notice, $remote); -- } -+ if (common_config('queue', 'enabled')) { -+ // Do it later! -+ return common_enqueue_notice($notice); -+ } else { -+ return common_real_broadcast($notice, $remote); -+ } -hunk ./lib/util.php 1478 -- global $config; -- $success = true; -- $fuser = $flink->getForeignUser(); -- $twitter_user = $fuser->nickname; -- $twitter_password = $flink->credentials; -- $uri = 'http://www.twitter.com/statuses/update.json'; -+ global $config; -+ $success = true; -+ $fuser = $flink->getForeignUser(); -+ $twitter_user = $fuser->nickname; -+ $twitter_password = $flink->credentials; -+ $uri = 'http://www.twitter.com/statuses/update.json'; -hunk ./lib/util.php 1485 -- // XXX: Hack to get around PHP cURL's use of @ being a a meta character -- $statustxt = preg_replace('/^@/', ' @', $notice->content); -+ // XXX: Hack to get around PHP cURL's use of @ being a a meta character -+ $statustxt = preg_replace('/^@/', ' @', $notice->content); -hunk ./lib/util.php 1488 -- $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 -- ); -+ $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 -+ ); -hunk ./lib/util.php 1504 -- $ch = curl_init($uri); -+ $ch = curl_init($uri); -hunk ./lib/util.php 1509 -- if ($errmsg) { -- common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", -- __FILE__); -- $success = false; +hunk ./lib/action.php 103 +- function _has_etag($etag, $if_none_match) { +- return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); - } -+ if ($errmsg) { -+ common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.", -+ __FILE__); -+ $success = false; -+ } -hunk ./lib/util.php 1515 -- curl_close($ch); -+ curl_close($ch); -hunk ./lib/util.php 1517 -- if (!$data) { -- common_debug("No data returned by Twitter's API trying to send update for $twitter_user", -- __FILE__); -- $success = false; -- } -+ if (!$data) { -+ common_debug("No data returned by Twitter's API trying to send update for $twitter_user", -+ __FILE__); -+ $success = false; -+ } -hunk ./lib/util.php 1523 -- // Twitter should return a status -- $status = json_decode($data); -+ // Twitter should return a status -+ $status = json_decode($data); -hunk ./lib/util.php 1526 -- if (!$status->id) { -- common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user", -- __FILE__); -- $success = false; -- } -+ if (!$status->id) { -+ common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user", -+ __FILE__); -+ $success = false; ++ function _has_etag($etag, $if_none_match) ++ { ++ return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); + } -hunk ./lib/util.php 1532 -- return $success; -+ return $success; -hunk ./lib/util.php 1535 --# Stick the notice on the queue -+// Stick the notice on the queue -hunk ./lib/util.php 1538 -- foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { -- $qi = new Queue_item(); -- $qi->notice_id = $notice->id; -- $qi->transport = $transport; -- $qi->created = $notice->created; -+ foreach (array('jabber', 'omb', 'sms', 'public') as $transport) { -+ $qi = new Queue_item(); -+ $qi->notice_id = $notice->id; -+ $qi->transport = $transport; -+ $qi->created = $notice->created; -hunk ./lib/util.php 1544 -- if (!$result) { -- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -- common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); +hunk ./lib/action.php 108 +- function boolean($key, $def=false) { +- $arg = strtolower($this->trimmed($key)); ++ function boolean($key, $def=false) ++ { ++ $arg = strtolower($this->trimmed($key)); +hunk ./lib/action.php 112 +- if (is_null($arg)) { +- return $def; +- } else if (in_array($arg, array('true', 'yes', '1'))) { +- return true; +- } else if (in_array($arg, array('false', 'no', '0'))) { - return false; -- } -- common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); -- } -- return $result; -+ if (!$result) { -+ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -+ common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message); -+ return false; -+ } -+ common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport); -+ } -+ return $result; -hunk ./lib/util.php 1555 -- $qi = Queue_item::staticGet($notice->id); -- if ($qi) { -- $result = $qi->delete(); -- if (!$result) { -- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -- common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); -- return false; -- } -- common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); -- return $result; -- } else { -+ $qi = Queue_item::staticGet($notice->id); -+ if ($qi) { -+ $result = $qi->delete(); -+ if (!$result) { -+ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -+ common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message); -hunk ./lib/util.php 1563 -+ common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id); -+ return $result; -+ } else { -+ return false; -+ } -hunk ./lib/util.php 1571 -- $success = true; -- if (!$remote) { -- # Make sure we have the OMB stuff -- require_once(INSTALLDIR.'/lib/omb.php'); -- $success = omb_broadcast_remote_subscribers($notice); -- if (!$success) { -- common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); -- } -- } -- if ($success) { -- require_once(INSTALLDIR.'/lib/jabber.php'); -- $success = jabber_broadcast_notice($notice); -- if (!$success) { -- common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); -- } -- } -- if ($success) { -- require_once(INSTALLDIR.'/lib/mail.php'); -- $success = mail_broadcast_notice_sms($notice); -- if (!$success) { -- common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); -- } -- } -- if ($success) { -- $success = jabber_public_notice($notice); -- if (!$success) { -- common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); -- } -- } -- // XXX: broadcast notices to other IM -- return $success; -+ $success = true; -+ if (!$remote) { -+ // Make sure we have the OMB stuff -+ require_once(INSTALLDIR.'/lib/omb.php'); -+ $success = omb_broadcast_remote_subscribers($notice); -+ if (!$success) { -+ common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id); -+ } -+ } -+ if ($success) { -+ require_once(INSTALLDIR.'/lib/jabber.php'); -+ $success = jabber_broadcast_notice($notice); -+ if (!$success) { -+ common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id); -+ } -+ } -+ if ($success) { -+ require_once(INSTALLDIR.'/lib/mail.php'); -+ $success = mail_broadcast_notice_sms($notice); -+ if (!$success) { -+ common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id); -+ } -+ } -+ if ($success) { -+ $success = jabber_public_notice($notice); -+ if (!$success) { -+ common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id); -+ } -+ } -+ // XXX: broadcast notices to other IM -+ return $success; -hunk ./lib/util.php 1605 -- // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ -- require_once(INSTALLDIR.'/lib/omb.php'); -- omb_broadcast_profile($profile); -- // XXX: Other broadcasts...? -- return true; -+ // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ -+ require_once(INSTALLDIR.'/lib/omb.php'); -+ omb_broadcast_profile($profile); -+ // XXX: Other broadcasts...? -+ return true; -hunk ./lib/util.php 1613 -- return common_local_url('showstream', array('nickname' => $nickname)); -+ return common_local_url('showstream', array('nickname' => $nickname)); -hunk ./lib/util.php 1616 --# Don't call if nobody's logged in -+// Don't call if nobody's logged in -hunk ./lib/util.php 1618 --function common_notice_form($action=NULL, $content=NULL) { -- $user = common_current_user(); -- assert(!is_null($user)); -- common_element_start('form', array('id' => 'status_form', -- 'method' => 'post', -- 'action' => common_local_url('newnotice'))); -- common_element_start('p'); -- common_element('label', array('for' => 'status_textarea', -- 'id' => 'status_label'), -- sprintf(_('What\'s up, %s?'), $user->nickname)); -+function common_notice_form($action=null, $content=null) { -+ $user = common_current_user(); -+ assert(!is_null($user)); -+ common_element_start('form', array('id' => 'status_form', -+ 'method' => 'post', -+ 'action' => common_local_url('newnotice'))); -+ common_element_start('p'); -+ common_element('label', array('for' => 'status_textarea', -+ 'id' => 'status_label'), -+ sprintf(_('What\'s up, %s?'), $user->nickname)); -hunk ./lib/util.php 1629 -- common_element('textarea', array('id' => 'status_textarea', -- 'cols' => 60, -- 'rows' => 3, -- 'name' => 'status_textarea'), -- ($content) ? $content : ''); -- common_hidden('token', common_session_token()); -- if ($action) { -- common_hidden('returnto', $action); -- } -- # set by JavaScript -- common_hidden('inreplyto', 'false'); -- common_element('input', array('id' => 'status_submit', -- 'name' => 'status_submit', -- 'type' => 'submit', -- 'value' => _('Send'))); -- common_element_end('p'); -- common_element_end('form'); -+ common_element('textarea', array('id' => 'status_textarea', -+ 'cols' => 60, -+ 'rows' => 3, -+ 'name' => 'status_textarea'), -+ ($content) ? $content : ''); -+ common_hidden('token', common_session_token()); -+ if ($action) { -+ common_hidden('returnto', $action); -+ } -+ // set by JavaScript -+ common_hidden('inreplyto', 'false'); -+ common_element('input', array('id' => 'status_submit', -+ 'name' => 'status_submit', -+ 'type' => 'submit', -+ 'value' => _('Send'))); -+ common_element_end('p'); -+ common_element_end('form'); -hunk ./lib/util.php 1648 --# Should make up a reasonable root URL -+// Should make up a reasonable root URL -hunk ./lib/util.php 1651 -- return common_path(''); -+ return common_path(''); -hunk ./lib/util.php 1654 --# returns $bytes bytes of random data as a hexadecimal string --# "good" here is a goal and not a guarantee -+// returns $bytes bytes of random data as a hexadecimal string -+// "good" here is a goal and not a guarantee -hunk ./lib/util.php 1658 -- # XXX: use random.org...? -- if (file_exists('/dev/urandom')) { -- return common_urandom($bytes); -- } else { # FIXME: this is probably not good enough -- return common_mtrand($bytes); -- } -+ // XXX: use random.org...? -+ if (file_exists('/dev/urandom')) { -+ return common_urandom($bytes); -+ } else { // FIXME: this is probably not good enough -+ return common_mtrand($bytes); -+ } -hunk ./lib/util.php 1667 -- $h = fopen('/dev/urandom', 'rb'); -- # should not block -- $src = fread($h, $bytes); -- fclose($h); -- $enc = ''; -- for ($i = 0; $i < $bytes; $i++) { -- $enc .= sprintf("%02x", (ord($src[$i]))); -- } -- return $enc; -+ $h = fopen('/dev/urandom', 'rb'); -+ // should not block -+ $src = fread($h, $bytes); -+ fclose($h); -+ $enc = ''; -+ for ($i = 0; $i < $bytes; $i++) { -+ $enc .= sprintf("%02x", (ord($src[$i]))); -+ } -+ return $enc; -hunk ./lib/util.php 1679 -- $enc = ''; -- for ($i = 0; $i < $bytes; $i++) { -- $enc .= sprintf("%02x", mt_rand(0, 255)); -- } -- return $enc; -+ $enc = ''; -+ for ($i = 0; $i < $bytes; $i++) { -+ $enc .= sprintf("%02x", mt_rand(0, 255)); -+ } -+ return $enc; -hunk ./lib/util.php 1687 -- common_ensure_session(); -- $_SESSION['returnto'] = $url; -+ common_ensure_session(); -+ $_SESSION['returnto'] = $url; -hunk ./lib/util.php 1692 -- common_ensure_session(); -- return $_SESSION['returnto']; -+ common_ensure_session(); -+ return $_SESSION['returnto']; -hunk ./lib/util.php 1697 -- return date('YmdHis'); -+ return date('YmdHis'); -hunk ./lib/util.php 1701 -- static $initialized = false; -- if (!$initialized) { -- global $config; -- openlog($config['syslog']['appname'], 0, LOG_USER); -- $initialized = true; -- } -+ static $initialized = false; -+ if (!$initialized) { -+ global $config; -+ openlog($config['syslog']['appname'], 0, LOG_USER); -+ $initialized = true; -+ } -hunk ./lib/util.php 1709 --function common_log($priority, $msg, $filename=NULL) { -- $logfile = common_config('site', 'logfile'); -- if ($logfile) { -- $log = fopen($logfile, "a"); -- if ($log) { -- static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', -- 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); -- $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; -- fwrite($log, $output); -- fclose($log); -- } -- } else { -- common_ensure_syslog(); -- syslog($priority, $msg); -- } -+function common_log($priority, $msg, $filename=null) { -+ $logfile = common_config('site', 'logfile'); -+ if ($logfile) { -+ $log = fopen($logfile, "a"); -+ if ($log) { -+ static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR', -+ 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG'); -+ $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; -+ fwrite($log, $output); -+ fclose($log); -+ } -+ } else { -+ common_ensure_syslog(); -+ syslog($priority, $msg); -+ } -hunk ./lib/util.php 1726 --function common_debug($msg, $filename=NULL) { -- if ($filename) { -- common_log(LOG_DEBUG, basename($filename).' - '.$msg); -- } else { -- common_log(LOG_DEBUG, $msg); -- } -+function common_debug($msg, $filename=null) { -+ if ($filename) { -+ common_log(LOG_DEBUG, basename($filename).' - '.$msg); -+ } else { -+ common_log(LOG_DEBUG, $msg); -+ } -hunk ./lib/util.php 1734 --function common_log_db_error(&$object, $verb, $filename=NULL) { -- $objstr = common_log_objstring($object); -- $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -- common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); -+function common_log_db_error(&$object, $verb, $filename=null) { -+ $objstr = common_log_objstring($object); -+ $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError'); -+ common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename); -hunk ./lib/util.php 1741 -- if (is_null($object)) { -- return "NULL"; -- } -- $arr = $object->toArray(); -- $fields = array(); -- foreach ($arr as $k => $v) { -- $fields[] = "$k='$v'"; -- } -- $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; -- return $objstring; -+ if (is_null($object)) { -+ return "null"; -+ } -+ $arr = $object->toArray(); -+ $fields = array(); -+ foreach ($arr as $k => $v) { -+ $fields[] = "$k='$v'"; -+ } -+ $objstring = $object->tableName() . '[' . implode(',', $fields) . ']'; -+ return $objstring; -hunk ./lib/util.php 1754 -- return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); -+ return Validate::uri($url, array('allowed_schemes' => array('http', 'https'))); -hunk ./lib/util.php 1758 -- if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { -- return (Validate::email($matches[1]) || -- preg_match('/^([\w-\.]+)$/', $matches[1])); -- } -- return false; -+ if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) { -+ return (Validate::email($matches[1]) || -+ preg_match('/^([\w-\.]+)$/', $matches[1])); -+ } -+ return false; -hunk ./lib/util.php 1765 --# Does a little before-after block for next/prev page -+// Does a little before-after block for next/prev page -hunk ./lib/util.php 1767 --function common_pagination($have_before, $have_after, $page, $action, $args=NULL) { -+function common_pagination($have_before, $have_after, $page, $action, $args=null) { -hunk ./lib/util.php 1769 -- if ($have_before || $have_after) { -- common_element_start('div', array('id' => 'pagination')); -- common_element_start('ul', array('id' => 'nav_pagination')); -- } -+ if ($have_before || $have_after) { -+ common_element_start('div', array('id' => 'pagination')); -+ common_element_start('ul', array('id' => 'nav_pagination')); -+ } -hunk ./lib/util.php 1774 -- if ($have_before) { -- $pargs = array('page' => $page-1); -- $newargs = ($args) ? array_merge($args,$pargs) : $pargs; -+ if ($have_before) { -+ $pargs = array('page' => $page-1); -+ $newargs = ($args) ? array_merge($args,$pargs) : $pargs; -hunk ./lib/util.php 1778 -- common_element_start('li', 'before'); -- common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), -- _('« After')); -- common_element_end('li'); -- } -+ common_element_start('li', 'before'); -+ common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'prev'), -+ _('« After')); -+ common_element_end('li'); -+ } -hunk ./lib/util.php 1784 -- if ($have_after) { -- $pargs = array('page' => $page+1); -- $newargs = ($args) ? array_merge($args,$pargs) : $pargs; -- common_element_start('li', 'after'); -- common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), -- _('Before »')); -- common_element_end('li'); -- } -+ if ($have_after) { -+ $pargs = array('page' => $page+1); -+ $newargs = ($args) ? array_merge($args,$pargs) : $pargs; -+ common_element_start('li', 'after'); -+ common_element('a', array('href' => common_local_url($action, $newargs), 'rel' => 'next'), -+ _('Before »')); -+ common_element_end('li'); -+ } -hunk ./lib/util.php 1793 -- if ($have_before || $have_after) { -- common_element_end('ul'); -- common_element_end('div'); -- } -+ if ($have_before || $have_after) { -+ common_element_end('ul'); -+ common_element_end('div'); -+ } -hunk ./lib/util.php 1803 -- # No arg means accept anything (per HTTP spec) -- if(!$accept) { -- return array($def => 1); -- } -+ // No arg means accept anything (per HTTP spec) -+ if(!$accept) { -+ return array($def => 1); -+ } -hunk ./lib/util.php 1808 -- $prefs = array(); -+ $prefs = array(); -hunk ./lib/util.php 1810 -- $parts = explode(',', $accept); -+ $parts = explode(',', $accept); -hunk ./lib/util.php 1812 -- foreach($parts as $part) { -- # FIXME: doesn't deal with params like 'text/html; level=1' -- @list($value, $qpart) = explode(';', $part); -- $match = array(); -- if(!isset($qpart)) { -- $prefs[$value] = 1; -- } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { -- $prefs[$value] = $match[1]; -- } -- } -+ foreach($parts as $part) { -+ // FIXME: doesn't deal with params like 'text/html; level=1' -+ @list($value, $qpart) = explode(';', $part); -+ $match = array(); -+ if(!isset($qpart)) { -+ $prefs[$value] = 1; -+ } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) { -+ $prefs[$value] = $match[1]; -+ } -+ } -hunk ./lib/util.php 1823 -- return $prefs; -+ return $prefs; -hunk ./lib/util.php 1827 -- if(array_key_exists($type, $avail)) { -- return $type; -- } else { -- $parts = explode('/', $type); -- if(array_key_exists($parts[0] . '/*', $avail)) { -- return $parts[0] . '/*'; -- } elseif(array_key_exists('*/*', $avail)) { -- return '*/*'; - } else { -- return NULL; +- return $def; - } - } -+ if(array_key_exists($type, $avail)) { -+ return $type; -+ } else { -+ $parts = explode('/', $type); -+ if(array_key_exists($parts[0] . '/*', $avail)) { -+ return $parts[0] . '/*'; -+ } elseif(array_key_exists('*/*', $avail)) { -+ return '*/*'; ++ if (is_null($arg)) { ++ return $def; ++ } else if (in_array($arg, array('true', 'yes', '1'))) { ++ return true; ++ } else if (in_array($arg, array('false', 'no', '0'))) { ++ return false; + } else { -+ return null; ++ return $def; + } + } -hunk ./lib/util.php 1842 -- $combine = array(); -+ $combine = array(); -hunk ./lib/util.php 1844 -- foreach(array_keys($sprefs) as $type) { -- $parts = explode('/', $type); -- if($parts[1] != '*') { -- $ckey = common_mime_type_match($type, $cprefs); -- if($ckey) { -- $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; -- } -- } -- } -+ foreach(array_keys($sprefs) as $type) { -+ $parts = explode('/', $type); -+ if($parts[1] != '*') { -+ $ckey = common_mime_type_match($type, $cprefs); -+ if($ckey) { -+ $combine[$type] = $sprefs[$type] * $cprefs[$ckey]; -+ } -+ } -+ } -hunk ./lib/util.php 1854 -- foreach(array_keys($cprefs) as $type) { -- $parts = explode('/', $type); -- if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { -- $skey = common_mime_type_match($type, $sprefs); -- if($skey) { -- $combine[$type] = $sprefs[$skey] * $cprefs[$type]; -- } -- } -- } -+ foreach(array_keys($cprefs) as $type) { -+ $parts = explode('/', $type); -+ if($parts[1] != '*' && !array_key_exists($type, $sprefs)) { -+ $skey = common_mime_type_match($type, $sprefs); -+ if($skey) { -+ $combine[$type] = $sprefs[$skey] * $cprefs[$type]; -+ } -+ } -+ } -hunk ./lib/util.php 1864 -- $bestq = 0; -- $besttype = "text/html"; -+ $bestq = 0; -+ $besttype = "text/html"; -hunk ./lib/util.php 1867 -- foreach(array_keys($combine) as $type) { -- if($combine[$type] > $bestq) { -- $besttype = $type; -- $bestq = $combine[$type]; -- } -- } -+ foreach(array_keys($combine) as $type) { -+ if($combine[$type] > $bestq) { -+ $besttype = $type; -+ $bestq = $combine[$type]; -+ } -+ } -hunk ./lib/util.php 1874 -- return $besttype; -+ return $besttype; -hunk ./lib/util.php 1878 -- global $config; -- return isset($config[$main][$sub]) ? $config[$main][$sub] : false; -+ global $config; -+ return isset($config[$main][$sub]) ? $config[$main][$sub] : false; -hunk ./lib/util.php 1883 -- $to = array(); -- $strip = get_magic_quotes_gpc(); -- foreach ($from as $k => $v) { -- $to[$k] = ($strip) ? stripslashes($v) : $v; -- } -- return $to; -+ $to = array(); -+ $strip = get_magic_quotes_gpc(); -+ foreach ($from as $k => $v) { -+ $to[$k] = ($strip) ? stripslashes($v) : $v; -+ } -+ return $to; -hunk ./lib/util.php 1894 -- if(get_magic_quotes_gpc()) { -- $_POST=array_map('stripslashes',$_POST); -- $_GET=array_map('stripslashes',$_GET); -- } -+ if(get_magic_quotes_gpc()) { -+ $_POST=array_map('stripslashes',$_POST); -+ $_GET=array_map('stripslashes',$_GET); -+ } -hunk ./lib/util.php 1901 -- return common_local_url('userbyid', array('id' => $user->id)); -+ return common_local_url('userbyid', array('id' => $user->id)); -hunk ./lib/util.php 1905 -- return common_local_url('shownotice', -- array('notice' => $notice->id)); -+ return common_local_url('shownotice', -+ array('notice' => $notice->id)); -hunk ./lib/util.php 1909 --# 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits -+// 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits -hunk ./lib/util.php 1912 -- # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits -- static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; -- $chars = ceil($bits/5); -- $code = ''; -- for ($i = 0; $i < $chars; $i++) { -- # XXX: convert to string and back -- $num = hexdec(common_good_rand(1)); -- # XXX: randomness is too precious to throw away almost -- # 40% of the bits we get! -- $code .= $codechars[$num%32]; -- } -- return $code; -+ // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits -+ static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; -+ $chars = ceil($bits/5); -+ $code = ''; -+ for ($i = 0; $i < $chars; $i++) { -+ // XXX: convert to string and back -+ $num = hexdec(common_good_rand(1)); -+ // XXX: randomness is too precious to throw away almost -+ // 40% of the bits we get! -+ $code .= $codechars[$num%32]; -+ } -+ return $code; -hunk ./lib/util.php 1926 --# convert markup to HTML -+// convert markup to HTML -hunk ./lib/util.php 1929 -- $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); -- $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); -- $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); -- return Markdown($c); -+ $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c); -+ $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c); -+ $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c); -+ return Markdown($c); -hunk ./lib/util.php 1936 -- $avatar = $profile->getAvatar($size); -- if ($avatar) { -- return common_avatar_display_url($avatar); -- } else { -- return common_default_avatar($size); +hunk ./lib/action.php 123 +- function server_error($msg, $code=500) { +- $action = $this->trimmed('action'); +- common_debug("Server error '$code' on '$action': $msg", __FILE__); +- common_server_error($msg, $code); - } -+ $avatar = $profile->getAvatar($size); -+ if ($avatar) { -+ return common_avatar_display_url($avatar); -+ } else { -+ return common_default_avatar($size); -+ } -hunk ./lib/util.php 1945 -- if (!$profile) { -- return NULL; -- } -- $user = User::staticGet($profile->id); -- if ($user) { -- return $user->uri; -- } -+ if (!$profile) { -+ return null; -+ } -+ $user = User::staticGet($profile->id); -+ if ($user) { -+ return $user->uri; -+ } -hunk ./lib/util.php 1953 -- $remote = Remote_profile::staticGet($profile->id); -- if ($remote) { -- return $remote->uri; -- } -- # XXX: this is a very bad profile! -- return NULL; -+ $remote = Remote_profile::staticGet($profile->id); -+ if ($remote) { -+ return $remote->uri; -+ } -+ // XXX: this is a very bad profile! -+ return null; -hunk ./lib/util.php 1962 -- # strip non-digits -- preg_replace('/\D/', '', $sms); -- return $sms; -+ // strip non-digits -+ preg_replace('/\D/', '', $sms); -+ return $sms; -hunk ./lib/util.php 1970 -- common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); -- exit(1); -- break; -+ common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)"); -+ exit(1); -+ break; -hunk ./lib/util.php 1974 -- case E_USER_WARNING: -- common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); -- break; -+ case E_USER_WARNING: -+ common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)"); -+ break; -hunk ./lib/util.php 1979 -- common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); -- break; -+ common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)"); -+ break; -hunk ./lib/util.php 1983 -- # FIXME: show error page if we're on the Web -+ // FIXME: show error page if we're on the Web -hunk ./lib/util.php 1989 -- common_ensure_session(); -- if (!array_key_exists('token', $_SESSION)) { -- $_SESSION['token'] = common_good_rand(64); -- } -- return $_SESSION['token']; -+ common_ensure_session(); -+ if (!array_key_exists('token', $_SESSION)) { -+ $_SESSION['token'] = common_good_rand(64); ++ function server_error($msg, $code=500) ++ { ++ $action = $this->trimmed('action'); ++ common_debug("Server error '$code' on '$action': $msg", __FILE__); ++ common_server_error($msg, $code); + } -+ return $_SESSION['token']; -hunk ./lib/util.php 1997 -- common_element_start('form', array('id' => 'disfavor-' . $notice->id, -- 'method' => 'post', -- 'class' => 'disfavor', -- 'action' => common_local_url('disfavor'))); -+ common_element_start('form', array('id' => 'disfavor-' . $notice->id, -+ 'method' => 'post', -+ 'class' => 'disfavor', -+ 'action' => common_local_url('disfavor'))); -hunk ./lib/util.php 2002 -- common_element('input', array('type' => 'hidden', -- 'name' => 'token-'. $notice->id, -- 'id' => 'token-'. $notice->id, -- 'class' => 'token', -- 'value' => common_session_token())); -+ common_element('input', array('type' => 'hidden', -+ 'name' => 'token-'. $notice->id, -+ 'id' => 'token-'. $notice->id, -+ 'class' => 'token', -+ 'value' => common_session_token())); -hunk ./lib/util.php 2008 -- common_element('input', array('type' => 'hidden', -- 'name' => 'notice', -- 'id' => 'notice-n'. $notice->id, -- 'class' => 'notice', -- 'value' => $notice->id)); -+ common_element('input', array('type' => 'hidden', -+ 'name' => 'notice', -+ 'id' => 'notice-n'. $notice->id, -+ 'class' => 'notice', -+ 'value' => $notice->id)); -hunk ./lib/util.php 2014 -- common_element('input', array('type' => 'submit', -- 'id' => 'disfavor-submit-' . $notice->id, -- 'name' => 'disfavor-submit-' . $notice->id, -- 'class' => 'disfavor', -- 'value' => 'Disfavor favorite', -- 'title' => 'Remove this message from favorites')); -- common_element_end('form'); -+ common_element('input', array('type' => 'submit', -+ 'id' => 'disfavor-submit-' . $notice->id, -+ 'name' => 'disfavor-submit-' . $notice->id, -+ 'class' => 'disfavor', -+ 'value' => 'Disfavor favorite', -+ 'title' => 'Remove this message from favorites')); -+ common_element_end('form'); -hunk ./lib/util.php 2024 -- common_element_start('form', array('id' => 'favor-' . $notice->id, -- 'method' => 'post', -- 'class' => 'favor', -- 'action' => common_local_url('favor'))); -+ common_element_start('form', array('id' => 'favor-' . $notice->id, -+ 'method' => 'post', -+ 'class' => 'favor', -+ 'action' => common_local_url('favor'))); -hunk ./lib/util.php 2029 -- common_element('input', array('type' => 'hidden', -- 'name' => 'token-'. $notice->id, -- 'id' => 'token-'. $notice->id, -- 'class' => 'token', -- 'value' => common_session_token())); -+ common_element('input', array('type' => 'hidden', -+ 'name' => 'token-'. $notice->id, -+ 'id' => 'token-'. $notice->id, -+ 'class' => 'token', -+ 'value' => common_session_token())); -hunk ./lib/util.php 2035 -- common_element('input', array('type' => 'hidden', -- 'name' => 'notice', -- 'id' => 'notice-n'. $notice->id, -- 'class' => 'notice', -- 'value' => $notice->id)); -+ common_element('input', array('type' => 'hidden', -+ 'name' => 'notice', -+ 'id' => 'notice-n'. $notice->id, -+ 'class' => 'notice', -+ 'value' => $notice->id)); -hunk ./lib/util.php 2041 -- common_element('input', array('type' => 'submit', -- 'id' => 'favor-submit-' . $notice->id, -- 'name' => 'favor-submit-' . $notice->id, -- 'class' => 'favor', -- 'value' => 'Add to favorites', -- 'title' => 'Add this message to favorites')); -- common_element_end('form'); -+ common_element('input', array('type' => 'submit', -+ 'id' => 'favor-submit-' . $notice->id, -+ 'name' => 'favor-submit-' . $notice->id, -+ 'class' => 'favor', -+ 'value' => 'Add to favorites', -+ 'title' => 'Add this message to favorites')); -+ common_element_end('form'); -hunk ./lib/util.php 2051 -- common_element_start('form', array('id' => 'nudge', 'method' => 'post', -- 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); -- common_hidden('token', common_session_token()); -- common_element('input', array('type' => 'submit', -- 'class' => 'submit', -- 'value' => _('Send a nudge'))); -- common_element_end('form'); -+ common_element_start('form', array('id' => 'nudge', 'method' => 'post', -+ 'action' => common_local_url('nudge', array('nickname' => $profile->nickname)))); -+ common_hidden('token', common_session_token()); -+ common_element('input', array('type' => 'submit', -+ 'class' => 'submit', -+ 'value' => _('Send a nudge'))); -+ common_element_end('form'); -hunk ./lib/util.php 2060 -- common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); -+ common_element('p', array('id' => 'nudge_response'), _('Nudge sent!')); -hunk ./lib/util.php 2064 -- common_element_start('form', array('id' => 'subscribe-' . $profile->id, -- 'method' => 'post', -- 'class' => 'subscribe', -- 'action' => common_local_url('subscribe'))); -- common_hidden('token', common_session_token()); -- common_element('input', array('id' => 'subscribeto-' . $profile->id, -- 'name' => 'subscribeto', -- 'type' => 'hidden', -- 'value' => $profile->id)); -- common_element('input', array('type' => 'submit', -- 'class' => 'submit', -- 'value' => _('Subscribe'))); -- common_element_end('form'); -+ common_element_start('form', array('id' => 'subscribe-' . $profile->id, -+ 'method' => 'post', -+ 'class' => 'subscribe', -+ 'action' => common_local_url('subscribe'))); -+ common_hidden('token', common_session_token()); -+ common_element('input', array('id' => 'subscribeto-' . $profile->id, -+ 'name' => 'subscribeto', -+ 'type' => 'hidden', -+ 'value' => $profile->id)); -+ common_element('input', array('type' => 'submit', -+ 'class' => 'submit', -+ 'value' => _('Subscribe'))); -+ common_element_end('form'); -hunk ./lib/util.php 2080 -- common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, -- 'method' => 'post', -- 'class' => 'unsubscribe', -- 'action' => common_local_url('unsubscribe'))); -- common_hidden('token', common_session_token()); -- common_element('input', array('id' => 'unsubscribeto-' . $profile->id, -- 'name' => 'unsubscribeto', -- 'type' => 'hidden', -- 'value' => $profile->id)); -- common_element('input', array('type' => 'submit', -- 'class' => 'submit', -- 'value' => _('Unsubscribe'))); -- common_element_end('form'); -+ common_element_start('form', array('id' => 'unsubscribe-' . $profile->id, -+ 'method' => 'post', -+ 'class' => 'unsubscribe', -+ 'action' => common_local_url('unsubscribe'))); -+ common_hidden('token', common_session_token()); -+ common_element('input', array('id' => 'unsubscribeto-' . $profile->id, -+ 'name' => 'unsubscribeto', -+ 'type' => 'hidden', -+ 'value' => $profile->id)); -+ common_element('input', array('type' => 'submit', -+ 'class' => 'submit', -+ 'value' => _('Unsubscribe'))); -+ common_element_end('form'); -hunk ./lib/util.php 2097 -- $user = User::staticGet('id', $profile->id); -+ $user = User::staticGet('id', $profile->id); -hunk ./lib/util.php 2099 -- if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { -+ if ($cur && $cur->id != $user->id && $cur->mutuallySubscribed($user)) { -hunk ./lib/util.php 2101 -- common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), -- _('Send a message')); -+ common_element('a', array('href' => common_local_url('newmessage', array('to' => $user->id))), -+ _('Send a message')); -hunk ./lib/util.php 2105 -- if ($user->email && $user->emailnotifynudge) { -+ if ($user->email && $user->emailnotifynudge) { -hunk ./lib/util.php 2110 +hunk ./lib/action.php 130 +- function client_error($msg, $code=400) { +- $action = $this->trimmed('action'); +- common_debug("User error '$code' on '$action': $msg", __FILE__); +- common_user_error($msg, $code); - } ++ function client_error($msg, $code=400) ++ { ++ $action = $this->trimmed('action'); ++ common_debug("User error '$code' on '$action': $msg", __FILE__); ++ common_user_error($msg, $code); + } -hunk ./lib/util.php 2114 -- return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; -+ return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra; -hunk ./lib/util.php 2118 -- $str = strtolower($str); -- $str = preg_replace('/\s/', '_', $str); -- return $str; -+ $str = strtolower($str); -+ $str = preg_replace('/\s/', '_', $str); -+ return $str; -hunk ./lib/util.php 2125 -- common_element_start('form', array('id' => 'message_form', -- 'method' => 'post', -- 'action' => common_local_url('newmessage'))); -+ common_element_start('form', array('id' => 'message_form', -+ 'method' => 'post', -+ 'action' => common_local_url('newmessage'))); -hunk ./lib/util.php 2129 -- $mutual_users = $user->mutuallySubscribedUsers(); -+ $mutual_users = $user->mutuallySubscribedUsers(); -hunk ./lib/util.php 2131 -- $mutual = array(); -+ $mutual = array(); -hunk ./lib/util.php 2133 -- while ($mutual_users->fetch()) { -- if ($mutual_users->id != $user->id) { -- $mutual[$mutual_users->id] = $mutual_users->nickname; +hunk ./lib/action.php 137 +- function self_url() { +- $action = $this->trimmed('action'); +- $args = $this->args; +- unset($args['action']); +- foreach (array_keys($_COOKIE) as $cookie) { +- unset($args[$cookie]); - } +- return common_local_url($action, $args); - } -+ while ($mutual_users->fetch()) { -+ if ($mutual_users->id != $user->id) { -+ $mutual[$mutual_users->id] = $mutual_users->nickname; ++ function self_url() ++ { ++ $action = $this->trimmed('action'); ++ $args = $this->args; ++ unset($args['action']); ++ foreach (array_keys($_COOKIE) as $cookie) { ++ unset($args[$cookie]); + } ++ return common_local_url($action, $args); + } -hunk ./lib/util.php 2139 -- $mutual_users->free(); -- unset($mutual_users); -+ $mutual_users->free(); -+ unset($mutual_users); -hunk ./lib/util.php 2142 -- common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id); -+ common_dropdown('to', _('To'), $mutual, null, FALSE, $to->id); -hunk ./lib/util.php 2144 -- common_element_start('p'); -+ common_element_start('p'); -hunk ./lib/util.php 2146 -- common_element('textarea', array('id' => 'message_content', -- 'cols' => 60, -- 'rows' => 3, -- 'name' => 'content'), -- ($content) ? $content : ''); -+ common_element('textarea', array('id' => 'message_content', -+ 'cols' => 60, -+ 'rows' => 3, -+ 'name' => 'content'), -+ ($content) ? $content : ''); -hunk ./lib/util.php 2152 -- common_element('input', array('id' => 'message_send', -- 'name' => 'message_send', -- 'type' => 'submit', -- 'value' => _('Send'))); -+ common_element('input', array('id' => 'message_send', -+ 'name' => 'message_send', -+ 'type' => 'submit', -+ 'value' => _('Send'))); -hunk ./lib/util.php 2157 -- common_hidden('token', common_session_token()); -+ common_hidden('token', common_session_token()); -hunk ./lib/util.php 2159 -- common_element_end('p'); -- common_element_end('form'); -+ common_element_end('p'); -+ common_element_end('form'); -hunk ./lib/util.php 2164 -- static $cache = NULL; -- if (!common_config('memcached', 'enabled')) { -- return NULL; -- } else { -- if (!$cache) { -- $cache = new Memcache(); -- $servers = common_config('memcached', 'server'); -- if (is_array($servers)) { -- foreach($servers as $server) { -- $cache->addServer($server); -- } -- } else { -- $cache->addServer($servers); -- } -- } -- return $cache; +hunk ./lib/action.php 148 +- function nav_menu($menu) { ++ function nav_menu($menu) ++ { +hunk ./lib/action.php 153 +- common_menu_item(common_local_url($menuaction, isset($menudesc[2]) ? $menudesc[2] : NULL), +- $menudesc[0], +- $menudesc[1], +- $action == $menuaction); ++ common_menu_item(common_local_url($menuaction, ++ isset($menudesc[2]) ? $menudesc[2] : null), ++ $menudesc[0], ++ $menudesc[1], ++ $action == $menuaction); +hunk ./lib/action.php 160 - } -+ static $cache = null; -+ if (!common_config('memcached', 'enabled')) { -+ return null; -+ } else { -+ if (!$cache) { -+ $cache = new Memcache(); -+ $servers = common_config('memcached', 'server'); -+ if (is_array($servers)) { -+ foreach($servers as $server) { -+ $cache->addServer($server); -+ } -+ } else { -+ $cache->addServer($servers); -+ } -+ } -+ return $cache; + } -hunk ./lib/util.php 2184 -- # XXX: better compatibility check needed here! -- return ($from == $to); -+ // XXX: better compatibility check needed here! -+ return ($from == $to); -hunk ./lib/util.php 2190 --function common_block_form($profile, $args=NULL) { -+function common_block_form($profile, $args=null) { -hunk ./lib/util.php 2194 --function common_unblock_form($profile, $args=NULL) { -+function common_unblock_form($profile, $args=null) { -hunk ./lib/util.php 2198 --function common_blocking_form($type, $label, $profile, $args=NULL) { -+function common_blocking_form($type, $label, $profile, $args=null) { -hunk ./lib/util.php 2220 -- diff --git a/lib/action.php b/lib/action.php index 7a2461bb5..486b40387 100644 --- a/lib/action.php +++ b/lib/action.php @@ -1,5 +1,5 @@ . */ -if (!defined('LACONICA')) { exit(1); } - -class Action { // lawsuit - - var $args; - - function Action() { - } - - # For initializing members of the class - - function prepare($argarray) { - $this->args =& common_copy_args($argarray); - return true; - } - - # For comparison with If-Last-Modified - # If not applicable, return NULL - - function last_modified() { - return NULL; - } - - function etag() { - return NULL; - } - - function is_readonly() { - return false; - } - - function arg($key, $def=NULL) { - if (array_key_exists($key, $this->args)) { - return $this->args[$key]; - } else { - return $def; - } - } - - function trimmed($key, $def=NULL) { - $arg = $this->arg($key, $def); - return (is_string($arg)) ? trim($arg) : $arg; - } - - # Note: argarray ignored, since it's now passed in in prepare() - - function handle($argarray=NULL) { - - $lm = $this->last_modified(); - $etag = $this->etag(); - - if ($etag) { - header('ETag: ' . $etag); - } - - 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 ($lm <= $ims) { - if (!$etag || $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { - header('HTTP/1.1 304 Not Modified'); - # Better way to do this? - exit(0); - } - } - } - } - } - - function _has_etag($etag, $if_none_match) { - return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); - } - - function boolean($key, $def=false) { - $arg = strtolower($this->trimmed($key)); - - if (is_null($arg)) { - return $def; - } else if (in_array($arg, array('true', 'yes', '1'))) { - return true; - } else if (in_array($arg, array('false', 'no', '0'))) { - return false; - } else { - return $def; - } - } - - function server_error($msg, $code=500) { - $action = $this->trimmed('action'); - common_debug("Server error '$code' on '$action': $msg", __FILE__); - common_server_error($msg, $code); - } - - function client_error($msg, $code=400) { - $action = $this->trimmed('action'); - common_debug("User error '$code' on '$action': $msg", __FILE__); - common_user_error($msg, $code); - } - - function self_url() { - $action = $this->trimmed('action'); - $args = $this->args; - unset($args['action']); - foreach (array_keys($_COOKIE) as $cookie) { - unset($args[$cookie]); - } - return common_local_url($action, $args); - } - - function nav_menu($menu) { +if (!defined('LACONICA')) { + exit(1); +} + +class Action // lawsuit +{ + + var $args; + + function Action() + { + } + + // For initializing members of the class + + function prepare($argarray) + { + $this->args =& common_copy_args($argarray); + return true; + } + + // For comparison with If-Last-Modified + // If not applicable, return null + + function last_modified() + { + return null; + } + + function etag() + { + return null; + } + + function is_readonly() + { + return false; + } + + function arg($key, $def=null) + { + if (array_key_exists($key, $this->args)) { + return $this->args[$key]; + } else { + return $def; + } + } + + function trimmed($key, $def=null) + { + $arg = $this->arg($key, $def); + return (is_string($arg)) ? trim($arg) : $arg; + } + + // Note: argarray ignored, since it's now passed in in prepare() + + function handle($argarray=null) + { + + $lm = $this->last_modified(); + $etag = $this->etag(); + + if ($etag) { + header('ETag: ' . $etag); + } + + 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 ($lm <= $ims) { + if (!$etag || + $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { + header('HTTP/1.1 304 Not Modified'); + // Better way to do this? + exit(0); + } + } + } + } + } + + function _has_etag($etag, $if_none_match) + { + return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); + } + + function boolean($key, $def=false) + { + $arg = strtolower($this->trimmed($key)); + + if (is_null($arg)) { + return $def; + } else if (in_array($arg, array('true', 'yes', '1'))) { + return true; + } else if (in_array($arg, array('false', 'no', '0'))) { + return false; + } else { + return $def; + } + } + + function server_error($msg, $code=500) + { + $action = $this->trimmed('action'); + common_debug("Server error '$code' on '$action': $msg", __FILE__); + common_server_error($msg, $code); + } + + function client_error($msg, $code=400) + { + $action = $this->trimmed('action'); + common_debug("User error '$code' on '$action': $msg", __FILE__); + common_user_error($msg, $code); + } + + function self_url() + { + $action = $this->trimmed('action'); + $args = $this->args; + unset($args['action']); + foreach (array_keys($_COOKIE) as $cookie) { + unset($args[$cookie]); + } + return common_local_url($action, $args); + } + + function nav_menu($menu) + { $action = $this->trimmed('action'); common_element_start('ul', array('id' => 'nav_views')); foreach ($menu as $menuaction => $menudesc) { - common_menu_item(common_local_url($menuaction, isset($menudesc[2]) ? $menudesc[2] : NULL), - $menudesc[0], - $menudesc[1], - $action == $menuaction); + common_menu_item(common_local_url($menuaction, + isset($menudesc[2]) ? $menudesc[2] : null), + $menudesc[0], + $menudesc[1], + $action == $menuaction); } common_element_end('ul'); - } + } } -- cgit v1.2.3-54-g00ecf From f3c0d31688d2f079d0b5cb1926eb5a67c5ecce67 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sat, 20 Dec 2008 19:46:07 -0500 Subject: reformat lib/daemon.php for phpcs darcs-hash:20081221004607-84dde-d83d0661b29e532b8842b7ae45c961446669fb74.gz --- _darcs/inventory | 4 +- ...dde-d83d0661b29e532b8842b7ae45c961446669fb74.gz | Bin 0 -> 1238 bytes _darcs/pristine/lib/daemon.php | 239 +++++++------ _darcs/tentative_pristine | 384 ++++++++++----------- lib/daemon.php | 239 +++++++------ 5 files changed, 443 insertions(+), 423 deletions(-) create mode 100644 _darcs/patches/20081221004607-84dde-d83d0661b29e532b8842b7ae45c961446669fb74.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 0328b73d1..0ee79eeaa 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -25,4 +25,6 @@ Evan Prodromou **20081221002332] [reformatting for phpcs in lib/util.php Evan Prodromou **20081221003016] [some modifications to assuage phpcs -Evan Prodromou **20081221003955] \ No newline at end of file +Evan Prodromou **20081221003955] +[reformat lib/daemon.php for phpcs +Evan Prodromou **20081221004607] \ No newline at end of file diff --git a/_darcs/patches/20081221004607-84dde-d83d0661b29e532b8842b7ae45c961446669fb74.gz b/_darcs/patches/20081221004607-84dde-d83d0661b29e532b8842b7ae45c961446669fb74.gz new file mode 100644 index 000000000..9e51eb2f7 Binary files /dev/null and b/_darcs/patches/20081221004607-84dde-d83d0661b29e532b8842b7ae45c961446669fb74.gz differ diff --git a/_darcs/pristine/lib/daemon.php b/_darcs/pristine/lib/daemon.php index 359a4343b..9c1ae50a0 100644 --- a/_darcs/pristine/lib/daemon.php +++ b/_darcs/pristine/lib/daemon.php @@ -1,5 +1,5 @@ . */ -if (!defined('LACONICA')) { exit(1); } - -class Daemon { - - function name() { - return NULL; - } - - function background() { - $pid = pcntl_fork(); - if ($pid < 0) { # error - common_log(LOG_ERR, "Could not fork."); - return false; - } else if ($pid > 0) { # parent - common_log(LOG_INFO, "Successfully forked."); - exit(0); - } else { # child - return true; - } - } - - function alreadyRunning() { - - $pidfilename = $this->pidFilename(); - - if (!$pidfilename) { - return false; - } - - if (!file_exists($pidfilename)) { - return false; - } - $contents = file_get_contents($pidfilename); - if (posix_kill(trim($contents),0)) { - return true; - } else { - return false; - } - } - - function writePidFile() { - $pidfilename = $this->pidFilename(); - - if (!$pidfilename) { - return false; - } - - return file_put_contents($pidfilename, posix_getpid() . "\n"); - } - - function clearPidFile() { - $pidfilename = $this->pidFilename(); - if (!$pidfilename) { - return false; - } - return unlink($pidfilename); - } - - function pidFilename() { - $piddir = common_config('daemon', 'piddir'); - if (!$piddir) { - return NULL; - } - $name = $this->name(); - if (!$name) { - return NULL; - } - return $piddir . '/' . $name . '.pid'; - } - - function changeUser() { - - $username = common_config('daemon', 'user'); - - if ($username) { - $user_info = posix_getpwnam($username); - if (!$user_info) { - common_log(LOG_WARNING, 'Ignoring unknown user for daemon: ' . $username); - } else { - common_log(LOG_INFO, "Setting user to " . $username); - posix_setuid($user_info['uid']); - } - } - - $groupname = common_config('daemon', 'group'); - - if ($groupname) { - $group_info = posix_getgrnam($groupname); - if (!$group_info) { - common_log(LOG_WARNING, 'Ignoring unknown group for daemon: ' . $groupname); - } else { - common_log(LOG_INFO, "Setting group to " . $groupname); - posix_setgid($group_info['gid']); - } - } - } - - function runOnce() { - if ($this->alreadyRunning()) { - common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); - exit(0); - } - if ($this->background()) { - $this->writePidFile(); - $this->changeUser(); - $this->run(); - $this->clearPidFile(); - } - } - - function run() { - return true; - } +if (!defined('LACONICA')) { + exit(1); +} + +class Daemon +{ + function name() + { + return null; + } + + function background() + { + $pid = pcntl_fork(); + if ($pid < 0) { // error + common_log(LOG_ERR, "Could not fork."); + return false; + } else if ($pid > 0) { // parent + common_log(LOG_INFO, "Successfully forked."); + exit(0); + } else { // child + return true; + } + } + + function alreadyRunning() + { + $pidfilename = $this->pidFilename(); + + if (!$pidfilename) { + return false; + } + + if (!file_exists($pidfilename)) { + return false; + } + $contents = file_get_contents($pidfilename); + if (posix_kill(trim($contents), 0)) { + return true; + } else { + return false; + } + } + + function writePidFile() + { + $pidfilename = $this->pidFilename(); + + if (!$pidfilename) { + return false; + } + + return file_put_contents($pidfilename, posix_getpid() . "\n"); + } + + function clearPidFile() + { + $pidfilename = $this->pidFilename(); + if (!$pidfilename) { + return false; + } + return unlink($pidfilename); + } + + function pidFilename() + { + $piddir = common_config('daemon', 'piddir'); + if (!$piddir) { + return null; + } + $name = $this->name(); + if (!$name) { + return null; + } + return $piddir . '/' . $name . '.pid'; + } + + function changeUser() + { + $username = common_config('daemon', 'user'); + + if ($username) { + $user_info = posix_getpwnam($username); + if (!$user_info) { + common_log(LOG_WARNING, + 'Ignoring unknown user for daemon: ' . $username); + } else { + common_log(LOG_INFO, "Setting user to " . $username); + posix_setuid($user_info['uid']); + } + } + + $groupname = common_config('daemon', 'group'); + + if ($groupname) { + $group_info = posix_getgrnam($groupname); + if (!$group_info) { + common_log(LOG_WARNING, + 'Ignoring unknown group for daemon: ' . $groupname); + } else { + common_log(LOG_INFO, "Setting group to " . $groupname); + posix_setgid($group_info['gid']); + } + } + } + + function runOnce() + { + if ($this->alreadyRunning()) { + common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); + exit(0); + } + if ($this->background()) { + $this->writePidFile(); + $this->changeUser(); + $this->run(); + $this->clearPidFile(); + } + } + + function run() + { + return true; + } } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 529be5f2c..73c44f1dc 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,236 +1,232 @@ -hunk ./lib/action.php 2 +hunk ./lib/daemon.php 2 -/* +/** -hunk ./lib/action.php 20 +hunk ./lib/daemon.php 20 -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/action.php 24 --class Action { // lawsuit -+class Action // lawsuit +hunk ./lib/daemon.php 24 +-class Daemon { ++class Daemon +{ -hunk ./lib/action.php 27 -- var $args; -+ var $args; -hunk ./lib/action.php 29 -- function Action() { -- } -+ function Action() -+ { -+ } -hunk ./lib/action.php 33 -- # For initializing members of the class -+ // For initializing members of the class -hunk ./lib/action.php 35 -- function prepare($argarray) { -- $this->args =& common_copy_args($argarray); -- return true; -- } -+ function prepare($argarray) -+ { -+ $this->args =& common_copy_args($argarray); -+ return true; -+ } -hunk ./lib/action.php 41 -- # For comparison with If-Last-Modified -- # If not applicable, return NULL -+ // For comparison with If-Last-Modified -+ // If not applicable, return null -hunk ./lib/action.php 44 -- function last_modified() { -- return NULL; -- } -+ function last_modified() ++ function name() + { + return null; + } -hunk ./lib/action.php 49 -- function etag() { +hunk ./lib/daemon.php 31 +- function name() { - return NULL; - } -+ function etag() -+ { -+ return null; -+ } -hunk ./lib/action.php 54 -- function is_readonly() { -- return false; +- +- function background() { +- $pid = pcntl_fork(); +- if ($pid < 0) { # error +- common_log(LOG_ERR, "Could not fork."); +- return false; +- } else if ($pid > 0) { # parent +- common_log(LOG_INFO, "Successfully forked."); +- exit(0); +- } else { # child +- return true; +- } - } -+ function is_readonly() ++ function background() + { -+ return false; ++ $pid = pcntl_fork(); ++ if ($pid < 0) { // error ++ common_log(LOG_ERR, "Could not fork."); ++ return false; ++ } else if ($pid > 0) { // parent ++ common_log(LOG_INFO, "Successfully forked."); ++ exit(0); ++ } else { // child ++ return true; ++ } + } -hunk ./lib/action.php 59 -- function arg($key, $def=NULL) { -- if (array_key_exists($key, $this->args)) { -- return $this->args[$key]; +hunk ./lib/daemon.php 45 +- function alreadyRunning() { ++ function alreadyRunning() ++ { ++ $pidfilename = $this->pidFilename(); +hunk ./lib/daemon.php 49 +- $pidfilename = $this->pidFilename(); ++ if (!$pidfilename) { ++ return false; ++ } +hunk ./lib/daemon.php 53 +- if (!$pidfilename) { +- return false; +- } +- +- if (!file_exists($pidfilename)) { +- return false; +- } +- $contents = file_get_contents($pidfilename); +- if (posix_kill(trim($contents),0)) { +- return true; - } else { -- return $def; +- return false; - } - } -+ function arg($key, $def=null) -+ { -+ if (array_key_exists($key, $this->args)) { -+ return $this->args[$key]; +- +- function writePidFile() { +- $pidfilename = $this->pidFilename(); +- +- if (!$pidfilename) { +- return false; +- } +- +- return file_put_contents($pidfilename, posix_getpid() . "\n"); +- } ++ if (!file_exists($pidfilename)) { ++ return false; ++ } ++ $contents = file_get_contents($pidfilename); ++ if (posix_kill(trim($contents), 0)) { ++ return true; + } else { -+ return $def; ++ return false; + } + } -hunk ./lib/action.php 68 -- function trimmed($key, $def=NULL) { -- $arg = $this->arg($key, $def); -- return (is_string($arg)) ? trim($arg) : $arg; +hunk ./lib/daemon.php 64 +- function clearPidFile() { +- $pidfilename = $this->pidFilename(); +- if (!$pidfilename) { +- return false; +- } +- return unlink($pidfilename); - } -+ function trimmed($key, $def=null) -+ { -+ $arg = $this->arg($key, $def); -+ return (is_string($arg)) ? trim($arg) : $arg; -+ } -hunk ./lib/action.php 74 -- # Note: argarray ignored, since it's now passed in in prepare() -+ // Note: argarray ignored, since it's now passed in in prepare() -hunk ./lib/action.php 76 -- function handle($argarray=NULL) { -+ function handle($argarray=null) -+ { -hunk ./lib/action.php 79 -- $lm = $this->last_modified(); -- $etag = $this->etag(); -+ $lm = $this->last_modified(); -+ $etag = $this->etag(); -hunk ./lib/action.php 82 -- if ($etag) { -- header('ETag: ' . $etag); +- +- function pidFilename() { +- $piddir = common_config('daemon', 'piddir'); +- if (!$piddir) { +- return NULL; - } -+ if ($etag) { -+ header('ETag: ' . $etag); -+ } -hunk ./lib/action.php 86 -- 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 ($lm <= $ims) { -- if (!$etag || $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { -- header('HTTP/1.1 304 Not Modified'); -- # Better way to do this? -- exit(0); -- } -- } -- } +- $name = $this->name(); +- if (!$name) { +- return NULL; - } +- return $piddir . '/' . $name . '.pid'; - } -+ 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 ($lm <= $ims) { -+ if (!$etag || -+ $this->_has_etag($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) { -+ header('HTTP/1.1 304 Not Modified'); -+ // Better way to do this? -+ exit(0); -+ } -+ } -+ } ++ function writePidFile() ++ { ++ $pidfilename = $this->pidFilename(); +hunk ./lib/daemon.php 68 +- function changeUser() { ++ if (!$pidfilename) { ++ return false; + } +hunk ./lib/daemon.php 72 +- $username = common_config('daemon', 'user'); +- +- if ($username) { +- $user_info = posix_getpwnam($username); +- if (!$user_info) { +- common_log(LOG_WARNING, 'Ignoring unknown user for daemon: ' . $username); +- } else { +- common_log(LOG_INFO, "Setting user to " . $username); +- posix_setuid($user_info['uid']); +- } +- } ++ return file_put_contents($pidfilename, posix_getpid() . "\n"); + } -hunk ./lib/action.php 103 -- function _has_etag($etag, $if_none_match) { -- return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); +hunk ./lib/daemon.php 75 +- $groupname = common_config('daemon', 'group'); +- +- if ($groupname) { +- $group_info = posix_getgrnam($groupname); +- if (!$group_info) { +- common_log(LOG_WARNING, 'Ignoring unknown group for daemon: ' . $groupname); +- } else { +- common_log(LOG_INFO, "Setting group to " . $groupname); +- posix_setgid($group_info['gid']); +- } +- } - } -+ function _has_etag($etag, $if_none_match) -+ { -+ return ($if_none_match) && in_array($etag, explode(',', $if_none_match)); -+ } -hunk ./lib/action.php 108 -- function boolean($key, $def=false) { -- $arg = strtolower($this->trimmed($key)); -+ function boolean($key, $def=false) -+ { -+ $arg = strtolower($this->trimmed($key)); -hunk ./lib/action.php 112 -- if (is_null($arg)) { -- return $def; -- } else if (in_array($arg, array('true', 'yes', '1'))) { -- return true; -- } else if (in_array($arg, array('false', 'no', '0'))) { -- return false; -- } else { -- return $def; +- +- function runOnce() { +- if ($this->alreadyRunning()) { +- common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); +- exit(0); +- } +- if ($this->background()) { +- $this->writePidFile(); +- $this->changeUser(); +- $this->run(); +- $this->clearPidFile(); - } - } -+ if (is_null($arg)) { -+ return $def; -+ } else if (in_array($arg, array('true', 'yes', '1'))) { -+ return true; -+ } else if (in_array($arg, array('false', 'no', '0'))) { +- +- function run() { +- return true; +- } ++ function clearPidFile() ++ { ++ $pidfilename = $this->pidFilename(); ++ if (!$pidfilename) { + return false; -+ } else { -+ return $def; + } ++ return unlink($pidfilename); + } -hunk ./lib/action.php 123 -- function server_error($msg, $code=500) { -- $action = $this->trimmed('action'); -- common_debug("Server error '$code' on '$action': $msg", __FILE__); -- common_server_error($msg, $code); -- } -+ function server_error($msg, $code=500) ++ ++ function pidFilename() + { -+ $action = $this->trimmed('action'); -+ common_debug("Server error '$code' on '$action': $msg", __FILE__); -+ common_server_error($msg, $code); ++ $piddir = common_config('daemon', 'piddir'); ++ if (!$piddir) { ++ return null; ++ } ++ $name = $this->name(); ++ if (!$name) { ++ return null; ++ } ++ return $piddir . '/' . $name . '.pid'; + } -hunk ./lib/action.php 130 -- function client_error($msg, $code=400) { -- $action = $this->trimmed('action'); -- common_debug("User error '$code' on '$action': $msg", __FILE__); -- common_user_error($msg, $code); -- } -+ function client_error($msg, $code=400) ++ ++ function changeUser() + { -+ $action = $this->trimmed('action'); -+ common_debug("User error '$code' on '$action': $msg", __FILE__); -+ common_user_error($msg, $code); ++ $username = common_config('daemon', 'user'); ++ ++ if ($username) { ++ $user_info = posix_getpwnam($username); ++ if (!$user_info) { ++ common_log(LOG_WARNING, ++ 'Ignoring unknown user for daemon: ' . $username); ++ } else { ++ common_log(LOG_INFO, "Setting user to " . $username); ++ posix_setuid($user_info['uid']); ++ } ++ } ++ ++ $groupname = common_config('daemon', 'group'); ++ ++ if ($groupname) { ++ $group_info = posix_getgrnam($groupname); ++ if (!$group_info) { ++ common_log(LOG_WARNING, ++ 'Ignoring unknown group for daemon: ' . $groupname); ++ } else { ++ common_log(LOG_INFO, "Setting group to " . $groupname); ++ posix_setgid($group_info['gid']); ++ } ++ } + } -hunk ./lib/action.php 137 -- function self_url() { -- $action = $this->trimmed('action'); -- $args = $this->args; -- unset($args['action']); -- foreach (array_keys($_COOKIE) as $cookie) { -- unset($args[$cookie]); -- } -- return common_local_url($action, $args); -- } -+ function self_url() ++ ++ function runOnce() + { -+ $action = $this->trimmed('action'); -+ $args = $this->args; -+ unset($args['action']); -+ foreach (array_keys($_COOKIE) as $cookie) { -+ unset($args[$cookie]); ++ if ($this->alreadyRunning()) { ++ common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); ++ exit(0); ++ } ++ if ($this->background()) { ++ $this->writePidFile(); ++ $this->changeUser(); ++ $this->run(); ++ $this->clearPidFile(); + } -+ return common_local_url($action, $args); + } -hunk ./lib/action.php 148 -- function nav_menu($menu) { -+ function nav_menu($menu) ++ ++ function run() + { -hunk ./lib/action.php 153 -- common_menu_item(common_local_url($menuaction, isset($menudesc[2]) ? $menudesc[2] : NULL), -- $menudesc[0], -- $menudesc[1], -- $action == $menuaction); -+ common_menu_item(common_local_url($menuaction, -+ isset($menudesc[2]) ? $menudesc[2] : null), -+ $menudesc[0], -+ $menudesc[1], -+ $action == $menuaction); -hunk ./lib/action.php 160 -- } ++ return true; + } diff --git a/lib/daemon.php b/lib/daemon.php index 359a4343b..9c1ae50a0 100644 --- a/lib/daemon.php +++ b/lib/daemon.php @@ -1,5 +1,5 @@ . */ -if (!defined('LACONICA')) { exit(1); } - -class Daemon { - - function name() { - return NULL; - } - - function background() { - $pid = pcntl_fork(); - if ($pid < 0) { # error - common_log(LOG_ERR, "Could not fork."); - return false; - } else if ($pid > 0) { # parent - common_log(LOG_INFO, "Successfully forked."); - exit(0); - } else { # child - return true; - } - } - - function alreadyRunning() { - - $pidfilename = $this->pidFilename(); - - if (!$pidfilename) { - return false; - } - - if (!file_exists($pidfilename)) { - return false; - } - $contents = file_get_contents($pidfilename); - if (posix_kill(trim($contents),0)) { - return true; - } else { - return false; - } - } - - function writePidFile() { - $pidfilename = $this->pidFilename(); - - if (!$pidfilename) { - return false; - } - - return file_put_contents($pidfilename, posix_getpid() . "\n"); - } - - function clearPidFile() { - $pidfilename = $this->pidFilename(); - if (!$pidfilename) { - return false; - } - return unlink($pidfilename); - } - - function pidFilename() { - $piddir = common_config('daemon', 'piddir'); - if (!$piddir) { - return NULL; - } - $name = $this->name(); - if (!$name) { - return NULL; - } - return $piddir . '/' . $name . '.pid'; - } - - function changeUser() { - - $username = common_config('daemon', 'user'); - - if ($username) { - $user_info = posix_getpwnam($username); - if (!$user_info) { - common_log(LOG_WARNING, 'Ignoring unknown user for daemon: ' . $username); - } else { - common_log(LOG_INFO, "Setting user to " . $username); - posix_setuid($user_info['uid']); - } - } - - $groupname = common_config('daemon', 'group'); - - if ($groupname) { - $group_info = posix_getgrnam($groupname); - if (!$group_info) { - common_log(LOG_WARNING, 'Ignoring unknown group for daemon: ' . $groupname); - } else { - common_log(LOG_INFO, "Setting group to " . $groupname); - posix_setgid($group_info['gid']); - } - } - } - - function runOnce() { - if ($this->alreadyRunning()) { - common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); - exit(0); - } - if ($this->background()) { - $this->writePidFile(); - $this->changeUser(); - $this->run(); - $this->clearPidFile(); - } - } - - function run() { - return true; - } +if (!defined('LACONICA')) { + exit(1); +} + +class Daemon +{ + function name() + { + return null; + } + + function background() + { + $pid = pcntl_fork(); + if ($pid < 0) { // error + common_log(LOG_ERR, "Could not fork."); + return false; + } else if ($pid > 0) { // parent + common_log(LOG_INFO, "Successfully forked."); + exit(0); + } else { // child + return true; + } + } + + function alreadyRunning() + { + $pidfilename = $this->pidFilename(); + + if (!$pidfilename) { + return false; + } + + if (!file_exists($pidfilename)) { + return false; + } + $contents = file_get_contents($pidfilename); + if (posix_kill(trim($contents), 0)) { + return true; + } else { + return false; + } + } + + function writePidFile() + { + $pidfilename = $this->pidFilename(); + + if (!$pidfilename) { + return false; + } + + return file_put_contents($pidfilename, posix_getpid() . "\n"); + } + + function clearPidFile() + { + $pidfilename = $this->pidFilename(); + if (!$pidfilename) { + return false; + } + return unlink($pidfilename); + } + + function pidFilename() + { + $piddir = common_config('daemon', 'piddir'); + if (!$piddir) { + return null; + } + $name = $this->name(); + if (!$name) { + return null; + } + return $piddir . '/' . $name . '.pid'; + } + + function changeUser() + { + $username = common_config('daemon', 'user'); + + if ($username) { + $user_info = posix_getpwnam($username); + if (!$user_info) { + common_log(LOG_WARNING, + 'Ignoring unknown user for daemon: ' . $username); + } else { + common_log(LOG_INFO, "Setting user to " . $username); + posix_setuid($user_info['uid']); + } + } + + $groupname = common_config('daemon', 'group'); + + if ($groupname) { + $group_info = posix_getgrnam($groupname); + if (!$group_info) { + common_log(LOG_WARNING, + 'Ignoring unknown group for daemon: ' . $groupname); + } else { + common_log(LOG_INFO, "Setting group to " . $groupname); + posix_setgid($group_info['gid']); + } + } + } + + function runOnce() + { + if ($this->alreadyRunning()) { + common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); + exit(0); + } + if ($this->background()) { + $this->writePidFile(); + $this->changeUser(); + $this->run(); + $this->clearPidFile(); + } + } + + function run() + { + return true; + } } -- cgit v1.2.3-54-g00ecf From 5d76234a6031fdf5df2aeea974777b006961cc7a Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Sat, 20 Dec 2008 19:58:37 -0500 Subject: reformat for phpcs darcs-hash:20081221005837-84dde-07cd6bb27d5f601360a686538dd76f1dca9af3c4.gz --- _darcs/inventory | 4 +- ...dde-07cd6bb27d5f601360a686538dd76f1dca9af3c4.gz | Bin 0 -> 3698 bytes _darcs/pristine/lib/gallery.php | 580 +++++++++-------- _darcs/tentative_pristine | 704 +++++++++++++++------ lib/gallery.php | 580 +++++++++-------- 5 files changed, 1126 insertions(+), 742 deletions(-) create mode 100644 _darcs/patches/20081221005837-84dde-07cd6bb27d5f601360a686538dd76f1dca9af3c4.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 0ee79eeaa..3fba38822 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -27,4 +27,6 @@ Evan Prodromou **20081221003016] [some modifications to assuage phpcs Evan Prodromou **20081221003955] [reformat lib/daemon.php for phpcs -Evan Prodromou **20081221004607] \ No newline at end of file +Evan Prodromou **20081221004607] +[reformat for phpcs +Evan Prodromou **20081221005837] \ No newline at end of file diff --git a/_darcs/patches/20081221005837-84dde-07cd6bb27d5f601360a686538dd76f1dca9af3c4.gz b/_darcs/patches/20081221005837-84dde-07cd6bb27d5f601360a686538dd76f1dca9af3c4.gz new file mode 100644 index 000000000..34fd52db4 Binary files /dev/null and b/_darcs/patches/20081221005837-84dde-07cd6bb27d5f601360a686538dd76f1dca9af3c4.gz differ diff --git a/_darcs/pristine/lib/gallery.php b/_darcs/pristine/lib/gallery.php index 0dd351bab..34b58518c 100644 --- a/_darcs/pristine/lib/gallery.php +++ b/_darcs/pristine/lib/gallery.php @@ -1,6 +1,5 @@ . */ -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -require_once(INSTALLDIR.'/lib/profilelist.php'); +require_once INSTALLDIR.'/lib/profilelist.php'; -# 10x8 +// 10x8 define('AVATARS_PER_PAGE', 80); -class GalleryAction extends Action { - - function is_readonly() { - return true; - } - - function handle($args) { - parent::handle($args); - - # Post from the tag dropdown; redirect to a GET - - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - common_redirect($this->self_url(), 307); - } - - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); - - if (!$user) { - $this->no_such_user(); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - $this->server_error(_('User without matching profile in system.')); - return; - } - - $page = $this->arg('page'); - - if (!$page) { - $page = 1; - } - - $display = $this->arg('display'); - - if (!$display) { - $display = 'list'; - } - - $tag = $this->arg('tag'); - - common_show_header($profile->nickname . ": " . $this->gallery_type(), - NULL, $profile, - array($this, 'show_top')); - - $this->display_links($profile, $page, $display); - $this->show_tags_dropdown($profile); - - $this->show_gallery($profile, $page, $display, $tag); - common_show_footer(); - } - - function no_such_user() { - $this->client_error(_('No such user.')); - } - - function show_tags_dropdown($profile) { - $tag = $this->trimmed('tag'); - list($lst, $usr) = $this->fields(); - $tags = $this->get_all_tags($profile, $lst, $usr); - $content = array(); - foreach ($tags as $t) { - $content[$t] = $t; - } - if ($tags) { - common_element_start('dl', array('id'=>'filter_tags')); - common_element('dt', null, _('Filter tags')); - common_element_start('dd'); - common_element_start('ul'); - common_element_start('li', array('id'=>'filter_tags_all', 'class'=>'child_1')); - common_element('a', array('href' => common_local_url($this->trimmed('action'), - array('nickname' => $profile->nickname))), - _('All')); - common_element_end('li'); - common_element_start('li', array('id'=>'filter_tags_item')); - common_element_start('form', array('name' => 'bytag', 'id' => 'bytag', 'method' => 'post')); - common_dropdown('tag', _('Tag'), $content, - _('Choose a tag to narrow list'), FALSE, $tag); - common_submit('go', _('Go')); - common_element_end('form'); - common_element_end('li'); - common_element_end('ul'); - common_element_end('dd'); - common_element_end('dl'); - } - } - - function show_top($profile) { - common_element('div', 'instructions', - $this->get_instructions($profile)); +class GalleryAction extends Action +{ + function is_readonly() + { + return true; + } + + function handle($args) + { + parent::handle($args); + + // Post from the tag dropdown; redirect to a GET + + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + common_redirect($this->self_url(), 307); + } + + $nickname = common_canonical_nickname($this->arg('nickname')); + + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + $this->no_such_user(); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + $this->server_error(_('User without matching profile in system.')); + return; + } + + $page = $this->arg('page'); + + if (!$page) { + $page = 1; + } + + $display = $this->arg('display'); + + if (!$display) { + $display = 'list'; + } + + $tag = $this->arg('tag'); + + common_show_header($profile->nickname . ": " . $this->gallery_type(), + null, $profile, + array($this, 'show_top')); + + $this->display_links($profile, $page, $display); + $this->show_tags_dropdown($profile); + + $this->show_gallery($profile, $page, $display, $tag); + common_show_footer(); + } + + function no_such_user() + { + $this->client_error(_('No such user.')); + } + + function show_tags_dropdown($profile) + { + $tag = $this->trimmed('tag'); + + list($lst, $usr) = $this->fields(); + + $tags = $this->get_all_tags($profile, $lst, $usr); + + $content = array(); + + foreach ($tags as $t) { + $content[$t] = $t; + } + if ($tags) { + common_element_start('dl', array('id'=>'filter_tags')); + common_element('dt', null, _('Filter tags')); + common_element_start('dd'); + common_element_start('ul'); + common_element_start('li', array('id' => 'filter_tags_all', + 'class' => 'child_1')); + common_element('a', + array('href' => + common_local_url($this->trimmed('action'), + array('nickname' => + $profile->nickname))), + _('All')); + common_element_end('li'); + common_element_start('li', array('id'=>'filter_tags_item')); + common_element_start('form', array('name' => 'bytag', + 'id' => 'bytag', + 'method' => 'post')); + common_dropdown('tag', _('Tag'), $content, + _('Choose a tag to narrow list'), false, $tag); + common_submit('go', _('Go')); + common_element_end('form'); + common_element_end('li'); + common_element_end('ul'); + common_element_end('dd'); + common_element_end('dl'); + } + } + + function show_top($profile) + { + common_element('div', 'instructions', + $this->get_instructions($profile)); $this->show_menu(); - } - - function show_menu() { - # action => array('prompt', 'title', $args) - $action = $this->trimmed('action'); - $nickname = $this->trimmed('nickname'); - $menu = - array('subscriptions' => - array( _('Subscriptions'), - _('Subscriptions'), - array('nickname' => $nickname)), - 'subscribers' => - array( - _('Subscribers'), - _('Subscribers'), - array('nickname' => $nickname)), - ); - $this->nav_menu($menu); - } + } - function show_gallery($profile, $page, $display='list', $tag=NULL) { + function show_menu() + { + // action => array('prompt', 'title', $args) + $action = $this->trimmed('action'); + $nickname = $this->trimmed('nickname'); + + $menu = + array('subscriptions' => + array( _('Subscriptions'), + _('Subscriptions'), + array('nickname' => $nickname)), + 'subscribers' => + array( + _('Subscribers'), + _('Subscribers'), + array('nickname' => $nickname)), + ); + $this->nav_menu($menu); + } - $other = new Profile(); + function show_gallery($profile, $page, $display='list', $tag=null) + { + $other = new Profile(); - list($lst, $usr) = $this->fields(); + list($lst, $usr) = $this->fields(); - $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; + $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; - $offset = ($page-1)*$per_page; - $limit = $per_page + 1; + $offset = ($page-1)*$per_page; + $limit = $per_page + 1; - if (common_config('db','type') == 'pgsql') { - $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $lim = ' LIMIT ' . $offset . ', ' . $limit; - } + if (common_config('db', 'type') == 'pgsql') { + $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $lim = ' LIMIT ' . $offset . ', ' . $limit; + } - # XXX: memcached results - # FIXME: SQL injection on $tag + // XXX: memcached results + // FIXME: SQL injection on $tag - $other->query('SELECT profile.* ' . - 'FROM profile JOIN subscription ' . - 'ON profile.id = subscription.' . $lst . ' ' . - (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . - 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . - 'AND subscriber != subscribed ' . - (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . - 'ORDER BY subscription.created DESC, profile.id DESC ' . - $lim); + $other->query('SELECT profile.* ' . + 'FROM profile JOIN subscription ' . + 'ON profile.id = subscription.' . $lst . ' ' . + (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . + 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . + 'AND subscriber != subscribed ' . + (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . + 'ORDER BY subscription.created DESC, profile.id DESC ' . + $lim); - if ($display == 'list') { + if ($display == 'list') { $cls = $this->profile_list_class(); - $profile_list = new $cls($other, $profile, $this->trimmed('action')); - $cnt = $profile_list->show_list(); - } else { - $cnt = $this->icon_list($other); - } + $profile_list = new $cls($other, $profile, $this->trimmed('action')); + $cnt = $profile_list->show_list(); + } else { + $cnt = $this->icon_list($other); + } - # For building the pagination URLs + // For building the pagination URLs - $args = array('nickname' => $profile->nickname); + $args = array('nickname' => $profile->nickname); - if ($display != 'list') { - $args['display'] = $display; - } + if ($display != 'list') { + $args['display'] = $display; + } - common_pagination($page > 1, - $cnt > $per_page, - $page, - $this->trimmed('action'), - $args); - } + common_pagination($page > 1, + $cnt > $per_page, + $page, + $this->trimmed('action'), + $args); + } - function profile_list_class() { + function profile_list_class() + { return 'ProfileList'; } - function icon_list($other) { - - common_element_start('ul', $this->div_class()); - - $cnt = 0; - - while ($other->fetch()) { - - $cnt++; - - if ($cnt > AVATARS_PER_PAGE) { - break; - } - - common_element_start('li'); - - common_element_start('a', array('title' => ($other->fullname) ? - $other->fullname : - $other->nickname, - 'href' => $other->profileurl, - 'class' => 'subscription')); - $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); - common_element('img', - array('src' => - (($avatar) ? common_avatar_display_url($avatar) : - common_default_avatar(AVATAR_STREAM_SIZE)), - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'class' => 'avatar stream', - 'alt' => ($other->fullname) ? - $other->fullname : - $other->nickname)); - common_element_end('a'); - - # XXX: subscribe form here - - common_element_end('li'); - } - - common_element_end('ul'); - - return $cnt; - } - - function gallery_type() { - return NULL; - } - - function get_instructions(&$profile) { - return NULL; - } - - function fields() { - return NULL; - } - - function div_class() { - return ''; - } - - function display_links($profile, $page, $display) { - $tag = $this->trimmed('tag'); - - common_element_start('dl', array('id'=>'subscriptions_nav')); - common_element('dt', null, _('Subscriptions navigation')); - common_element_start('dd'); - common_element_start('ul', array('class'=>'nav')); - - switch ($display) { - case 'list': - common_element('li', array('class'=>'child_1'), _('List')); - common_element_start('li'); - $url_args = array('display' => 'icons', - 'nickname' => $profile->nickname, - 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); - if ($tag) { - $url_args['tag'] = $tag; - } - $url = common_local_url($this->trimmed('action'), $url_args); - common_element('a', array('href' => $url), - _('Icons')); - common_element_end('li'); - break; - default: - common_element_start('li', array('class'=>'child_1')); - $url_args = array('nickname' => $profile->nickname, - 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); - if ($tag) { - $url_args['tag'] = $tag; - } - $url = common_local_url($this->trimmed('action'), $url_args); - common_element('a', array('href' => $url), - _('List')); - common_element_end('li'); - common_element('li', NULL, _('Icons')); - break; - } - - common_element_end('ul'); - common_element_end('dd'); - common_element_end('dl'); - } - - # Get list of tags we tagged other users with - - function get_all_tags($profile, $lst, $usr) { - $profile_tag = new Notice_tag(); - $profile_tag->query('SELECT DISTINCT(tag) ' . - 'FROM profile_tag, subscription ' . - 'WHERE tagger = ' . $profile->id . ' ' . - 'AND ' . $usr . ' = ' . $profile->id . ' ' . - 'AND ' . $lst . ' = tagged ' . - 'AND tagger != tagged'); - $tags = array(); - while ($profile_tag->fetch()) { - $tags[] = $profile_tag->tag; - } - $profile_tag->free(); - return $tags; - } + function icon_list($other) + { + common_element_start('ul', $this->div_class()); + + $cnt = 0; + + while ($other->fetch()) { + + $cnt++; + + if ($cnt > AVATARS_PER_PAGE) { + break; + } + + common_element_start('li'); + + common_element_start('a', array('title' => ($other->fullname) ? + $other->fullname : + $other->nickname, + 'href' => $other->profileurl, + 'class' => 'subscription')); + $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); + common_element('img', + array('src' => + (($avatar) ? common_avatar_display_url($avatar) : + common_default_avatar(AVATAR_STREAM_SIZE)), + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'class' => 'avatar stream', + 'alt' => ($other->fullname) ? + $other->fullname : + $other->nickname)); + common_element_end('a'); + + // XXX: subscribe form here + + common_element_end('li'); + } + + common_element_end('ul'); + + return $cnt; + } + + function gallery_type() + { + return null; + } + + function get_instructions(&$profile) + { + return null; + } + + function fields() + { + return null; + } + + function div_class() + { + return ''; + } + + function display_links($profile, $page, $display) + { + $tag = $this->trimmed('tag'); + + common_element_start('dl', array('id'=>'subscriptions_nav')); + common_element('dt', null, _('Subscriptions navigation')); + common_element_start('dd'); + common_element_start('ul', array('class'=>'nav')); + + switch ($display) { + case 'list': + common_element('li', array('class'=>'child_1'), _('List')); + common_element_start('li'); + $url_args = array('display' => 'icons', + 'nickname' => $profile->nickname, + 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); + if ($tag) { + $url_args['tag'] = $tag; + } + $url = common_local_url($this->trimmed('action'), $url_args); + common_element('a', array('href' => $url), + _('Icons')); + common_element_end('li'); + break; + default: + common_element_start('li', array('class'=>'child_1')); + $url_args = array('nickname' => $profile->nickname, + 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); + if ($tag) { + $url_args['tag'] = $tag; + } + $url = common_local_url($this->trimmed('action'), $url_args); + common_element('a', array('href' => $url), + _('List')); + common_element_end('li'); + common_element('li', null, _('Icons')); + break; + } + + common_element_end('ul'); + common_element_end('dd'); + common_element_end('dl'); + } + + // Get list of tags we tagged other users with + + function get_all_tags($profile, $lst, $usr) + { + $profile_tag = new Notice_tag(); + $profile_tag->query('SELECT DISTINCT(tag) ' . + 'FROM profile_tag, subscription ' . + 'WHERE tagger = ' . $profile->id . ' ' . + 'AND ' . $usr . ' = ' . $profile->id . ' ' . + 'AND ' . $lst . ' = tagged ' . + 'AND tagger != tagged'); + $tags = array(); + while ($profile_tag->fetch()) { + $tags[] = $profile_tag->tag; + } + $profile_tag->free(); + return $tags; + } } \ No newline at end of file diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 73c44f1dc..4e6b1fca9 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,232 +1,562 @@ -hunk ./lib/daemon.php 2 +hunk ./lib/gallery.php 2 +- -/* +/** -hunk ./lib/daemon.php 20 +hunk ./lib/gallery.php 20 -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/daemon.php 24 --class Daemon { -+class Daemon +hunk ./lib/gallery.php 24 +-require_once(INSTALLDIR.'/lib/profilelist.php'); ++require_once INSTALLDIR.'/lib/profilelist.php'; +hunk ./lib/gallery.php 26 +-# 10x8 ++// 10x8 +hunk ./lib/gallery.php 30 +-class GalleryAction extends Action { ++class GalleryAction extends Action +{ -+ function name() ++ function is_readonly() + { -+ return null; ++ return true; + } -hunk ./lib/daemon.php 31 -- function name() { -- return NULL; ++ ++ function handle($args) ++ { ++ parent::handle($args); ++ ++ // Post from the tag dropdown; redirect to a GET ++ ++ if ($_SERVER['REQUEST_METHOD'] == 'POST') { ++ common_redirect($this->self_url(), 307); ++ } ++ ++ $nickname = common_canonical_nickname($this->arg('nickname')); +hunk ./lib/gallery.php 49 +- function is_readonly() { +- return true; - } -- -- function background() { -- $pid = pcntl_fork(); -- if ($pid < 0) { # error -- common_log(LOG_ERR, "Could not fork."); -- return false; -- } else if ($pid > 0) { # parent -- common_log(LOG_INFO, "Successfully forked."); -- exit(0); -- } else { # child -- return true; ++ $user = User::staticGet('nickname', $nickname); +hunk ./lib/gallery.php 51 +- function handle($args) { +- parent::handle($args); ++ if (!$user) { ++ $this->no_such_user(); ++ return; ++ } +hunk ./lib/gallery.php 56 +- # Post from the tag dropdown; redirect to a GET ++ $profile = $user->getProfile(); +hunk ./lib/gallery.php 58 +- if ($_SERVER['REQUEST_METHOD'] == 'POST') { +- common_redirect($this->self_url(), 307); - } -- } -+ function background() -+ { -+ $pid = pcntl_fork(); -+ if ($pid < 0) { // error -+ common_log(LOG_ERR, "Could not fork."); -+ return false; -+ } else if ($pid > 0) { // parent -+ common_log(LOG_INFO, "Successfully forked."); -+ exit(0); -+ } else { // child -+ return true; ++ if (!$profile) { ++ $this->server_error(_('User without matching profile in system.')); ++ return; + } -+ } -hunk ./lib/daemon.php 45 -- function alreadyRunning() { -+ function alreadyRunning() -+ { -+ $pidfilename = $this->pidFilename(); -hunk ./lib/daemon.php 49 -- $pidfilename = $this->pidFilename(); -+ if (!$pidfilename) { -+ return false; +hunk ./lib/gallery.php 63 +- $nickname = common_canonical_nickname($this->arg('nickname')); +- $user = User::staticGet('nickname', $nickname); ++ $page = $this->arg('page'); +hunk ./lib/gallery.php 65 +- if (!$user) { +- $this->no_such_user(); +- return; +- } ++ if (!$page) { ++ $page = 1; + } -hunk ./lib/daemon.php 53 -- if (!$pidfilename) { -- return false; +hunk ./lib/gallery.php 69 +- $profile = $user->getProfile(); ++ $display = $this->arg('display'); +hunk ./lib/gallery.php 71 +- if (!$profile) { +- $this->server_error(_('User without matching profile in system.')); +- return; - } -- -- if (!file_exists($pidfilename)) { -- return false; ++ if (!$display) { ++ $display = 'list'; ++ } +hunk ./lib/gallery.php 75 +- $page = $this->arg('page'); ++ $tag = $this->arg('tag'); +hunk ./lib/gallery.php 77 +- if (!$page) { +- $page = 1; - } -- $contents = file_get_contents($pidfilename); -- if (posix_kill(trim($contents),0)) { -- return true; -- } else { -- return false; ++ common_show_header($profile->nickname . ": " . $this->gallery_type(), ++ null, $profile, ++ array($this, 'show_top')); +hunk ./lib/gallery.php 81 +- $display = $this->arg('display'); ++ $this->display_links($profile, $page, $display); ++ $this->show_tags_dropdown($profile); +hunk ./lib/gallery.php 84 +- if (!$display) { +- $display = 'list'; - } ++ $this->show_gallery($profile, $page, $display, $tag); ++ common_show_footer(); ++ } +hunk ./lib/gallery.php 88 +- $tag = $this->arg('tag'); ++ function no_such_user() ++ { ++ $this->client_error(_('No such user.')); ++ } +hunk ./lib/gallery.php 93 +- common_show_header($profile->nickname . ": " . $this->gallery_type(), +- NULL, $profile, +- array($this, 'show_top')); ++ function show_tags_dropdown($profile) ++ { ++ $tag = $this->trimmed('tag'); +hunk ./lib/gallery.php 97 +- $this->display_links($profile, $page, $display); +- $this->show_tags_dropdown($profile); ++ list($lst, $usr) = $this->fields(); +hunk ./lib/gallery.php 99 +- $this->show_gallery($profile, $page, $display, $tag); +- common_show_footer(); +- } ++ $tags = $this->get_all_tags($profile, $lst, $usr); +hunk ./lib/gallery.php 101 +- function no_such_user() { +- $this->client_error(_('No such user.')); - } -- -- function writePidFile() { -- $pidfilename = $this->pidFilename(); -- -- if (!$pidfilename) { -- return false; ++ $content = array(); +hunk ./lib/gallery.php 103 +- function show_tags_dropdown($profile) { +- $tag = $this->trimmed('tag'); +- list($lst, $usr) = $this->fields(); +- $tags = $this->get_all_tags($profile, $lst, $usr); +- $content = array(); +- foreach ($tags as $t) { +- $content[$t] = $t; +- } +- if ($tags) { +- common_element_start('dl', array('id'=>'filter_tags')); +- common_element('dt', null, _('Filter tags')); +- common_element_start('dd'); +- common_element_start('ul'); +- common_element_start('li', array('id'=>'filter_tags_all', 'class'=>'child_1')); +- common_element('a', array('href' => common_local_url($this->trimmed('action'), +- array('nickname' => $profile->nickname))), +- _('All')); +- common_element_end('li'); +- common_element_start('li', array('id'=>'filter_tags_item')); +- common_element_start('form', array('name' => 'bytag', 'id' => 'bytag', 'method' => 'post')); +- common_dropdown('tag', _('Tag'), $content, +- _('Choose a tag to narrow list'), FALSE, $tag); +- common_submit('go', _('Go')); +- common_element_end('form'); +- common_element_end('li'); +- common_element_end('ul'); +- common_element_end('dd'); +- common_element_end('dl'); - } -- -- return file_put_contents($pidfilename, posix_getpid() . "\n"); - } -+ if (!file_exists($pidfilename)) { -+ return false; ++ foreach ($tags as $t) { ++ $content[$t] = $t; + } -+ $contents = file_get_contents($pidfilename); -+ if (posix_kill(trim($contents), 0)) { -+ return true; -+ } else { -+ return false; ++ if ($tags) { ++ common_element_start('dl', array('id'=>'filter_tags')); ++ common_element('dt', null, _('Filter tags')); ++ common_element_start('dd'); ++ common_element_start('ul'); ++ common_element_start('li', array('id' => 'filter_tags_all', ++ 'class' => 'child_1')); ++ common_element('a', ++ array('href' => ++ common_local_url($this->trimmed('action'), ++ array('nickname' => ++ $profile->nickname))), ++ _('All')); ++ common_element_end('li'); ++ common_element_start('li', array('id'=>'filter_tags_item')); ++ common_element_start('form', array('name' => 'bytag', ++ 'id' => 'bytag', ++ 'method' => 'post')); ++ common_dropdown('tag', _('Tag'), $content, ++ _('Choose a tag to narrow list'), false, $tag); ++ common_submit('go', _('Go')); ++ common_element_end('form'); ++ common_element_end('li'); ++ common_element_end('ul'); ++ common_element_end('dd'); ++ common_element_end('dl'); + } + } -hunk ./lib/daemon.php 64 -- function clearPidFile() { -- $pidfilename = $this->pidFilename(); -- if (!$pidfilename) { -- return false; -- } -- return unlink($pidfilename); +hunk ./lib/gallery.php 135 +- function show_top($profile) { +- common_element('div', 'instructions', +- $this->get_instructions($profile)); ++ function show_top($profile) ++ { ++ common_element('div', 'instructions', ++ $this->get_instructions($profile)); +hunk ./lib/gallery.php 140 - } -- -- function pidFilename() { -- $piddir = common_config('daemon', 'piddir'); -- if (!$piddir) { -- return NULL; -- } -- $name = $this->name(); -- if (!$name) { -- return NULL; -- } -- return $piddir . '/' . $name . '.pid'; ++ } +hunk ./lib/gallery.php 142 +- function show_menu() { +- # action => array('prompt', 'title', $args) +- $action = $this->trimmed('action'); +- $nickname = $this->trimmed('nickname'); +- $menu = +- array('subscriptions' => +- array( _('Subscriptions'), +- _('Subscriptions'), +- array('nickname' => $nickname)), +- 'subscribers' => +- array( +- _('Subscribers'), +- _('Subscribers'), +- array('nickname' => $nickname)), +- ); +- $this->nav_menu($menu); - } -+ function writePidFile() ++ function show_menu() ++ { ++ // action => array('prompt', 'title', $args) ++ $action = $this->trimmed('action'); ++ $nickname = $this->trimmed('nickname'); +hunk ./lib/gallery.php 148 +- function show_gallery($profile, $page, $display='list', $tag=NULL) { ++ $menu = ++ array('subscriptions' => ++ array( _('Subscriptions'), ++ _('Subscriptions'), ++ array('nickname' => $nickname)), ++ 'subscribers' => ++ array( ++ _('Subscribers'), ++ _('Subscribers'), ++ array('nickname' => $nickname)), ++ ); ++ $this->nav_menu($menu); ++ } +hunk ./lib/gallery.php 162 +- $other = new Profile(); ++ function show_gallery($profile, $page, $display='list', $tag=null) + { -+ $pidfilename = $this->pidFilename(); -hunk ./lib/daemon.php 68 -- function changeUser() { -+ if (!$pidfilename) { -+ return false; ++ $other = new Profile(); +hunk ./lib/gallery.php 166 +- list($lst, $usr) = $this->fields(); ++ list($lst, $usr) = $this->fields(); +hunk ./lib/gallery.php 168 +- $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; ++ $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; +hunk ./lib/gallery.php 170 +- $offset = ($page-1)*$per_page; +- $limit = $per_page + 1; ++ $offset = ($page-1)*$per_page; ++ $limit = $per_page + 1; +hunk ./lib/gallery.php 173 +- if (common_config('db','type') == 'pgsql') { +- $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; +- } else { +- $lim = ' LIMIT ' . $offset . ', ' . $limit; +- } ++ if (common_config('db', 'type') == 'pgsql') { ++ $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; ++ } else { ++ $lim = ' LIMIT ' . $offset . ', ' . $limit; + } -hunk ./lib/daemon.php 72 -- $username = common_config('daemon', 'user'); -- -- if ($username) { -- $user_info = posix_getpwnam($username); -- if (!$user_info) { -- common_log(LOG_WARNING, 'Ignoring unknown user for daemon: ' . $username); -- } else { -- common_log(LOG_INFO, "Setting user to " . $username); -- posix_setuid($user_info['uid']); -- } +hunk ./lib/gallery.php 179 +- # XXX: memcached results +- # FIXME: SQL injection on $tag ++ // XXX: memcached results ++ // FIXME: SQL injection on $tag +hunk ./lib/gallery.php 182 +- $other->query('SELECT profile.* ' . +- 'FROM profile JOIN subscription ' . +- 'ON profile.id = subscription.' . $lst . ' ' . +- (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . +- 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . +- 'AND subscriber != subscribed ' . +- (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . +- 'ORDER BY subscription.created DESC, profile.id DESC ' . +- $lim); ++ $other->query('SELECT profile.* ' . ++ 'FROM profile JOIN subscription ' . ++ 'ON profile.id = subscription.' . $lst . ' ' . ++ (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . ++ 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . ++ 'AND subscriber != subscribed ' . ++ (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . ++ 'ORDER BY subscription.created DESC, profile.id DESC ' . ++ $lim); +hunk ./lib/gallery.php 192 +- if ($display == 'list') { ++ if ($display == 'list') { +hunk ./lib/gallery.php 194 +- $profile_list = new $cls($other, $profile, $this->trimmed('action')); +- $cnt = $profile_list->show_list(); +- } else { +- $cnt = $this->icon_list($other); - } -+ return file_put_contents($pidfilename, posix_getpid() . "\n"); ++ $profile_list = new $cls($other, $profile, $this->trimmed('action')); ++ $cnt = $profile_list->show_list(); ++ } else { ++ $cnt = $this->icon_list($other); ++ } +hunk ./lib/gallery.php 200 +- # For building the pagination URLs ++ // For building the pagination URLs +hunk ./lib/gallery.php 202 +- $args = array('nickname' => $profile->nickname); ++ $args = array('nickname' => $profile->nickname); +hunk ./lib/gallery.php 204 +- if ($display != 'list') { +- $args['display'] = $display; +- } ++ if ($display != 'list') { ++ $args['display'] = $display; ++ } +hunk ./lib/gallery.php 208 +- common_pagination($page > 1, +- $cnt > $per_page, +- $page, +- $this->trimmed('action'), +- $args); +- } ++ common_pagination($page > 1, ++ $cnt > $per_page, ++ $page, ++ $this->trimmed('action'), ++ $args); + } -hunk ./lib/daemon.php 75 -- $groupname = common_config('daemon', 'group'); -- -- if ($groupname) { -- $group_info = posix_getgrnam($groupname); -- if (!$group_info) { -- common_log(LOG_WARNING, 'Ignoring unknown group for daemon: ' . $groupname); -- } else { -- common_log(LOG_INFO, "Setting group to " . $groupname); -- posix_setgid($group_info['gid']); +hunk ./lib/gallery.php 215 +- function profile_list_class() { ++ function profile_list_class() ++ { +hunk ./lib/gallery.php 220 +- function icon_list($other) { ++ function icon_list($other) ++ { ++ common_element_start('ul', $this->div_class()); +hunk ./lib/gallery.php 224 +- common_element_start('ul', $this->div_class()); ++ $cnt = 0; +hunk ./lib/gallery.php 226 +- $cnt = 0; ++ while ($other->fetch()) { +hunk ./lib/gallery.php 228 +- while ($other->fetch()) { ++ $cnt++; +hunk ./lib/gallery.php 230 +- $cnt++; ++ if ($cnt > AVATARS_PER_PAGE) { ++ break; ++ } +hunk ./lib/gallery.php 234 +- if ($cnt > AVATARS_PER_PAGE) { +- break; - } ++ common_element_start('li'); +hunk ./lib/gallery.php 236 +- common_element_start('li'); ++ common_element_start('a', array('title' => ($other->fullname) ? ++ $other->fullname : ++ $other->nickname, ++ 'href' => $other->profileurl, ++ 'class' => 'subscription')); ++ $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); ++ common_element('img', ++ array('src' => ++ (($avatar) ? common_avatar_display_url($avatar) : ++ common_default_avatar(AVATAR_STREAM_SIZE)), ++ 'width' => AVATAR_STREAM_SIZE, ++ 'height' => AVATAR_STREAM_SIZE, ++ 'class' => 'avatar stream', ++ 'alt' => ($other->fullname) ? ++ $other->fullname : ++ $other->nickname)); ++ common_element_end('a'); +hunk ./lib/gallery.php 254 +- common_element_start('a', array('title' => ($other->fullname) ? +- $other->fullname : +- $other->nickname, +- 'href' => $other->profileurl, +- 'class' => 'subscription')); +- $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); +- common_element('img', +- array('src' => +- (($avatar) ? common_avatar_display_url($avatar) : +- common_default_avatar(AVATAR_STREAM_SIZE)), +- 'width' => AVATAR_STREAM_SIZE, +- 'height' => AVATAR_STREAM_SIZE, +- 'class' => 'avatar stream', +- 'alt' => ($other->fullname) ? +- $other->fullname : +- $other->nickname)); +- common_element_end('a'); ++ // XXX: subscribe form here +hunk ./lib/gallery.php 256 +- # XXX: subscribe form here ++ common_element_end('li'); ++ } +hunk ./lib/gallery.php 259 +- common_element_end('li'); - } ++ common_element_end('ul'); +hunk ./lib/gallery.php 261 +- common_element_end('ul'); +- +- return $cnt; - } -- -- function runOnce() { -- if ($this->alreadyRunning()) { -- common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); -- exit(0); -- } -- if ($this->background()) { -- $this->writePidFile(); -- $this->changeUser(); -- $this->run(); -- $this->clearPidFile(); -- } ++ return $cnt; ++ } +hunk ./lib/gallery.php 264 +- function gallery_type() { +- return NULL; - } -- -- function run() { -- return true; ++ function gallery_type() ++ { ++ return null; ++ } +hunk ./lib/gallery.php 269 +- function get_instructions(&$profile) { +- return NULL; - } -+ function clearPidFile() ++ function get_instructions(&$profile) + { -+ $pidfilename = $this->pidFilename(); -+ if (!$pidfilename) { -+ return false; -+ } -+ return unlink($pidfilename); ++ return null; + } -+ -+ function pidFilename() +hunk ./lib/gallery.php 274 +- function fields() { +- return NULL; +- } ++ function fields() + { -+ $piddir = common_config('daemon', 'piddir'); -+ if (!$piddir) { -+ return null; -+ } -+ $name = $this->name(); -+ if (!$name) { -+ return null; -+ } -+ return $piddir . '/' . $name . '.pid'; ++ return null; + } -+ -+ function changeUser() +hunk ./lib/gallery.php 279 +- function div_class() { +- return ''; +- } ++ function div_class() + { -+ $username = common_config('daemon', 'user'); -+ -+ if ($username) { -+ $user_info = posix_getpwnam($username); -+ if (!$user_info) { -+ common_log(LOG_WARNING, -+ 'Ignoring unknown user for daemon: ' . $username); -+ } else { -+ common_log(LOG_INFO, "Setting user to " . $username); -+ posix_setuid($user_info['uid']); ++ return ''; ++ } +hunk ./lib/gallery.php 284 +- function display_links($profile, $page, $display) { +- $tag = $this->trimmed('tag'); ++ function display_links($profile, $page, $display) ++ { ++ $tag = $this->trimmed('tag'); +hunk ./lib/gallery.php 288 +- common_element_start('dl', array('id'=>'subscriptions_nav')); +- common_element('dt', null, _('Subscriptions navigation')); +- common_element_start('dd'); +- common_element_start('ul', array('class'=>'nav')); ++ common_element_start('dl', array('id'=>'subscriptions_nav')); ++ common_element('dt', null, _('Subscriptions navigation')); ++ common_element_start('dd'); ++ common_element_start('ul', array('class'=>'nav')); +hunk ./lib/gallery.php 293 +- switch ($display) { +- case 'list': +- common_element('li', array('class'=>'child_1'), _('List')); +- common_element_start('li'); +- $url_args = array('display' => 'icons', +- 'nickname' => $profile->nickname, +- 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); +- if ($tag) { +- $url_args['tag'] = $tag; +- } +- $url = common_local_url($this->trimmed('action'), $url_args); +- common_element('a', array('href' => $url), +- _('Icons')); +- common_element_end('li'); +- break; +- default: +- common_element_start('li', array('class'=>'child_1')); +- $url_args = array('nickname' => $profile->nickname, +- 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); +- if ($tag) { +- $url_args['tag'] = $tag; +- } +- $url = common_local_url($this->trimmed('action'), $url_args); +- common_element('a', array('href' => $url), +- _('List')); +- common_element_end('li'); +- common_element('li', NULL, _('Icons')); +- break; +- } ++ switch ($display) { ++ case 'list': ++ common_element('li', array('class'=>'child_1'), _('List')); ++ common_element_start('li'); ++ $url_args = array('display' => 'icons', ++ 'nickname' => $profile->nickname, ++ 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); ++ if ($tag) { ++ $url_args['tag'] = $tag; + } -+ } -+ -+ $groupname = common_config('daemon', 'group'); -+ -+ if ($groupname) { -+ $group_info = posix_getgrnam($groupname); -+ if (!$group_info) { -+ common_log(LOG_WARNING, -+ 'Ignoring unknown group for daemon: ' . $groupname); -+ } else { -+ common_log(LOG_INFO, "Setting group to " . $groupname); -+ posix_setgid($group_info['gid']); ++ $url = common_local_url($this->trimmed('action'), $url_args); ++ common_element('a', array('href' => $url), ++ _('Icons')); ++ common_element_end('li'); ++ break; ++ default: ++ common_element_start('li', array('class'=>'child_1')); ++ $url_args = array('nickname' => $profile->nickname, ++ 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); ++ if ($tag) { ++ $url_args['tag'] = $tag; + } ++ $url = common_local_url($this->trimmed('action'), $url_args); ++ common_element('a', array('href' => $url), ++ _('List')); ++ common_element_end('li'); ++ common_element('li', null, _('Icons')); ++ break; + } +hunk ./lib/gallery.php 323 +- common_element_end('ul'); +- common_element_end('dd'); +- common_element_end('dl'); +- } ++ common_element_end('ul'); ++ common_element_end('dd'); ++ common_element_end('dl'); + } -+ -+ function runOnce() +hunk ./lib/gallery.php 328 +- # Get list of tags we tagged other users with ++ // Get list of tags we tagged other users with +hunk ./lib/gallery.php 330 +- function get_all_tags($profile, $lst, $usr) { +- $profile_tag = new Notice_tag(); +- $profile_tag->query('SELECT DISTINCT(tag) ' . +- 'FROM profile_tag, subscription ' . +- 'WHERE tagger = ' . $profile->id . ' ' . +- 'AND ' . $usr . ' = ' . $profile->id . ' ' . +- 'AND ' . $lst . ' = tagged ' . +- 'AND tagger != tagged'); +- $tags = array(); +- while ($profile_tag->fetch()) { +- $tags[] = $profile_tag->tag; +- } +- $profile_tag->free(); +- return $tags; +- } ++ function get_all_tags($profile, $lst, $usr) + { -+ if ($this->alreadyRunning()) { -+ common_log(LOG_INFO, $this->name() . ' already running. Exiting.'); -+ exit(0); ++ $profile_tag = new Notice_tag(); ++ $profile_tag->query('SELECT DISTINCT(tag) ' . ++ 'FROM profile_tag, subscription ' . ++ 'WHERE tagger = ' . $profile->id . ' ' . ++ 'AND ' . $usr . ' = ' . $profile->id . ' ' . ++ 'AND ' . $lst . ' = tagged ' . ++ 'AND tagger != tagged'); ++ $tags = array(); ++ while ($profile_tag->fetch()) { ++ $tags[] = $profile_tag->tag; + } -+ if ($this->background()) { -+ $this->writePidFile(); -+ $this->changeUser(); -+ $this->run(); -+ $this->clearPidFile(); -+ } -+ } -+ -+ function run() -+ { -+ return true; ++ $profile_tag->free(); ++ return $tags; + } diff --git a/lib/gallery.php b/lib/gallery.php index 0dd351bab..34b58518c 100644 --- a/lib/gallery.php +++ b/lib/gallery.php @@ -1,6 +1,5 @@ . */ -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -require_once(INSTALLDIR.'/lib/profilelist.php'); +require_once INSTALLDIR.'/lib/profilelist.php'; -# 10x8 +// 10x8 define('AVATARS_PER_PAGE', 80); -class GalleryAction extends Action { - - function is_readonly() { - return true; - } - - function handle($args) { - parent::handle($args); - - # Post from the tag dropdown; redirect to a GET - - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - common_redirect($this->self_url(), 307); - } - - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); - - if (!$user) { - $this->no_such_user(); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - $this->server_error(_('User without matching profile in system.')); - return; - } - - $page = $this->arg('page'); - - if (!$page) { - $page = 1; - } - - $display = $this->arg('display'); - - if (!$display) { - $display = 'list'; - } - - $tag = $this->arg('tag'); - - common_show_header($profile->nickname . ": " . $this->gallery_type(), - NULL, $profile, - array($this, 'show_top')); - - $this->display_links($profile, $page, $display); - $this->show_tags_dropdown($profile); - - $this->show_gallery($profile, $page, $display, $tag); - common_show_footer(); - } - - function no_such_user() { - $this->client_error(_('No such user.')); - } - - function show_tags_dropdown($profile) { - $tag = $this->trimmed('tag'); - list($lst, $usr) = $this->fields(); - $tags = $this->get_all_tags($profile, $lst, $usr); - $content = array(); - foreach ($tags as $t) { - $content[$t] = $t; - } - if ($tags) { - common_element_start('dl', array('id'=>'filter_tags')); - common_element('dt', null, _('Filter tags')); - common_element_start('dd'); - common_element_start('ul'); - common_element_start('li', array('id'=>'filter_tags_all', 'class'=>'child_1')); - common_element('a', array('href' => common_local_url($this->trimmed('action'), - array('nickname' => $profile->nickname))), - _('All')); - common_element_end('li'); - common_element_start('li', array('id'=>'filter_tags_item')); - common_element_start('form', array('name' => 'bytag', 'id' => 'bytag', 'method' => 'post')); - common_dropdown('tag', _('Tag'), $content, - _('Choose a tag to narrow list'), FALSE, $tag); - common_submit('go', _('Go')); - common_element_end('form'); - common_element_end('li'); - common_element_end('ul'); - common_element_end('dd'); - common_element_end('dl'); - } - } - - function show_top($profile) { - common_element('div', 'instructions', - $this->get_instructions($profile)); +class GalleryAction extends Action +{ + function is_readonly() + { + return true; + } + + function handle($args) + { + parent::handle($args); + + // Post from the tag dropdown; redirect to a GET + + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + common_redirect($this->self_url(), 307); + } + + $nickname = common_canonical_nickname($this->arg('nickname')); + + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + $this->no_such_user(); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + $this->server_error(_('User without matching profile in system.')); + return; + } + + $page = $this->arg('page'); + + if (!$page) { + $page = 1; + } + + $display = $this->arg('display'); + + if (!$display) { + $display = 'list'; + } + + $tag = $this->arg('tag'); + + common_show_header($profile->nickname . ": " . $this->gallery_type(), + null, $profile, + array($this, 'show_top')); + + $this->display_links($profile, $page, $display); + $this->show_tags_dropdown($profile); + + $this->show_gallery($profile, $page, $display, $tag); + common_show_footer(); + } + + function no_such_user() + { + $this->client_error(_('No such user.')); + } + + function show_tags_dropdown($profile) + { + $tag = $this->trimmed('tag'); + + list($lst, $usr) = $this->fields(); + + $tags = $this->get_all_tags($profile, $lst, $usr); + + $content = array(); + + foreach ($tags as $t) { + $content[$t] = $t; + } + if ($tags) { + common_element_start('dl', array('id'=>'filter_tags')); + common_element('dt', null, _('Filter tags')); + common_element_start('dd'); + common_element_start('ul'); + common_element_start('li', array('id' => 'filter_tags_all', + 'class' => 'child_1')); + common_element('a', + array('href' => + common_local_url($this->trimmed('action'), + array('nickname' => + $profile->nickname))), + _('All')); + common_element_end('li'); + common_element_start('li', array('id'=>'filter_tags_item')); + common_element_start('form', array('name' => 'bytag', + 'id' => 'bytag', + 'method' => 'post')); + common_dropdown('tag', _('Tag'), $content, + _('Choose a tag to narrow list'), false, $tag); + common_submit('go', _('Go')); + common_element_end('form'); + common_element_end('li'); + common_element_end('ul'); + common_element_end('dd'); + common_element_end('dl'); + } + } + + function show_top($profile) + { + common_element('div', 'instructions', + $this->get_instructions($profile)); $this->show_menu(); - } - - function show_menu() { - # action => array('prompt', 'title', $args) - $action = $this->trimmed('action'); - $nickname = $this->trimmed('nickname'); - $menu = - array('subscriptions' => - array( _('Subscriptions'), - _('Subscriptions'), - array('nickname' => $nickname)), - 'subscribers' => - array( - _('Subscribers'), - _('Subscribers'), - array('nickname' => $nickname)), - ); - $this->nav_menu($menu); - } + } - function show_gallery($profile, $page, $display='list', $tag=NULL) { + function show_menu() + { + // action => array('prompt', 'title', $args) + $action = $this->trimmed('action'); + $nickname = $this->trimmed('nickname'); + + $menu = + array('subscriptions' => + array( _('Subscriptions'), + _('Subscriptions'), + array('nickname' => $nickname)), + 'subscribers' => + array( + _('Subscribers'), + _('Subscribers'), + array('nickname' => $nickname)), + ); + $this->nav_menu($menu); + } - $other = new Profile(); + function show_gallery($profile, $page, $display='list', $tag=null) + { + $other = new Profile(); - list($lst, $usr) = $this->fields(); + list($lst, $usr) = $this->fields(); - $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; + $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; - $offset = ($page-1)*$per_page; - $limit = $per_page + 1; + $offset = ($page-1)*$per_page; + $limit = $per_page + 1; - if (common_config('db','type') == 'pgsql') { - $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $lim = ' LIMIT ' . $offset . ', ' . $limit; - } + if (common_config('db', 'type') == 'pgsql') { + $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $lim = ' LIMIT ' . $offset . ', ' . $limit; + } - # XXX: memcached results - # FIXME: SQL injection on $tag + // XXX: memcached results + // FIXME: SQL injection on $tag - $other->query('SELECT profile.* ' . - 'FROM profile JOIN subscription ' . - 'ON profile.id = subscription.' . $lst . ' ' . - (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . - 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . - 'AND subscriber != subscribed ' . - (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . - 'ORDER BY subscription.created DESC, profile.id DESC ' . - $lim); + $other->query('SELECT profile.* ' . + 'FROM profile JOIN subscription ' . + 'ON profile.id = subscription.' . $lst . ' ' . + (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . + 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . + 'AND subscriber != subscribed ' . + (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . + 'ORDER BY subscription.created DESC, profile.id DESC ' . + $lim); - if ($display == 'list') { + if ($display == 'list') { $cls = $this->profile_list_class(); - $profile_list = new $cls($other, $profile, $this->trimmed('action')); - $cnt = $profile_list->show_list(); - } else { - $cnt = $this->icon_list($other); - } + $profile_list = new $cls($other, $profile, $this->trimmed('action')); + $cnt = $profile_list->show_list(); + } else { + $cnt = $this->icon_list($other); + } - # For building the pagination URLs + // For building the pagination URLs - $args = array('nickname' => $profile->nickname); + $args = array('nickname' => $profile->nickname); - if ($display != 'list') { - $args['display'] = $display; - } + if ($display != 'list') { + $args['display'] = $display; + } - common_pagination($page > 1, - $cnt > $per_page, - $page, - $this->trimmed('action'), - $args); - } + common_pagination($page > 1, + $cnt > $per_page, + $page, + $this->trimmed('action'), + $args); + } - function profile_list_class() { + function profile_list_class() + { return 'ProfileList'; } - function icon_list($other) { - - common_element_start('ul', $this->div_class()); - - $cnt = 0; - - while ($other->fetch()) { - - $cnt++; - - if ($cnt > AVATARS_PER_PAGE) { - break; - } - - common_element_start('li'); - - common_element_start('a', array('title' => ($other->fullname) ? - $other->fullname : - $other->nickname, - 'href' => $other->profileurl, - 'class' => 'subscription')); - $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); - common_element('img', - array('src' => - (($avatar) ? common_avatar_display_url($avatar) : - common_default_avatar(AVATAR_STREAM_SIZE)), - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'class' => 'avatar stream', - 'alt' => ($other->fullname) ? - $other->fullname : - $other->nickname)); - common_element_end('a'); - - # XXX: subscribe form here - - common_element_end('li'); - } - - common_element_end('ul'); - - return $cnt; - } - - function gallery_type() { - return NULL; - } - - function get_instructions(&$profile) { - return NULL; - } - - function fields() { - return NULL; - } - - function div_class() { - return ''; - } - - function display_links($profile, $page, $display) { - $tag = $this->trimmed('tag'); - - common_element_start('dl', array('id'=>'subscriptions_nav')); - common_element('dt', null, _('Subscriptions navigation')); - common_element_start('dd'); - common_element_start('ul', array('class'=>'nav')); - - switch ($display) { - case 'list': - common_element('li', array('class'=>'child_1'), _('List')); - common_element_start('li'); - $url_args = array('display' => 'icons', - 'nickname' => $profile->nickname, - 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); - if ($tag) { - $url_args['tag'] = $tag; - } - $url = common_local_url($this->trimmed('action'), $url_args); - common_element('a', array('href' => $url), - _('Icons')); - common_element_end('li'); - break; - default: - common_element_start('li', array('class'=>'child_1')); - $url_args = array('nickname' => $profile->nickname, - 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); - if ($tag) { - $url_args['tag'] = $tag; - } - $url = common_local_url($this->trimmed('action'), $url_args); - common_element('a', array('href' => $url), - _('List')); - common_element_end('li'); - common_element('li', NULL, _('Icons')); - break; - } - - common_element_end('ul'); - common_element_end('dd'); - common_element_end('dl'); - } - - # Get list of tags we tagged other users with - - function get_all_tags($profile, $lst, $usr) { - $profile_tag = new Notice_tag(); - $profile_tag->query('SELECT DISTINCT(tag) ' . - 'FROM profile_tag, subscription ' . - 'WHERE tagger = ' . $profile->id . ' ' . - 'AND ' . $usr . ' = ' . $profile->id . ' ' . - 'AND ' . $lst . ' = tagged ' . - 'AND tagger != tagged'); - $tags = array(); - while ($profile_tag->fetch()) { - $tags[] = $profile_tag->tag; - } - $profile_tag->free(); - return $tags; - } + function icon_list($other) + { + common_element_start('ul', $this->div_class()); + + $cnt = 0; + + while ($other->fetch()) { + + $cnt++; + + if ($cnt > AVATARS_PER_PAGE) { + break; + } + + common_element_start('li'); + + common_element_start('a', array('title' => ($other->fullname) ? + $other->fullname : + $other->nickname, + 'href' => $other->profileurl, + 'class' => 'subscription')); + $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); + common_element('img', + array('src' => + (($avatar) ? common_avatar_display_url($avatar) : + common_default_avatar(AVATAR_STREAM_SIZE)), + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'class' => 'avatar stream', + 'alt' => ($other->fullname) ? + $other->fullname : + $other->nickname)); + common_element_end('a'); + + // XXX: subscribe form here + + common_element_end('li'); + } + + common_element_end('ul'); + + return $cnt; + } + + function gallery_type() + { + return null; + } + + function get_instructions(&$profile) + { + return null; + } + + function fields() + { + return null; + } + + function div_class() + { + return ''; + } + + function display_links($profile, $page, $display) + { + $tag = $this->trimmed('tag'); + + common_element_start('dl', array('id'=>'subscriptions_nav')); + common_element('dt', null, _('Subscriptions navigation')); + common_element_start('dd'); + common_element_start('ul', array('class'=>'nav')); + + switch ($display) { + case 'list': + common_element('li', array('class'=>'child_1'), _('List')); + common_element_start('li'); + $url_args = array('display' => 'icons', + 'nickname' => $profile->nickname, + 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); + if ($tag) { + $url_args['tag'] = $tag; + } + $url = common_local_url($this->trimmed('action'), $url_args); + common_element('a', array('href' => $url), + _('Icons')); + common_element_end('li'); + break; + default: + common_element_start('li', array('class'=>'child_1')); + $url_args = array('nickname' => $profile->nickname, + 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); + if ($tag) { + $url_args['tag'] = $tag; + } + $url = common_local_url($this->trimmed('action'), $url_args); + common_element('a', array('href' => $url), + _('List')); + common_element_end('li'); + common_element('li', null, _('Icons')); + break; + } + + common_element_end('ul'); + common_element_end('dd'); + common_element_end('dl'); + } + + // Get list of tags we tagged other users with + + function get_all_tags($profile, $lst, $usr) + { + $profile_tag = new Notice_tag(); + $profile_tag->query('SELECT DISTINCT(tag) ' . + 'FROM profile_tag, subscription ' . + 'WHERE tagger = ' . $profile->id . ' ' . + 'AND ' . $usr . ' = ' . $profile->id . ' ' . + 'AND ' . $lst . ' = tagged ' . + 'AND tagger != tagged'); + $tags = array(); + while ($profile_tag->fetch()) { + $tags[] = $profile_tag->tag; + } + $profile_tag->free(); + return $tags; + } } \ No newline at end of file -- cgit v1.2.3-54-g00ecf From 8cd89d80f147d602b232bd18232f06ce5afc3718 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 22 Dec 2008 12:32:49 -0500 Subject: reformat lib/jabber.php for phpcs, including doc comments darcs-hash:20081222173249-84dde-202ba409e32e2b27089a1bc5431507c9d8a2782e.gz --- _darcs/inventory | 4 +- ...dde-202ba409e32e2b27089a1bc5431507c9d8a2782e.gz | Bin 0 -> 5199 bytes _darcs/pristine/lib/jabber.php | 655 ++++++----- _darcs/tentative_pristine | 1143 +++++++++++--------- lib/jabber.php | 655 ++++++----- 5 files changed, 1444 insertions(+), 1013 deletions(-) create mode 100644 _darcs/patches/20081222173249-84dde-202ba409e32e2b27089a1bc5431507c9d8a2782e.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 3fba38822..b3846949e 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -29,4 +29,6 @@ Evan Prodromou **20081221003955] [reformat lib/daemon.php for phpcs Evan Prodromou **20081221004607] [reformat for phpcs -Evan Prodromou **20081221005837] \ No newline at end of file +Evan Prodromou **20081221005837] +[reformat lib/jabber.php for phpcs, including doc comments +Evan Prodromou **20081222173249] \ No newline at end of file diff --git a/_darcs/patches/20081222173249-84dde-202ba409e32e2b27089a1bc5431507c9d8a2782e.gz b/_darcs/patches/20081222173249-84dde-202ba409e32e2b27089a1bc5431507c9d8a2782e.gz new file mode 100644 index 000000000..908bf5769 Binary files /dev/null and b/_darcs/patches/20081222173249-84dde-202ba409e32e2b27089a1bc5431507c9d8a2782e.gz differ diff --git a/_darcs/pristine/lib/jabber.php b/_darcs/pristine/lib/jabber.php index ab0fd6af8..099ded9eb 100644 --- a/_darcs/pristine/lib/jabber.php +++ b/_darcs/pristine/lib/jabber.php @@ -1,9 +1,12 @@ . + * + * @category Network + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} -require_once('XMPPHP/XMPP.php'); +require_once 'XMPPHP/XMPP.php'; -function jabber_valid_base_jid($jid) { - # Cheap but effective - return Validate::email($jid); -} +/** + * checks whether a string is a syntactically valid Jabber ID (JID) + * + * @param string $jid string to check + * + * @return boolean whether the string is a valid JID + */ -function jabber_normalize_jid($jid) { - if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { - $node = $matches[1]; - $server = $matches[2]; - return strtolower($node.'@'.$server); - } else { - return NULL; - } +function jabber_valid_base_jid($jid) +{ + // Cheap but effective + return Validate::email($jid); } -function jabber_daemon_address() { - return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); +/** + * normalizes a Jabber ID for comparison + * + * @param string $jid JID to check + * + * @return string an equivalent JID in normalized (lowercase) form + */ + +function jabber_normalize_jid($jid) +{ + if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { + $node = $matches[1]; + $server = $matches[2]; + return strtolower($node.'@'.$server); + } else { + return null; + } } -function jabber_connect($resource=NULL) { - static $conn = NULL; - if (!$conn) { - $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? - common_config('xmpp', 'host') : - common_config('xmpp', 'server'), - common_config('xmpp', 'port'), - common_config('xmpp', 'user'), - common_config('xmpp', 'password'), - ($resource) ? $resource : - common_config('xmpp', 'resource'), - common_config('xmpp', 'server'), - common_config('xmpp', 'debug') ? - true : false, - common_config('xmpp', 'debug') ? - XMPPHP_Log::LEVEL_VERBOSE : NULL - ); - - if (!$conn) { - return false; - } - - $conn->autoSubscribe(); - $conn->useEncryption(common_config('xmpp', 'encryption')); - - try { - $conn->connect(true); # true = persistent connection - } catch (XMPPHP_Exception $e) { - common_log(LOG_ERROR, $e->getMessage()); - return false; - } - - $conn->processUntil('session_start'); - } - return $conn; +/** + * the JID of the Jabber daemon for this Laconica instance + * + * @return string JID of the Jabber daemon + */ + +function jabber_daemon_address() +{ + return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); } -function jabber_send_notice($to, $notice) { - $conn = jabber_connect(); - if (!$conn) { - return false; - } - $profile = Profile::staticGet($notice->profile_id); - if (!$profile) { - common_log(LOG_WARNING, 'Refusing to send notice with ' . - 'unknown profile ' . common_log_objstring($notice), - __FILE__); - return false; - } - $msg = jabber_format_notice($profile, $notice); - $entry = jabber_format_entry($profile, $notice); - $conn->message($to, $msg, 'chat', NULL, $entry); - $profile->free(); - return true; +/** + * connect the configured Jabber account to the configured server + * + * @param string $resource Resource to connect (defaults to configured resource) + * + * @return XMPPHP connection to the configured server + */ + +function jabber_connect($resource=null) +{ + static $conn = null; + if (!$conn) { + $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? + common_config('xmpp', 'host') : + common_config('xmpp', 'server'), + common_config('xmpp', 'port'), + common_config('xmpp', 'user'), + common_config('xmpp', 'password'), + ($resource) ? $resource : + common_config('xmpp', 'resource'), + common_config('xmpp', 'server'), + common_config('xmpp', 'debug') ? + true : false, + common_config('xmpp', 'debug') ? + XMPPHP_Log::LEVEL_VERBOSE : null + ); + + if (!$conn) { + return false; + } + + $conn->autoSubscribe(); + $conn->useEncryption(common_config('xmpp', 'encryption')); + + try { + $conn->connect(true); // true = persistent connection + } catch (XMPPHP_Exception $e) { + common_log(LOG_ERROR, $e->getMessage()); + return false; + } + + $conn->processUntil('session_start'); + } + return $conn; } -# Extra stuff defined by Twitter, needed by twitter clients - -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); - $entry = "\n\n"; - $entry .= "\n"; - $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; - $entry .= "\n"; - $entry .= " $profile->nickname)) . "'/>\n"; - $entry .= "" . $profile->nickname . "\n"; - $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; - $entry .= "\n"; - $entry .= "" . htmlspecialchars($msg) . "\n"; - $entry .= "" . htmlspecialchars($msg) . "\n"; - $entry .= "\n"; - $entry .= "". $notice->uri . "\n"; - $entry .= "".common_date_w3dtf($notice->created)."\n"; - $entry .= "".common_date_w3dtf($notice->modified)."\n"; - $entry .= "\n"; - - $html = "\n\n"; - $html .= "\n"; - $html .= "".$profile->nickname.": "; - $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); - $html .= "\n\n"; - $html .= "\n\n"; - - $address = "\n"; - $address .= "
\n"; - $address .= "\n"; - - # FIXME: include a pubsub event, too. - - return $html . $entry . $address; +/** + * send a single notice to a given Jabber address + * + * @param string $to JID to send the notice to + * @param Notice $notice notice to send + * + * @return boolean success value + */ + +function jabber_send_notice($to, $notice) +{ + $conn = jabber_connect(); + if (!$conn) { + return false; + } + $profile = Profile::staticGet($notice->profile_id); + if (!$profile) { + common_log(LOG_WARNING, 'Refusing to send notice with ' . + 'unknown profile ' . common_log_objstring($notice), + __FILE__); + return false; + } + $msg = jabber_format_notice($profile, $notice); + $entry = jabber_format_entry($profile, $notice); + $conn->message($to, $msg, 'chat', null, $entry); + $profile->free(); + return true; } -function jabber_send_message($to, $body, $type='chat', $subject=NULL) { - $conn = jabber_connect(); - if (!$conn) { - return false; - } - $conn->message($to, $body, $type, $subject); - return true; +/** + * extra information for XMPP messages, as defined by Twitter + * + * @param Profile $profile Profile of the sending user + * @param Notice $notice Notice being sent + * + * @return string Extra information (Atom, HTML, addresses) in string format + */ + +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\n"; + $entry .= "\n"; + $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; + $entry .= "\n"; + $entry .= "\n"; + $entry .= "" . $profile->nickname . "\n"; + $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; + $entry .= "\n"; + $entry .= "" . htmlspecialchars($msg) . "\n"; + $entry .= "" . htmlspecialchars($msg) . "\n"; + $entry .= "\n"; + $entry .= "". $notice->uri . "\n"; + $entry .= "".common_date_w3dtf($notice->created)."\n"; + $entry .= "".common_date_w3dtf($notice->modified)."\n"; + $entry .= "\n"; + + $html = "\n\n"; + $html .= "\n"; + $html .= "".$profile->nickname.": "; + $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); + $html .= "\n\n"; + $html .= "\n\n"; + + $address = "\n"; + $address .= "
\n"; + $address .= "\n"; + + // FIXME: include a pubsub event, too. + + return $html . $entry . $address; } -function jabber_send_presence($status, $show='available', $to=NULL, - $type = 'available', $priority=NULL) +/** + * sends a single text message to a given JID + * + * @param string $to JID to send the message to + * @param string $body body of the message + * @param string $type type of the message + * @param string $subject subject of the message + * + * @return boolean success flag + */ + +function jabber_send_message($to, $body, $type='chat', $subject=null) { - $conn = jabber_connect(); - if (!$conn) { - return false; - } - $conn->presence($status, $show, $to, $type, $priority); - return true; + $conn = jabber_connect(); + if (!$conn) { + return false; + } + $conn->message($to, $body, $type, $subject); + return true; } -function jabber_confirm_address($code, $nickname, $address) { - $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . - 'has said that your Jabber ID belongs to them. ' . - 'If that\'s true, you can confirm by clicking on this URL: ' . - common_local_url('confirmaddress', array('code' => $code)) . - ' . (If you cannot click it, copy-and-paste it into the ' . - 'address bar of your browser). If that user isn\'t you, ' . - 'or if you didn\'t request this confirmation, just ignore this message.'; +/** + * sends a presence stanza on the Jabber network + * + * @param string $status current status, free-form string + * @param string $show structured status value + * @param string $to recipient of presence, null for general + * @param string $type type of status message, related to $show + * @param int $priority priority of the presence + * + * @return boolean success value + */ - return jabber_send_message($address, $body); +function jabber_send_presence($status, $show='available', $to=null, + $type = 'available', $priority=null) +{ + $conn = jabber_connect(); + if (!$conn) { + return false; + } + $conn->presence($status, $show, $to, $type, $priority); + return true; } -function jabber_special_presence($type, $to=NULL, $show=NULL, $status=NULL) { - $conn = jabber_connect(); - - $to = htmlspecialchars($to); - $status = htmlspecialchars($status); - $out = "send($out); +/** + * sends a confirmation request to a JID + * + * @param string $code confirmation code for confirmation URL + * @param string $nickname nickname of confirming user + * @param string $address JID to send confirmation to + * + * @return boolean success flag + */ + +function jabber_confirm_address($code, $nickname, $address) +{ + $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . + 'has said that your Jabber ID belongs to them. ' . + 'If that\'s true, you can confirm by clicking on this URL: ' . + common_local_url('confirmaddress', array('code' => $code)) . + ' . (If you cannot click it, copy-and-paste it into the ' . + 'address bar of your browser). If that user isn\'t you, ' . + 'or if you didn\'t request this confirmation, just ignore this message.'; + + return jabber_send_message($address, $body); } -function jabber_broadcast_notice($notice) { - - if (!common_config('xmpp', 'enabled')) { - return true; - } - $profile = Profile::staticGet($notice->profile_id); - - if (!$profile) { - common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . - 'unknown profile ' . common_log_objstring($notice), - __FILE__); - return false; - } - - $msg = jabber_format_notice($profile, $notice); - $entry = jabber_format_entry($profile, $notice); - - $profile->free(); - unset($profile); - - $sent_to = array(); - $conn = jabber_connect(); - - # First, get users to whom this is a direct reply - $user = new User(); - $user->query('SELECT user.id, user.jabber ' . - 'FROM user JOIN reply ON user.id = reply.profile_id ' . - 'WHERE reply.notice_id = ' . $notice->id . ' ' . - 'AND user.jabber is not null ' . - 'AND user.jabbernotify = 1 ' . - 'AND user.jabberreplies = 1 '); - - while ($user->fetch()) { - common_log(LOG_INFO, - 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, - __FILE__); - $conn->message($user->jabber, $msg, 'chat', NULL, $entry); - $conn->processTime(0); - $sent_to[$user->id] = 1; - } - - $user->free(); - - # Now, get users subscribed to this profile - - $user = new User(); - $user->query('SELECT user.id, user.jabber ' . - 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . - 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . - 'AND user.jabber is not null ' . - 'AND user.jabbernotify = 1 ' . - 'AND subscription.jabber = 1 '); +/** + * sends a "special" presence stanza on the Jabber network + * + * @param string $type Type of presence + * @param string $to JID to send presence to + * @param string $show show value for presence + * @param string $status status value for presence + * + * @return boolean success flag + * + * @see jabber_send_presence() + */ - while ($user->fetch()) { - if (!array_key_exists($user->id, $sent_to)) { - common_log(LOG_INFO, - 'Sending notice ' . $notice->id . ' to ' . $user->jabber, - __FILE__); - $conn->message($user->jabber, $msg, 'chat', NULL, $entry); - # To keep the incoming queue from filling up, we service it after each send. - $conn->processTime(0); - } - } +function jabber_special_presence($type, $to=null, $show=null, $status=null) +{ + // FIXME: why use this instead of jabber_send_presence()? + $conn = jabber_connect(); + + $to = htmlspecialchars($to); + $status = htmlspecialchars($status); + + $out = "send($out); +} - $user->free(); +/** + * broadcast a notice to all subscribers and reply recipients + * + * This function will send a notice to all subscribers on the local server + * who have Jabber addresses, and have Jabber notification enabled, and + * have this subscription enabled for Jabber. It also sends the notice to + * all recipients of @-replies who have Jabber addresses and Jabber notification + * enabled. This is really the heart of Jabber distribution in Laconica. + * + * @param Notice $notice The notice to broadcast + * + * @return boolean success flag + */ - return true; +function jabber_broadcast_notice($notice) +{ + if (!common_config('xmpp', 'enabled')) { + return true; + } + $profile = Profile::staticGet($notice->profile_id); + + if (!$profile) { + common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . + 'unknown profile ' . common_log_objstring($notice), + __FILE__); + return false; + } + + $msg = jabber_format_notice($profile, $notice); + $entry = jabber_format_entry($profile, $notice); + + $profile->free(); + unset($profile); + + $sent_to = array(); + + $conn = jabber_connect(); + + // First, get users to whom this is a direct reply + $user = new User(); + $user->query('SELECT user.id, user.jabber ' . + 'FROM user JOIN reply ON user.id = reply.profile_id ' . + 'WHERE reply.notice_id = ' . $notice->id . ' ' . + 'AND user.jabber is not null ' . + 'AND user.jabbernotify = 1 ' . + 'AND user.jabberreplies = 1 '); + + while ($user->fetch()) { + common_log(LOG_INFO, + 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, + __FILE__); + $conn->message($user->jabber, $msg, 'chat', null, $entry); + $conn->processTime(0); + $sent_to[$user->id] = 1; + } + + $user->free(); + + // Now, get users subscribed to this profile + + $user = new User(); + $user->query('SELECT user.id, user.jabber ' . + 'FROM user JOIN subscription ' . + 'ON user.id = subscription.subscriber ' . + 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . + 'AND user.jabber is not null ' . + 'AND user.jabbernotify = 1 ' . + 'AND subscription.jabber = 1 '); + + while ($user->fetch()) { + if (!array_key_exists($user->id, $sent_to)) { + common_log(LOG_INFO, + 'Sending notice ' . $notice->id . ' to ' . $user->jabber, + __FILE__); + $conn->message($user->jabber, $msg, 'chat', null, $entry); + // To keep the incoming queue from filling up, + // we service it after each send. + $conn->processTime(0); + } + } + + $user->free(); + + return true; } -function jabber_public_notice($notice) { +/** + * send a notice to all public listeners + * + * For notices that are generated on the local system (by users), we can optionally + * forward them to remote listeners by XMPP. + * + * @param Notice $notice notice to broadcast + * + * @return boolean success flag + */ - # Now, users who want everything +function jabber_public_notice($notice) +{ + // Now, users who want everything - $public = common_config('xmpp', 'public'); + $public = common_config('xmpp', 'public'); - # FIXME PRIV don't send out private messages here - # XXX: should we send out non-local messages if public,localonly - # = false? I think not + // FIXME PRIV don't send out private messages here + // XXX: should we send out non-local messages if public,localonly + // = false? I think not - if ($public && $notice->is_local) { - $profile = Profile::staticGet($notice->profile_id); + if ($public && $notice->is_local) { + $profile = Profile::staticGet($notice->profile_id); - if (!$profile) { - common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . - 'unknown profile ' . common_log_objstring($notice), - __FILE__); - return false; - } + if (!$profile) { + common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . + 'unknown profile ' . common_log_objstring($notice), + __FILE__); + return false; + } - $msg = jabber_format_notice($profile, $notice); - $entry = jabber_format_entry($profile, $notice); + $msg = jabber_format_notice($profile, $notice); + $entry = jabber_format_entry($profile, $notice); - $conn = jabber_connect(); + $conn = jabber_connect(); - foreach ($public as $address) { - common_log(LOG_INFO, - 'Sending notice ' . $notice->id . ' to public listener ' . $address, - __FILE__); - $conn->message($address, $msg, 'chat', NULL, $entry); - $conn->processTime(0); - } - $profile->free(); - } + foreach ($public as $address) { + common_log(LOG_INFO, + 'Sending notice ' . $notice->id . + ' to public listener ' . $address, + __FILE__); + $conn->message($address, $msg, 'chat', null, $entry); + $conn->processTime(0); + } + $profile->free(); + } - return true; + return true; } -function jabber_format_notice(&$profile, &$notice) { - return $profile->nickname . ': ' . $notice->content; +/** + * makes a plain-text formatted version of a notice, suitable for Jabber distribution + * + * @param Profile &$profile profile of the sending user + * @param Notice &$notice notice being sent + * + * @return string plain-text version of the notice, with user nickname prefixed + */ + +function jabber_format_notice(&$profile, &$notice) +{ + return $profile->nickname . ': ' . $notice->content; } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 4e6b1fca9..402ea252b 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,562 +1,661 @@ -hunk ./lib/gallery.php 2 -- +hunk ./lib/jabber.php 2 -/* +- * Laconica - a distributed open-source microblogging tool +- * Copyright (C) 2008, Controlez-Vous, Inc. +/** -hunk ./lib/gallery.php 20 ++ * Laconica, the distributed open-source microblogging tool +hunk ./lib/jabber.php 5 +- * This program is free software: you can redistribute it and/or modify ++ * utility functions for Jabber/GTalk/XMPP messages ++ * ++ * PHP version 5 ++ * ++ * LICENCE: This program is free software: you can redistribute it and/or modify +hunk ./lib/jabber.php 21 ++ * ++ * @category Network ++ * @package Laconica ++ * @author Evan Prodromou ++ * @copyright 2008 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/ +hunk ./lib/jabber.php 30 -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/gallery.php 24 --require_once(INSTALLDIR.'/lib/profilelist.php'); -+require_once INSTALLDIR.'/lib/profilelist.php'; -hunk ./lib/gallery.php 26 --# 10x8 -+// 10x8 -hunk ./lib/gallery.php 30 --class GalleryAction extends Action { -+class GalleryAction extends Action -+{ -+ function is_readonly() -+ { -+ return true; -+ } +hunk ./lib/jabber.php 34 +-require_once('XMPPHP/XMPP.php'); ++require_once 'XMPPHP/XMPP.php'; +hunk ./lib/jabber.php 36 +-function jabber_valid_base_jid($jid) { +- # Cheap but effective +- return Validate::email($jid); ++/** ++ * checks whether a string is a syntactically valid Jabber ID (JID) ++ * ++ * @param string $jid string to check ++ * ++ * @return boolean whether the string is a valid JID ++ */ + -+ function handle($args) -+ { -+ parent::handle($args); ++function jabber_valid_base_jid($jid) ++{ ++ // Cheap but effective ++ return Validate::email($jid); +hunk ./lib/jabber.php 50 +-function jabber_normalize_jid($jid) { +- if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { +- $node = $matches[1]; +- $server = $matches[2]; +- return strtolower($node.'@'.$server); +- } else { +- return NULL; +- } ++/** ++ * normalizes a Jabber ID for comparison ++ * ++ * @param string $jid JID to check ++ * ++ * @return string an equivalent JID in normalized (lowercase) form ++ */ + -+ // Post from the tag dropdown; redirect to a GET ++function jabber_normalize_jid($jid) ++{ ++ if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { ++ $node = $matches[1]; ++ $server = $matches[2]; ++ return strtolower($node.'@'.$server); ++ } else { ++ return null; ++ } +hunk ./lib/jabber.php 69 +-function jabber_daemon_address() { +- return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); ++/** ++ * the JID of the Jabber daemon for this Laconica instance ++ * ++ * @return string JID of the Jabber daemon ++ */ + -+ if ($_SERVER['REQUEST_METHOD'] == 'POST') { -+ common_redirect($this->self_url(), 307); -+ } ++function jabber_daemon_address() ++{ ++ return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); +hunk ./lib/jabber.php 80 +-function jabber_connect($resource=NULL) { +- static $conn = NULL; +- if (!$conn) { +- $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? +- common_config('xmpp', 'host') : +- common_config('xmpp', 'server'), +- common_config('xmpp', 'port'), +- common_config('xmpp', 'user'), +- common_config('xmpp', 'password'), +- ($resource) ? $resource : +- common_config('xmpp', 'resource'), +- common_config('xmpp', 'server'), +- common_config('xmpp', 'debug') ? +- true : false, +- common_config('xmpp', 'debug') ? +- XMPPHP_Log::LEVEL_VERBOSE : NULL +- ); ++/** ++ * connect the configured Jabber account to the configured server ++ * ++ * @param string $resource Resource to connect (defaults to configured resource) ++ * ++ * @return XMPPHP connection to the configured server ++ */ + -+ $nickname = common_canonical_nickname($this->arg('nickname')); -hunk ./lib/gallery.php 49 -- function is_readonly() { -- return true; -- } -+ $user = User::staticGet('nickname', $nickname); -hunk ./lib/gallery.php 51 -- function handle($args) { -- parent::handle($args); -+ if (!$user) { -+ $this->no_such_user(); -+ return; -+ } -hunk ./lib/gallery.php 56 -- # Post from the tag dropdown; redirect to a GET -+ $profile = $user->getProfile(); -hunk ./lib/gallery.php 58 -- if ($_SERVER['REQUEST_METHOD'] == 'POST') { -- common_redirect($this->self_url(), 307); -- } -+ if (!$profile) { -+ $this->server_error(_('User without matching profile in system.')); -+ return; -+ } -hunk ./lib/gallery.php 63 -- $nickname = common_canonical_nickname($this->arg('nickname')); -- $user = User::staticGet('nickname', $nickname); -+ $page = $this->arg('page'); -hunk ./lib/gallery.php 65 -- if (!$user) { -- $this->no_such_user(); -- return; ++function jabber_connect($resource=null) ++{ ++ static $conn = null; ++ if (!$conn) { ++ $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? ++ common_config('xmpp', 'host') : ++ common_config('xmpp', 'server'), ++ common_config('xmpp', 'port'), ++ common_config('xmpp', 'user'), ++ common_config('xmpp', 'password'), ++ ($resource) ? $resource : ++ common_config('xmpp', 'resource'), ++ common_config('xmpp', 'server'), ++ common_config('xmpp', 'debug') ? ++ true : false, ++ common_config('xmpp', 'debug') ? ++ XMPPHP_Log::LEVEL_VERBOSE : null ++ ); +hunk ./lib/jabber.php 107 +- if (!$conn) { +- return false; - } -+ if (!$page) { -+ $page = 1; ++ if (!$conn) { ++ return false; + } -hunk ./lib/gallery.php 69 -- $profile = $user->getProfile(); -+ $display = $this->arg('display'); -hunk ./lib/gallery.php 71 -- if (!$profile) { -- $this->server_error(_('User without matching profile in system.')); -- return; +hunk ./lib/jabber.php 111 +- $conn->autoSubscribe(); +- $conn->useEncryption(common_config('xmpp', 'encryption')); ++ $conn->autoSubscribe(); ++ $conn->useEncryption(common_config('xmpp', 'encryption')); +hunk ./lib/jabber.php 114 +- try { +- $conn->connect(true); # true = persistent connection +- } catch (XMPPHP_Exception $e) { +- common_log(LOG_ERROR, $e->getMessage()); +- return false; - } -+ if (!$display) { -+ $display = 'list'; ++ try { ++ $conn->connect(true); // true = persistent connection ++ } catch (XMPPHP_Exception $e) { ++ common_log(LOG_ERROR, $e->getMessage()); ++ return false; + } -hunk ./lib/gallery.php 75 -- $page = $this->arg('page'); -+ $tag = $this->arg('tag'); -hunk ./lib/gallery.php 77 -- if (!$page) { -- $page = 1; -- } -+ common_show_header($profile->nickname . ": " . $this->gallery_type(), -+ null, $profile, -+ array($this, 'show_top')); -hunk ./lib/gallery.php 81 -- $display = $this->arg('display'); -+ $this->display_links($profile, $page, $display); -+ $this->show_tags_dropdown($profile); -hunk ./lib/gallery.php 84 -- if (!$display) { -- $display = 'list'; -- } -+ $this->show_gallery($profile, $page, $display, $tag); -+ common_show_footer(); -+ } -hunk ./lib/gallery.php 88 -- $tag = $this->arg('tag'); -+ function no_such_user() -+ { -+ $this->client_error(_('No such user.')); +hunk ./lib/jabber.php 121 +- $conn->processUntil('session_start'); +- } +- return $conn; ++ $conn->processUntil('session_start'); + } -hunk ./lib/gallery.php 93 -- common_show_header($profile->nickname . ": " . $this->gallery_type(), -- NULL, $profile, -- array($this, 'show_top')); -+ function show_tags_dropdown($profile) -+ { -+ $tag = $this->trimmed('tag'); -hunk ./lib/gallery.php 97 -- $this->display_links($profile, $page, $display); -- $this->show_tags_dropdown($profile); -+ list($lst, $usr) = $this->fields(); -hunk ./lib/gallery.php 99 -- $this->show_gallery($profile, $page, $display, $tag); -- common_show_footer(); ++ return $conn; +hunk ./lib/jabber.php 126 +-function jabber_send_notice($to, $notice) { +- $conn = jabber_connect(); +- if (!$conn) { +- return false; - } -+ $tags = $this->get_all_tags($profile, $lst, $usr); -hunk ./lib/gallery.php 101 -- function no_such_user() { -- $this->client_error(_('No such user.')); +- $profile = Profile::staticGet($notice->profile_id); +- if (!$profile) { +- common_log(LOG_WARNING, 'Refusing to send notice with ' . +- 'unknown profile ' . common_log_objstring($notice), +- __FILE__); +- return false; - } -+ $content = array(); -hunk ./lib/gallery.php 103 -- function show_tags_dropdown($profile) { -- $tag = $this->trimmed('tag'); -- list($lst, $usr) = $this->fields(); -- $tags = $this->get_all_tags($profile, $lst, $usr); -- $content = array(); -- foreach ($tags as $t) { -- $content[$t] = $t; -- } -- if ($tags) { -- common_element_start('dl', array('id'=>'filter_tags')); -- common_element('dt', null, _('Filter tags')); -- common_element_start('dd'); -- common_element_start('ul'); -- common_element_start('li', array('id'=>'filter_tags_all', 'class'=>'child_1')); -- common_element('a', array('href' => common_local_url($this->trimmed('action'), -- array('nickname' => $profile->nickname))), -- _('All')); -- common_element_end('li'); -- common_element_start('li', array('id'=>'filter_tags_item')); -- common_element_start('form', array('name' => 'bytag', 'id' => 'bytag', 'method' => 'post')); -- common_dropdown('tag', _('Tag'), $content, -- _('Choose a tag to narrow list'), FALSE, $tag); -- common_submit('go', _('Go')); -- common_element_end('form'); -- common_element_end('li'); -- common_element_end('ul'); -- common_element_end('dd'); -- common_element_end('dl'); -- } +- $msg = jabber_format_notice($profile, $notice); +- $entry = jabber_format_entry($profile, $notice); +- $conn->message($to, $msg, 'chat', NULL, $entry); +- $profile->free(); +- return true; ++/** ++ * send a single notice to a given Jabber address ++ * ++ * @param string $to JID to send the notice to ++ * @param Notice $notice notice to send ++ * ++ * @return boolean success value ++ */ ++ ++function jabber_send_notice($to, $notice) ++{ ++ $conn = jabber_connect(); ++ if (!$conn) { ++ return false; ++ } ++ $profile = Profile::staticGet($notice->profile_id); ++ if (!$profile) { ++ common_log(LOG_WARNING, 'Refusing to send notice with ' . ++ 'unknown profile ' . common_log_objstring($notice), ++ __FILE__); ++ return false; ++ } ++ $msg = jabber_format_notice($profile, $notice); ++ $entry = jabber_format_entry($profile, $notice); ++ $conn->message($to, $msg, 'chat', null, $entry); ++ $profile->free(); ++ return true; +hunk ./lib/jabber.php 155 +-# Extra stuff defined by Twitter, needed by twitter clients ++/** ++ * extra information for XMPP messages, as defined by Twitter ++ * ++ * @param Profile $profile Profile of the sending user ++ * @param Notice $notice Notice being sent ++ * ++ * @return string Extra information (Atom, HTML, addresses) in string format ++ */ +hunk ./lib/jabber.php 164 +-function jabber_format_entry($profile, $notice) { ++function jabber_format_entry($profile, $notice) ++{ ++ // FIXME: notice url might be remote +hunk ./lib/jabber.php 168 +- # FIXME: notice url might be remote ++ $noticeurl = common_local_url('shownotice', ++ array('notice' => $notice->id)); +hunk ./lib/jabber.php 171 +- $noticeurl = common_local_url('shownotice', +- array('notice' => $notice->id)); +- $msg = jabber_format_notice($profile, $notice); +- $entry = "\n\n"; +- $entry .= "\n"; +- $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; +- $entry .= "\n"; +- $entry .= " $profile->nickname)) . "'/>\n"; +- $entry .= "" . $profile->nickname . "\n"; +- $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; +- $entry .= "\n"; +- $entry .= "" . htmlspecialchars($msg) . "\n"; +- $entry .= "" . htmlspecialchars($msg) . "\n"; +- $entry .= "\n"; +- $entry .= "". $notice->uri . "\n"; +- $entry .= "".common_date_w3dtf($notice->created)."\n"; +- $entry .= "".common_date_w3dtf($notice->modified)."\n"; +- $entry .= "\n"; ++ $msg = jabber_format_notice($profile, $notice); +hunk ./lib/jabber.php 173 +- $html = "\n\n"; +- $html .= "\n"; +- $html .= "".$profile->nickname.": "; +- $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); +- $html .= "\n\n"; +- $html .= "\n\n"; ++ $self_url = common_local_url('userrss', array('nickname' => $profile->nickname)); +hunk ./lib/jabber.php 175 +- $address = "\n"; +- $address .= "
\n"; +- $address .= "\n"; ++ $entry = "\n\n"; ++ $entry .= "\n"; ++ $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; ++ $entry .= "\n"; ++ $entry .= "\n"; ++ $entry .= "" . $profile->nickname . "\n"; ++ $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; ++ $entry .= "\n"; ++ $entry .= "" . htmlspecialchars($msg) . "\n"; ++ $entry .= "" . htmlspecialchars($msg) . "\n"; ++ $entry .= "\n"; ++ $entry .= "". $notice->uri . "\n"; ++ $entry .= "".common_date_w3dtf($notice->created)."\n"; ++ $entry .= "".common_date_w3dtf($notice->modified)."\n"; ++ $entry .= "\n"; +hunk ./lib/jabber.php 191 +- # FIXME: include a pubsub event, too. ++ $html = "\n\n"; ++ $html .= "\n"; ++ $html .= "".$profile->nickname.": "; ++ $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); ++ $html .= "\n\n"; ++ $html .= "\n\n"; +hunk ./lib/jabber.php 198 +- return $html . $entry . $address; ++ $address = "\n"; ++ $address .= "
\n"; ++ $address .= "\n"; ++ ++ // FIXME: include a pubsub event, too. ++ ++ return $html . $entry . $address; +hunk ./lib/jabber.php 207 +-function jabber_send_message($to, $body, $type='chat', $subject=NULL) { +- $conn = jabber_connect(); +- if (!$conn) { +- return false; - } -+ foreach ($tags as $t) { -+ $content[$t] = $t; -+ } -+ if ($tags) { -+ common_element_start('dl', array('id'=>'filter_tags')); -+ common_element('dt', null, _('Filter tags')); -+ common_element_start('dd'); -+ common_element_start('ul'); -+ common_element_start('li', array('id' => 'filter_tags_all', -+ 'class' => 'child_1')); -+ common_element('a', -+ array('href' => -+ common_local_url($this->trimmed('action'), -+ array('nickname' => -+ $profile->nickname))), -+ _('All')); -+ common_element_end('li'); -+ common_element_start('li', array('id'=>'filter_tags_item')); -+ common_element_start('form', array('name' => 'bytag', -+ 'id' => 'bytag', -+ 'method' => 'post')); -+ common_dropdown('tag', _('Tag'), $content, -+ _('Choose a tag to narrow list'), false, $tag); -+ common_submit('go', _('Go')); -+ common_element_end('form'); -+ common_element_end('li'); -+ common_element_end('ul'); -+ common_element_end('dd'); -+ common_element_end('dl'); -+ } +- $conn->message($to, $body, $type, $subject); +- return true; ++/** ++ * sends a single text message to a given JID ++ * ++ * @param string $to JID to send the message to ++ * @param string $body body of the message ++ * @param string $type type of the message ++ * @param string $subject subject of the message ++ * ++ * @return boolean success flag ++ */ ++ ++function jabber_send_message($to, $body, $type='chat', $subject=null) ++{ ++ $conn = jabber_connect(); ++ if (!$conn) { ++ return false; + } -hunk ./lib/gallery.php 135 -- function show_top($profile) { -- common_element('div', 'instructions', -- $this->get_instructions($profile)); -+ function show_top($profile) -+ { -+ common_element('div', 'instructions', -+ $this->get_instructions($profile)); -hunk ./lib/gallery.php 140 ++ $conn->message($to, $body, $type, $subject); ++ return true; +hunk ./lib/jabber.php 228 +-function jabber_send_presence($status, $show='available', $to=NULL, +- $type = 'available', $priority=NULL) ++/** ++ * sends a presence stanza on the Jabber network ++ * ++ * @param string $status current status, free-form string ++ * @param string $show structured status value ++ * @param string $to recipient of presence, null for general ++ * @param string $type type of status message, related to $show ++ * @param int $priority priority of the presence ++ * ++ * @return boolean success value ++ */ ++ ++function jabber_send_presence($status, $show='available', $to=null, ++ $type = 'available', $priority=null) +hunk ./lib/jabber.php 243 +- $conn = jabber_connect(); +- if (!$conn) { +- return false; - } +- $conn->presence($status, $show, $to, $type, $priority); +- return true; ++ $conn = jabber_connect(); ++ if (!$conn) { ++ return false; + } -hunk ./lib/gallery.php 142 -- function show_menu() { -- # action => array('prompt', 'title', $args) -- $action = $this->trimmed('action'); -- $nickname = $this->trimmed('nickname'); -- $menu = -- array('subscriptions' => -- array( _('Subscriptions'), -- _('Subscriptions'), -- array('nickname' => $nickname)), -- 'subscribers' => -- array( -- _('Subscribers'), -- _('Subscribers'), -- array('nickname' => $nickname)), -- ); -- $this->nav_menu($menu); ++ $conn->presence($status, $show, $to, $type, $priority); ++ return true; +hunk ./lib/jabber.php 251 +-function jabber_confirm_address($code, $nickname, $address) { +- $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . +- 'has said that your Jabber ID belongs to them. ' . +- 'If that\'s true, you can confirm by clicking on this URL: ' . +- common_local_url('confirmaddress', array('code' => $code)) . +- ' . (If you cannot click it, copy-and-paste it into the ' . +- 'address bar of your browser). If that user isn\'t you, ' . +- 'or if you didn\'t request this confirmation, just ignore this message.'; ++/** ++ * sends a confirmation request to a JID ++ * ++ * @param string $code confirmation code for confirmation URL ++ * @param string $nickname nickname of confirming user ++ * @param string $address JID to send confirmation to ++ * ++ * @return boolean success flag ++ */ ++ ++function jabber_confirm_address($code, $nickname, $address) ++{ ++ $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . ++ 'has said that your Jabber ID belongs to them. ' . ++ 'If that\'s true, you can confirm by clicking on this URL: ' . ++ common_local_url('confirmaddress', array('code' => $code)) . ++ ' . (If you cannot click it, copy-and-paste it into the ' . ++ 'address bar of your browser). If that user isn\'t you, ' . ++ 'or if you didn\'t request this confirmation, just ignore this message.'; +hunk ./lib/jabber.php 271 +- return jabber_send_message($address, $body); ++ return jabber_send_message($address, $body); +hunk ./lib/jabber.php 274 +-function jabber_special_presence($type, $to=NULL, $show=NULL, $status=NULL) { +- $conn = jabber_connect(); ++/** ++ * sends a "special" presence stanza on the Jabber network ++ * ++ * @param string $type Type of presence ++ * @param string $to JID to send presence to ++ * @param string $show show value for presence ++ * @param string $status status value for presence ++ * ++ * @return boolean success flag ++ * ++ * @see jabber_send_presence() ++ */ ++ ++function jabber_special_presence($type, $to=null, $show=null, $status=null) ++{ ++ // FIXME: why use this instead of jabber_send_presence()? ++ $conn = jabber_connect(); +hunk ./lib/jabber.php 292 +- $to = htmlspecialchars($to); +- $status = htmlspecialchars($status); +- $out = " array('prompt', 'title', $args) -+ $action = $this->trimmed('action'); -+ $nickname = $this->trimmed('nickname'); -hunk ./lib/gallery.php 148 -- function show_gallery($profile, $page, $display='list', $tag=NULL) { -+ $menu = -+ array('subscriptions' => -+ array( _('Subscriptions'), -+ _('Subscriptions'), -+ array('nickname' => $nickname)), -+ 'subscribers' => -+ array( -+ _('Subscribers'), -+ _('Subscribers'), -+ array('nickname' => $nickname)), -+ ); -+ $this->nav_menu($menu); +- $conn->send($out); ++ $to = htmlspecialchars($to); ++ $status = htmlspecialchars($status); ++ ++ $out = "fields(); -+ list($lst, $usr) = $this->fields(); -hunk ./lib/gallery.php 168 -- $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; -+ $per_page = ($display == 'list') ? PROFILES_PER_PAGE : AVATARS_PER_PAGE; -hunk ./lib/gallery.php 170 -- $offset = ($page-1)*$per_page; -- $limit = $per_page + 1; -+ $offset = ($page-1)*$per_page; -+ $limit = $per_page + 1; -hunk ./lib/gallery.php 173 -- if (common_config('db','type') == 'pgsql') { -- $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; -- } else { -- $lim = ' LIMIT ' . $offset . ', ' . $limit; -- } -+ if (common_config('db', 'type') == 'pgsql') { -+ $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; -+ } else { -+ $lim = ' LIMIT ' . $offset . ', ' . $limit; ++ if ($type) { ++ $out .= " type='$type'"; ++ } ++ if ($show == 'available' and !$status) { ++ $out .= "/>"; ++ } else { ++ $out .= ">"; ++ if ($show && ($show != 'available')) { ++ $out .= "$show"; + } -hunk ./lib/gallery.php 179 -- # XXX: memcached results -- # FIXME: SQL injection on $tag -+ // XXX: memcached results -+ // FIXME: SQL injection on $tag -hunk ./lib/gallery.php 182 -- $other->query('SELECT profile.* ' . -- 'FROM profile JOIN subscription ' . -- 'ON profile.id = subscription.' . $lst . ' ' . -- (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . -- 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . -- 'AND subscriber != subscribed ' . -- (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . -- 'ORDER BY subscription.created DESC, profile.id DESC ' . -- $lim); -+ $other->query('SELECT profile.* ' . -+ 'FROM profile JOIN subscription ' . -+ 'ON profile.id = subscription.' . $lst . ' ' . -+ (($tag) ? 'JOIN profile_tag ON (profile.id = profile_tag.tagged AND subscription.'.$usr.'= profile_tag.tagger) ' : '') . -+ 'WHERE ' . $usr . ' = ' . $profile->id . ' ' . -+ 'AND subscriber != subscribed ' . -+ (($tag) ? 'AND profile_tag.tag= "' . $tag . '" ': '') . -+ 'ORDER BY subscription.created DESC, profile.id DESC ' . -+ $lim); -hunk ./lib/gallery.php 192 -- if ($display == 'list') { -+ if ($display == 'list') { -hunk ./lib/gallery.php 194 -- $profile_list = new $cls($other, $profile, $this->trimmed('action')); -- $cnt = $profile_list->show_list(); -- } else { -- $cnt = $this->icon_list($other); -- } -+ $profile_list = new $cls($other, $profile, $this->trimmed('action')); -+ $cnt = $profile_list->show_list(); -+ } else { -+ $cnt = $this->icon_list($other); ++ if ($status) { ++ $out .= "$status"; + } -hunk ./lib/gallery.php 200 -- # For building the pagination URLs -+ // For building the pagination URLs -hunk ./lib/gallery.php 202 -- $args = array('nickname' => $profile->nickname); -+ $args = array('nickname' => $profile->nickname); -hunk ./lib/gallery.php 204 -- if ($display != 'list') { -- $args['display'] = $display; -- } -+ if ($display != 'list') { -+ $args['display'] = $display; -+ } -hunk ./lib/gallery.php 208 -- common_pagination($page > 1, -- $cnt > $per_page, -- $page, -- $this->trimmed('action'), -- $args); -- } -+ common_pagination($page > 1, -+ $cnt > $per_page, -+ $page, -+ $this->trimmed('action'), -+ $args); ++ $out .= ""; + } -hunk ./lib/gallery.php 215 -- function profile_list_class() { -+ function profile_list_class() -+ { -hunk ./lib/gallery.php 220 -- function icon_list($other) { -+ function icon_list($other) -+ { -+ common_element_start('ul', $this->div_class()); -hunk ./lib/gallery.php 224 -- common_element_start('ul', $this->div_class()); -+ $cnt = 0; -hunk ./lib/gallery.php 226 -- $cnt = 0; -+ while ($other->fetch()) { -hunk ./lib/gallery.php 228 -- while ($other->fetch()) { -+ $cnt++; -hunk ./lib/gallery.php 230 -- $cnt++; -+ if ($cnt > AVATARS_PER_PAGE) { -+ break; -+ } -hunk ./lib/gallery.php 234 -- if ($cnt > AVATARS_PER_PAGE) { -- break; -- } -+ common_element_start('li'); -hunk ./lib/gallery.php 236 -- common_element_start('li'); -+ common_element_start('a', array('title' => ($other->fullname) ? -+ $other->fullname : -+ $other->nickname, -+ 'href' => $other->profileurl, -+ 'class' => 'subscription')); -+ $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); -+ common_element('img', -+ array('src' => -+ (($avatar) ? common_avatar_display_url($avatar) : -+ common_default_avatar(AVATAR_STREAM_SIZE)), -+ 'width' => AVATAR_STREAM_SIZE, -+ 'height' => AVATAR_STREAM_SIZE, -+ 'class' => 'avatar stream', -+ 'alt' => ($other->fullname) ? -+ $other->fullname : -+ $other->nickname)); -+ common_element_end('a'); -hunk ./lib/gallery.php 254 -- common_element_start('a', array('title' => ($other->fullname) ? -- $other->fullname : -- $other->nickname, -- 'href' => $other->profileurl, -- 'class' => 'subscription')); -- $avatar = $other->getAvatar(AVATAR_STREAM_SIZE); -- common_element('img', -- array('src' => -- (($avatar) ? common_avatar_display_url($avatar) : -- common_default_avatar(AVATAR_STREAM_SIZE)), -- 'width' => AVATAR_STREAM_SIZE, -- 'height' => AVATAR_STREAM_SIZE, -- 'class' => 'avatar stream', -- 'alt' => ($other->fullname) ? -- $other->fullname : -- $other->nickname)); -- common_element_end('a'); -+ // XXX: subscribe form here -hunk ./lib/gallery.php 256 -- # XXX: subscribe form here -+ common_element_end('li'); -+ } -hunk ./lib/gallery.php 259 -- common_element_end('li'); -- } -+ common_element_end('ul'); -hunk ./lib/gallery.php 261 -- common_element_end('ul'); -- -- return $cnt; ++ $conn->send($out); +hunk ./lib/jabber.php 317 +-function jabber_broadcast_notice($notice) { ++/** ++ * broadcast a notice to all subscribers and reply recipients ++ * ++ * This function will send a notice to all subscribers on the local server ++ * who have Jabber addresses, and have Jabber notification enabled, and ++ * have this subscription enabled for Jabber. It also sends the notice to ++ * all recipients of @-replies who have Jabber addresses and Jabber notification ++ * enabled. This is really the heart of Jabber distribution in Laconica. ++ * ++ * @param Notice $notice The notice to broadcast ++ * ++ * @return boolean success flag ++ */ +hunk ./lib/jabber.php 331 +- if (!common_config('xmpp', 'enabled')) { +- return true; - } -+ return $cnt; +- $profile = Profile::staticGet($notice->profile_id); ++function jabber_broadcast_notice($notice) ++{ ++ if (!common_config('xmpp', 'enabled')) { ++ return true; + } -hunk ./lib/gallery.php 264 -- function gallery_type() { -- return NULL; -- } -+ function gallery_type() -+ { -+ return null; ++ $profile = Profile::staticGet($notice->profile_id); ++ ++ if (!$profile) { ++ common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . ++ 'unknown profile ' . common_log_objstring($notice), ++ __FILE__); ++ return false; + } -hunk ./lib/gallery.php 269 -- function get_instructions(&$profile) { -- return NULL; +hunk ./lib/jabber.php 345 +- if (!$profile) { +- common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . +- 'unknown profile ' . common_log_objstring($notice), +- __FILE__); +- return false; - } -+ function get_instructions(&$profile) -+ { -+ return null; -+ } -hunk ./lib/gallery.php 274 -- function fields() { -- return NULL; ++ $msg = jabber_format_notice($profile, $notice); ++ $entry = jabber_format_entry($profile, $notice); +hunk ./lib/jabber.php 348 +- $msg = jabber_format_notice($profile, $notice); +- $entry = jabber_format_entry($profile, $notice); ++ $profile->free(); ++ unset($profile); +hunk ./lib/jabber.php 351 +- $profile->free(); +- unset($profile); ++ $sent_to = array(); +hunk ./lib/jabber.php 353 +- $sent_to = array(); +- $conn = jabber_connect(); ++ $conn = jabber_connect(); +hunk ./lib/jabber.php 355 +- # First, get users to whom this is a direct reply +- $user = new User(); +- $user->query('SELECT user.id, user.jabber ' . +- 'FROM user JOIN reply ON user.id = reply.profile_id ' . +- 'WHERE reply.notice_id = ' . $notice->id . ' ' . +- 'AND user.jabber is not null ' . +- 'AND user.jabbernotify = 1 ' . +- 'AND user.jabberreplies = 1 '); ++ // First, get users to whom this is a direct reply ++ $user = new User(); ++ $user->query('SELECT user.id, user.jabber ' . ++ 'FROM user JOIN reply ON user.id = reply.profile_id ' . ++ 'WHERE reply.notice_id = ' . $notice->id . ' ' . ++ 'AND user.jabber is not null ' . ++ 'AND user.jabbernotify = 1 ' . ++ 'AND user.jabberreplies = 1 '); +hunk ./lib/jabber.php 364 +- while ($user->fetch()) { +- common_log(LOG_INFO, +- 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, +- __FILE__); +- $conn->message($user->jabber, $msg, 'chat', NULL, $entry); +- $conn->processTime(0); +- $sent_to[$user->id] = 1; - } -+ function fields() -+ { -+ return null; ++ while ($user->fetch()) { ++ common_log(LOG_INFO, ++ 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, ++ __FILE__); ++ $conn->message($user->jabber, $msg, 'chat', null, $entry); ++ $conn->processTime(0); ++ $sent_to[$user->id] = 1; + } -hunk ./lib/gallery.php 279 -- function div_class() { -- return ''; +hunk ./lib/jabber.php 373 +- $user->free(); ++ $user->free(); +hunk ./lib/jabber.php 375 +- # Now, get users subscribed to this profile ++ // Now, get users subscribed to this profile +hunk ./lib/jabber.php 377 +- $user = new User(); +- $user->query('SELECT user.id, user.jabber ' . +- 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . +- 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . +- 'AND user.jabber is not null ' . +- 'AND user.jabbernotify = 1 ' . ++ $user = new User(); ++ $user->query('SELECT user.id, user.jabber ' . ++ 'FROM user JOIN subscription ' . ++ 'ON user.id = subscription.subscriber ' . ++ 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . ++ 'AND user.jabber is not null ' . ++ 'AND user.jabbernotify = 1 ' . +hunk ./lib/jabber.php 386 +- while ($user->fetch()) { +- if (!array_key_exists($user->id, $sent_to)) { +- common_log(LOG_INFO, +- 'Sending notice ' . $notice->id . ' to ' . $user->jabber, +- __FILE__); +- $conn->message($user->jabber, $msg, 'chat', NULL, $entry); +- # To keep the incoming queue from filling up, we service it after each send. +- $conn->processTime(0); +- } - } -+ function div_class() -+ { -+ return ''; ++ while ($user->fetch()) { ++ if (!array_key_exists($user->id, $sent_to)) { ++ common_log(LOG_INFO, ++ 'Sending notice ' . $notice->id . ' to ' . $user->jabber, ++ __FILE__); ++ $conn->message($user->jabber, $msg, 'chat', null, $entry); ++ // To keep the incoming queue from filling up, ++ // we service it after each send. ++ $conn->processTime(0); ++ } + } -hunk ./lib/gallery.php 284 -- function display_links($profile, $page, $display) { -- $tag = $this->trimmed('tag'); -+ function display_links($profile, $page, $display) -+ { -+ $tag = $this->trimmed('tag'); -hunk ./lib/gallery.php 288 -- common_element_start('dl', array('id'=>'subscriptions_nav')); -- common_element('dt', null, _('Subscriptions navigation')); -- common_element_start('dd'); -- common_element_start('ul', array('class'=>'nav')); -+ common_element_start('dl', array('id'=>'subscriptions_nav')); -+ common_element('dt', null, _('Subscriptions navigation')); -+ common_element_start('dd'); -+ common_element_start('ul', array('class'=>'nav')); -hunk ./lib/gallery.php 293 -- switch ($display) { -- case 'list': -- common_element('li', array('class'=>'child_1'), _('List')); -- common_element_start('li'); -- $url_args = array('display' => 'icons', -- 'nickname' => $profile->nickname, -- 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); -- if ($tag) { -- $url_args['tag'] = $tag; -- } -- $url = common_local_url($this->trimmed('action'), $url_args); -- common_element('a', array('href' => $url), -- _('Icons')); -- common_element_end('li'); -- break; -- default: -- common_element_start('li', array('class'=>'child_1')); -- $url_args = array('nickname' => $profile->nickname, -- 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); -- if ($tag) { -- $url_args['tag'] = $tag; -- } -- $url = common_local_url($this->trimmed('action'), $url_args); -- common_element('a', array('href' => $url), -- _('List')); -- common_element_end('li'); -- common_element('li', NULL, _('Icons')); -- break; +hunk ./lib/jabber.php 398 +- $user->free(); ++ $user->free(); +hunk ./lib/jabber.php 400 +- return true; ++ return true; +hunk ./lib/jabber.php 403 +-function jabber_public_notice($notice) { ++/** ++ * send a notice to all public listeners ++ * ++ * For notices that are generated on the local system (by users), we can optionally ++ * forward them to remote listeners by XMPP. ++ * ++ * @param Notice $notice notice to broadcast ++ * ++ * @return boolean success flag ++ */ +hunk ./lib/jabber.php 414 +- # Now, users who want everything ++function jabber_public_notice($notice) ++{ ++ // Now, users who want everything +hunk ./lib/jabber.php 418 +- $public = common_config('xmpp', 'public'); ++ $public = common_config('xmpp', 'public'); +hunk ./lib/jabber.php 420 +- # FIXME PRIV don't send out private messages here +- # XXX: should we send out non-local messages if public,localonly +- # = false? I think not ++ // FIXME PRIV don't send out private messages here ++ // XXX: should we send out non-local messages if public,localonly ++ // = false? I think not +hunk ./lib/jabber.php 424 +- if ($public && $notice->is_local) { +- $profile = Profile::staticGet($notice->profile_id); ++ if ($public && $notice->is_local) { ++ $profile = Profile::staticGet($notice->profile_id); +hunk ./lib/jabber.php 427 +- if (!$profile) { +- common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . +- 'unknown profile ' . common_log_objstring($notice), +- __FILE__); +- return false; - } -+ switch ($display) { -+ case 'list': -+ common_element('li', array('class'=>'child_1'), _('List')); -+ common_element_start('li'); -+ $url_args = array('display' => 'icons', -+ 'nickname' => $profile->nickname, -+ 'page' => 1 + floor((($page - 1) * PROFILES_PER_PAGE) / AVATARS_PER_PAGE)); -+ if ($tag) { -+ $url_args['tag'] = $tag; -+ } -+ $url = common_local_url($this->trimmed('action'), $url_args); -+ common_element('a', array('href' => $url), -+ _('Icons')); -+ common_element_end('li'); -+ break; -+ default: -+ common_element_start('li', array('class'=>'child_1')); -+ $url_args = array('nickname' => $profile->nickname, -+ 'page' => 1 + floor((($page - 1) * AVATARS_PER_PAGE) / PROFILES_PER_PAGE)); -+ if ($tag) { -+ $url_args['tag'] = $tag; -+ } -+ $url = common_local_url($this->trimmed('action'), $url_args); -+ common_element('a', array('href' => $url), -+ _('List')); -+ common_element_end('li'); -+ common_element('li', null, _('Icons')); -+ break; ++ if (!$profile) { ++ common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . ++ 'unknown profile ' . common_log_objstring($notice), ++ __FILE__); ++ return false; + } -hunk ./lib/gallery.php 323 -- common_element_end('ul'); -- common_element_end('dd'); -- common_element_end('dl'); -- } -+ common_element_end('ul'); -+ common_element_end('dd'); -+ common_element_end('dl'); -+ } -hunk ./lib/gallery.php 328 -- # Get list of tags we tagged other users with -+ // Get list of tags we tagged other users with -hunk ./lib/gallery.php 330 -- function get_all_tags($profile, $lst, $usr) { -- $profile_tag = new Notice_tag(); -- $profile_tag->query('SELECT DISTINCT(tag) ' . -- 'FROM profile_tag, subscription ' . -- 'WHERE tagger = ' . $profile->id . ' ' . -- 'AND ' . $usr . ' = ' . $profile->id . ' ' . -- 'AND ' . $lst . ' = tagged ' . -- 'AND tagger != tagged'); -- $tags = array(); -- while ($profile_tag->fetch()) { -- $tags[] = $profile_tag->tag; +hunk ./lib/jabber.php 434 +- $msg = jabber_format_notice($profile, $notice); +- $entry = jabber_format_entry($profile, $notice); ++ $msg = jabber_format_notice($profile, $notice); ++ $entry = jabber_format_entry($profile, $notice); +hunk ./lib/jabber.php 437 +- $conn = jabber_connect(); ++ $conn = jabber_connect(); +hunk ./lib/jabber.php 439 +- foreach ($public as $address) { +- common_log(LOG_INFO, +- 'Sending notice ' . $notice->id . ' to public listener ' . $address, +- __FILE__); +- $conn->message($address, $msg, 'chat', NULL, $entry); +- $conn->processTime(0); - } -- $profile_tag->free(); -- return $tags; +- $profile->free(); - } -+ function get_all_tags($profile, $lst, $usr) -+ { -+ $profile_tag = new Notice_tag(); -+ $profile_tag->query('SELECT DISTINCT(tag) ' . -+ 'FROM profile_tag, subscription ' . -+ 'WHERE tagger = ' . $profile->id . ' ' . -+ 'AND ' . $usr . ' = ' . $profile->id . ' ' . -+ 'AND ' . $lst . ' = tagged ' . -+ 'AND tagger != tagged'); -+ $tags = array(); -+ while ($profile_tag->fetch()) { -+ $tags[] = $profile_tag->tag; ++ foreach ($public as $address) { ++ common_log(LOG_INFO, ++ 'Sending notice ' . $notice->id . ++ ' to public listener ' . $address, ++ __FILE__); ++ $conn->message($address, $msg, 'chat', null, $entry); ++ $conn->processTime(0); + } -+ $profile_tag->free(); -+ return $tags; ++ $profile->free(); + } +hunk ./lib/jabber.php 450 +- return true; ++ return true; +hunk ./lib/jabber.php 453 +-function jabber_format_notice(&$profile, &$notice) { +- return $profile->nickname . ': ' . $notice->content; ++/** ++ * makes a plain-text formatted version of a notice, suitable for Jabber distribution ++ * ++ * @param Profile &$profile profile of the sending user ++ * @param Notice &$notice notice being sent ++ * ++ * @return string plain-text version of the notice, with user nickname prefixed ++ */ ++ ++function jabber_format_notice(&$profile, &$notice) ++{ ++ return $profile->nickname . ': ' . $notice->content; diff --git a/lib/jabber.php b/lib/jabber.php index ab0fd6af8..099ded9eb 100644 --- a/lib/jabber.php +++ b/lib/jabber.php @@ -1,9 +1,12 @@ . + * + * @category Network + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} -require_once('XMPPHP/XMPP.php'); +require_once 'XMPPHP/XMPP.php'; -function jabber_valid_base_jid($jid) { - # Cheap but effective - return Validate::email($jid); -} +/** + * checks whether a string is a syntactically valid Jabber ID (JID) + * + * @param string $jid string to check + * + * @return boolean whether the string is a valid JID + */ -function jabber_normalize_jid($jid) { - if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { - $node = $matches[1]; - $server = $matches[2]; - return strtolower($node.'@'.$server); - } else { - return NULL; - } +function jabber_valid_base_jid($jid) +{ + // Cheap but effective + return Validate::email($jid); } -function jabber_daemon_address() { - return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); +/** + * normalizes a Jabber ID for comparison + * + * @param string $jid JID to check + * + * @return string an equivalent JID in normalized (lowercase) form + */ + +function jabber_normalize_jid($jid) +{ + if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { + $node = $matches[1]; + $server = $matches[2]; + return strtolower($node.'@'.$server); + } else { + return null; + } } -function jabber_connect($resource=NULL) { - static $conn = NULL; - if (!$conn) { - $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? - common_config('xmpp', 'host') : - common_config('xmpp', 'server'), - common_config('xmpp', 'port'), - common_config('xmpp', 'user'), - common_config('xmpp', 'password'), - ($resource) ? $resource : - common_config('xmpp', 'resource'), - common_config('xmpp', 'server'), - common_config('xmpp', 'debug') ? - true : false, - common_config('xmpp', 'debug') ? - XMPPHP_Log::LEVEL_VERBOSE : NULL - ); - - if (!$conn) { - return false; - } - - $conn->autoSubscribe(); - $conn->useEncryption(common_config('xmpp', 'encryption')); - - try { - $conn->connect(true); # true = persistent connection - } catch (XMPPHP_Exception $e) { - common_log(LOG_ERROR, $e->getMessage()); - return false; - } - - $conn->processUntil('session_start'); - } - return $conn; +/** + * the JID of the Jabber daemon for this Laconica instance + * + * @return string JID of the Jabber daemon + */ + +function jabber_daemon_address() +{ + return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); } -function jabber_send_notice($to, $notice) { - $conn = jabber_connect(); - if (!$conn) { - return false; - } - $profile = Profile::staticGet($notice->profile_id); - if (!$profile) { - common_log(LOG_WARNING, 'Refusing to send notice with ' . - 'unknown profile ' . common_log_objstring($notice), - __FILE__); - return false; - } - $msg = jabber_format_notice($profile, $notice); - $entry = jabber_format_entry($profile, $notice); - $conn->message($to, $msg, 'chat', NULL, $entry); - $profile->free(); - return true; +/** + * connect the configured Jabber account to the configured server + * + * @param string $resource Resource to connect (defaults to configured resource) + * + * @return XMPPHP connection to the configured server + */ + +function jabber_connect($resource=null) +{ + static $conn = null; + if (!$conn) { + $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? + common_config('xmpp', 'host') : + common_config('xmpp', 'server'), + common_config('xmpp', 'port'), + common_config('xmpp', 'user'), + common_config('xmpp', 'password'), + ($resource) ? $resource : + common_config('xmpp', 'resource'), + common_config('xmpp', 'server'), + common_config('xmpp', 'debug') ? + true : false, + common_config('xmpp', 'debug') ? + XMPPHP_Log::LEVEL_VERBOSE : null + ); + + if (!$conn) { + return false; + } + + $conn->autoSubscribe(); + $conn->useEncryption(common_config('xmpp', 'encryption')); + + try { + $conn->connect(true); // true = persistent connection + } catch (XMPPHP_Exception $e) { + common_log(LOG_ERROR, $e->getMessage()); + return false; + } + + $conn->processUntil('session_start'); + } + return $conn; } -# Extra stuff defined by Twitter, needed by twitter clients - -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); - $entry = "\n\n"; - $entry .= "\n"; - $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; - $entry .= "\n"; - $entry .= " $profile->nickname)) . "'/>\n"; - $entry .= "" . $profile->nickname . "\n"; - $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; - $entry .= "\n"; - $entry .= "" . htmlspecialchars($msg) . "\n"; - $entry .= "" . htmlspecialchars($msg) . "\n"; - $entry .= "\n"; - $entry .= "". $notice->uri . "\n"; - $entry .= "".common_date_w3dtf($notice->created)."\n"; - $entry .= "".common_date_w3dtf($notice->modified)."\n"; - $entry .= "\n"; - - $html = "\n\n"; - $html .= "\n"; - $html .= "".$profile->nickname.": "; - $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); - $html .= "\n\n"; - $html .= "\n\n"; - - $address = "\n"; - $address .= "
\n"; - $address .= "\n"; - - # FIXME: include a pubsub event, too. - - return $html . $entry . $address; +/** + * send a single notice to a given Jabber address + * + * @param string $to JID to send the notice to + * @param Notice $notice notice to send + * + * @return boolean success value + */ + +function jabber_send_notice($to, $notice) +{ + $conn = jabber_connect(); + if (!$conn) { + return false; + } + $profile = Profile::staticGet($notice->profile_id); + if (!$profile) { + common_log(LOG_WARNING, 'Refusing to send notice with ' . + 'unknown profile ' . common_log_objstring($notice), + __FILE__); + return false; + } + $msg = jabber_format_notice($profile, $notice); + $entry = jabber_format_entry($profile, $notice); + $conn->message($to, $msg, 'chat', null, $entry); + $profile->free(); + return true; } -function jabber_send_message($to, $body, $type='chat', $subject=NULL) { - $conn = jabber_connect(); - if (!$conn) { - return false; - } - $conn->message($to, $body, $type, $subject); - return true; +/** + * extra information for XMPP messages, as defined by Twitter + * + * @param Profile $profile Profile of the sending user + * @param Notice $notice Notice being sent + * + * @return string Extra information (Atom, HTML, addresses) in string format + */ + +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\n"; + $entry .= "\n"; + $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; + $entry .= "\n"; + $entry .= "\n"; + $entry .= "" . $profile->nickname . "\n"; + $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; + $entry .= "\n"; + $entry .= "" . htmlspecialchars($msg) . "\n"; + $entry .= "" . htmlspecialchars($msg) . "\n"; + $entry .= "\n"; + $entry .= "". $notice->uri . "\n"; + $entry .= "".common_date_w3dtf($notice->created)."\n"; + $entry .= "".common_date_w3dtf($notice->modified)."\n"; + $entry .= "\n"; + + $html = "\n\n"; + $html .= "\n"; + $html .= "".$profile->nickname.": "; + $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); + $html .= "\n\n"; + $html .= "\n\n"; + + $address = "\n"; + $address .= "
\n"; + $address .= "\n"; + + // FIXME: include a pubsub event, too. + + return $html . $entry . $address; } -function jabber_send_presence($status, $show='available', $to=NULL, - $type = 'available', $priority=NULL) +/** + * sends a single text message to a given JID + * + * @param string $to JID to send the message to + * @param string $body body of the message + * @param string $type type of the message + * @param string $subject subject of the message + * + * @return boolean success flag + */ + +function jabber_send_message($to, $body, $type='chat', $subject=null) { - $conn = jabber_connect(); - if (!$conn) { - return false; - } - $conn->presence($status, $show, $to, $type, $priority); - return true; + $conn = jabber_connect(); + if (!$conn) { + return false; + } + $conn->message($to, $body, $type, $subject); + return true; } -function jabber_confirm_address($code, $nickname, $address) { - $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . - 'has said that your Jabber ID belongs to them. ' . - 'If that\'s true, you can confirm by clicking on this URL: ' . - common_local_url('confirmaddress', array('code' => $code)) . - ' . (If you cannot click it, copy-and-paste it into the ' . - 'address bar of your browser). If that user isn\'t you, ' . - 'or if you didn\'t request this confirmation, just ignore this message.'; +/** + * sends a presence stanza on the Jabber network + * + * @param string $status current status, free-form string + * @param string $show structured status value + * @param string $to recipient of presence, null for general + * @param string $type type of status message, related to $show + * @param int $priority priority of the presence + * + * @return boolean success value + */ - return jabber_send_message($address, $body); +function jabber_send_presence($status, $show='available', $to=null, + $type = 'available', $priority=null) +{ + $conn = jabber_connect(); + if (!$conn) { + return false; + } + $conn->presence($status, $show, $to, $type, $priority); + return true; } -function jabber_special_presence($type, $to=NULL, $show=NULL, $status=NULL) { - $conn = jabber_connect(); - - $to = htmlspecialchars($to); - $status = htmlspecialchars($status); - $out = "send($out); +/** + * sends a confirmation request to a JID + * + * @param string $code confirmation code for confirmation URL + * @param string $nickname nickname of confirming user + * @param string $address JID to send confirmation to + * + * @return boolean success flag + */ + +function jabber_confirm_address($code, $nickname, $address) +{ + $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . + 'has said that your Jabber ID belongs to them. ' . + 'If that\'s true, you can confirm by clicking on this URL: ' . + common_local_url('confirmaddress', array('code' => $code)) . + ' . (If you cannot click it, copy-and-paste it into the ' . + 'address bar of your browser). If that user isn\'t you, ' . + 'or if you didn\'t request this confirmation, just ignore this message.'; + + return jabber_send_message($address, $body); } -function jabber_broadcast_notice($notice) { - - if (!common_config('xmpp', 'enabled')) { - return true; - } - $profile = Profile::staticGet($notice->profile_id); - - if (!$profile) { - common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . - 'unknown profile ' . common_log_objstring($notice), - __FILE__); - return false; - } - - $msg = jabber_format_notice($profile, $notice); - $entry = jabber_format_entry($profile, $notice); - - $profile->free(); - unset($profile); - - $sent_to = array(); - $conn = jabber_connect(); - - # First, get users to whom this is a direct reply - $user = new User(); - $user->query('SELECT user.id, user.jabber ' . - 'FROM user JOIN reply ON user.id = reply.profile_id ' . - 'WHERE reply.notice_id = ' . $notice->id . ' ' . - 'AND user.jabber is not null ' . - 'AND user.jabbernotify = 1 ' . - 'AND user.jabberreplies = 1 '); - - while ($user->fetch()) { - common_log(LOG_INFO, - 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, - __FILE__); - $conn->message($user->jabber, $msg, 'chat', NULL, $entry); - $conn->processTime(0); - $sent_to[$user->id] = 1; - } - - $user->free(); - - # Now, get users subscribed to this profile - - $user = new User(); - $user->query('SELECT user.id, user.jabber ' . - 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . - 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . - 'AND user.jabber is not null ' . - 'AND user.jabbernotify = 1 ' . - 'AND subscription.jabber = 1 '); +/** + * sends a "special" presence stanza on the Jabber network + * + * @param string $type Type of presence + * @param string $to JID to send presence to + * @param string $show show value for presence + * @param string $status status value for presence + * + * @return boolean success flag + * + * @see jabber_send_presence() + */ - while ($user->fetch()) { - if (!array_key_exists($user->id, $sent_to)) { - common_log(LOG_INFO, - 'Sending notice ' . $notice->id . ' to ' . $user->jabber, - __FILE__); - $conn->message($user->jabber, $msg, 'chat', NULL, $entry); - # To keep the incoming queue from filling up, we service it after each send. - $conn->processTime(0); - } - } +function jabber_special_presence($type, $to=null, $show=null, $status=null) +{ + // FIXME: why use this instead of jabber_send_presence()? + $conn = jabber_connect(); + + $to = htmlspecialchars($to); + $status = htmlspecialchars($status); + + $out = "send($out); +} - $user->free(); +/** + * broadcast a notice to all subscribers and reply recipients + * + * This function will send a notice to all subscribers on the local server + * who have Jabber addresses, and have Jabber notification enabled, and + * have this subscription enabled for Jabber. It also sends the notice to + * all recipients of @-replies who have Jabber addresses and Jabber notification + * enabled. This is really the heart of Jabber distribution in Laconica. + * + * @param Notice $notice The notice to broadcast + * + * @return boolean success flag + */ - return true; +function jabber_broadcast_notice($notice) +{ + if (!common_config('xmpp', 'enabled')) { + return true; + } + $profile = Profile::staticGet($notice->profile_id); + + if (!$profile) { + common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . + 'unknown profile ' . common_log_objstring($notice), + __FILE__); + return false; + } + + $msg = jabber_format_notice($profile, $notice); + $entry = jabber_format_entry($profile, $notice); + + $profile->free(); + unset($profile); + + $sent_to = array(); + + $conn = jabber_connect(); + + // First, get users to whom this is a direct reply + $user = new User(); + $user->query('SELECT user.id, user.jabber ' . + 'FROM user JOIN reply ON user.id = reply.profile_id ' . + 'WHERE reply.notice_id = ' . $notice->id . ' ' . + 'AND user.jabber is not null ' . + 'AND user.jabbernotify = 1 ' . + 'AND user.jabberreplies = 1 '); + + while ($user->fetch()) { + common_log(LOG_INFO, + 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, + __FILE__); + $conn->message($user->jabber, $msg, 'chat', null, $entry); + $conn->processTime(0); + $sent_to[$user->id] = 1; + } + + $user->free(); + + // Now, get users subscribed to this profile + + $user = new User(); + $user->query('SELECT user.id, user.jabber ' . + 'FROM user JOIN subscription ' . + 'ON user.id = subscription.subscriber ' . + 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . + 'AND user.jabber is not null ' . + 'AND user.jabbernotify = 1 ' . + 'AND subscription.jabber = 1 '); + + while ($user->fetch()) { + if (!array_key_exists($user->id, $sent_to)) { + common_log(LOG_INFO, + 'Sending notice ' . $notice->id . ' to ' . $user->jabber, + __FILE__); + $conn->message($user->jabber, $msg, 'chat', null, $entry); + // To keep the incoming queue from filling up, + // we service it after each send. + $conn->processTime(0); + } + } + + $user->free(); + + return true; } -function jabber_public_notice($notice) { +/** + * send a notice to all public listeners + * + * For notices that are generated on the local system (by users), we can optionally + * forward them to remote listeners by XMPP. + * + * @param Notice $notice notice to broadcast + * + * @return boolean success flag + */ - # Now, users who want everything +function jabber_public_notice($notice) +{ + // Now, users who want everything - $public = common_config('xmpp', 'public'); + $public = common_config('xmpp', 'public'); - # FIXME PRIV don't send out private messages here - # XXX: should we send out non-local messages if public,localonly - # = false? I think not + // FIXME PRIV don't send out private messages here + // XXX: should we send out non-local messages if public,localonly + // = false? I think not - if ($public && $notice->is_local) { - $profile = Profile::staticGet($notice->profile_id); + if ($public && $notice->is_local) { + $profile = Profile::staticGet($notice->profile_id); - if (!$profile) { - common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . - 'unknown profile ' . common_log_objstring($notice), - __FILE__); - return false; - } + if (!$profile) { + common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . + 'unknown profile ' . common_log_objstring($notice), + __FILE__); + return false; + } - $msg = jabber_format_notice($profile, $notice); - $entry = jabber_format_entry($profile, $notice); + $msg = jabber_format_notice($profile, $notice); + $entry = jabber_format_entry($profile, $notice); - $conn = jabber_connect(); + $conn = jabber_connect(); - foreach ($public as $address) { - common_log(LOG_INFO, - 'Sending notice ' . $notice->id . ' to public listener ' . $address, - __FILE__); - $conn->message($address, $msg, 'chat', NULL, $entry); - $conn->processTime(0); - } - $profile->free(); - } + foreach ($public as $address) { + common_log(LOG_INFO, + 'Sending notice ' . $notice->id . + ' to public listener ' . $address, + __FILE__); + $conn->message($address, $msg, 'chat', null, $entry); + $conn->processTime(0); + } + $profile->free(); + } - return true; + return true; } -function jabber_format_notice(&$profile, &$notice) { - return $profile->nickname . ': ' . $notice->content; +/** + * makes a plain-text formatted version of a notice, suitable for Jabber distribution + * + * @param Profile &$profile profile of the sending user + * @param Notice &$notice notice being sent + * + * @return string plain-text version of the notice, with user nickname prefixed + */ + +function jabber_format_notice(&$profile, &$notice) +{ + return $profile->nickname . ': ' . $notice->content; } -- cgit v1.2.3-54-g00ecf From 9de0583196ec8f5afa56afc192861d0d735860b4 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 22 Dec 2008 14:30:29 -0500 Subject: reformat lib/language.php for PEAR Coding Standards darcs-hash:20081222193029-84dde-8d0f64d0fad2a2854d1a3a294a30e74d73fd1bd1.gz --- _darcs/inventory | 4 +- ...dde-8d0f64d0fad2a2854d1a3a294a30e74d73fd1bd1.gz | Bin 0 -> 2233 bytes _darcs/pristine/lib/language.php | 193 +++-- _darcs/tentative_pristine | 790 +++++---------------- lib/language.php | 193 +++-- 5 files changed, 422 insertions(+), 758 deletions(-) create mode 100644 _darcs/patches/20081222193029-84dde-8d0f64d0fad2a2854d1a3a294a30e74d73fd1bd1.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index b3846949e..b3f004503 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -31,4 +31,6 @@ Evan Prodromou **20081221004607] [reformat for phpcs Evan Prodromou **20081221005837] [reformat lib/jabber.php for phpcs, including doc comments -Evan Prodromou **20081222173249] \ No newline at end of file +Evan Prodromou **20081222173249] +[reformat lib/language.php for PEAR Coding Standards +Evan Prodromou **20081222193029] \ No newline at end of file diff --git a/_darcs/patches/20081222193029-84dde-8d0f64d0fad2a2854d1a3a294a30e74d73fd1bd1.gz b/_darcs/patches/20081222193029-84dde-8d0f64d0fad2a2854d1a3a294a30e74d73fd1bd1.gz new file mode 100644 index 000000000..14fdbabbf Binary files /dev/null and b/_darcs/patches/20081222193029-84dde-8d0f64d0fad2a2854d1a3a294a30e74d73fd1bd1.gz differ diff --git a/_darcs/pristine/lib/language.php b/_darcs/pristine/lib/language.php index 796e28870..1d00cc31e 100644 --- a/_darcs/pristine/lib/language.php +++ b/_darcs/pristine/lib/language.php @@ -1,9 +1,12 @@ . + * + * @category I18n + * @package Laconica + * @author Matthew Gregg + * @author Ciaran Gultnieks + * @author Evan Prodromou + * @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); } +if (!defined('LACONICA')) { + exit(1); +} +/** + * Content negotiation for language codes + * + * @param string $httplang HTTP Accept-Language header + * + * @return string language code for best language match + */ +function client_prefered_language($httplang) +{ + $client_langs = array(); -function client_prefered_language($httplang) { - $client_langs = array(); - $all_languages = common_config('site','languages'); + $all_languages = common_config('site', 'languages'); - preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"',strtolower($httplang),$httplang); - for ($i = 0; $i < count($httplang); $i++) { - if(!empty($httplang[2][$i])) { - #if no q default to 1.0 - $client_langs[$httplang[2][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); - } - if(!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { - #if a catchall default 0.01 lower - $client_langs[$httplang[3][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); - } - } - #sort in decending q - arsort($client_langs); + preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"', + strtolower($httplang), $httplang); - foreach ($client_langs as $lang => $q) { - if (isset($all_languages[$lang])) { - return($all_languages[$lang]['lang']); - } - } - return FALSE; -} + for ($i = 0; $i < count($httplang); $i++) { + if (!empty($httplang[2][$i])) { + // if no q default to 1.0 + $client_langs[$httplang[2][$i]] = + ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); + } + if (!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { + // if a catchall default 0.01 lower + $client_langs[$httplang[3][$i]] = + ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); + } + } + // sort in decending q + arsort($client_langs); -function get_nice_language_list() { - $nice_lang = array(); - $all_languages = common_config('site','languages'); - foreach ($all_languages as $lang) { - $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); + foreach ($client_langs as $lang => $q) { + if (isset($all_languages[$lang])) { + return($all_languages[$lang]['lang']); } - return $nice_lang; + } + return false; } -// 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 -// common_config('site','languages') -function get_all_languages() { - return array( - 'en-us' => array('q' => 1, 'lang' => 'en_US', 'name' => 'English (US)', 'direction' => 'ltr'), - 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', 'name' => 'English (NZ)', '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'), - 'da' => array('q' => 0.1, 'lang' => 'da_DK', 'name' => 'Danish', 'direction' => 'ltr'), - 'nl' => array('q' => 1, 'lang' => 'nl_NL', 'name' => 'Dutch', 'direction' => 'ltr'), - 'eo' => array('q' => 0.1, 'lang' => 'eo', 'name' => 'Esperanto', 'direction' => 'ltr'), - 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', 'name' => 'French', 'direction' => 'ltr'), - 'de' => array('q' => 1, 'lang' => 'de_DE', 'name' => 'German', 'direction' => 'ltr'), - 'it' => array('q' => 1, 'lang' => 'it_IT', 'name' => 'Italian', 'direction' => 'ltr'), - 'ko' => array('q' => 0.1, 'lang' => 'ko', 'name' => 'Korean', 'direction' => 'ltr'), - 'nb' => array('q' => 1, 'lang' => 'nb_NO', 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), - 'pt' => array('q' => 0.2, 'lang' => 'pt', 'name' => 'Portuguese', 'direction' => 'ltr'), - 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), -# 'ru' => array('q' => 0.1, 'lang' => 'ru_RU', 'name' => 'Russian', 'direction' => 'ltr'), - 'es' => array('q' => 1, 'lang' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'), - 'tr' => array('q' => 1, 'lang' => 'tr_TR', 'name' => 'Turkish', 'direction' => 'ltr'), - 'uk' => array('q' => 1, 'lang' => 'uk_UA', 'name' => 'Ukrainian', 'direction' => 'ltr'), -# 'lt' => array('q' => 0.1, 'lang' => 'lt_LT', 'name' => 'Lithuanian', 'direction' => 'ltr'), -# 'sv' => array('q' => 1, 'lang' => 'sv_SE', 'name' => 'Swedish', 'direction' => 'ltr'), - 'pl' => array('q' => 1, 'lang' => 'pl_PL', 'name' => 'Polish', 'direction' => 'ltr'), - 'mk' => array('q' => 1, 'lang' => 'mk_MK', 'name' => 'Macedonian', 'direction' => 'ltr'), - 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', 'name' => 'Japanese', 'direction' => 'ltr'), - 'cs' => array('q' => 1, 'lang' => 'cs_CZ', 'name' => 'Czech', 'direction' => 'ltr'), - 'ca' => array('q' => 1, 'lang' => 'ca_ES', 'name' => 'Catalan', 'direction' => 'ltr'), -# 'hr' => array('q' => 0.1, 'lang' => 'he_IL', 'name' => 'Hebrew', 'direction' => 'ltr') - ); +/** + * returns a simple code -> name mapping for languages + * + * @return array map of available languages by code to language name. + */ + +function get_nice_language_list() +{ + $nice_lang = array(); + + $all_languages = common_config('site', 'languages'); + + foreach ($all_languages as $lang) { + $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); + } + return $nice_lang; +} + +/** + * 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 + * common_config('site','languages') + * + * @return array mapping of language codes to language info + */ + +function get_all_languages() +{ + return + array('en-us' => array('q' => 1, 'lang' => 'en_US', + 'name' => 'English (US)', 'direction' => 'ltr'), + 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', + 'name' => 'English (NZ)', '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'), + 'da' => array('q' => 0.1, 'lang' => 'da_DK', + 'name' => 'Danish', 'direction' => 'ltr'), + 'nl' => array('q' => 1, 'lang' => 'nl_NL', + 'name' => 'Dutch', 'direction' => 'ltr'), + 'eo' => array('q' => 0.1, 'lang' => 'eo', + 'name' => 'Esperanto', 'direction' => 'ltr'), + 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', + 'name' => 'French', 'direction' => 'ltr'), + 'de' => array('q' => 1, 'lang' => 'de_DE', + 'name' => 'German', 'direction' => 'ltr'), + 'it' => array('q' => 1, 'lang' => 'it_IT', + 'name' => 'Italian', 'direction' => 'ltr'), + 'ko' => array('q' => 0.1, 'lang' => 'ko', + 'name' => 'Korean', 'direction' => 'ltr'), + 'nb' => array('q' => 1, 'lang' => 'nb_NO', + 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), + 'pt' => array('q' => 0.2, 'lang' => 'pt', + 'name' => 'Portuguese', 'direction' => 'ltr'), + 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', + 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), + 'es' => array('q' => 1, 'lang' => 'es', + 'name' => 'Spanish', 'direction' => 'ltr'), + 'tr' => array('q' => 1, 'lang' => 'tr_TR', + 'name' => 'Turkish', 'direction' => 'ltr'), + 'uk' => array('q' => 1, 'lang' => 'uk_UA', + 'name' => 'Ukrainian', 'direction' => 'ltr'), + 'pl' => array('q' => 1, 'lang' => 'pl_PL', + 'name' => 'Polish', 'direction' => 'ltr'), + 'mk' => array('q' => 1, 'lang' => 'mk_MK', + 'name' => 'Macedonian', 'direction' => 'ltr'), + 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', + 'name' => 'Japanese', 'direction' => 'ltr'), + 'cs' => array('q' => 1, 'lang' => 'cs_CZ', + 'name' => 'Czech', 'direction' => 'ltr'), + 'ca' => array('q' => 1, 'lang' => 'ca_ES', + 'name' => 'Catalan', 'direction' => 'ltr'), + ); } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 402ea252b..9b17c08d1 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,661 +1,205 @@ -hunk ./lib/jabber.php 2 +hunk ./lib/language.php 2 -/* - * Laconica - a distributed open-source microblogging tool - * Copyright (C) 2008, Controlez-Vous, Inc. +/** + * Laconica, the distributed open-source microblogging tool -hunk ./lib/jabber.php 5 +hunk ./lib/language.php 5 - * This program is free software: you can redistribute it and/or modify -+ * utility functions for Jabber/GTalk/XMPP messages ++ * utility functions for i18n + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./lib/jabber.php 21 -+ * -+ * @category Network -+ * @package Laconica -+ * @author Evan Prodromou -+ * @copyright 2008 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/ -hunk ./lib/jabber.php 30 +hunk ./lib/language.php 21 ++ * ++ * @category I18n ++ * @package Laconica ++ * @author Matthew Gregg ++ * @author Ciaran Gultnieks ++ * @author Evan Prodromou ++ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 ++ * @link http://laconi.ca/ +hunk ./lib/language.php 31 -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/jabber.php 34 --require_once('XMPPHP/XMPP.php'); -+require_once 'XMPPHP/XMPP.php'; -hunk ./lib/jabber.php 36 --function jabber_valid_base_jid($jid) { -- # Cheap but effective -- return Validate::email($jid); -+/** -+ * checks whether a string is a syntactically valid Jabber ID (JID) -+ * -+ * @param string $jid string to check -+ * -+ * @return boolean whether the string is a valid JID -+ */ -+ -+function jabber_valid_base_jid($jid) -+{ -+ // Cheap but effective -+ return Validate::email($jid); -hunk ./lib/jabber.php 50 --function jabber_normalize_jid($jid) { -- if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { -- $node = $matches[1]; -- $server = $matches[2]; -- return strtolower($node.'@'.$server); -- } else { -- return NULL; -- } -+/** -+ * normalizes a Jabber ID for comparison -+ * -+ * @param string $jid JID to check -+ * -+ * @return string an equivalent JID in normalized (lowercase) form -+ */ -+ -+function jabber_normalize_jid($jid) -+{ -+ if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) { -+ $node = $matches[1]; -+ $server = $matches[2]; -+ return strtolower($node.'@'.$server); -+ } else { -+ return null; -+ } -hunk ./lib/jabber.php 69 --function jabber_daemon_address() { -- return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); -+/** -+ * the JID of the Jabber daemon for this Laconica instance -+ * -+ * @return string JID of the Jabber daemon -+ */ -+ -+function jabber_daemon_address() -+{ -+ return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server'); -hunk ./lib/jabber.php 80 --function jabber_connect($resource=NULL) { -- static $conn = NULL; -- if (!$conn) { -- $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? -- common_config('xmpp', 'host') : -- common_config('xmpp', 'server'), -- common_config('xmpp', 'port'), -- common_config('xmpp', 'user'), -- common_config('xmpp', 'password'), -- ($resource) ? $resource : -- common_config('xmpp', 'resource'), -- common_config('xmpp', 'server'), -- common_config('xmpp', 'debug') ? -- true : false, -- common_config('xmpp', 'debug') ? -- XMPPHP_Log::LEVEL_VERBOSE : NULL -- ); +hunk ./lib/language.php 35 +/** -+ * connect the configured Jabber account to the configured server ++ * Content negotiation for language codes + * -+ * @param string $resource Resource to connect (defaults to configured resource) ++ * @param string $httplang HTTP Accept-Language header + * -+ * @return XMPPHP connection to the configured server ++ * @return string language code for best language match + */ -+ -+function jabber_connect($resource=null) +hunk ./lib/language.php 43 ++function client_prefered_language($httplang) +{ -+ static $conn = null; -+ if (!$conn) { -+ $conn = new XMPPHP_XMPP(common_config('xmpp', 'host') ? -+ common_config('xmpp', 'host') : -+ common_config('xmpp', 'server'), -+ common_config('xmpp', 'port'), -+ common_config('xmpp', 'user'), -+ common_config('xmpp', 'password'), -+ ($resource) ? $resource : -+ common_config('xmpp', 'resource'), -+ common_config('xmpp', 'server'), -+ common_config('xmpp', 'debug') ? -+ true : false, -+ common_config('xmpp', 'debug') ? -+ XMPPHP_Log::LEVEL_VERBOSE : null -+ ); -hunk ./lib/jabber.php 107 -- if (!$conn) { -- return false; -- } -+ if (!$conn) { -+ return false; ++ $client_langs = array(); +hunk ./lib/language.php 47 +-function client_prefered_language($httplang) { +- $client_langs = array(); +- $all_languages = common_config('site','languages'); ++ $all_languages = common_config('site', 'languages'); +hunk ./lib/language.php 49 +- preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"',strtolower($httplang),$httplang); +- for ($i = 0; $i < count($httplang); $i++) { +- if(!empty($httplang[2][$i])) { +- #if no q default to 1.0 +- $client_langs[$httplang[2][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); +- } +- if(!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { +- #if a catchall default 0.01 lower +- $client_langs[$httplang[3][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); +- } +- } +- #sort in decending q +- arsort($client_langs); ++ preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"', ++ strtolower($httplang), $httplang); +hunk ./lib/language.php 52 +- foreach ($client_langs as $lang => $q) { +- if (isset($all_languages[$lang])) { +- return($all_languages[$lang]['lang']); +- } +- } +- return FALSE; +-} ++ for ($i = 0; $i < count($httplang); $i++) { ++ if (!empty($httplang[2][$i])) { ++ // if no q default to 1.0 ++ $client_langs[$httplang[2][$i]] = ++ ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); + } -hunk ./lib/jabber.php 111 -- $conn->autoSubscribe(); -- $conn->useEncryption(common_config('xmpp', 'encryption')); -+ $conn->autoSubscribe(); -+ $conn->useEncryption(common_config('xmpp', 'encryption')); -hunk ./lib/jabber.php 114 -- try { -- $conn->connect(true); # true = persistent connection -- } catch (XMPPHP_Exception $e) { -- common_log(LOG_ERROR, $e->getMessage()); -- return false; -- } -+ try { -+ $conn->connect(true); // true = persistent connection -+ } catch (XMPPHP_Exception $e) { -+ common_log(LOG_ERROR, $e->getMessage()); -+ return false; ++ if (!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { ++ // if a catchall default 0.01 lower ++ $client_langs[$httplang[3][$i]] = ++ ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); + } -hunk ./lib/jabber.php 121 -- $conn->processUntil('session_start'); -- } -- return $conn; -+ $conn->processUntil('session_start'); + } -+ return $conn; -hunk ./lib/jabber.php 126 --function jabber_send_notice($to, $notice) { -- $conn = jabber_connect(); -- if (!$conn) { -- return false; -- } -- $profile = Profile::staticGet($notice->profile_id); -- if (!$profile) { -- common_log(LOG_WARNING, 'Refusing to send notice with ' . -- 'unknown profile ' . common_log_objstring($notice), -- __FILE__); -- return false; -- } -- $msg = jabber_format_notice($profile, $notice); -- $entry = jabber_format_entry($profile, $notice); -- $conn->message($to, $msg, 'chat', NULL, $entry); -- $profile->free(); -- return true; -+/** -+ * send a single notice to a given Jabber address -+ * -+ * @param string $to JID to send the notice to -+ * @param Notice $notice notice to send -+ * -+ * @return boolean success value -+ */ -+ -+function jabber_send_notice($to, $notice) -+{ -+ $conn = jabber_connect(); -+ if (!$conn) { -+ return false; -+ } -+ $profile = Profile::staticGet($notice->profile_id); -+ if (!$profile) { -+ common_log(LOG_WARNING, 'Refusing to send notice with ' . -+ 'unknown profile ' . common_log_objstring($notice), -+ __FILE__); -+ return false; ++ // sort in decending q ++ arsort($client_langs); +hunk ./lib/language.php 67 +-function get_nice_language_list() { +- $nice_lang = array(); +- $all_languages = common_config('site','languages'); +- foreach ($all_languages as $lang) { +- $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); ++ foreach ($client_langs as $lang => $q) { ++ if (isset($all_languages[$lang])) { ++ return($all_languages[$lang]['lang']); +hunk ./lib/language.php 71 +- return $nice_lang; + } -+ $msg = jabber_format_notice($profile, $notice); -+ $entry = jabber_format_entry($profile, $notice); -+ $conn->message($to, $msg, 'chat', null, $entry); -+ $profile->free(); -+ return true; -hunk ./lib/jabber.php 155 --# Extra stuff defined by Twitter, needed by twitter clients -+/** -+ * extra information for XMPP messages, as defined by Twitter -+ * -+ * @param Profile $profile Profile of the sending user -+ * @param Notice $notice Notice being sent -+ * -+ * @return string Extra information (Atom, HTML, addresses) in string format -+ */ -hunk ./lib/jabber.php 164 --function jabber_format_entry($profile, $notice) { -+function jabber_format_entry($profile, $notice) -+{ -+ // FIXME: notice url might be remote -hunk ./lib/jabber.php 168 -- # FIXME: notice url might be remote -+ $noticeurl = common_local_url('shownotice', -+ array('notice' => $notice->id)); -hunk ./lib/jabber.php 171 -- $noticeurl = common_local_url('shownotice', -- array('notice' => $notice->id)); -- $msg = jabber_format_notice($profile, $notice); -- $entry = "\n\n"; -- $entry .= "\n"; -- $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; -- $entry .= "\n"; -- $entry .= " $profile->nickname)) . "'/>\n"; -- $entry .= "" . $profile->nickname . "\n"; -- $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; -- $entry .= "\n"; -- $entry .= "" . htmlspecialchars($msg) . "\n"; -- $entry .= "" . htmlspecialchars($msg) . "\n"; -- $entry .= "\n"; -- $entry .= "". $notice->uri . "\n"; -- $entry .= "".common_date_w3dtf($notice->created)."\n"; -- $entry .= "".common_date_w3dtf($notice->modified)."\n"; -- $entry .= "\n"; -+ $msg = jabber_format_notice($profile, $notice); -hunk ./lib/jabber.php 173 -- $html = "\n\n"; -- $html .= "\n"; -- $html .= "".$profile->nickname.": "; -- $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); -- $html .= "\n\n"; -- $html .= "\n\n"; -+ $self_url = common_local_url('userrss', array('nickname' => $profile->nickname)); -hunk ./lib/jabber.php 175 -- $address = "\n"; -- $address .= "
\n"; -- $address .= "\n"; -+ $entry = "\n\n"; -+ $entry .= "\n"; -+ $entry .= "" . $profile->nickname . " - " . common_config('site', 'name') . "\n"; -+ $entry .= "\n"; -+ $entry .= "\n"; -+ $entry .= "" . $profile->nickname . "\n"; -+ $entry .= "" . common_profile_avatar_url($profile, AVATAR_PROFILE_SIZE) . "\n"; -+ $entry .= "\n"; -+ $entry .= "" . htmlspecialchars($msg) . "\n"; -+ $entry .= "" . htmlspecialchars($msg) . "\n"; -+ $entry .= "\n"; -+ $entry .= "". $notice->uri . "\n"; -+ $entry .= "".common_date_w3dtf($notice->created)."\n"; -+ $entry .= "".common_date_w3dtf($notice->modified)."\n"; -+ $entry .= "\n"; -hunk ./lib/jabber.php 191 -- # FIXME: include a pubsub event, too. -+ $html = "\n\n"; -+ $html .= "\n"; -+ $html .= "".$profile->nickname.": "; -+ $html .= ($notice->rendered) ? $notice->rendered : common_render_content($notice->content, $notice); -+ $html .= "\n\n"; -+ $html .= "\n\n"; -hunk ./lib/jabber.php 198 -- return $html . $entry . $address; -+ $address = "\n"; -+ $address .= "
\n"; -+ $address .= "\n"; -+ -+ // FIXME: include a pubsub event, too. -+ -+ return $html . $entry . $address; -hunk ./lib/jabber.php 207 --function jabber_send_message($to, $body, $type='chat', $subject=NULL) { -- $conn = jabber_connect(); -- if (!$conn) { -- return false; -- } -- $conn->message($to, $body, $type, $subject); -- return true; ++ return false; +hunk ./lib/language.php 75 +-// 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 +-// common_config('site','languages') +-function get_all_languages() { +- return array( +- 'en-us' => array('q' => 1, 'lang' => 'en_US', 'name' => 'English (US)', 'direction' => 'ltr'), +- 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', 'name' => 'English (NZ)', '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'), +- 'da' => array('q' => 0.1, 'lang' => 'da_DK', 'name' => 'Danish', 'direction' => 'ltr'), +- 'nl' => array('q' => 1, 'lang' => 'nl_NL', 'name' => 'Dutch', 'direction' => 'ltr'), +- 'eo' => array('q' => 0.1, 'lang' => 'eo', 'name' => 'Esperanto', 'direction' => 'ltr'), +- 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', 'name' => 'French', 'direction' => 'ltr'), +- 'de' => array('q' => 1, 'lang' => 'de_DE', 'name' => 'German', 'direction' => 'ltr'), +- 'it' => array('q' => 1, 'lang' => 'it_IT', 'name' => 'Italian', 'direction' => 'ltr'), +- 'ko' => array('q' => 0.1, 'lang' => 'ko', 'name' => 'Korean', 'direction' => 'ltr'), +- 'nb' => array('q' => 1, 'lang' => 'nb_NO', 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), +- 'pt' => array('q' => 0.2, 'lang' => 'pt', 'name' => 'Portuguese', 'direction' => 'ltr'), +- 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), +-# 'ru' => array('q' => 0.1, 'lang' => 'ru_RU', 'name' => 'Russian', 'direction' => 'ltr'), +- 'es' => array('q' => 1, 'lang' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'), +- 'tr' => array('q' => 1, 'lang' => 'tr_TR', 'name' => 'Turkish', 'direction' => 'ltr'), +- 'uk' => array('q' => 1, 'lang' => 'uk_UA', 'name' => 'Ukrainian', 'direction' => 'ltr'), +-# 'lt' => array('q' => 0.1, 'lang' => 'lt_LT', 'name' => 'Lithuanian', 'direction' => 'ltr'), +-# 'sv' => array('q' => 1, 'lang' => 'sv_SE', 'name' => 'Swedish', 'direction' => 'ltr'), +- 'pl' => array('q' => 1, 'lang' => 'pl_PL', 'name' => 'Polish', 'direction' => 'ltr'), +- 'mk' => array('q' => 1, 'lang' => 'mk_MK', 'name' => 'Macedonian', 'direction' => 'ltr'), +- 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', 'name' => 'Japanese', 'direction' => 'ltr'), +- 'cs' => array('q' => 1, 'lang' => 'cs_CZ', 'name' => 'Czech', 'direction' => 'ltr'), +- 'ca' => array('q' => 1, 'lang' => 'ca_ES', 'name' => 'Catalan', 'direction' => 'ltr'), +-# 'hr' => array('q' => 0.1, 'lang' => 'he_IL', 'name' => 'Hebrew', 'direction' => 'ltr') +- ); +/** -+ * sends a single text message to a given JID -+ * -+ * @param string $to JID to send the message to -+ * @param string $body body of the message -+ * @param string $type type of the message -+ * @param string $subject subject of the message ++ * returns a simple code -> name mapping for languages + * -+ * @return boolean success flag ++ * @return array map of available languages by code to language name. + */ + -+function jabber_send_message($to, $body, $type='chat', $subject=null) ++function get_nice_language_list() +{ -+ $conn = jabber_connect(); -+ if (!$conn) { -+ return false; -+ } -+ $conn->message($to, $body, $type, $subject); -+ return true; -hunk ./lib/jabber.php 228 --function jabber_send_presence($status, $show='available', $to=NULL, -- $type = 'available', $priority=NULL) -+/** -+ * sends a presence stanza on the Jabber network -+ * -+ * @param string $status current status, free-form string -+ * @param string $show structured status value -+ * @param string $to recipient of presence, null for general -+ * @param string $type type of status message, related to $show -+ * @param int $priority priority of the presence -+ * -+ * @return boolean success value -+ */ ++ $nice_lang = array(); + -+function jabber_send_presence($status, $show='available', $to=null, -+ $type = 'available', $priority=null) -hunk ./lib/jabber.php 243 -- $conn = jabber_connect(); -- if (!$conn) { -- return false; -- } -- $conn->presence($status, $show, $to, $type, $priority); -- return true; -+ $conn = jabber_connect(); -+ if (!$conn) { -+ return false; -+ } -+ $conn->presence($status, $show, $to, $type, $priority); -+ return true; -hunk ./lib/jabber.php 251 --function jabber_confirm_address($code, $nickname, $address) { -- $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . -- 'has said that your Jabber ID belongs to them. ' . -- 'If that\'s true, you can confirm by clicking on this URL: ' . -- common_local_url('confirmaddress', array('code' => $code)) . -- ' . (If you cannot click it, copy-and-paste it into the ' . -- 'address bar of your browser). If that user isn\'t you, ' . -- 'or if you didn\'t request this confirmation, just ignore this message.'; -+/** -+ * sends a confirmation request to a JID -+ * -+ * @param string $code confirmation code for confirmation URL -+ * @param string $nickname nickname of confirming user -+ * @param string $address JID to send confirmation to -+ * -+ * @return boolean success flag -+ */ -+ -+function jabber_confirm_address($code, $nickname, $address) -+{ -+ $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' . -+ 'has said that your Jabber ID belongs to them. ' . -+ 'If that\'s true, you can confirm by clicking on this URL: ' . -+ common_local_url('confirmaddress', array('code' => $code)) . -+ ' . (If you cannot click it, copy-and-paste it into the ' . -+ 'address bar of your browser). If that user isn\'t you, ' . -+ 'or if you didn\'t request this confirmation, just ignore this message.'; -hunk ./lib/jabber.php 271 -- return jabber_send_message($address, $body); -+ return jabber_send_message($address, $body); -hunk ./lib/jabber.php 274 --function jabber_special_presence($type, $to=NULL, $show=NULL, $status=NULL) { -- $conn = jabber_connect(); -+/** -+ * sends a "special" presence stanza on the Jabber network -+ * -+ * @param string $type Type of presence -+ * @param string $to JID to send presence to -+ * @param string $show show value for presence -+ * @param string $status status value for presence -+ * -+ * @return boolean success flag -+ * -+ * @see jabber_send_presence() -+ */ ++ $all_languages = common_config('site', 'languages'); + -+function jabber_special_presence($type, $to=null, $show=null, $status=null) -+{ -+ // FIXME: why use this instead of jabber_send_presence()? -+ $conn = jabber_connect(); -hunk ./lib/jabber.php 292 -- $to = htmlspecialchars($to); -- $status = htmlspecialchars($status); -- $out = "send($out); -+ $to = htmlspecialchars($to); -+ $status = htmlspecialchars($status); -+ -+ $out = " $lang['name']); + } -+ if ($show == 'available' and !$status) { -+ $out .= "/>"; -+ } else { -+ $out .= ">"; -+ if ($show && ($show != 'available')) { -+ $out .= "$show"; -+ } -+ if ($status) { -+ $out .= "$status"; -+ } -+ $out .= ""; -+ } -+ $conn->send($out); -hunk ./lib/jabber.php 317 --function jabber_broadcast_notice($notice) { -+/** -+ * broadcast a notice to all subscribers and reply recipients -+ * -+ * This function will send a notice to all subscribers on the local server -+ * who have Jabber addresses, and have Jabber notification enabled, and -+ * have this subscription enabled for Jabber. It also sends the notice to -+ * all recipients of @-replies who have Jabber addresses and Jabber notification -+ * enabled. This is really the heart of Jabber distribution in Laconica. -+ * -+ * @param Notice $notice The notice to broadcast -+ * -+ * @return boolean success flag -+ */ -hunk ./lib/jabber.php 331 -- if (!common_config('xmpp', 'enabled')) { -- return true; -- } -- $profile = Profile::staticGet($notice->profile_id); -+function jabber_broadcast_notice($notice) -+{ -+ if (!common_config('xmpp', 'enabled')) { -+ return true; -+ } -+ $profile = Profile::staticGet($notice->profile_id); ++ return $nice_lang; ++} + -+ if (!$profile) { -+ common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . -+ 'unknown profile ' . common_log_objstring($notice), -+ __FILE__); -+ return false; -+ } -hunk ./lib/jabber.php 345 -- if (!$profile) { -- common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . -- 'unknown profile ' . common_log_objstring($notice), -- __FILE__); -- return false; -- } -+ $msg = jabber_format_notice($profile, $notice); -+ $entry = jabber_format_entry($profile, $notice); -hunk ./lib/jabber.php 348 -- $msg = jabber_format_notice($profile, $notice); -- $entry = jabber_format_entry($profile, $notice); -+ $profile->free(); -+ unset($profile); -hunk ./lib/jabber.php 351 -- $profile->free(); -- unset($profile); -+ $sent_to = array(); -hunk ./lib/jabber.php 353 -- $sent_to = array(); -- $conn = jabber_connect(); -+ $conn = jabber_connect(); -hunk ./lib/jabber.php 355 -- # First, get users to whom this is a direct reply -- $user = new User(); -- $user->query('SELECT user.id, user.jabber ' . -- 'FROM user JOIN reply ON user.id = reply.profile_id ' . -- 'WHERE reply.notice_id = ' . $notice->id . ' ' . -- 'AND user.jabber is not null ' . -- 'AND user.jabbernotify = 1 ' . -- 'AND user.jabberreplies = 1 '); -+ // First, get users to whom this is a direct reply -+ $user = new User(); -+ $user->query('SELECT user.id, user.jabber ' . -+ 'FROM user JOIN reply ON user.id = reply.profile_id ' . -+ 'WHERE reply.notice_id = ' . $notice->id . ' ' . -+ 'AND user.jabber is not null ' . -+ 'AND user.jabbernotify = 1 ' . -+ 'AND user.jabberreplies = 1 '); -hunk ./lib/jabber.php 364 -- while ($user->fetch()) { -- common_log(LOG_INFO, -- 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, -- __FILE__); -- $conn->message($user->jabber, $msg, 'chat', NULL, $entry); -- $conn->processTime(0); -- $sent_to[$user->id] = 1; -- } -+ while ($user->fetch()) { -+ common_log(LOG_INFO, -+ 'Sending reply notice ' . $notice->id . ' to ' . $user->jabber, -+ __FILE__); -+ $conn->message($user->jabber, $msg, 'chat', null, $entry); -+ $conn->processTime(0); -+ $sent_to[$user->id] = 1; -+ } -hunk ./lib/jabber.php 373 -- $user->free(); -+ $user->free(); -hunk ./lib/jabber.php 375 -- # Now, get users subscribed to this profile -+ // Now, get users subscribed to this profile -hunk ./lib/jabber.php 377 -- $user = new User(); -- $user->query('SELECT user.id, user.jabber ' . -- 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . -- 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . -- 'AND user.jabber is not null ' . -- 'AND user.jabbernotify = 1 ' . -+ $user = new User(); -+ $user->query('SELECT user.id, user.jabber ' . -+ 'FROM user JOIN subscription ' . -+ 'ON user.id = subscription.subscriber ' . -+ 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . -+ 'AND user.jabber is not null ' . -+ 'AND user.jabbernotify = 1 ' . -hunk ./lib/jabber.php 386 -- while ($user->fetch()) { -- if (!array_key_exists($user->id, $sent_to)) { -- common_log(LOG_INFO, -- 'Sending notice ' . $notice->id . ' to ' . $user->jabber, -- __FILE__); -- $conn->message($user->jabber, $msg, 'chat', NULL, $entry); -- # To keep the incoming queue from filling up, we service it after each send. -- $conn->processTime(0); -- } -- } -+ while ($user->fetch()) { -+ if (!array_key_exists($user->id, $sent_to)) { -+ common_log(LOG_INFO, -+ 'Sending notice ' . $notice->id . ' to ' . $user->jabber, -+ __FILE__); -+ $conn->message($user->jabber, $msg, 'chat', null, $entry); -+ // To keep the incoming queue from filling up, -+ // we service it after each send. -+ $conn->processTime(0); -+ } -+ } -hunk ./lib/jabber.php 398 -- $user->free(); -+ $user->free(); -hunk ./lib/jabber.php 400 -- return true; -+ return true; -hunk ./lib/jabber.php 403 --function jabber_public_notice($notice) { -+/** -+ * send a notice to all public listeners -+ * -+ * For notices that are generated on the local system (by users), we can optionally -+ * forward them to remote listeners by XMPP. -+ * -+ * @param Notice $notice notice to broadcast -+ * -+ * @return boolean success flag -+ */ -hunk ./lib/jabber.php 414 -- # Now, users who want everything -+function jabber_public_notice($notice) -+{ -+ // Now, users who want everything -hunk ./lib/jabber.php 418 -- $public = common_config('xmpp', 'public'); -+ $public = common_config('xmpp', 'public'); -hunk ./lib/jabber.php 420 -- # FIXME PRIV don't send out private messages here -- # XXX: should we send out non-local messages if public,localonly -- # = false? I think not -+ // FIXME PRIV don't send out private messages here -+ // XXX: should we send out non-local messages if public,localonly -+ // = false? I think not -hunk ./lib/jabber.php 424 -- if ($public && $notice->is_local) { -- $profile = Profile::staticGet($notice->profile_id); -+ if ($public && $notice->is_local) { -+ $profile = Profile::staticGet($notice->profile_id); -hunk ./lib/jabber.php 427 -- if (!$profile) { -- common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . -- 'unknown profile ' . common_log_objstring($notice), -- __FILE__); -- return false; -- } -+ if (!$profile) { -+ common_log(LOG_WARNING, 'Refusing to broadcast notice with ' . -+ 'unknown profile ' . common_log_objstring($notice), -+ __FILE__); -+ return false; -+ } -hunk ./lib/jabber.php 434 -- $msg = jabber_format_notice($profile, $notice); -- $entry = jabber_format_entry($profile, $notice); -+ $msg = jabber_format_notice($profile, $notice); -+ $entry = jabber_format_entry($profile, $notice); -hunk ./lib/jabber.php 437 -- $conn = jabber_connect(); -+ $conn = jabber_connect(); -hunk ./lib/jabber.php 439 -- foreach ($public as $address) { -- common_log(LOG_INFO, -- 'Sending notice ' . $notice->id . ' to public listener ' . $address, -- __FILE__); -- $conn->message($address, $msg, 'chat', NULL, $entry); -- $conn->processTime(0); -- } -- $profile->free(); -- } -+ foreach ($public as $address) { -+ common_log(LOG_INFO, -+ 'Sending notice ' . $notice->id . -+ ' to public listener ' . $address, -+ __FILE__); -+ $conn->message($address, $msg, 'chat', null, $entry); -+ $conn->processTime(0); -+ } -+ $profile->free(); -+ } -hunk ./lib/jabber.php 450 -- return true; -+ return true; -hunk ./lib/jabber.php 453 --function jabber_format_notice(&$profile, &$notice) { -- return $profile->nickname . ': ' . $notice->content; +/** -+ * makes a plain-text formatted version of a notice, suitable for Jabber distribution ++ * Get a list of all languages that are enabled in the default config + * -+ * @param Profile &$profile profile of the sending user -+ * @param Notice &$notice notice being sent ++ * 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 ++ * common_config('site','languages') + * -+ * @return string plain-text version of the notice, with user nickname prefixed ++ * @return array mapping of language codes to language info + */ + -+function jabber_format_notice(&$profile, &$notice) ++function get_all_languages() +{ -+ return $profile->nickname . ': ' . $notice->content; ++ return ++ array('en-us' => array('q' => 1, 'lang' => 'en_US', ++ 'name' => 'English (US)', 'direction' => 'ltr'), ++ 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', ++ 'name' => 'English (NZ)', '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'), ++ 'da' => array('q' => 0.1, 'lang' => 'da_DK', ++ 'name' => 'Danish', 'direction' => 'ltr'), ++ 'nl' => array('q' => 1, 'lang' => 'nl_NL', ++ 'name' => 'Dutch', 'direction' => 'ltr'), ++ 'eo' => array('q' => 0.1, 'lang' => 'eo', ++ 'name' => 'Esperanto', 'direction' => 'ltr'), ++ 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', ++ 'name' => 'French', 'direction' => 'ltr'), ++ 'de' => array('q' => 1, 'lang' => 'de_DE', ++ 'name' => 'German', 'direction' => 'ltr'), ++ 'it' => array('q' => 1, 'lang' => 'it_IT', ++ 'name' => 'Italian', 'direction' => 'ltr'), ++ 'ko' => array('q' => 0.1, 'lang' => 'ko', ++ 'name' => 'Korean', 'direction' => 'ltr'), ++ 'nb' => array('q' => 1, 'lang' => 'nb_NO', ++ 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), ++ 'pt' => array('q' => 0.2, 'lang' => 'pt', ++ 'name' => 'Portuguese', 'direction' => 'ltr'), ++ 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', ++ 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), ++ 'es' => array('q' => 1, 'lang' => 'es', ++ 'name' => 'Spanish', 'direction' => 'ltr'), ++ 'tr' => array('q' => 1, 'lang' => 'tr_TR', ++ 'name' => 'Turkish', 'direction' => 'ltr'), ++ 'uk' => array('q' => 1, 'lang' => 'uk_UA', ++ 'name' => 'Ukrainian', 'direction' => 'ltr'), ++ 'pl' => array('q' => 1, 'lang' => 'pl_PL', ++ 'name' => 'Polish', 'direction' => 'ltr'), ++ 'mk' => array('q' => 1, 'lang' => 'mk_MK', ++ 'name' => 'Macedonian', 'direction' => 'ltr'), ++ 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', ++ 'name' => 'Japanese', 'direction' => 'ltr'), ++ 'cs' => array('q' => 1, 'lang' => 'cs_CZ', ++ 'name' => 'Czech', 'direction' => 'ltr'), ++ 'ca' => array('q' => 1, 'lang' => 'ca_ES', ++ 'name' => 'Catalan', 'direction' => 'ltr'), ++ ); diff --git a/lib/language.php b/lib/language.php index 796e28870..1d00cc31e 100644 --- a/lib/language.php +++ b/lib/language.php @@ -1,9 +1,12 @@ . + * + * @category I18n + * @package Laconica + * @author Matthew Gregg + * @author Ciaran Gultnieks + * @author Evan Prodromou + * @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); } +if (!defined('LACONICA')) { + exit(1); +} +/** + * Content negotiation for language codes + * + * @param string $httplang HTTP Accept-Language header + * + * @return string language code for best language match + */ +function client_prefered_language($httplang) +{ + $client_langs = array(); -function client_prefered_language($httplang) { - $client_langs = array(); - $all_languages = common_config('site','languages'); + $all_languages = common_config('site', 'languages'); - preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"',strtolower($httplang),$httplang); - for ($i = 0; $i < count($httplang); $i++) { - if(!empty($httplang[2][$i])) { - #if no q default to 1.0 - $client_langs[$httplang[2][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); - } - if(!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { - #if a catchall default 0.01 lower - $client_langs[$httplang[3][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); - } - } - #sort in decending q - arsort($client_langs); + preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"', + strtolower($httplang), $httplang); - foreach ($client_langs as $lang => $q) { - if (isset($all_languages[$lang])) { - return($all_languages[$lang]['lang']); - } - } - return FALSE; -} + for ($i = 0; $i < count($httplang); $i++) { + if (!empty($httplang[2][$i])) { + // if no q default to 1.0 + $client_langs[$httplang[2][$i]] = + ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); + } + if (!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { + // if a catchall default 0.01 lower + $client_langs[$httplang[3][$i]] = + ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); + } + } + // sort in decending q + arsort($client_langs); -function get_nice_language_list() { - $nice_lang = array(); - $all_languages = common_config('site','languages'); - foreach ($all_languages as $lang) { - $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); + foreach ($client_langs as $lang => $q) { + if (isset($all_languages[$lang])) { + return($all_languages[$lang]['lang']); } - return $nice_lang; + } + return false; } -// 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 -// common_config('site','languages') -function get_all_languages() { - return array( - 'en-us' => array('q' => 1, 'lang' => 'en_US', 'name' => 'English (US)', 'direction' => 'ltr'), - 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', 'name' => 'English (NZ)', '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'), - 'da' => array('q' => 0.1, 'lang' => 'da_DK', 'name' => 'Danish', 'direction' => 'ltr'), - 'nl' => array('q' => 1, 'lang' => 'nl_NL', 'name' => 'Dutch', 'direction' => 'ltr'), - 'eo' => array('q' => 0.1, 'lang' => 'eo', 'name' => 'Esperanto', 'direction' => 'ltr'), - 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', 'name' => 'French', 'direction' => 'ltr'), - 'de' => array('q' => 1, 'lang' => 'de_DE', 'name' => 'German', 'direction' => 'ltr'), - 'it' => array('q' => 1, 'lang' => 'it_IT', 'name' => 'Italian', 'direction' => 'ltr'), - 'ko' => array('q' => 0.1, 'lang' => 'ko', 'name' => 'Korean', 'direction' => 'ltr'), - 'nb' => array('q' => 1, 'lang' => 'nb_NO', 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), - 'pt' => array('q' => 0.2, 'lang' => 'pt', 'name' => 'Portuguese', 'direction' => 'ltr'), - 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), -# 'ru' => array('q' => 0.1, 'lang' => 'ru_RU', 'name' => 'Russian', 'direction' => 'ltr'), - 'es' => array('q' => 1, 'lang' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'), - 'tr' => array('q' => 1, 'lang' => 'tr_TR', 'name' => 'Turkish', 'direction' => 'ltr'), - 'uk' => array('q' => 1, 'lang' => 'uk_UA', 'name' => 'Ukrainian', 'direction' => 'ltr'), -# 'lt' => array('q' => 0.1, 'lang' => 'lt_LT', 'name' => 'Lithuanian', 'direction' => 'ltr'), -# 'sv' => array('q' => 1, 'lang' => 'sv_SE', 'name' => 'Swedish', 'direction' => 'ltr'), - 'pl' => array('q' => 1, 'lang' => 'pl_PL', 'name' => 'Polish', 'direction' => 'ltr'), - 'mk' => array('q' => 1, 'lang' => 'mk_MK', 'name' => 'Macedonian', 'direction' => 'ltr'), - 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', 'name' => 'Japanese', 'direction' => 'ltr'), - 'cs' => array('q' => 1, 'lang' => 'cs_CZ', 'name' => 'Czech', 'direction' => 'ltr'), - 'ca' => array('q' => 1, 'lang' => 'ca_ES', 'name' => 'Catalan', 'direction' => 'ltr'), -# 'hr' => array('q' => 0.1, 'lang' => 'he_IL', 'name' => 'Hebrew', 'direction' => 'ltr') - ); +/** + * returns a simple code -> name mapping for languages + * + * @return array map of available languages by code to language name. + */ + +function get_nice_language_list() +{ + $nice_lang = array(); + + $all_languages = common_config('site', 'languages'); + + foreach ($all_languages as $lang) { + $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); + } + return $nice_lang; +} + +/** + * 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 + * common_config('site','languages') + * + * @return array mapping of language codes to language info + */ + +function get_all_languages() +{ + return + array('en-us' => array('q' => 1, 'lang' => 'en_US', + 'name' => 'English (US)', 'direction' => 'ltr'), + 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', + 'name' => 'English (NZ)', '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'), + 'da' => array('q' => 0.1, 'lang' => 'da_DK', + 'name' => 'Danish', 'direction' => 'ltr'), + 'nl' => array('q' => 1, 'lang' => 'nl_NL', + 'name' => 'Dutch', 'direction' => 'ltr'), + 'eo' => array('q' => 0.1, 'lang' => 'eo', + 'name' => 'Esperanto', 'direction' => 'ltr'), + 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', + 'name' => 'French', 'direction' => 'ltr'), + 'de' => array('q' => 1, 'lang' => 'de_DE', + 'name' => 'German', 'direction' => 'ltr'), + 'it' => array('q' => 1, 'lang' => 'it_IT', + 'name' => 'Italian', 'direction' => 'ltr'), + 'ko' => array('q' => 0.1, 'lang' => 'ko', + 'name' => 'Korean', 'direction' => 'ltr'), + 'nb' => array('q' => 1, 'lang' => 'nb_NO', + 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), + 'pt' => array('q' => 0.2, 'lang' => 'pt', + 'name' => 'Portuguese', 'direction' => 'ltr'), + 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', + 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), + 'es' => array('q' => 1, 'lang' => 'es', + 'name' => 'Spanish', 'direction' => 'ltr'), + 'tr' => array('q' => 1, 'lang' => 'tr_TR', + 'name' => 'Turkish', 'direction' => 'ltr'), + 'uk' => array('q' => 1, 'lang' => 'uk_UA', + 'name' => 'Ukrainian', 'direction' => 'ltr'), + 'pl' => array('q' => 1, 'lang' => 'pl_PL', + 'name' => 'Polish', 'direction' => 'ltr'), + 'mk' => array('q' => 1, 'lang' => 'mk_MK', + 'name' => 'Macedonian', 'direction' => 'ltr'), + 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', + 'name' => 'Japanese', 'direction' => 'ltr'), + 'cs' => array('q' => 1, 'lang' => 'cs_CZ', + 'name' => 'Czech', 'direction' => 'ltr'), + 'ca' => array('q' => 1, 'lang' => 'ca_ES', + 'name' => 'Catalan', 'direction' => 'ltr'), + ); } -- cgit v1.2.3-54-g00ecf From 073ec99c54ad66e42dea1af62bab646aa9e48564 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 22 Dec 2008 14:50:41 -0500 Subject: bring mailbox.php into line with PEAR Coding Standards (mostly) darcs-hash:20081222195041-84dde-3cc82f6b0f3e4e753c9525aa9a881cfb0c25830c.gz --- _darcs/inventory | 4 +- ...dde-3cc82f6b0f3e4e753c9525aa9a881cfb0c25830c.gz | Bin 0 -> 2729 bytes _darcs/pristine/lib/mailbox.php | 402 +++++++++------ _darcs/tentative_pristine | 540 ++++++++++++++------- lib/mailbox.php | 402 +++++++++------ 5 files changed, 867 insertions(+), 481 deletions(-) create mode 100644 _darcs/patches/20081222195041-84dde-3cc82f6b0f3e4e753c9525aa9a881cfb0c25830c.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index b3f004503..7f21ac58a 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -33,4 +33,6 @@ Evan Prodromou **20081221005837] [reformat lib/jabber.php for phpcs, including doc comments Evan Prodromou **20081222173249] [reformat lib/language.php for PEAR Coding Standards -Evan Prodromou **20081222193029] \ No newline at end of file +Evan Prodromou **20081222193029] +[bring mailbox.php into line with PEAR Coding Standards (mostly) +Evan Prodromou **20081222195041] \ No newline at end of file diff --git a/_darcs/patches/20081222195041-84dde-3cc82f6b0f3e4e753c9525aa9a881cfb0c25830c.gz b/_darcs/patches/20081222195041-84dde-3cc82f6b0f3e4e753c9525aa9a881cfb0c25830c.gz new file mode 100644 index 000000000..502586ee8 Binary files /dev/null and b/_darcs/patches/20081222195041-84dde-3cc82f6b0f3e4e753c9525aa9a881cfb0c25830c.gz differ diff --git a/_darcs/pristine/lib/mailbox.php b/_darcs/pristine/lib/mailbox.php index 4ed8d1758..9039c5fda 100644 --- a/_darcs/pristine/lib/mailbox.php +++ b/_darcs/pristine/lib/mailbox.php @@ -1,9 +1,12 @@ . + * + * @category Action + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} -require_once(INSTALLDIR.'/lib/personal.php'); +require_once INSTALLDIR.'/lib/personal.php'; define('MESSAGES_PER_PAGE', 20); -class MailboxAction extends PersonalAction { - - function handle($args) { - - parent::handle($args); - - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); - - if (!$user) { - $this->client_error(_('No such user.'), 404); - return; - } - - $cur = common_current_user(); - - if (!$cur || $cur->id != $user->id) { - $this->client_error(_('Only the user can read their own mailboxes.'), 403); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - $this->server_error(_('User has no profile.')); - return; - } - - $page = $this->trimmed('page'); - - if (!$page) { - $page = 1; - } - - $this->show_page($user, $page); - } - - function get_title($user, $page) { - return ''; - } - - function get_instructions() { - return ''; - } - - function show_top() { - - $cur = common_current_user(); - - common_message_form(NULL, $cur, NULL); - - $this->views_menu(); - } - - function show_page($user, $page) { - - common_show_header($this->get_title($user, $page), - NULL, NULL, - array($this, 'show_top')); - - $this->show_box($user, $page); - - common_show_footer(); - } - - function show_box($user, $page) { - - $message = $this->get_messages($user, $page); - - if ($message) { - - $cnt = 0; - common_element_start('ul', array('id' => 'messages')); - - while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { - $cnt++; - - if ($cnt > MESSAGES_PER_PAGE) { - break; - } - - $this->show_message($message); - } - - common_element_end('ul'); - - common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, - $page, $this->trimmed('action'), - array('nickname' => $user->nickname)); - - $message->free(); - unset($message); - } - } - - # returns the profile we want to show with the message - - function get_message_profile($message) { - return NULL; - } - - function show_message($message) { - - common_element_start('li', array('class' => 'message_single', - 'id' => 'message-' . $message->id)); - - $profile = $this->get_message_profile($message); - - $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); - common_element_start('a', array('href' => $profile->profileurl)); - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), - 'class' => 'avatar stream', - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'alt' => - ($profile->fullname) ? $profile->fullname : - $profile->nickname)); - common_element_end('a'); - common_element('a', array('href' => $profile->profileurl, - 'class' => 'nickname'), - $profile->nickname); - # FIXME: URL, image, video, audio - common_element_start('p', array('class' => 'content')); - common_raw($message->rendered); - common_element_end('p'); - - $messageurl = common_local_url('showmessage', array('message' => $message->id)); - - # XXX: we need to figure this out better. Is this right? - if (strcmp($message->uri, $messageurl) != 0 && preg_match('/^http/', $message->uri)) { - $messageurl = $message->uri; - } - common_element_start('p', 'time'); - common_element('a', array('class' => 'permalink', - 'href' => $messageurl, - 'title' => common_exact_date($message->created)), - common_date_string($message->created)); - if ($message->source) { - common_text(_(' from ')); - $this->source_link($message->source); - } - - common_element_end('p'); - - common_element_end('li'); - } +/** + * common superclass for direct messages inbox and outbox + * + * @category Action + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see InboxAction + * @see OutboxAction + */ + +class MailboxAction extends PersonalAction +{ + /** + * output page based on arguments + * + * @param array $args HTTP arguments (from $_REQUEST) + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + $nickname = common_canonical_nickname($this->arg('nickname')); + + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + $this->client_error(_('No such user.'), 404); + return; + } + + $cur = common_current_user(); + + if (!$cur || $cur->id != $user->id) { + $this->client_error(_('Only the user can read their own mailboxes.'), + 403); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + $this->server_error(_('User has no profile.')); + return; + } + + $page = $this->trimmed('page'); + + if (!$page) { + $page = 1; + } + + $this->show_page($user, $page); + } + + /** + * returns the title of the page + * + * @param User $user current user + * @param int $page current page + * + * @return string localised title of the page + */ + + function get_title($user, $page) + { + return ''; + } + + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ + + function get_instructions() + { + return ''; + } + + /** + * do structured output for the "instructions" are of the page + * + * @return void + */ + + function show_top() + { + $cur = common_current_user(); + + common_message_form(null, $cur, null); + + $this->views_menu(); + } + + /** + * show a full page of output + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return void + */ + + function show_page($user, $page) + { + common_show_header($this->get_title($user, $page), + null, null, + array($this, 'show_top')); + + $this->show_box($user, $page); + + common_show_footer(); + } + + /** + * show the messages for a mailbox in list format + * + * Includes the pagination links (before, after). + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return void + */ + + function show_box($user, $page) + { + $message = $this->get_messages($user, $page); + + if ($message) { + + $cnt = 0; + common_element_start('ul', array('id' => 'messages')); + + while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { + $cnt++; + + if ($cnt > MESSAGES_PER_PAGE) { + break; + } + + $this->show_message($message); + } + + common_element_end('ul'); + + common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, + $page, $this->trimmed('action'), + array('nickname' => $user->nickname)); + + $message->free(); + unset($message); + } + } + + /** + * returns the profile we want to show with the message + * + * For inboxes, we show the sender; for outboxes, the recipient. + * + * @param Message $message The message to get the profile for + * + * @return Profile The profile that matches the message + */ + + function get_message_profile($message) + { + return null; + } + + /** + * show a single message in the list format + * + * @param Message $message the message to show + * + * @return void + */ + + function show_message($message) + { + common_element_start('li', array('class' => 'message_single', + 'id' => 'message-' . $message->id)); + + $profile = $this->get_message_profile($message); + + $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); + common_element_start('a', array('href' => $profile->profileurl)); + common_element('img', array('src' => ($avatar) ? + common_avatar_display_url($avatar) : + common_default_avatar(AVATAR_STREAM_SIZE), + 'class' => 'avatar stream', + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'alt' => + ($profile->fullname) ? $profile->fullname : + $profile->nickname)); + common_element_end('a'); + common_element('a', array('href' => $profile->profileurl, + 'class' => 'nickname'), + $profile->nickname); + // FIXME: URL, image, video, audio + common_element_start('p', array('class' => 'content')); + common_raw($message->rendered); + common_element_end('p'); + + $messageurl = common_local_url('showmessage', + array('message' => $message->id)); + + // XXX: we need to figure this out better. Is this right? + if (strcmp($message->uri, $messageurl) != 0 && + preg_match('/^http/', $message->uri)) { + $messageurl = $message->uri; + } + common_element_start('p', 'time'); + common_element('a', array('class' => 'permalink', + 'href' => $messageurl, + 'title' => common_exact_date($message->created)), + common_date_string($message->created)); + if ($message->source) { + common_text(_(' from ')); + $this->source_link($message->source); + } + + common_element_end('p'); + + common_element_end('li'); + } } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 9b17c08d1..dd4a35214 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,205 +1,393 @@ -hunk ./lib/language.php 2 +hunk ./lib/mailbox.php 2 -/* - * Laconica - a distributed open-source microblogging tool - * Copyright (C) 2008, Controlez-Vous, Inc. +/** + * Laconica, the distributed open-source microblogging tool -hunk ./lib/language.php 5 +hunk ./lib/mailbox.php 5 - * This program is free software: you can redistribute it and/or modify -+ * utility functions for i18n ++ * common superclass for direct messages inbox and outbox + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./lib/language.php 21 +hunk ./lib/mailbox.php 21 + * -+ * @category I18n -+ * @package Laconica -+ * @author Matthew Gregg -+ * @author Ciaran Gultnieks -+ * @author Evan Prodromou -+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 -+ * @link http://laconi.ca/ -hunk ./lib/language.php 31 ++ * @category Action ++ * @package Laconica ++ * @author Evan Prodromou ++ * @copyright 2008 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/ +hunk ./lib/mailbox.php 30 -if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/language.php 35 +hunk ./lib/mailbox.php 34 +-require_once(INSTALLDIR.'/lib/personal.php'); ++require_once INSTALLDIR.'/lib/personal.php'; +hunk ./lib/mailbox.php 38 +-class MailboxAction extends PersonalAction { +- +- function handle($args) { +/** -+ * Content negotiation for language codes ++ * common superclass for direct messages inbox and outbox + * -+ * @param string $httplang HTTP Accept-Language header -+ * -+ * @return string language code for best language match ++ * @category Action ++ * @package Laconica ++ * @author Evan Prodromou ++ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 ++ * @link http://laconi.ca/ ++ * @see InboxAction ++ * @see OutboxAction + */ -hunk ./lib/language.php 43 -+function client_prefered_language($httplang) ++ ++class MailboxAction extends PersonalAction +{ -+ $client_langs = array(); -hunk ./lib/language.php 47 --function client_prefered_language($httplang) { -- $client_langs = array(); -- $all_languages = common_config('site','languages'); -+ $all_languages = common_config('site', 'languages'); -hunk ./lib/language.php 49 -- preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"',strtolower($httplang),$httplang); -- for ($i = 0; $i < count($httplang); $i++) { -- if(!empty($httplang[2][$i])) { -- #if no q default to 1.0 -- $client_langs[$httplang[2][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); -- } -- if(!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { -- #if a catchall default 0.01 lower -- $client_langs[$httplang[3][$i]] = ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); -- } -- } -- #sort in decending q -- arsort($client_langs); -+ preg_match_all('"(((\S\S)-?(\S\S)?)(;q=([0-9.]+))?)\s*(,\s*|$)"', -+ strtolower($httplang), $httplang); -hunk ./lib/language.php 52 -- foreach ($client_langs as $lang => $q) { -- if (isset($all_languages[$lang])) { -- return($all_languages[$lang]['lang']); -- } -- } -- return FALSE; --} -+ for ($i = 0; $i < count($httplang); $i++) { -+ if (!empty($httplang[2][$i])) { -+ // if no q default to 1.0 -+ $client_langs[$httplang[2][$i]] = -+ ($httplang[6][$i]? (float) $httplang[6][$i] : 1.0); ++ /** ++ * output page based on arguments ++ * ++ * @param array $args HTTP arguments (from $_REQUEST) ++ * ++ * @return void ++ */ ++ ++ function handle($args) ++ { ++ parent::handle($args); ++ ++ $nickname = common_canonical_nickname($this->arg('nickname')); ++ ++ $user = User::staticGet('nickname', $nickname); ++ ++ if (!$user) { ++ $this->client_error(_('No such user.'), 404); ++ return; + } -+ if (!empty($httplang[3][$i]) && empty($client_langs[$httplang[3][$i]])) { -+ // if a catchall default 0.01 lower -+ $client_langs[$httplang[3][$i]] = -+ ($httplang[6][$i]? (float) $httplang[6][$i]-0.01 : 0.99); ++ ++ $cur = common_current_user(); ++ ++ if (!$cur || $cur->id != $user->id) { ++ $this->client_error(_('Only the user can read their own mailboxes.'), ++ 403); ++ return; + } ++ ++ $profile = $user->getProfile(); ++ ++ if (!$profile) { ++ $this->server_error(_('User has no profile.')); ++ return; ++ } ++ ++ $page = $this->trimmed('page'); ++ ++ if (!$page) { ++ $page = 1; ++ } ++ ++ $this->show_page($user, $page); + } -+ // sort in decending q -+ arsort($client_langs); -hunk ./lib/language.php 67 --function get_nice_language_list() { -- $nice_lang = array(); -- $all_languages = common_config('site','languages'); -- foreach ($all_languages as $lang) { -- $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); -+ foreach ($client_langs as $lang => $q) { -+ if (isset($all_languages[$lang])) { -+ return($all_languages[$lang]['lang']); -hunk ./lib/language.php 71 -- return $nice_lang; ++ ++ /** ++ * returns the title of the page ++ * ++ * @param User $user current user ++ * @param int $page current page ++ * ++ * @return string localised title of the page ++ */ ++ ++ function get_title($user, $page) ++ { ++ return ''; + } -+ return false; -hunk ./lib/language.php 75 --// 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 --// common_config('site','languages') --function get_all_languages() { -- return array( -- 'en-us' => array('q' => 1, 'lang' => 'en_US', 'name' => 'English (US)', 'direction' => 'ltr'), -- 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', 'name' => 'English (NZ)', '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'), -- 'da' => array('q' => 0.1, 'lang' => 'da_DK', 'name' => 'Danish', 'direction' => 'ltr'), -- 'nl' => array('q' => 1, 'lang' => 'nl_NL', 'name' => 'Dutch', 'direction' => 'ltr'), -- 'eo' => array('q' => 0.1, 'lang' => 'eo', 'name' => 'Esperanto', 'direction' => 'ltr'), -- 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', 'name' => 'French', 'direction' => 'ltr'), -- 'de' => array('q' => 1, 'lang' => 'de_DE', 'name' => 'German', 'direction' => 'ltr'), -- 'it' => array('q' => 1, 'lang' => 'it_IT', 'name' => 'Italian', 'direction' => 'ltr'), -- 'ko' => array('q' => 0.1, 'lang' => 'ko', 'name' => 'Korean', 'direction' => 'ltr'), -- 'nb' => array('q' => 1, 'lang' => 'nb_NO', 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), -- 'pt' => array('q' => 0.2, 'lang' => 'pt', 'name' => 'Portuguese', 'direction' => 'ltr'), -- 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), --# 'ru' => array('q' => 0.1, 'lang' => 'ru_RU', 'name' => 'Russian', 'direction' => 'ltr'), -- 'es' => array('q' => 1, 'lang' => 'es', 'name' => 'Spanish', 'direction' => 'ltr'), -- 'tr' => array('q' => 1, 'lang' => 'tr_TR', 'name' => 'Turkish', 'direction' => 'ltr'), -- 'uk' => array('q' => 1, 'lang' => 'uk_UA', 'name' => 'Ukrainian', 'direction' => 'ltr'), --# 'lt' => array('q' => 0.1, 'lang' => 'lt_LT', 'name' => 'Lithuanian', 'direction' => 'ltr'), --# 'sv' => array('q' => 1, 'lang' => 'sv_SE', 'name' => 'Swedish', 'direction' => 'ltr'), -- 'pl' => array('q' => 1, 'lang' => 'pl_PL', 'name' => 'Polish', 'direction' => 'ltr'), -- 'mk' => array('q' => 1, 'lang' => 'mk_MK', 'name' => 'Macedonian', 'direction' => 'ltr'), -- 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', 'name' => 'Japanese', 'direction' => 'ltr'), -- 'cs' => array('q' => 1, 'lang' => 'cs_CZ', 'name' => 'Czech', 'direction' => 'ltr'), -- 'ca' => array('q' => 1, 'lang' => 'ca_ES', 'name' => 'Catalan', 'direction' => 'ltr'), --# 'hr' => array('q' => 0.1, 'lang' => 'he_IL', 'name' => 'Hebrew', 'direction' => 'ltr') -- ); -+/** -+ * returns a simple code -> name mapping for languages -+ * -+ * @return array map of available languages by code to language name. -+ */ + -+function get_nice_language_list() -+{ -+ $nice_lang = array(); ++ /** ++ * instructions for using this page ++ * ++ * @return string localised instructions for using the page ++ */ ++ ++ function get_instructions() ++ { ++ return ''; ++ } + -+ $all_languages = common_config('site', 'languages'); ++ /** ++ * do structured output for the "instructions" are of the page ++ * ++ * @return void ++ */ + -+ foreach ($all_languages as $lang) { -+ $nice_lang = $nice_lang + array($lang['lang'] => $lang['name']); ++ function show_top() ++ { ++ $cur = common_current_user(); ++ ++ common_message_form(null, $cur, null); ++ ++ $this->views_menu(); + } -+ return $nice_lang; -+} + -+/** -+ * 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 -+ * common_config('site','languages') -+ * -+ * @return array mapping of language codes to language info -+ */ ++ /** ++ * show a full page of output ++ * ++ * @param User $user The current user ++ * @param int $page The page the user is on ++ * ++ * @return void ++ */ + -+function get_all_languages() -+{ -+ return -+ array('en-us' => array('q' => 1, 'lang' => 'en_US', -+ 'name' => 'English (US)', 'direction' => 'ltr'), -+ 'en-nz' => array('q' => 1, 'lang' => 'en_NZ', -+ 'name' => 'English (NZ)', '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'), -+ 'da' => array('q' => 0.1, 'lang' => 'da_DK', -+ 'name' => 'Danish', 'direction' => 'ltr'), -+ 'nl' => array('q' => 1, 'lang' => 'nl_NL', -+ 'name' => 'Dutch', 'direction' => 'ltr'), -+ 'eo' => array('q' => 0.1, 'lang' => 'eo', -+ 'name' => 'Esperanto', 'direction' => 'ltr'), -+ 'fr-fr' => array('q' => 0.9, 'lang' => 'fr_FR', -+ 'name' => 'French', 'direction' => 'ltr'), -+ 'de' => array('q' => 1, 'lang' => 'de_DE', -+ 'name' => 'German', 'direction' => 'ltr'), -+ 'it' => array('q' => 1, 'lang' => 'it_IT', -+ 'name' => 'Italian', 'direction' => 'ltr'), -+ 'ko' => array('q' => 0.1, 'lang' => 'ko', -+ 'name' => 'Korean', 'direction' => 'ltr'), -+ 'nb' => array('q' => 1, 'lang' => 'nb_NO', -+ 'name' => 'Norwegian (bokmal)', 'direction' => 'ltr'), -+ 'pt' => array('q' => 0.2, 'lang' => 'pt', -+ 'name' => 'Portuguese', 'direction' => 'ltr'), -+ 'pt-br' => array('q' => 1, 'lang' => 'pt_BR', -+ 'name' => 'Portuguese Brazil', 'direction' => 'ltr'), -+ 'es' => array('q' => 1, 'lang' => 'es', -+ 'name' => 'Spanish', 'direction' => 'ltr'), -+ 'tr' => array('q' => 1, 'lang' => 'tr_TR', -+ 'name' => 'Turkish', 'direction' => 'ltr'), -+ 'uk' => array('q' => 1, 'lang' => 'uk_UA', -+ 'name' => 'Ukrainian', 'direction' => 'ltr'), -+ 'pl' => array('q' => 1, 'lang' => 'pl_PL', -+ 'name' => 'Polish', 'direction' => 'ltr'), -+ 'mk' => array('q' => 1, 'lang' => 'mk_MK', -+ 'name' => 'Macedonian', 'direction' => 'ltr'), -+ 'jp' => array('q' => 0.1, 'lang' => 'ja_JP', -+ 'name' => 'Japanese', 'direction' => 'ltr'), -+ 'cs' => array('q' => 1, 'lang' => 'cs_CZ', -+ 'name' => 'Czech', 'direction' => 'ltr'), -+ 'ca' => array('q' => 1, 'lang' => 'ca_ES', -+ 'name' => 'Catalan', 'direction' => 'ltr'), -+ ); ++ function show_page($user, $page) ++ { ++ common_show_header($this->get_title($user, $page), ++ null, null, ++ array($this, 'show_top')); ++ ++ $this->show_box($user, $page); ++ ++ common_show_footer(); ++ } ++ ++ /** ++ * show the messages for a mailbox in list format ++ * ++ * Includes the pagination links (before, after). ++ * ++ * @param User $user The current user ++ * @param int $page The page the user is on ++ * ++ * @return void ++ */ ++ ++ function show_box($user, $page) ++ { ++ $message = $this->get_messages($user, $page); ++ ++ if ($message) { ++ ++ $cnt = 0; ++ common_element_start('ul', array('id' => 'messages')); ++ ++ while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { ++ $cnt++; +hunk ./lib/mailbox.php 180 +- parent::handle($args); ++ if ($cnt > MESSAGES_PER_PAGE) { ++ break; ++ } +hunk ./lib/mailbox.php 184 +- $nickname = common_canonical_nickname($this->arg('nickname')); +- $user = User::staticGet('nickname', $nickname); ++ $this->show_message($message); ++ } +hunk ./lib/mailbox.php 187 +- if (!$user) { +- $this->client_error(_('No such user.'), 404); +- return; +- } ++ common_element_end('ul'); +hunk ./lib/mailbox.php 189 +- $cur = common_current_user(); +- +- if (!$cur || $cur->id != $user->id) { +- $this->client_error(_('Only the user can read their own mailboxes.'), 403); +- return; +- } +- +- $profile = $user->getProfile(); ++ common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, ++ $page, $this->trimmed('action'), ++ array('nickname' => $user->nickname)); +hunk ./lib/mailbox.php 193 +- if (!$profile) { +- $this->server_error(_('User has no profile.')); +- return; +- } ++ $message->free(); ++ unset($message); ++ } ++ } +hunk ./lib/mailbox.php 198 +- $page = $this->trimmed('page'); +- +- if (!$page) { +- $page = 1; +- } +- +- $this->show_page($user, $page); +- } ++ /** ++ * returns the profile we want to show with the message ++ * ++ * For inboxes, we show the sender; for outboxes, the recipient. ++ * ++ * @param Message $message The message to get the profile for ++ * ++ * @return Profile The profile that matches the message ++ */ +hunk ./lib/mailbox.php 208 +- function get_title($user, $page) { +- return ''; +- } ++ function get_message_profile($message) ++ { ++ return null; ++ } +hunk ./lib/mailbox.php 213 +- function get_instructions() { +- return ''; +- } ++ /** ++ * show a single message in the list format ++ * ++ * @param Message $message the message to show ++ * ++ * @return void ++ */ +hunk ./lib/mailbox.php 221 +- function show_top() { ++ function show_message($message) ++ { ++ common_element_start('li', array('class' => 'message_single', ++ 'id' => 'message-' . $message->id)); +hunk ./lib/mailbox.php 226 +- $cur = common_current_user(); +- +- common_message_form(NULL, $cur, NULL); +- +- $this->views_menu(); +- } +- +- function show_page($user, $page) { ++ $profile = $this->get_message_profile($message); +hunk ./lib/mailbox.php 228 +- common_show_header($this->get_title($user, $page), +- NULL, NULL, +- array($this, 'show_top')); +- +- $this->show_box($user, $page); +- +- common_show_footer(); +- } +- +- function show_box($user, $page) { +- +- $message = $this->get_messages($user, $page); +- +- if ($message) { +- +- $cnt = 0; +- common_element_start('ul', array('id' => 'messages')); +- +- while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { +- $cnt++; +- +- if ($cnt > MESSAGES_PER_PAGE) { +- break; +- } +- +- $this->show_message($message); +- } ++ $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); ++ common_element_start('a', array('href' => $profile->profileurl)); ++ common_element('img', array('src' => ($avatar) ? ++ common_avatar_display_url($avatar) : ++ common_default_avatar(AVATAR_STREAM_SIZE), ++ 'class' => 'avatar stream', ++ 'width' => AVATAR_STREAM_SIZE, ++ 'height' => AVATAR_STREAM_SIZE, ++ 'alt' => ++ ($profile->fullname) ? $profile->fullname : ++ $profile->nickname)); ++ common_element_end('a'); ++ common_element('a', array('href' => $profile->profileurl, ++ 'class' => 'nickname'), ++ $profile->nickname); ++ // FIXME: URL, image, video, audio ++ common_element_start('p', array('class' => 'content')); ++ common_raw($message->rendered); ++ common_element_end('p'); +hunk ./lib/mailbox.php 248 +- common_element_end('ul'); +- +- common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, +- $page, $this->trimmed('action'), +- array('nickname' => $user->nickname)); +- +- $message->free(); +- unset($message); +- } +- } ++ $messageurl = common_local_url('showmessage', ++ array('message' => $message->id)); +hunk ./lib/mailbox.php 251 +- # returns the profile we want to show with the message +- +- function get_message_profile($message) { +- return NULL; +- } +- +- function show_message($message) { ++ // XXX: we need to figure this out better. Is this right? ++ if (strcmp($message->uri, $messageurl) != 0 && ++ preg_match('/^http/', $message->uri)) { ++ $messageurl = $message->uri; ++ } ++ common_element_start('p', 'time'); ++ common_element('a', array('class' => 'permalink', ++ 'href' => $messageurl, ++ 'title' => common_exact_date($message->created)), ++ common_date_string($message->created)); ++ if ($message->source) { ++ common_text(_(' from ')); ++ $this->source_link($message->source); ++ } +hunk ./lib/mailbox.php 266 +- common_element_start('li', array('class' => 'message_single', +- 'id' => 'message-' . $message->id)); ++ common_element_end('p'); +hunk ./lib/mailbox.php 268 +- $profile = $this->get_message_profile($message); +- +- $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); +- common_element_start('a', array('href' => $profile->profileurl)); +- common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), +- 'class' => 'avatar stream', +- 'width' => AVATAR_STREAM_SIZE, +- 'height' => AVATAR_STREAM_SIZE, +- 'alt' => +- ($profile->fullname) ? $profile->fullname : +- $profile->nickname)); +- common_element_end('a'); +- common_element('a', array('href' => $profile->profileurl, +- 'class' => 'nickname'), +- $profile->nickname); +- # FIXME: URL, image, video, audio +- common_element_start('p', array('class' => 'content')); +- common_raw($message->rendered); +- common_element_end('p'); +- +- $messageurl = common_local_url('showmessage', array('message' => $message->id)); +- +- # XXX: we need to figure this out better. Is this right? +- if (strcmp($message->uri, $messageurl) != 0 && preg_match('/^http/', $message->uri)) { +- $messageurl = $message->uri; +- } +- common_element_start('p', 'time'); +- common_element('a', array('class' => 'permalink', +- 'href' => $messageurl, +- 'title' => common_exact_date($message->created)), +- common_date_string($message->created)); +- if ($message->source) { +- common_text(_(' from ')); +- $this->source_link($message->source); +- } +- +- common_element_end('p'); +- +- common_element_end('li'); +- } ++ common_element_end('li'); ++ } diff --git a/lib/mailbox.php b/lib/mailbox.php index 4ed8d1758..9039c5fda 100644 --- a/lib/mailbox.php +++ b/lib/mailbox.php @@ -1,9 +1,12 @@ . + * + * @category Action + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} -require_once(INSTALLDIR.'/lib/personal.php'); +require_once INSTALLDIR.'/lib/personal.php'; define('MESSAGES_PER_PAGE', 20); -class MailboxAction extends PersonalAction { - - function handle($args) { - - parent::handle($args); - - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); - - if (!$user) { - $this->client_error(_('No such user.'), 404); - return; - } - - $cur = common_current_user(); - - if (!$cur || $cur->id != $user->id) { - $this->client_error(_('Only the user can read their own mailboxes.'), 403); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - $this->server_error(_('User has no profile.')); - return; - } - - $page = $this->trimmed('page'); - - if (!$page) { - $page = 1; - } - - $this->show_page($user, $page); - } - - function get_title($user, $page) { - return ''; - } - - function get_instructions() { - return ''; - } - - function show_top() { - - $cur = common_current_user(); - - common_message_form(NULL, $cur, NULL); - - $this->views_menu(); - } - - function show_page($user, $page) { - - common_show_header($this->get_title($user, $page), - NULL, NULL, - array($this, 'show_top')); - - $this->show_box($user, $page); - - common_show_footer(); - } - - function show_box($user, $page) { - - $message = $this->get_messages($user, $page); - - if ($message) { - - $cnt = 0; - common_element_start('ul', array('id' => 'messages')); - - while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { - $cnt++; - - if ($cnt > MESSAGES_PER_PAGE) { - break; - } - - $this->show_message($message); - } - - common_element_end('ul'); - - common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, - $page, $this->trimmed('action'), - array('nickname' => $user->nickname)); - - $message->free(); - unset($message); - } - } - - # returns the profile we want to show with the message - - function get_message_profile($message) { - return NULL; - } - - function show_message($message) { - - common_element_start('li', array('class' => 'message_single', - 'id' => 'message-' . $message->id)); - - $profile = $this->get_message_profile($message); - - $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); - common_element_start('a', array('href' => $profile->profileurl)); - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), - 'class' => 'avatar stream', - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'alt' => - ($profile->fullname) ? $profile->fullname : - $profile->nickname)); - common_element_end('a'); - common_element('a', array('href' => $profile->profileurl, - 'class' => 'nickname'), - $profile->nickname); - # FIXME: URL, image, video, audio - common_element_start('p', array('class' => 'content')); - common_raw($message->rendered); - common_element_end('p'); - - $messageurl = common_local_url('showmessage', array('message' => $message->id)); - - # XXX: we need to figure this out better. Is this right? - if (strcmp($message->uri, $messageurl) != 0 && preg_match('/^http/', $message->uri)) { - $messageurl = $message->uri; - } - common_element_start('p', 'time'); - common_element('a', array('class' => 'permalink', - 'href' => $messageurl, - 'title' => common_exact_date($message->created)), - common_date_string($message->created)); - if ($message->source) { - common_text(_(' from ')); - $this->source_link($message->source); - } - - common_element_end('p'); - - common_element_end('li'); - } +/** + * common superclass for direct messages inbox and outbox + * + * @category Action + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see InboxAction + * @see OutboxAction + */ + +class MailboxAction extends PersonalAction +{ + /** + * output page based on arguments + * + * @param array $args HTTP arguments (from $_REQUEST) + * + * @return void + */ + + function handle($args) + { + parent::handle($args); + + $nickname = common_canonical_nickname($this->arg('nickname')); + + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + $this->client_error(_('No such user.'), 404); + return; + } + + $cur = common_current_user(); + + if (!$cur || $cur->id != $user->id) { + $this->client_error(_('Only the user can read their own mailboxes.'), + 403); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + $this->server_error(_('User has no profile.')); + return; + } + + $page = $this->trimmed('page'); + + if (!$page) { + $page = 1; + } + + $this->show_page($user, $page); + } + + /** + * returns the title of the page + * + * @param User $user current user + * @param int $page current page + * + * @return string localised title of the page + */ + + function get_title($user, $page) + { + return ''; + } + + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ + + function get_instructions() + { + return ''; + } + + /** + * do structured output for the "instructions" are of the page + * + * @return void + */ + + function show_top() + { + $cur = common_current_user(); + + common_message_form(null, $cur, null); + + $this->views_menu(); + } + + /** + * show a full page of output + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return void + */ + + function show_page($user, $page) + { + common_show_header($this->get_title($user, $page), + null, null, + array($this, 'show_top')); + + $this->show_box($user, $page); + + common_show_footer(); + } + + /** + * show the messages for a mailbox in list format + * + * Includes the pagination links (before, after). + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return void + */ + + function show_box($user, $page) + { + $message = $this->get_messages($user, $page); + + if ($message) { + + $cnt = 0; + common_element_start('ul', array('id' => 'messages')); + + while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { + $cnt++; + + if ($cnt > MESSAGES_PER_PAGE) { + break; + } + + $this->show_message($message); + } + + common_element_end('ul'); + + common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, + $page, $this->trimmed('action'), + array('nickname' => $user->nickname)); + + $message->free(); + unset($message); + } + } + + /** + * returns the profile we want to show with the message + * + * For inboxes, we show the sender; for outboxes, the recipient. + * + * @param Message $message The message to get the profile for + * + * @return Profile The profile that matches the message + */ + + function get_message_profile($message) + { + return null; + } + + /** + * show a single message in the list format + * + * @param Message $message the message to show + * + * @return void + */ + + function show_message($message) + { + common_element_start('li', array('class' => 'message_single', + 'id' => 'message-' . $message->id)); + + $profile = $this->get_message_profile($message); + + $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); + common_element_start('a', array('href' => $profile->profileurl)); + common_element('img', array('src' => ($avatar) ? + common_avatar_display_url($avatar) : + common_default_avatar(AVATAR_STREAM_SIZE), + 'class' => 'avatar stream', + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'alt' => + ($profile->fullname) ? $profile->fullname : + $profile->nickname)); + common_element_end('a'); + common_element('a', array('href' => $profile->profileurl, + 'class' => 'nickname'), + $profile->nickname); + // FIXME: URL, image, video, audio + common_element_start('p', array('class' => 'content')); + common_raw($message->rendered); + common_element_end('p'); + + $messageurl = common_local_url('showmessage', + array('message' => $message->id)); + + // XXX: we need to figure this out better. Is this right? + if (strcmp($message->uri, $messageurl) != 0 && + preg_match('/^http/', $message->uri)) { + $messageurl = $message->uri; + } + common_element_start('p', 'time'); + common_element('a', array('class' => 'permalink', + 'href' => $messageurl, + 'title' => common_exact_date($message->created)), + common_date_string($message->created)); + if ($message->source) { + common_text(_(' from ')); + $this->source_link($message->source); + } + + common_element_end('p'); + + common_element_end('li'); + } } -- cgit v1.2.3-54-g00ecf From 2d0aec255f3cc49e246d972a3482f444c5a44980 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Mon, 22 Dec 2008 15:13:04 -0500 Subject: bring messaging section (inbox, outbox, mailbox) into PEAR Code Standards compliance Actually refactored the method names on these classes to come into complete compliance with the code standards. Untested; maybe there are some bad method names now. darcs-hash:20081222201304-84dde-3effcce0f9ef25fbe0bfebd505037d9ff37252fa.gz --- _darcs/inventory | 10 +- ...dde-3effcce0f9ef25fbe0bfebd505037d9ff37252fa.gz | Bin 0 -> 1931 bytes _darcs/pristine/actions/inbox.php | 149 ++++-- _darcs/pristine/actions/outbox.php | 149 ++++-- _darcs/pristine/lib/mailbox.php | 48 +- _darcs/tentative_pristine | 560 ++++++++++----------- actions/inbox.php | 149 ++++-- actions/outbox.php | 149 ++++-- lib/mailbox.php | 48 +- 9 files changed, 777 insertions(+), 485 deletions(-) create mode 100644 _darcs/patches/20081222201304-84dde-3effcce0f9ef25fbe0bfebd505037d9ff37252fa.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 7f21ac58a..083e53fd0 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -35,4 +35,12 @@ Evan Prodromou **20081222173249] [reformat lib/language.php for PEAR Coding Standards Evan Prodromou **20081222193029] [bring mailbox.php into line with PEAR Coding Standards (mostly) -Evan Prodromou **20081222195041] \ No newline at end of file +Evan Prodromou **20081222195041] +[bring messaging section (inbox, outbox, mailbox) into PEAR Code Standards compliance +Evan Prodromou **20081222201304 + + Actually refactored the method names on these classes to come into + complete compliance with the code standards. Untested; maybe there are + some bad method names now. + +] \ No newline at end of file diff --git a/_darcs/patches/20081222201304-84dde-3effcce0f9ef25fbe0bfebd505037d9ff37252fa.gz b/_darcs/patches/20081222201304-84dde-3effcce0f9ef25fbe0bfebd505037d9ff37252fa.gz new file mode 100644 index 000000000..60517eb79 Binary files /dev/null and b/_darcs/patches/20081222201304-84dde-3effcce0f9ef25fbe0bfebd505037d9ff37252fa.gz differ diff --git a/_darcs/pristine/actions/inbox.php b/_darcs/pristine/actions/inbox.php index c752e404e..da27814a6 100644 --- a/_darcs/pristine/actions/inbox.php +++ b/_darcs/pristine/actions/inbox.php @@ -1,9 +1,12 @@ . + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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/mailbox.php'; + +/** + * action handler for message inbox + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see MailboxAction */ -if (!defined('LACONICA')) { exit(1); } - -require_once(INSTALLDIR.'/lib/mailbox.php'); - -class InboxAction extends MailboxAction { - - function get_title($user, $page) { - if ($page > 1) { - $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); - } else { - $title = sprintf(_("Inbox for %s"), $user->nickname); - } - return $title; - } - - function get_messages($user, $page) { - $message = new Message(); - $message->to_profile = $user->id; - $message->orderBy('created DESC, id DESC'); - $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); - - if ($message->find()) { - return $message; - } else { - return NULL; - } - } - - function get_message_profile($message) { - return $message->getFrom(); - } - - function get_instructions() { - return _('This is your inbox, which lists your incoming private messages.'); - } +class InboxAction extends MailboxAction +{ + /** + * returns the title of the page + * + * @param User $user current user + * @param int $page current page + * + * @return string localised title of the page + * + * @see MailboxAction::getTitle() + */ + + function getTitle($user, $page) + { + if ($page > 1) { + $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); + } else { + $title = sprintf(_("Inbox for %s"), $user->nickname); + } + return $title; + } + + /** + * retrieve the messages for this user and this page + * + * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return Message data object with stream for messages + * + * @see MailboxAction::getMessages() + */ + + function getMessages($user, $page) + { + $message = new Message(); + + $message->to_profile = $user->id; + + $message->orderBy('created DESC, id DESC'); + $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + + if ($message->find()) { + return $message; + } else { + return null; + } + } + + /** + * returns the profile we want to show with the message + * + * For inboxes, we show the sender. + * + * @param Message $message The message to get the profile for + * + * @return Profile The profile of the message sender + * + * @see MailboxAction::getMessageProfile() + */ + + function getMessageProfile($message) + { + return $message->getFrom(); + } + + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ + + function getInstructions() + { + return _('This is your inbox, which lists your incoming private messages.'); + } } diff --git a/_darcs/pristine/actions/outbox.php b/_darcs/pristine/actions/outbox.php index c48d9c206..9fb6dbf9f 100644 --- a/_darcs/pristine/actions/outbox.php +++ b/_darcs/pristine/actions/outbox.php @@ -1,9 +1,12 @@ . + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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/mailbox.php'; + +/** + * action handler for message outbox + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see MailboxAction */ -if (!defined('LACONICA')) { exit(1); } - -require_once(INSTALLDIR.'/lib/mailbox.php'); - -class OutboxAction extends MailboxAction { - - function get_title($user, $page) { - if ($page > 1) { - $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); - } else { - $title = sprintf(_("Outbox for %s"), $user->nickname); - } - return $title; - } - - function get_messages($user, $page) { - $message = new Message(); - $message->from_profile = $user->id; - $message->orderBy('created DESC, id DESC'); - $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); - - if ($message->find()) { - return $message; - } else { - return NULL; - } - } - - function get_message_profile($message) { - return $message->getTo(); - } - - function get_instructions() { - return _('This is your outbox, which lists private messages you have sent.'); - } - +class OutboxAction extends MailboxAction +{ + /** + * returns the title of the page + * + * @param User $user current user + * @param int $page current page + * + * @return string localised title of the page + * + * @see MailboxAction::getTitle() + */ + + function getTitle($user, $page) + { + if ($page > 1) { + $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); + } else { + $title = sprintf(_("Outbox for %s"), $user->nickname); + } + return $title; + } + + /** + * retrieve the messages for this user and this page + * + * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return Message data object with stream for messages + * + * @see MailboxAction::getMessages() + */ + + function getMessages($user, $page) + { + $message = new Message(); + + $message->from_profile = $user->id; + $message->orderBy('created DESC, id DESC'); + $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + + if ($message->find()) { + return $message; + } else { + return null; + } + } + + /** + * returns the profile we want to show with the message + * + * For outboxes, we show the recipient. + * + * @param Message $message The message to get the profile for + * + * @return Profile The profile of the message recipient + * + * @see MailboxAction::getMessageProfile() + */ + + function getMessageProfile($message) + { + return $message->getTo(); + } + + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ + + function getInstructions() + { + return _('This is your outbox, which lists private messages you have sent.'); + } } diff --git a/_darcs/pristine/lib/mailbox.php b/_darcs/pristine/lib/mailbox.php index 9039c5fda..bdc360a35 100644 --- a/_darcs/pristine/lib/mailbox.php +++ b/_darcs/pristine/lib/mailbox.php @@ -19,7 +19,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * - * @category Action + * @category Message * @package Laconica * @author Evan Prodromou * @copyright 2008 Control Yourself, Inc. @@ -38,7 +38,7 @@ define('MESSAGES_PER_PAGE', 20); /** * common superclass for direct messages inbox and outbox * - * @category Action + * @category Message * @package Laconica * @author Evan Prodromou * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 @@ -91,7 +91,7 @@ class MailboxAction extends PersonalAction $page = 1; } - $this->show_page($user, $page); + $this->showPage($user, $page); } /** @@ -103,7 +103,7 @@ class MailboxAction extends PersonalAction * @return string localised title of the page */ - function get_title($user, $page) + function getTitle($user, $page) { return ''; } @@ -114,7 +114,7 @@ class MailboxAction extends PersonalAction * @return string localised instructions for using the page */ - function get_instructions() + function getInstructions() { return ''; } @@ -125,7 +125,7 @@ class MailboxAction extends PersonalAction * @return void */ - function show_top() + function showTop() { $cur = common_current_user(); @@ -143,17 +143,33 @@ class MailboxAction extends PersonalAction * @return void */ - function show_page($user, $page) + function showPage($user, $page) { - common_show_header($this->get_title($user, $page), + common_show_header($this->getTitle($user, $page), null, null, - array($this, 'show_top')); + array($this, 'showTop')); - $this->show_box($user, $page); + $this->showBox($user, $page); common_show_footer(); } + /** + * retrieve the messages appropriate for this mailbox + * + * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return Message data object with stream for messages + */ + + function getMessages($user, $page) + { + return null; + } + /** * show the messages for a mailbox in list format * @@ -165,9 +181,9 @@ class MailboxAction extends PersonalAction * @return void */ - function show_box($user, $page) + function showBox($user, $page) { - $message = $this->get_messages($user, $page); + $message = $this->getMessages($user, $page); if ($message) { @@ -181,7 +197,7 @@ class MailboxAction extends PersonalAction break; } - $this->show_message($message); + $this->showMessage($message); } common_element_end('ul'); @@ -205,7 +221,7 @@ class MailboxAction extends PersonalAction * @return Profile The profile that matches the message */ - function get_message_profile($message) + function getMessageProfile($message) { return null; } @@ -218,12 +234,12 @@ class MailboxAction extends PersonalAction * @return void */ - function show_message($message) + function showMessage($message) { common_element_start('li', array('class' => 'message_single', 'id' => 'message-' . $message->id)); - $profile = $this->get_message_profile($message); + $profile = $this->getMessageProfile($message); $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); common_element_start('a', array('href' => $profile->profileurl)); diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index dd4a35214..5a45154e6 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,393 +1,365 @@ -hunk ./lib/mailbox.php 2 +hunk ./actions/inbox.php 2 -/* - * Laconica - a distributed open-source microblogging tool - * Copyright (C) 2008, Controlez-Vous, Inc. +/** + * Laconica, the distributed open-source microblogging tool -hunk ./lib/mailbox.php 5 +hunk ./actions/inbox.php 5 - * This program is free software: you can redistribute it and/or modify -+ * common superclass for direct messages inbox and outbox ++ * action handler for message inbox + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./lib/mailbox.php 21 +hunk ./actions/inbox.php 21 + * -+ * @category Action ++ * @category Message + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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/ -hunk ./lib/mailbox.php 30 --if (!defined('LACONICA')) { exit(1); } ++ */ ++ +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/mailbox.php 34 --require_once(INSTALLDIR.'/lib/personal.php'); -+require_once INSTALLDIR.'/lib/personal.php'; -hunk ./lib/mailbox.php 38 --class MailboxAction extends PersonalAction { -- -- function handle($args) { ++ ++require_once INSTALLDIR.'/lib/mailbox.php'; ++ +/** -+ * common superclass for direct messages inbox and outbox ++ * action handler for message inbox + * -+ * @category Action ++ * @category Message + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ -+ * @see InboxAction -+ * @see OutboxAction -+ */ -+ -+class MailboxAction extends PersonalAction ++ * @see MailboxAction +hunk ./actions/inbox.php 47 +-if (!defined('LACONICA')) { exit(1); } ++class InboxAction extends MailboxAction +{ + /** -+ * output page based on arguments ++ * returns the title of the page + * -+ * @param array $args HTTP arguments (from $_REQUEST) ++ * @param User $user current user ++ * @param int $page current page + * -+ * @return void ++ * @return string localised title of the page ++ * ++ * @see MailboxAction::getTitle() + */ + -+ function handle($args) ++ function getTitle($user, $page) + { -+ parent::handle($args); -+ -+ $nickname = common_canonical_nickname($this->arg('nickname')); -+ -+ $user = User::staticGet('nickname', $nickname); -+ -+ if (!$user) { -+ $this->client_error(_('No such user.'), 404); -+ return; ++ if ($page > 1) { ++ $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); ++ } else { ++ $title = sprintf(_("Inbox for %s"), $user->nickname); + } ++ return $title; ++ } + -+ $cur = common_current_user(); -+ -+ if (!$cur || $cur->id != $user->id) { -+ $this->client_error(_('Only the user can read their own mailboxes.'), -+ 403); -+ return; -+ } ++ /** ++ * retrieve the messages for this user and this page ++ * ++ * Does a query for the right messages ++ * ++ * @param User $user The current user ++ * @param int $page The page the user is on ++ * ++ * @return Message data object with stream for messages ++ * ++ * @see MailboxAction::getMessages() ++ */ + -+ $profile = $user->getProfile(); ++ function getMessages($user, $page) ++ { ++ $message = new Message(); + -+ if (!$profile) { -+ $this->server_error(_('User has no profile.')); -+ return; -+ } ++ $message->to_profile = $user->id; + -+ $page = $this->trimmed('page'); ++ $message->orderBy('created DESC, id DESC'); ++ $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + -+ if (!$page) { -+ $page = 1; ++ if ($message->find()) { ++ return $message; ++ } else { ++ return null; + } -+ -+ $this->show_page($user, $page); + } + + /** -+ * returns the title of the page ++ * returns the profile we want to show with the message + * -+ * @param User $user current user -+ * @param int $page current page ++ * For inboxes, we show the sender. + * -+ * @return string localised title of the page ++ * @param Message $message The message to get the profile for ++ * ++ * @return Profile The profile of the message sender ++ * ++ * @see MailboxAction::getMessageProfile() + */ -+ -+ function get_title($user, $page) +hunk ./actions/inbox.php 111 +-require_once(INSTALLDIR.'/lib/mailbox.php'); ++ function getMessageProfile($message) + { -+ return ''; ++ return $message->getFrom(); + } -+ +hunk ./actions/inbox.php 116 +-class InboxAction extends MailboxAction { +- +- function get_title($user, $page) { +- if ($page > 1) { +- $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); +- } else { +- $title = sprintf(_("Inbox for %s"), $user->nickname); +- } +- return $title; +- } +- +- function get_messages($user, $page) { +- $message = new Message(); +- $message->to_profile = $user->id; +- $message->orderBy('created DESC, id DESC'); +- $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ -+ -+ function get_instructions() +hunk ./actions/inbox.php 122 +- if ($message->find()) { +- return $message; +- } else { +- return NULL; +- } +- } +- +- function get_message_profile($message) { +- return $message->getFrom(); +- } +- +- function get_instructions() { +- return _('This is your inbox, which lists your incoming private messages.'); +- } ++ function getInstructions() + { -+ return ''; ++ return _('This is your inbox, which lists your incoming private messages.'); + } +hunk ./actions/outbox.php 2 +-/* +- * Laconica - a distributed open-source microblogging tool +- * Copyright (C) 2008, Controlez-Vous, Inc. ++/** ++ * Laconica, the distributed open-source microblogging tool +hunk ./actions/outbox.php 5 +- * This program is free software: you can redistribute it and/or modify ++ * action handler for message inbox ++ * ++ * PHP version 5 ++ * ++ * LICENCE: This program is free software: you can redistribute it and/or modify +hunk ./actions/outbox.php 21 ++ * ++ * @category Message ++ * @package Laconica ++ * @author Evan Prodromou ++ * @copyright 2008 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/ ++ */ + -+ /** -+ * do structured output for the "instructions" are of the page -+ * -+ * @return void -+ */ -+ -+ function show_top() -+ { -+ $cur = common_current_user(); -+ -+ common_message_form(null, $cur, null); ++if (!defined('LACONICA')) { ++ exit(1); ++} + -+ $this->views_menu(); -+ } ++require_once INSTALLDIR.'/lib/mailbox.php'; + ++/** ++ * action handler for message outbox ++ * ++ * @category Message ++ * @package Laconica ++ * @author Evan Prodromou ++ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 ++ * @link http://laconi.ca/ ++ * @see MailboxAction +hunk ./actions/outbox.php 47 +-if (!defined('LACONICA')) { exit(1); } ++class OutboxAction extends MailboxAction ++{ + /** -+ * show a full page of output ++ * returns the title of the page + * -+ * @param User $user The current user -+ * @param int $page The page the user is on ++ * @param User $user current user ++ * @param int $page current page ++ * ++ * @return string localised title of the page + * -+ * @return void ++ * @see MailboxAction::getTitle() + */ + -+ function show_page($user, $page) ++ function getTitle($user, $page) + { -+ common_show_header($this->get_title($user, $page), -+ null, null, -+ array($this, 'show_top')); -+ -+ $this->show_box($user, $page); -+ -+ common_show_footer(); ++ if ($page > 1) { ++ $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); ++ } else { ++ $title = sprintf(_("Outbox for %s"), $user->nickname); ++ } ++ return $title; + } + + /** -+ * show the messages for a mailbox in list format ++ * retrieve the messages for this user and this page + * -+ * Includes the pagination links (before, after). ++ * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * -+ * @return void ++ * @return Message data object with stream for messages ++ * ++ * @see MailboxAction::getMessages() + */ + -+ function show_box($user, $page) ++ function getMessages($user, $page) + { -+ $message = $this->get_messages($user, $page); ++ $message = new Message(); + -+ if ($message) { ++ $message->from_profile = $user->id; ++ $message->orderBy('created DESC, id DESC'); ++ $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + -+ $cnt = 0; -+ common_element_start('ul', array('id' => 'messages')); -+ -+ while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { -+ $cnt++; -hunk ./lib/mailbox.php 180 -- parent::handle($args); -+ if ($cnt > MESSAGES_PER_PAGE) { -+ break; -+ } -hunk ./lib/mailbox.php 184 -- $nickname = common_canonical_nickname($this->arg('nickname')); -- $user = User::staticGet('nickname', $nickname); -+ $this->show_message($message); -+ } -hunk ./lib/mailbox.php 187 -- if (!$user) { -- $this->client_error(_('No such user.'), 404); -- return; -- } -+ common_element_end('ul'); -hunk ./lib/mailbox.php 189 -- $cur = common_current_user(); -- -- if (!$cur || $cur->id != $user->id) { -- $this->client_error(_('Only the user can read their own mailboxes.'), 403); -- return; -- } -- -- $profile = $user->getProfile(); -+ common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, -+ $page, $this->trimmed('action'), -+ array('nickname' => $user->nickname)); -hunk ./lib/mailbox.php 193 -- if (!$profile) { -- $this->server_error(_('User has no profile.')); -- return; -- } -+ $message->free(); -+ unset($message); ++ if ($message->find()) { ++ return $message; ++ } else { ++ return null; + } + } -hunk ./lib/mailbox.php 198 -- $page = $this->trimmed('page'); -- -- if (!$page) { -- $page = 1; -- } -- -- $this->show_page($user, $page); -- } ++ + /** + * returns the profile we want to show with the message + * -+ * For inboxes, we show the sender; for outboxes, the recipient. ++ * For outboxes, we show the recipient. + * + * @param Message $message The message to get the profile for + * -+ * @return Profile The profile that matches the message ++ * @return Profile The profile of the message recipient ++ * ++ * @see MailboxAction::getMessageProfile() + */ -hunk ./lib/mailbox.php 208 -- function get_title($user, $page) { -- return ''; -- } -+ function get_message_profile($message) +hunk ./actions/outbox.php 110 +-require_once(INSTALLDIR.'/lib/mailbox.php'); ++ function getMessageProfile($message) + { -+ return null; ++ return $message->getTo(); + } -hunk ./lib/mailbox.php 213 -- function get_instructions() { -- return ''; +hunk ./actions/outbox.php 115 +-class OutboxAction extends MailboxAction { +- +- function get_title($user, $page) { +- if ($page > 1) { +- $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); +- } else { +- $title = sprintf(_("Outbox for %s"), $user->nickname); +- } +- return $title; - } +- +- function get_messages($user, $page) { +- $message = new Message(); +- $message->from_profile = $user->id; +- $message->orderBy('created DESC, id DESC'); +- $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + /** -+ * show a single message in the list format -+ * -+ * @param Message $message the message to show ++ * instructions for using this page + * -+ * @return void ++ * @return string localised instructions for using the page + */ -hunk ./lib/mailbox.php 221 -- function show_top() { -+ function show_message($message) -+ { -+ common_element_start('li', array('class' => 'message_single', -+ 'id' => 'message-' . $message->id)); -hunk ./lib/mailbox.php 226 -- $cur = common_current_user(); -- -- common_message_form(NULL, $cur, NULL); -- -- $this->views_menu(); -- } -- -- function show_page($user, $page) { -+ $profile = $this->get_message_profile($message); -hunk ./lib/mailbox.php 228 -- common_show_header($this->get_title($user, $page), -- NULL, NULL, -- array($this, 'show_top')); -- -- $this->show_box($user, $page); -- -- common_show_footer(); -- } -- -- function show_box($user, $page) { -- -- $message = $this->get_messages($user, $page); -- -- if ($message) { -- -- $cnt = 0; -- common_element_start('ul', array('id' => 'messages')); -- -- while ($message->fetch() && $cnt <= MESSAGES_PER_PAGE) { -- $cnt++; -- -- if ($cnt > MESSAGES_PER_PAGE) { -- break; -- } -- -- $this->show_message($message); -- } -+ $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); -+ common_element_start('a', array('href' => $profile->profileurl)); -+ common_element('img', array('src' => ($avatar) ? -+ common_avatar_display_url($avatar) : -+ common_default_avatar(AVATAR_STREAM_SIZE), -+ 'class' => 'avatar stream', -+ 'width' => AVATAR_STREAM_SIZE, -+ 'height' => AVATAR_STREAM_SIZE, -+ 'alt' => -+ ($profile->fullname) ? $profile->fullname : -+ $profile->nickname)); -+ common_element_end('a'); -+ common_element('a', array('href' => $profile->profileurl, -+ 'class' => 'nickname'), -+ $profile->nickname); -+ // FIXME: URL, image, video, audio -+ common_element_start('p', array('class' => 'content')); -+ common_raw($message->rendered); -+ common_element_end('p'); -hunk ./lib/mailbox.php 248 -- common_element_end('ul'); -- -- common_pagination($page > 1, $cnt > MESSAGES_PER_PAGE, -- $page, $this->trimmed('action'), -- array('nickname' => $user->nickname)); -- -- $message->free(); -- unset($message); +hunk ./actions/outbox.php 121 +- if ($message->find()) { +- return $message; +- } else { +- return NULL; - } - } -+ $messageurl = common_local_url('showmessage', -+ array('message' => $message->id)); -hunk ./lib/mailbox.php 251 -- # returns the profile we want to show with the message - - function get_message_profile($message) { -- return NULL; +- return $message->getTo(); - } - -- function show_message($message) { -+ // XXX: we need to figure this out better. Is this right? -+ if (strcmp($message->uri, $messageurl) != 0 && -+ preg_match('/^http/', $message->uri)) { -+ $messageurl = $message->uri; -+ } -+ common_element_start('p', 'time'); -+ common_element('a', array('class' => 'permalink', -+ 'href' => $messageurl, -+ 'title' => common_exact_date($message->created)), -+ common_date_string($message->created)); -+ if ($message->source) { -+ common_text(_(' from ')); -+ $this->source_link($message->source); -+ } -hunk ./lib/mailbox.php 266 -- common_element_start('li', array('class' => 'message_single', -- 'id' => 'message-' . $message->id)); -+ common_element_end('p'); -hunk ./lib/mailbox.php 268 -- $profile = $this->get_message_profile($message); -- -- $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); -- common_element_start('a', array('href' => $profile->profileurl)); -- common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), -- 'class' => 'avatar stream', -- 'width' => AVATAR_STREAM_SIZE, -- 'height' => AVATAR_STREAM_SIZE, -- 'alt' => -- ($profile->fullname) ? $profile->fullname : -- $profile->nickname)); -- common_element_end('a'); -- common_element('a', array('href' => $profile->profileurl, -- 'class' => 'nickname'), -- $profile->nickname); -- # FIXME: URL, image, video, audio -- common_element_start('p', array('class' => 'content')); -- common_raw($message->rendered); -- common_element_end('p'); -- -- $messageurl = common_local_url('showmessage', array('message' => $message->id)); -- -- # XXX: we need to figure this out better. Is this right? -- if (strcmp($message->uri, $messageurl) != 0 && preg_match('/^http/', $message->uri)) { -- $messageurl = $message->uri; -- } -- common_element_start('p', 'time'); -- common_element('a', array('class' => 'permalink', -- 'href' => $messageurl, -- 'title' => common_exact_date($message->created)), -- common_date_string($message->created)); -- if ($message->source) { -- common_text(_(' from ')); -- $this->source_link($message->source); -- } -- -- common_element_end('p'); -- -- common_element_end('li'); +- function get_instructions() { +- return _('This is your outbox, which lists private messages you have sent.'); - } -+ common_element_end('li'); +- ++ function getInstructions() ++ { ++ return _('This is your outbox, which lists private messages you have sent.'); ++ } +hunk ./lib/mailbox.php 22 +- * @category Action ++ * @category Message +hunk ./lib/mailbox.php 41 +- * @category Action ++ * @category Message +hunk ./lib/mailbox.php 94 +- $this->show_page($user, $page); ++ $this->showPage($user, $page); +hunk ./lib/mailbox.php 106 +- function get_title($user, $page) ++ function getTitle($user, $page) +hunk ./lib/mailbox.php 117 +- function get_instructions() ++ function getInstructions() +hunk ./lib/mailbox.php 128 +- function show_top() ++ function showTop() +hunk ./lib/mailbox.php 146 +- function show_page($user, $page) ++ function showPage($user, $page) +hunk ./lib/mailbox.php 148 +- common_show_header($this->get_title($user, $page), ++ common_show_header($this->getTitle($user, $page), +hunk ./lib/mailbox.php 150 +- array($this, 'show_top')); ++ array($this, 'showTop')); +hunk ./lib/mailbox.php 152 +- $this->show_box($user, $page); ++ $this->showBox($user, $page); +hunk ./lib/mailbox.php 157 ++ /** ++ * retrieve the messages appropriate for this mailbox ++ * ++ * Does a query for the right messages ++ * ++ * @param User $user The current user ++ * @param int $page The page the user is on ++ * ++ * @return Message data object with stream for messages ++ */ ++ ++ function getMessages($user, $page) ++ { ++ return null; + } ++ +hunk ./lib/mailbox.php 184 +- function show_box($user, $page) ++ function showBox($user, $page) +hunk ./lib/mailbox.php 186 +- $message = $this->get_messages($user, $page); ++ $message = $this->getMessages($user, $page); +hunk ./lib/mailbox.php 200 +- $this->show_message($message); ++ $this->showMessage($message); +hunk ./lib/mailbox.php 224 +- function get_message_profile($message) ++ function getMessageProfile($message) +hunk ./lib/mailbox.php 237 +- function show_message($message) ++ function showMessage($message) +hunk ./lib/mailbox.php 242 +- $profile = $this->get_message_profile($message); ++ $profile = $this->getMessageProfile($message); diff --git a/actions/inbox.php b/actions/inbox.php index c752e404e..da27814a6 100644 --- a/actions/inbox.php +++ b/actions/inbox.php @@ -1,9 +1,12 @@ . + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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/mailbox.php'; + +/** + * action handler for message inbox + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see MailboxAction */ -if (!defined('LACONICA')) { exit(1); } - -require_once(INSTALLDIR.'/lib/mailbox.php'); - -class InboxAction extends MailboxAction { - - function get_title($user, $page) { - if ($page > 1) { - $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); - } else { - $title = sprintf(_("Inbox for %s"), $user->nickname); - } - return $title; - } - - function get_messages($user, $page) { - $message = new Message(); - $message->to_profile = $user->id; - $message->orderBy('created DESC, id DESC'); - $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); - - if ($message->find()) { - return $message; - } else { - return NULL; - } - } - - function get_message_profile($message) { - return $message->getFrom(); - } - - function get_instructions() { - return _('This is your inbox, which lists your incoming private messages.'); - } +class InboxAction extends MailboxAction +{ + /** + * returns the title of the page + * + * @param User $user current user + * @param int $page current page + * + * @return string localised title of the page + * + * @see MailboxAction::getTitle() + */ + + function getTitle($user, $page) + { + if ($page > 1) { + $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); + } else { + $title = sprintf(_("Inbox for %s"), $user->nickname); + } + return $title; + } + + /** + * retrieve the messages for this user and this page + * + * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return Message data object with stream for messages + * + * @see MailboxAction::getMessages() + */ + + function getMessages($user, $page) + { + $message = new Message(); + + $message->to_profile = $user->id; + + $message->orderBy('created DESC, id DESC'); + $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + + if ($message->find()) { + return $message; + } else { + return null; + } + } + + /** + * returns the profile we want to show with the message + * + * For inboxes, we show the sender. + * + * @param Message $message The message to get the profile for + * + * @return Profile The profile of the message sender + * + * @see MailboxAction::getMessageProfile() + */ + + function getMessageProfile($message) + { + return $message->getFrom(); + } + + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ + + function getInstructions() + { + return _('This is your inbox, which lists your incoming private messages.'); + } } diff --git a/actions/outbox.php b/actions/outbox.php index c48d9c206..9fb6dbf9f 100644 --- a/actions/outbox.php +++ b/actions/outbox.php @@ -1,9 +1,12 @@ . + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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/mailbox.php'; + +/** + * action handler for message outbox + * + * @category Message + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see MailboxAction */ -if (!defined('LACONICA')) { exit(1); } - -require_once(INSTALLDIR.'/lib/mailbox.php'); - -class OutboxAction extends MailboxAction { - - function get_title($user, $page) { - if ($page > 1) { - $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); - } else { - $title = sprintf(_("Outbox for %s"), $user->nickname); - } - return $title; - } - - function get_messages($user, $page) { - $message = new Message(); - $message->from_profile = $user->id; - $message->orderBy('created DESC, id DESC'); - $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); - - if ($message->find()) { - return $message; - } else { - return NULL; - } - } - - function get_message_profile($message) { - return $message->getTo(); - } - - function get_instructions() { - return _('This is your outbox, which lists private messages you have sent.'); - } - +class OutboxAction extends MailboxAction +{ + /** + * returns the title of the page + * + * @param User $user current user + * @param int $page current page + * + * @return string localised title of the page + * + * @see MailboxAction::getTitle() + */ + + function getTitle($user, $page) + { + if ($page > 1) { + $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); + } else { + $title = sprintf(_("Outbox for %s"), $user->nickname); + } + return $title; + } + + /** + * retrieve the messages for this user and this page + * + * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return Message data object with stream for messages + * + * @see MailboxAction::getMessages() + */ + + function getMessages($user, $page) + { + $message = new Message(); + + $message->from_profile = $user->id; + $message->orderBy('created DESC, id DESC'); + $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); + + if ($message->find()) { + return $message; + } else { + return null; + } + } + + /** + * returns the profile we want to show with the message + * + * For outboxes, we show the recipient. + * + * @param Message $message The message to get the profile for + * + * @return Profile The profile of the message recipient + * + * @see MailboxAction::getMessageProfile() + */ + + function getMessageProfile($message) + { + return $message->getTo(); + } + + /** + * instructions for using this page + * + * @return string localised instructions for using the page + */ + + function getInstructions() + { + return _('This is your outbox, which lists private messages you have sent.'); + } } diff --git a/lib/mailbox.php b/lib/mailbox.php index 9039c5fda..bdc360a35 100644 --- a/lib/mailbox.php +++ b/lib/mailbox.php @@ -19,7 +19,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * - * @category Action + * @category Message * @package Laconica * @author Evan Prodromou * @copyright 2008 Control Yourself, Inc. @@ -38,7 +38,7 @@ define('MESSAGES_PER_PAGE', 20); /** * common superclass for direct messages inbox and outbox * - * @category Action + * @category Message * @package Laconica * @author Evan Prodromou * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 @@ -91,7 +91,7 @@ class MailboxAction extends PersonalAction $page = 1; } - $this->show_page($user, $page); + $this->showPage($user, $page); } /** @@ -103,7 +103,7 @@ class MailboxAction extends PersonalAction * @return string localised title of the page */ - function get_title($user, $page) + function getTitle($user, $page) { return ''; } @@ -114,7 +114,7 @@ class MailboxAction extends PersonalAction * @return string localised instructions for using the page */ - function get_instructions() + function getInstructions() { return ''; } @@ -125,7 +125,7 @@ class MailboxAction extends PersonalAction * @return void */ - function show_top() + function showTop() { $cur = common_current_user(); @@ -143,17 +143,33 @@ class MailboxAction extends PersonalAction * @return void */ - function show_page($user, $page) + function showPage($user, $page) { - common_show_header($this->get_title($user, $page), + common_show_header($this->getTitle($user, $page), null, null, - array($this, 'show_top')); + array($this, 'showTop')); - $this->show_box($user, $page); + $this->showBox($user, $page); common_show_footer(); } + /** + * retrieve the messages appropriate for this mailbox + * + * Does a query for the right messages + * + * @param User $user The current user + * @param int $page The page the user is on + * + * @return Message data object with stream for messages + */ + + function getMessages($user, $page) + { + return null; + } + /** * show the messages for a mailbox in list format * @@ -165,9 +181,9 @@ class MailboxAction extends PersonalAction * @return void */ - function show_box($user, $page) + function showBox($user, $page) { - $message = $this->get_messages($user, $page); + $message = $this->getMessages($user, $page); if ($message) { @@ -181,7 +197,7 @@ class MailboxAction extends PersonalAction break; } - $this->show_message($message); + $this->showMessage($message); } common_element_end('ul'); @@ -205,7 +221,7 @@ class MailboxAction extends PersonalAction * @return Profile The profile that matches the message */ - function get_message_profile($message) + function getMessageProfile($message) { return null; } @@ -218,12 +234,12 @@ class MailboxAction extends PersonalAction * @return void */ - function show_message($message) + function showMessage($message) { common_element_start('li', array('class' => 'message_single', 'id' => 'message-' . $message->id)); - $profile = $this->get_message_profile($message); + $profile = $this->getMessageProfile($message); $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); common_element_start('a', array('href' => $profile->profileurl)); -- cgit v1.2.3-54-g00ecf From ba31059fef3f609673178c7a041c397540da1789 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Tue, 23 Dec 2008 12:33:30 -0500 Subject: reformat and document lib/mail.php for phpcs conformance darcs-hash:20081223173330-84dde-8cbbfd3953e8a67d5e58679431f93651ddf3122a.gz --- _darcs/inventory | 4 +- ...dde-8cbbfd3953e8a67d5e58679431f93651ddf3122a.gz | Bin 0 -> 5889 bytes _darcs/pristine/lib/mail.php | 704 +++++++++----- _darcs/tentative_pristine | 1015 ++++++++++++++------ lib/mail.php | 704 +++++++++----- 5 files changed, 1667 insertions(+), 760 deletions(-) create mode 100644 _darcs/patches/20081223173330-84dde-8cbbfd3953e8a67d5e58679431f93651ddf3122a.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 083e53fd0..167d793d7 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -43,4 +43,6 @@ Evan Prodromou **20081222201304 complete compliance with the code standards. Untested; maybe there are some bad method names now. -] \ No newline at end of file +] +[reformat and document lib/mail.php for phpcs conformance +Evan Prodromou **20081223173330] \ No newline at end of file diff --git a/_darcs/patches/20081223173330-84dde-8cbbfd3953e8a67d5e58679431f93651ddf3122a.gz b/_darcs/patches/20081223173330-84dde-8cbbfd3953e8a67d5e58679431f93651ddf3122a.gz new file mode 100644 index 000000000..30dd86a19 Binary files /dev/null and b/_darcs/patches/20081223173330-84dde-8cbbfd3953e8a67d5e58679431f93651ddf3122a.gz differ diff --git a/_darcs/pristine/lib/mail.php b/_darcs/pristine/lib/mail.php index c90140d3c..5638ae9bf 100644 --- a/_darcs/pristine/lib/mail.php +++ b/_darcs/pristine/lib/mail.php @@ -1,9 +1,12 @@ . + * + * @category Mail + * @package Laconica + * @author Evan Prodromou + * @author Zach Copley + * @author Robin Millette + * @author Sarven Capadisli + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} -require_once('Mail.php'); +require_once 'Mail.php'; -function mail_backend() { - static $backend = NULL; +/** + * return the configured mail backend + * + * Uses the $config array to make a mail backend. Cached so it is safe to call + * more than once. + * + * @return Mail backend + */ - if (!$backend) { - global $config; - $backend = Mail::factory($config['mail']['backend'], - ($config['mail']['params']) ? $config['mail']['params'] : array()); - if (PEAR::isError($backend)) { - common_server_error($backend->getMessage(), 500); - } - } - return $backend; +function mail_backend() +{ + static $backend = null; + + if (!$backend) { + global $config; + $backend = Mail::factory($config['mail']['backend'], + ($config['mail']['params']) ? + $config['mail']['params'] : + array()); + if (PEAR::isError($backend)) { + common_server_error($backend->getMessage(), 500); + } + } + return $backend; } -# XXX: use Mail_Queue... maybe +/** + * send an email to one or more recipients + * + * @param array $recipients array of strings with email addresses of recipients + * @param array $headers array mapping strings to strings for email headers + * @param string $body body of the email + * + * @return boolean success flag + */ -function mail_send($recipients, $headers, $body) { - $backend = mail_backend(); +function mail_send($recipients, $headers, $body) +{ + // XXX: use Mail_Queue... maybe + $backend = mail_backend(); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/plain; charset=UTF-8'; } - assert($backend); # throws an error if it's bad - $sent = $backend->send($recipients, $headers, $body); - if (PEAR::isError($sent)) { - common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); - return false; - } - return true; + assert($backend); // throws an error if it's bad + $sent = $backend->send($recipients, $headers, $body); + if (PEAR::isError($sent)) { + common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); + return false; + } + return true; } -function mail_domain() { - $maildomain = common_config('mail', 'domain'); - if (!$maildomain) { - $maildomain = common_config('site', 'server'); - } - return $maildomain; -} +/** + * returns the configured mail domain + * + * Defaults to the server name. + * + * @return string mail domain, suitable for making email addresses. + */ -function mail_notify_from() { - $notifyfrom = common_config('mail', 'notifyfrom'); - if (!$notifyfrom) { - $domain = mail_domain(); - $notifyfrom = common_config('site', 'name') .' '; - } - return $notifyfrom; +function mail_domain() +{ + $maildomain = common_config('mail', 'domain'); + if (!$maildomain) { + $maildomain = common_config('site', 'server'); + } + return $maildomain; } -function mail_to_user(&$user, $subject, $body, $address=NULL) { - if (!$address) { - $address = $user->email; - } +/** + * returns a good address for sending email from this server + * + * Uses either the configured value or a faked-up value made + * from the mail domain. + * + * @return string notify from address + */ + +function mail_notify_from() +{ + $notifyfrom = common_config('mail', 'notifyfrom'); - $recipients = $address; - $profile = $user->getProfile(); + if (!$notifyfrom) { - $headers['From'] = mail_notify_from(); - $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; - $headers['Subject'] = $subject; + $domain = mail_domain(); - return mail_send($recipients, $headers, $body); + $notifyfrom = common_config('site', 'name') .' '; + } + + return $notifyfrom; } -# For confirming a Jabber address +/** + * sends email to a user + * + * @param User &$user user to send email to + * @param string $subject subject of the email + * @param string $body body of the email + * @param string $address optional specification of email address + * + * @return boolean success flag + */ -function mail_confirm_address($user, $code, $nickname, $address) { +function mail_to_user(&$user, $subject, $body, $address=null) +{ + if (!$address) { + $address = $user->email; + } - $subject = _('Email address confirmation'); + $recipients = $address; + $profile = $user->getProfile(); - $body = sprintf(_("Hey, %s.\n\nSomeone just entered this email address on %s.\n\n" . - "If it was you, and you want to confirm your entry, use the URL below:\n\n\t%s\n\n" . - "If not, just ignore this message.\n\nThanks for your time, \n%s\n") - , $nickname, common_config('site', 'name') - , common_local_url('confirmaddress', array('code' => $code)), common_config('site', 'name')); - return mail_to_user($user, $subject, $body, $address); + $headers['From'] = mail_notify_from(); + $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; + $headers['Subject'] = $subject; + + return mail_send($recipients, $headers, $body); } -function mail_subscribe_notify($listenee, $listener) { - $other = $listener->getProfile(); - mail_subscribe_notify_profile($listenee, $other); +/** + * Send an email to confirm a user's control of an email address + * + * @param User $user User claiming the email address + * @param string $code Confirmation code + * @param string $nickname Nickname of user + * @param string $address email address to confirm + * + * @see common_confirmation_code() + * + * @return success flag + */ + +function mail_confirm_address($user, $code, $nickname, $address) +{ + $subject = _('Email address confirmation'); + + $body = sprintf(_("Hey, %s.\n\n". + "Someone just entered this email address on %s.\n\n" . + "If it was you, and you want to confirm your entry, ". + "use the URL below:\n\n\t%s\n\n" . + "If not, just ignore this message.\n\n". + "Thanks for your time, \n%s\n"), + $nickname, common_config('site', 'name'), + common_local_url('confirmaddress', array('code' => $code)), + common_config('site', 'name')); + return mail_to_user($user, $subject, $body, $address); +} + +/** + * notify a user of subscription by another user + * + * This is just a wrapper around the profile-based version. + * + * @param User $listenee user who is being subscribed to + * @param User $listener user who is subscribing + * + * @see mail_subscribe_notify_profile() + * + * @return void + */ + +function mail_subscribe_notify($listenee, $listener) +{ + $other = $listener->getProfile(); + mail_subscribe_notify_profile($listenee, $other); } -function mail_subscribe_notify_profile($listenee, $other) { - if ($listenee->email && $listenee->emailnotifysub) { - // use the recipients localization +/** + * notify a user of subscription by a profile (remote or local) + * + * This function checks to see if the listenee has an email + * address and wants subscription notices. + * + * @param User $listenee user who's being subscribed to + * @param Profile $other profile of person who's listening + * + * @return void + */ + +function mail_subscribe_notify_profile($listenee, $other) +{ + if ($listenee->email && $listenee->emailnotifysub) { + + // use the recipient's localization common_init_locale($listenee->language); - $profile = $listenee->getProfile(); - $name = $profile->getBestName(); - $long_name = ($other->fullname) ? ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; - $recipients = $listenee->email; - $headers['From'] = mail_notify_from(); - $headers['To'] = $name . ' <' . $listenee->email . '>'; - $headers['Subject'] = sprintf(_('%1$s is now listening to your notices on %2$s.'), + + $profile = $listenee->getProfile(); + + $name = $profile->getBestName(); + + $long_name = ($other->fullname) ? + ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; + + $recipients = $listenee->email; + + $headers['From'] = mail_notify_from(); + $headers['To'] = $name . ' <' . $listenee->email . '>'; + $headers['Subject'] = sprintf(_('%1$s is now listening to '. + 'your notices on %2$s.'), $other->getBestName(), - common_config('site', 'name')); - $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". - "\t".'%3$s'."\n\n". - '%4$s'. - '%5$s'. - '%6$s'. - "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". - "----\n". - "Change your email address or notification options at %8$s"), - $long_name, - common_config('site', 'name'), - $other->profileurl, - ($other->location) ? sprintf(_("Location: %s\n"), $other->location) : '', - ($other->homepage) ? sprintf(_("Homepage: %s\n"), $other->homepage) : '', - ($other->bio) ? sprintf(_("Bio: %s\n\n"), $other->bio) : '', - common_config('site', 'name'), - common_local_url('emailsettings')); + common_config('site', 'name')); + + $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". + "\t".'%3$s'."\n\n". + '%4$s'. + '%5$s'. + '%6$s'. + "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". + "----\n". + "Change your email address or ". + "notification options at %8$s\n"), + $long_name, + common_config('site', 'name'), + $other->profileurl, + ($other->location) ? + sprintf(_("Location: %s\n"), $other->location) : '', + ($other->homepage) ? + sprintf(_("Homepage: %s\n"), $other->homepage) : '', + ($other->bio) ? + sprintf(_("Bio: %s\n\n"), $other->bio) : '', + common_config('site', 'name'), + common_local_url('emailsettings')); + // reset localization common_init_locale(); - mail_send($recipients, $headers, $body); - } + mail_send($recipients, $headers, $body); + } } -function mail_new_incoming_notify($user) { +/** + * notify a user of their new incoming email address + * + * User's email and incoming fields should already be updated. + * + * @param User $user user with the new address + * + * @return void + */ + +function mail_new_incoming_notify($user) +{ + $profile = $user->getProfile(); - $profile = $user->getProfile(); - $name = $profile->getBestName(); + $name = $profile->getBestName(); - $headers['From'] = $user->incomingemail; - $headers['To'] = $name . ' <' . $user->email . '>'; - $headers['Subject'] = sprintf(_('New email address for posting to %s'), - common_config('site', 'name')); + $headers['From'] = $user->incomingemail; + $headers['To'] = $name . ' <' . $user->email . '>'; + $headers['Subject'] = sprintf(_('New email address for posting to %s'), + common_config('site', 'name')); - $body = sprintf(_("You have a new posting address on %1\$s.\n\n". - "Send email to %2\$s to post new messages.\n\n". - "More email instructions at %3\$s.\n\n". - "Faithfully yours,\n%4\$s"), - common_config('site', 'name'), - $user->incomingemail, - common_local_url('doc', array('title' => 'email')), - common_config('site', 'name')); + $body = sprintf(_("You have a new posting address on %1\$s.\n\n". + "Send email to %2\$s to post new messages.\n\n". + "More email instructions at %3\$s.\n\n". + "Faithfully yours,\n%4\$s"), + common_config('site', 'name'), + $user->incomingemail, + common_local_url('doc', array('title' => 'email')), + common_config('site', 'name')); - mail_send($user->email, $headers, $body); + mail_send($user->email, $headers, $body); } -function mail_new_incoming_address() { - $prefix = common_confirmation_code(64); - $suffix = mail_domain(); - return $prefix . '@' . $suffix; +/** + * generate a new address for incoming messages + * + * @todo check the database for uniqueness + * + * @return string new email address for incoming messages + */ + +function mail_new_incoming_address() +{ + $prefix = common_confirmation_code(64); + $suffix = mail_domain(); + return $prefix . '@' . $suffix; } -function mail_broadcast_notice_sms($notice) { +/** + * broadcast a notice to all subscribers with SMS notification on + * + * This function sends SMS messages to all users who have sms addresses; + * have sms notification on; and have sms enabled for this particular + * subscription. + * + * @param Notice $notice The notice to broadcast + * + * @return success flag + */ - # Now, get users subscribed to this profile +function mail_broadcast_notice_sms($notice) +{ + // Now, get users subscribed to this profile - $user = new User(); + $user = new User(); - $user->query('SELECT nickname, smsemail, incomingemail ' . - 'FROM user JOIN subscription ' . - 'ON user.id = subscription.subscriber ' . - 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . - 'AND user.smsemail IS NOT NULL ' . - 'AND user.smsnotify = 1 ' . + $user->query('SELECT nickname, smsemail, incomingemail ' . + 'FROM user JOIN subscription ' . + 'ON user.id = subscription.subscriber ' . + 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . + 'AND user.smsemail IS NOT null ' . + 'AND user.smsnotify = 1 ' . 'AND subscription.sms = 1 '); - while ($user->fetch()) { - common_log(LOG_INFO, - 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, - __FILE__); - $success = mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); - if (!$success) { - # XXX: Not sure, but I think that's the right thing to do - common_log(LOG_WARNING, - 'Sending notice ' . $notice->id . ' to ' . $user->smsemail . ' FAILED, cancelling.', - __FILE__); - return false; - } - } - - $user->free(); - unset($user); - - return true; + while ($user->fetch()) { + common_log(LOG_INFO, + 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, + __FILE__); + $success = mail_send_sms_notice_address($notice, + $user->smsemail, + $user->incomingemail); + if (!$success) { + // XXX: Not sure, but I think that's the right thing to do + common_log(LOG_WARNING, + 'Sending notice ' . $notice->id . ' to ' . + $user->smsemail . ' FAILED, cancelling.', + __FILE__); + return false; + } + } + + $user->free(); + unset($user); + + return true; } -function mail_send_sms_notice($notice, $user) { - return mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); +/** + * send a notice to a user via SMS + * + * A convenience wrapper around mail_send_sms_notice_address() + * + * @param Notice $notice notice to send + * @param User $user user to receive notice + * + * @see mail_send_sms_notice_address() + * + * @return boolean success flag + */ + +function mail_send_sms_notice($notice, $user) +{ + return mail_send_sms_notice_address($notice, + $user->smsemail, + $user->incomingemail); } -function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) { +/** + * send a notice to an SMS email address from a given address + * + * We use the user's incoming email address as the "From" address to make + * replying to notices easier. + * + * @param Notice $notice notice to send + * @param string $smsemail email address to send to + * @param string $incomingemail email address to set as 'from' + * + * @return boolean success flag + */ - $to = $nickname . ' <' . $smsemail . '>'; - $other = $notice->getProfile(); +function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) +{ + $to = $nickname . ' <' . $smsemail . '>'; - common_log(LOG_INFO, "Sending notice " . $notice->id . " to " . $smsemail, __FILE__); + $other = $notice->getProfile(); - $headers = array(); - $headers['From'] = (isset($incomingemail)) ? $incomingemail : mail_notify_from(); - $headers['To'] = $to; - $headers['Subject'] = sprintf(_('%s status'), - $other->getBestName()); - $body = $notice->content; + common_log(LOG_INFO, 'Sending notice ' . $notice->id . + ' to ' . $smsemail, __FILE__); - return mail_send($smsemail, $headers, $body); + $headers = array(); + + $headers['From'] = ($incomingemail) ? $incomingemail : mail_notify_from(); + $headers['To'] = $to; + $headers['Subject'] = sprintf(_('%s status'), + $other->getBestName()); + + $body = $notice->content; + + return mail_send($smsemail, $headers, $body); } -function mail_confirm_sms($code, $nickname, $address) { +/** + * send a message to confirm a claim for an SMS number + * + * @param string $code confirmation code + * @param string $nickname nickname of user claiming number + * @param string $address email address to send the confirmation to + * + * @see common_confirmation_code() + * + * @return void + */ - $recipients = $address; +function mail_confirm_sms($code, $nickname, $address) +{ + $recipients = $address; - $headers['From'] = mail_notify_from(); - $headers['To'] = $nickname . ' <' . $address . '>'; - $headers['Subject'] = _('SMS confirmation'); + $headers['From'] = mail_notify_from(); + $headers['To'] = $nickname . ' <' . $address . '>'; + $headers['Subject'] = _('SMS confirmation'); - $body = "$nickname: confirm you own this phone number with this code:"; - $body .= "\n\n"; - $body .= $code; - $body .= "\n\n"; + // FIXME: I18N - mail_send($recipients, $headers, $body); + $body = "$nickname: confirm you own this phone number with this code:"; + $body .= "\n\n"; + $body .= $code; + $body .= "\n\n"; + + mail_send($recipients, $headers, $body); } -function mail_notify_nudge($from, $to) { +/** + * send a mail message to notify a user of a 'nudge' + * + * @param User $from user nudging + * @param User $to user being nudged + * + * @return boolean success flag + */ + +function mail_notify_nudge($from, $to) +{ common_init_locale($to->language); - $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); - - $from_profile = $from->getProfile(); - - $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to these days and is inviting you to post some news.\n\n". - "So let's hear from you :)\n\n". - "%3\$s\n\n". - "Don't reply to this email; it won't get to them.\n\n". - "With kind regards,\n". - "%4\$s\n"), - $from_profile->getBestName(), - $from->nickname, - common_local_url('all', array('nickname' => $to->nickname)), - common_config('site', 'name')); + $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); + + $from_profile = $from->getProfile(); + + $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ". + "these days and is inviting you to post some news.\n\n". + "So let's hear from you :)\n\n". + "%3\$s\n\n". + "Don't reply to this email; it won't get to them.\n\n". + "With kind regards,\n". + "%4\$s\n"), + $from_profile->getBestName(), + $from->nickname, + common_local_url('all', array('nickname' => $to->nickname)), + common_config('site', 'name')); common_init_locale(); - return mail_to_user($to, $subject, $body); + return mail_to_user($to, $subject, $body); } -function mail_notify_message($message, $from=NULL, $to=NULL) { +/** + * send a message to notify a user of a direct message (DM) + * + * This function checks to see if the recipient wants notification + * of DMs and has a configured email address. + * + * @param Message $message message to notify about + * @param User $from user sending message; default to sender + * @param User $to user receiving message; default to recipient + * + * @return boolean success code + */ - if (is_null($from)) { - $from = User::staticGet('id', $message->from_profile); - } +function mail_notify_message($message, $from=null, $to=null) +{ + if (is_null($from)) { + $from = User::staticGet('id', $message->from_profile); + } - if (is_null($to)) { - $to = User::staticGet('id', $message->to_profile); - } + if (is_null($to)) { + $to = User::staticGet('id', $message->to_profile); + } - if (is_null($to->email) || !$to->emailnotifymsg) { - return true; - } + if (is_null($to->email) || !$to->emailnotifymsg) { + return true; + } common_init_locale($to->language); - $subject = sprintf(_('New private message from %s'), $from->nickname); - - $from_profile = $from->getProfile(); - - $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". - "------------------------------------------------------\n". - "%3\$s\n". - "------------------------------------------------------\n\n". - "You can reply to their message here:\n\n". - "%4\$s\n\n". - "Don't reply to this email; it won't get to them.\n\n". - "With kind regards,\n". - "%5\$s\n"), - $from_profile->getBestName(), - $from->nickname, - $message->content, - common_local_url('newmessage', array('to' => $from->id)), - common_config('site', 'name')); + $subject = sprintf(_('New private message from %s'), $from->nickname); + + $from_profile = $from->getProfile(); + + $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". + "------------------------------------------------------\n". + "%3\$s\n". + "------------------------------------------------------\n\n". + "You can reply to their message here:\n\n". + "%4\$s\n\n". + "Don't reply to this email; it won't get to them.\n\n". + "With kind regards,\n". + "%5\$s\n"), + $from_profile->getBestName(), + $from->nickname, + $message->content, + common_local_url('newmessage', array('to' => $from->id)), + common_config('site', 'name')); common_init_locale(); - return mail_to_user($to, $subject, $body); + return mail_to_user($to, $subject, $body); } -function mail_notify_fave($other, $user, $notice) { +/** + * notify a user that one of their notices has been chosen as a 'fave' + * + * Doesn't check that the user has an email address nor if they + * want to receive notification of faves. Maybe this happens higher + * up the stack...? + * + * @param User $other The user whose notice was faved + * @param User $user The user who faved the notice + * @param Notice $notice The notice that was faved + * + * @return void + */ + +function mail_notify_fave($other, $user, $notice) +{ + $profile = $user->getProfile(); + + $bestname = $profile->getBestName(); - $profile = $user->getProfile(); - $bestname = $profile->getBestName(); common_init_locale($other->language); - $subject = sprintf(_('%s added your notice as a favorite'), $bestname); - $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . - "In case you forgot, you can see the text of your notice here:\n\n" . - "%3\$s\n\n" . - "You can see the list of %1\$s's favorites here:\n\n" . - "%4\$s\n\n" . - "Faithfully yours,\n" . - "%5\$s\n"), - $bestname, - common_exact_date($notice->created), - common_local_url('shownotice', array('notice' => $notice->id)), - common_local_url('showfavorites', array('nickname' => $user->nickname)), - common_config('site', 'name')); + + $subject = sprintf(_('%s added your notice as a favorite'), $bestname); + + $body = sprintf(_("%1\$s just added your notice from %2\$s". + " as one of their favorites.\n\n" . + "In case you forgot, you can see the text". + " of your notice here:\n\n" . + "%3\$s\n\n" . + "You can see the list of %1\$s's favorites here:\n\n" . + "%4\$s\n\n" . + "Faithfully yours,\n" . + "%5\$s\n"), + $bestname, + common_exact_date($notice->created), + common_local_url('shownotice', + array('notice' => $notice->id)), + common_local_url('showfavorites', + array('nickname' => $user->nickname)), + common_config('site', 'name')); common_init_locale(); - mail_to_user($other, $subject, $body); + mail_to_user($other, $subject, $body); } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 5a45154e6..8ce5499a9 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,365 +1,758 @@ -hunk ./actions/inbox.php 2 +hunk ./lib/mail.php 2 -/* - * Laconica - a distributed open-source microblogging tool - * Copyright (C) 2008, Controlez-Vous, Inc. +/** + * Laconica, the distributed open-source microblogging tool -hunk ./actions/inbox.php 5 +hunk ./lib/mail.php 5 - * This program is free software: you can redistribute it and/or modify -+ * action handler for message inbox ++ * utilities for sending email + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./actions/inbox.php 21 +hunk ./lib/mail.php 21 + * -+ * @category Message ++ * @category Mail + * @package Laconica + * @author Evan Prodromou ++ * @author Zach Copley ++ * @author Robin Millette ++ * @author Sarven Capadisli + * @copyright 2008 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/ -+ */ -+ +hunk ./lib/mail.php 33 +-if (!defined('LACONICA')) { exit(1); } +if (!defined('LACONICA')) { + exit(1); +} -+ -+require_once INSTALLDIR.'/lib/mailbox.php'; +hunk ./lib/mail.php 37 +-require_once('Mail.php'); ++require_once 'Mail.php'; + +/** -+ * action handler for message inbox -+ * -+ * @category Message -+ * @package Laconica -+ * @author Evan Prodromou -+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 -+ * @link http://laconi.ca/ -+ * @see MailboxAction -hunk ./actions/inbox.php 47 --if (!defined('LACONICA')) { exit(1); } -+class InboxAction extends MailboxAction ++ * return the configured mail backend ++ * ++ * Uses the $config array to make a mail backend. Cached so it is safe to call ++ * more than once. ++ * ++ * @return Mail backend ++ */ +hunk ./lib/mail.php 48 +-function mail_backend() { +- static $backend = NULL; ++function mail_backend() +{ -+ /** -+ * returns the title of the page -+ * -+ * @param User $user current user -+ * @param int $page current page -+ * -+ * @return string localised title of the page -+ * -+ * @see MailboxAction::getTitle() -+ */ -+ -+ function getTitle($user, $page) -+ { -+ if ($page > 1) { -+ $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); -+ } else { -+ $title = sprintf(_("Inbox for %s"), $user->nickname); -+ } -+ return $title; -+ } -+ -+ /** -+ * retrieve the messages for this user and this page -+ * -+ * Does a query for the right messages -+ * -+ * @param User $user The current user -+ * @param int $page The page the user is on -+ * -+ * @return Message data object with stream for messages -+ * -+ * @see MailboxAction::getMessages() -+ */ -+ -+ function getMessages($user, $page) -+ { -+ $message = new Message(); -+ -+ $message->to_profile = $user->id; -+ -+ $message->orderBy('created DESC, id DESC'); -+ $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); -+ -+ if ($message->find()) { -+ return $message; -+ } else { -+ return null; ++ static $backend = null; +hunk ./lib/mail.php 52 +- if (!$backend) { +- global $config; +- $backend = Mail::factory($config['mail']['backend'], +- ($config['mail']['params']) ? $config['mail']['params'] : array()); +- if (PEAR::isError($backend)) { +- common_server_error($backend->getMessage(), 500); +- } +- } +- return $backend; ++ if (!$backend) { ++ global $config; ++ $backend = Mail::factory($config['mail']['backend'], ++ ($config['mail']['params']) ? ++ $config['mail']['params'] : ++ array()); ++ if (PEAR::isError($backend)) { ++ common_server_error($backend->getMessage(), 500); + } + } -+ -+ /** -+ * returns the profile we want to show with the message -+ * -+ * For inboxes, we show the sender. -+ * -+ * @param Message $message The message to get the profile for -+ * -+ * @return Profile The profile of the message sender -+ * -+ * @see MailboxAction::getMessageProfile() -+ */ -hunk ./actions/inbox.php 111 --require_once(INSTALLDIR.'/lib/mailbox.php'); -+ function getMessageProfile($message) -+ { -+ return $message->getFrom(); -+ } -hunk ./actions/inbox.php 116 --class InboxAction extends MailboxAction { -- -- function get_title($user, $page) { -- if ($page > 1) { -- $title = sprintf(_("Inbox for %s - page %d"), $user->nickname, $page); -- } else { -- $title = sprintf(_("Inbox for %s"), $user->nickname); -- } -- return $title; ++ return $backend; +hunk ./lib/mail.php 65 +-# XXX: use Mail_Queue... maybe ++/** ++ * send an email to one or more recipients ++ * ++ * @param array $recipients array of strings with email addresses of recipients ++ * @param array $headers array mapping strings to strings for email headers ++ * @param string $body body of the email ++ * ++ * @return boolean success flag ++ */ +hunk ./lib/mail.php 75 +-function mail_send($recipients, $headers, $body) { +- $backend = mail_backend(); ++function mail_send($recipients, $headers, $body) ++{ ++ // XXX: use Mail_Queue... maybe ++ $backend = mail_backend(); +hunk ./lib/mail.php 82 +- assert($backend); # throws an error if it's bad +- $sent = $backend->send($recipients, $headers, $body); +- if (PEAR::isError($sent)) { +- common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); +- return false; - } -- -- function get_messages($user, $page) { -- $message = new Message(); -- $message->to_profile = $user->id; -- $message->orderBy('created DESC, id DESC'); -- $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); -+ /** -+ * instructions for using this page -+ * -+ * @return string localised instructions for using the page -+ */ -hunk ./actions/inbox.php 122 -- if ($message->find()) { -- return $message; -- } else { -- return NULL; -- } +- return true; ++ assert($backend); // throws an error if it's bad ++ $sent = $backend->send($recipients, $headers, $body); ++ if (PEAR::isError($sent)) { ++ common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); ++ return false; ++ } ++ return true; +hunk ./lib/mail.php 91 +-function mail_domain() { +- $maildomain = common_config('mail', 'domain'); +- if (!$maildomain) { +- $maildomain = common_config('site', 'server'); - } -- -- function get_message_profile($message) { -- return $message->getFrom(); +- return $maildomain; +-} ++/** ++ * returns the configured mail domain ++ * ++ * Defaults to the server name. ++ * ++ * @return string mail domain, suitable for making email addresses. ++ */ +hunk ./lib/mail.php 99 +-function mail_notify_from() { +- $notifyfrom = common_config('mail', 'notifyfrom'); +- if (!$notifyfrom) { +- $domain = mail_domain(); +- $notifyfrom = common_config('site', 'name') .' '; - } -- -- function get_instructions() { -- return _('This is your inbox, which lists your incoming private messages.'); +- return $notifyfrom; ++function mail_domain() ++{ ++ $maildomain = common_config('mail', 'domain'); ++ if (!$maildomain) { ++ $maildomain = common_config('site', 'server'); ++ } ++ return $maildomain; +hunk ./lib/mail.php 108 +-function mail_to_user(&$user, $subject, $body, $address=NULL) { +- if (!$address) { +- $address = $user->email; - } -+ function getInstructions() -+ { -+ return _('This is your inbox, which lists your incoming private messages.'); ++/** ++ * returns a good address for sending email from this server ++ * ++ * Uses either the configured value or a faked-up value made ++ * from the mail domain. ++ * ++ * @return string notify from address ++ */ +hunk ./lib/mail.php 117 +- $recipients = $address; +- $profile = $user->getProfile(); ++function mail_notify_from() ++{ ++ $notifyfrom = common_config('mail', 'notifyfrom'); +hunk ./lib/mail.php 121 +- $headers['From'] = mail_notify_from(); +- $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; +- $headers['Subject'] = $subject; ++ if (!$notifyfrom) { +hunk ./lib/mail.php 123 +- return mail_send($recipients, $headers, $body); ++ $domain = mail_domain(); ++ ++ $notifyfrom = common_config('site', 'name') .' '; + } -hunk ./actions/outbox.php 2 --/* -- * Laconica - a distributed open-source microblogging tool -- * Copyright (C) 2008, Controlez-Vous, Inc. ++ ++ return $notifyfrom; +hunk ./lib/mail.php 131 +-# For confirming a Jabber address +/** -+ * Laconica, the distributed open-source microblogging tool -hunk ./actions/outbox.php 5 -- * This program is free software: you can redistribute it and/or modify -+ * action handler for message inbox ++ * sends email to a user + * -+ * PHP version 5 ++ * @param User &$user user to send email to ++ * @param string $subject subject of the email ++ * @param string $body body of the email ++ * @param string $address optional specification of email address + * -+ * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./actions/outbox.php 21 ++ * @return boolean success flag ++ */ ++ ++function mail_to_user(&$user, $subject, $body, $address=null) ++{ ++ if (!$address) { ++ $address = $user->email; ++ } +hunk ./lib/mail.php 148 +-function mail_confirm_address($user, $code, $nickname, $address) { ++ $recipients = $address; ++ $profile = $user->getProfile(); +hunk ./lib/mail.php 151 +- $subject = _('Email address confirmation'); ++ $headers['From'] = mail_notify_from(); ++ $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; ++ $headers['Subject'] = $subject; +hunk ./lib/mail.php 155 +- $body = sprintf(_("Hey, %s.\n\nSomeone just entered this email address on %s.\n\n" . +- "If it was you, and you want to confirm your entry, use the URL below:\n\n\t%s\n\n" . +- "If not, just ignore this message.\n\nThanks for your time, \n%s\n") +- , $nickname, common_config('site', 'name') +- , common_local_url('confirmaddress', array('code' => $code)), common_config('site', 'name')); +- return mail_to_user($user, $subject, $body, $address); ++ return mail_send($recipients, $headers, $body); +hunk ./lib/mail.php 158 +-function mail_subscribe_notify($listenee, $listener) { +- $other = $listener->getProfile(); +- mail_subscribe_notify_profile($listenee, $other); ++/** ++ * Send an email to confirm a user's control of an email address + * -+ * @category Message -+ * @package Laconica -+ * @author Evan Prodromou -+ * @copyright 2008 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/ ++ * @param User $user User claiming the email address ++ * @param string $code Confirmation code ++ * @param string $nickname Nickname of user ++ * @param string $address email address to confirm ++ * ++ * @see common_confirmation_code() ++ * ++ * @return success flag + */ + -+if (!defined('LACONICA')) { -+ exit(1); -+} ++function mail_confirm_address($user, $code, $nickname, $address) ++{ ++ $subject = _('Email address confirmation'); + -+require_once INSTALLDIR.'/lib/mailbox.php'; ++ $body = sprintf(_("Hey, %s.\n\n". ++ "Someone just entered this email address on %s.\n\n" . ++ "If it was you, and you want to confirm your entry, ". ++ "use the URL below:\n\n\t%s\n\n" . ++ "If not, just ignore this message.\n\n". ++ "Thanks for your time, \n%s\n"), ++ $nickname, common_config('site', 'name'), ++ common_local_url('confirmaddress', array('code' => $code)), ++ common_config('site', 'name')); ++ return mail_to_user($user, $subject, $body, $address); +hunk ./lib/mail.php 187 +-function mail_subscribe_notify_profile($listenee, $other) { +- if ($listenee->email && $listenee->emailnotifysub) { +- // use the recipients localization ++/** ++ * notify a user of subscription by another user ++ * ++ * This is just a wrapper around the profile-based version. ++ * ++ * @param User $listenee user who is being subscribed to ++ * @param User $listener user who is subscribing ++ * ++ * @see mail_subscribe_notify_profile() ++ * ++ * @return void ++ */ ++ ++function mail_subscribe_notify($listenee, $listener) ++{ ++ $other = $listener->getProfile(); ++ mail_subscribe_notify_profile($listenee, $other); ++} + +/** -+ * action handler for message outbox -+ * -+ * @category Message -+ * @package Laconica -+ * @author Evan Prodromou -+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 -+ * @link http://laconi.ca/ -+ * @see MailboxAction -hunk ./actions/outbox.php 47 --if (!defined('LACONICA')) { exit(1); } -+class OutboxAction extends MailboxAction ++ * notify a user of subscription by a profile (remote or local) ++ * ++ * This function checks to see if the listenee has an email ++ * address and wants subscription notices. ++ * ++ * @param User $listenee user who's being subscribed to ++ * @param Profile $other profile of person who's listening ++ * ++ * @return void ++ */ ++ ++function mail_subscribe_notify_profile($listenee, $other) +{ -+ /** -+ * returns the title of the page -+ * -+ * @param User $user current user -+ * @param int $page current page -+ * -+ * @return string localised title of the page -+ * -+ * @see MailboxAction::getTitle() -+ */ ++ if ($listenee->email && $listenee->emailnotifysub) { + -+ function getTitle($user, $page) -+ { -+ if ($page > 1) { -+ $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); -+ } else { -+ $title = sprintf(_("Outbox for %s"), $user->nickname); -+ } -+ return $title; -+ } ++ // use the recipient's localization +hunk ./lib/mail.php 224 +- $profile = $listenee->getProfile(); +- $name = $profile->getBestName(); +- $long_name = ($other->fullname) ? ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; +- $recipients = $listenee->email; +- $headers['From'] = mail_notify_from(); +- $headers['To'] = $name . ' <' . $listenee->email . '>'; +- $headers['Subject'] = sprintf(_('%1$s is now listening to your notices on %2$s.'), + -+ /** -+ * retrieve the messages for this user and this page -+ * -+ * Does a query for the right messages -+ * -+ * @param User $user The current user -+ * @param int $page The page the user is on -+ * -+ * @return Message data object with stream for messages -+ * -+ * @see MailboxAction::getMessages() -+ */ ++ $profile = $listenee->getProfile(); + -+ function getMessages($user, $page) -+ { -+ $message = new Message(); ++ $name = $profile->getBestName(); + -+ $message->from_profile = $user->id; -+ $message->orderBy('created DESC, id DESC'); -+ $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); ++ $long_name = ($other->fullname) ? ++ ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; + -+ if ($message->find()) { -+ return $message; -+ } else { -+ return null; -+ } -+ } ++ $recipients = $listenee->email; + -+ /** -+ * returns the profile we want to show with the message -+ * -+ * For outboxes, we show the recipient. -+ * -+ * @param Message $message The message to get the profile for -+ * -+ * @return Profile The profile of the message recipient -+ * -+ * @see MailboxAction::getMessageProfile() -+ */ -hunk ./actions/outbox.php 110 --require_once(INSTALLDIR.'/lib/mailbox.php'); -+ function getMessageProfile($message) -+ { -+ return $message->getTo(); ++ $headers['From'] = mail_notify_from(); ++ $headers['To'] = $name . ' <' . $listenee->email . '>'; ++ $headers['Subject'] = sprintf(_('%1$s is now listening to '. ++ 'your notices on %2$s.'), +hunk ./lib/mail.php 239 +- common_config('site', 'name')); +- $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". +- "\t".'%3$s'."\n\n". +- '%4$s'. +- '%5$s'. +- '%6$s'. +- "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". +- "----\n". +- "Change your email address or notification options at %8$s"), +- $long_name, +- common_config('site', 'name'), +- $other->profileurl, +- ($other->location) ? sprintf(_("Location: %s\n"), $other->location) : '', +- ($other->homepage) ? sprintf(_("Homepage: %s\n"), $other->homepage) : '', +- ($other->bio) ? sprintf(_("Bio: %s\n\n"), $other->bio) : '', +- common_config('site', 'name'), +- common_local_url('emailsettings')); ++ common_config('site', 'name')); ++ ++ $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". ++ "\t".'%3$s'."\n\n". ++ '%4$s'. ++ '%5$s'. ++ '%6$s'. ++ "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". ++ "----\n". ++ "Change your email address or ". ++ "notification options at %8$s\n"), ++ $long_name, ++ common_config('site', 'name'), ++ $other->profileurl, ++ ($other->location) ? ++ sprintf(_("Location: %s\n"), $other->location) : '', ++ ($other->homepage) ? ++ sprintf(_("Homepage: %s\n"), $other->homepage) : '', ++ ($other->bio) ? ++ sprintf(_("Bio: %s\n\n"), $other->bio) : '', ++ common_config('site', 'name'), ++ common_local_url('emailsettings')); ++ +hunk ./lib/mail.php 264 +- mail_send($recipients, $headers, $body); +- } ++ mail_send($recipients, $headers, $body); + } -hunk ./actions/outbox.php 115 --class OutboxAction extends MailboxAction { -- -- function get_title($user, $page) { -- if ($page > 1) { -- $title = sprintf(_("Outbox for %s - page %d"), $user->nickname, $page); -- } else { -- $title = sprintf(_("Outbox for %s"), $user->nickname); +hunk ./lib/mail.php 268 +-function mail_new_incoming_notify($user) { ++/** ++ * notify a user of their new incoming email address ++ * ++ * User's email and incoming fields should already be updated. ++ * ++ * @param User $user user with the new address ++ * ++ * @return void ++ */ ++ ++function mail_new_incoming_notify($user) ++{ ++ $profile = $user->getProfile(); +hunk ./lib/mail.php 282 +- $profile = $user->getProfile(); +- $name = $profile->getBestName(); ++ $name = $profile->getBestName(); +hunk ./lib/mail.php 284 +- $headers['From'] = $user->incomingemail; +- $headers['To'] = $name . ' <' . $user->email . '>'; +- $headers['Subject'] = sprintf(_('New email address for posting to %s'), +- common_config('site', 'name')); ++ $headers['From'] = $user->incomingemail; ++ $headers['To'] = $name . ' <' . $user->email . '>'; ++ $headers['Subject'] = sprintf(_('New email address for posting to %s'), ++ common_config('site', 'name')); +hunk ./lib/mail.php 289 +- $body = sprintf(_("You have a new posting address on %1\$s.\n\n". +- "Send email to %2\$s to post new messages.\n\n". +- "More email instructions at %3\$s.\n\n". +- "Faithfully yours,\n%4\$s"), +- common_config('site', 'name'), +- $user->incomingemail, +- common_local_url('doc', array('title' => 'email')), +- common_config('site', 'name')); ++ $body = sprintf(_("You have a new posting address on %1\$s.\n\n". ++ "Send email to %2\$s to post new messages.\n\n". ++ "More email instructions at %3\$s.\n\n". ++ "Faithfully yours,\n%4\$s"), ++ common_config('site', 'name'), ++ $user->incomingemail, ++ common_local_url('doc', array('title' => 'email')), ++ common_config('site', 'name')); +hunk ./lib/mail.php 298 +- mail_send($user->email, $headers, $body); ++ mail_send($user->email, $headers, $body); +hunk ./lib/mail.php 301 +-function mail_new_incoming_address() { +- $prefix = common_confirmation_code(64); +- $suffix = mail_domain(); +- return $prefix . '@' . $suffix; ++/** ++ * generate a new address for incoming messages ++ * ++ * @todo check the database for uniqueness ++ * ++ * @return string new email address for incoming messages ++ */ ++ ++function mail_new_incoming_address() ++{ ++ $prefix = common_confirmation_code(64); ++ $suffix = mail_domain(); ++ return $prefix . '@' . $suffix; +hunk ./lib/mail.php 316 +-function mail_broadcast_notice_sms($notice) { ++/** ++ * broadcast a notice to all subscribers with SMS notification on ++ * ++ * This function sends SMS messages to all users who have sms addresses; ++ * have sms notification on; and have sms enabled for this particular ++ * subscription. ++ * ++ * @param Notice $notice The notice to broadcast ++ * ++ * @return success flag ++ */ +hunk ./lib/mail.php 328 +- # Now, get users subscribed to this profile ++function mail_broadcast_notice_sms($notice) ++{ ++ // Now, get users subscribed to this profile +hunk ./lib/mail.php 332 +- $user = new User(); ++ $user = new User(); +hunk ./lib/mail.php 334 +- $user->query('SELECT nickname, smsemail, incomingemail ' . +- 'FROM user JOIN subscription ' . +- 'ON user.id = subscription.subscriber ' . +- 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . +- 'AND user.smsemail IS NOT NULL ' . +- 'AND user.smsnotify = 1 ' . ++ $user->query('SELECT nickname, smsemail, incomingemail ' . ++ 'FROM user JOIN subscription ' . ++ 'ON user.id = subscription.subscriber ' . ++ 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . ++ 'AND user.smsemail IS NOT null ' . ++ 'AND user.smsnotify = 1 ' . +hunk ./lib/mail.php 342 +- while ($user->fetch()) { +- common_log(LOG_INFO, +- 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, +- __FILE__); +- $success = mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); +- if (!$success) { +- # XXX: Not sure, but I think that's the right thing to do +- common_log(LOG_WARNING, +- 'Sending notice ' . $notice->id . ' to ' . $user->smsemail . ' FAILED, cancelling.', +- __FILE__); +- return false; - } -- return $title; - } -- -- function get_messages($user, $page) { -- $message = new Message(); -- $message->from_profile = $user->id; -- $message->orderBy('created DESC, id DESC'); -- $message->limit((($page-1)*MESSAGES_PER_PAGE), MESSAGES_PER_PAGE + 1); -+ /** -+ * instructions for using this page -+ * -+ * @return string localised instructions for using the page -+ */ -hunk ./actions/outbox.php 121 -- if ($message->find()) { -- return $message; -- } else { -- return NULL; -- } ++ while ($user->fetch()) { ++ common_log(LOG_INFO, ++ 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, ++ __FILE__); ++ $success = mail_send_sms_notice_address($notice, ++ $user->smsemail, ++ $user->incomingemail); ++ if (!$success) { ++ // XXX: Not sure, but I think that's the right thing to do ++ common_log(LOG_WARNING, ++ 'Sending notice ' . $notice->id . ' to ' . ++ $user->smsemail . ' FAILED, cancelling.', ++ __FILE__); ++ return false; ++ } ++ } +hunk ./lib/mail.php 359 +- $user->free(); +- unset($user); ++ $user->free(); ++ unset($user); +hunk ./lib/mail.php 362 +- return true; ++ return true; +hunk ./lib/mail.php 365 +-function mail_send_sms_notice($notice, $user) { +- return mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); ++/** ++ * send a notice to a user via SMS ++ * ++ * A convenience wrapper around mail_send_sms_notice_address() ++ * ++ * @param Notice $notice notice to send ++ * @param User $user user to receive notice ++ * ++ * @see mail_send_sms_notice_address() ++ * ++ * @return boolean success flag ++ */ ++ ++function mail_send_sms_notice($notice, $user) ++{ ++ return mail_send_sms_notice_address($notice, ++ $user->smsemail, ++ $user->incomingemail); +hunk ./lib/mail.php 385 +-function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) { ++/** ++ * send a notice to an SMS email address from a given address ++ * ++ * We use the user's incoming email address as the "From" address to make ++ * replying to notices easier. ++ * ++ * @param Notice $notice notice to send ++ * @param string $smsemail email address to send to ++ * @param string $incomingemail email address to set as 'from' ++ * ++ * @return boolean success flag ++ */ ++ ++function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) ++{ ++ $to = $nickname . ' <' . $smsemail . '>'; ++ ++ $other = $notice->getProfile(); +hunk ./lib/mail.php 404 +- $to = $nickname . ' <' . $smsemail . '>'; +- $other = $notice->getProfile(); ++ common_log(LOG_INFO, 'Sending notice ' . $notice->id . ++ ' to ' . $smsemail, __FILE__); +hunk ./lib/mail.php 407 +- common_log(LOG_INFO, "Sending notice " . $notice->id . " to " . $smsemail, __FILE__); ++ $headers = array(); +hunk ./lib/mail.php 409 +- $headers = array(); +- $headers['From'] = (isset($incomingemail)) ? $incomingemail : mail_notify_from(); +- $headers['To'] = $to; +- $headers['Subject'] = sprintf(_('%s status'), +- $other->getBestName()); +- $body = $notice->content; ++ $headers['From'] = ($incomingemail) ? $incomingemail : mail_notify_from(); ++ $headers['To'] = $to; ++ $headers['Subject'] = sprintf(_('%s status'), ++ $other->getBestName()); +hunk ./lib/mail.php 414 +- return mail_send($smsemail, $headers, $body); ++ $body = $notice->content; ++ ++ return mail_send($smsemail, $headers, $body); +hunk ./lib/mail.php 419 +-function mail_confirm_sms($code, $nickname, $address) { ++/** ++ * send a message to confirm a claim for an SMS number ++ * ++ * @param string $code confirmation code ++ * @param string $nickname nickname of user claiming number ++ * @param string $address email address to send the confirmation to ++ * ++ * @see common_confirmation_code() ++ * ++ * @return void ++ */ ++ ++function mail_confirm_sms($code, $nickname, $address) ++{ ++ $recipients = $address; +hunk ./lib/mail.php 435 +- $recipients = $address; ++ $headers['From'] = mail_notify_from(); ++ $headers['To'] = $nickname . ' <' . $address . '>'; ++ $headers['Subject'] = _('SMS confirmation'); +hunk ./lib/mail.php 439 +- $headers['From'] = mail_notify_from(); +- $headers['To'] = $nickname . ' <' . $address . '>'; +- $headers['Subject'] = _('SMS confirmation'); ++ // FIXME: I18N +hunk ./lib/mail.php 441 +- $body = "$nickname: confirm you own this phone number with this code:"; +- $body .= "\n\n"; +- $body .= $code; +- $body .= "\n\n"; ++ $body = "$nickname: confirm you own this phone number with this code:"; ++ $body .= "\n\n"; ++ $body .= $code; ++ $body .= "\n\n"; +hunk ./lib/mail.php 446 +- mail_send($recipients, $headers, $body); ++ mail_send($recipients, $headers, $body); +hunk ./lib/mail.php 449 +-function mail_notify_nudge($from, $to) { ++/** ++ * send a mail message to notify a user of a 'nudge' ++ * ++ * @param User $from user nudging ++ * @param User $to user being nudged ++ * ++ * @return boolean success flag ++ */ ++ ++function mail_notify_nudge($from, $to) ++{ +hunk ./lib/mail.php 461 +- $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); ++ $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); +hunk ./lib/mail.php 463 +- $from_profile = $from->getProfile(); ++ $from_profile = $from->getProfile(); +hunk ./lib/mail.php 465 +- $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to these days and is inviting you to post some news.\n\n". +- "So let's hear from you :)\n\n". +- "%3\$s\n\n". +- "Don't reply to this email; it won't get to them.\n\n". +- "With kind regards,\n". +- "%4\$s\n"), +- $from_profile->getBestName(), +- $from->nickname, +- common_local_url('all', array('nickname' => $to->nickname)), +- common_config('site', 'name')); ++ $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ". ++ "these days and is inviting you to post some news.\n\n". ++ "So let's hear from you :)\n\n". ++ "%3\$s\n\n". ++ "Don't reply to this email; it won't get to them.\n\n". ++ "With kind regards,\n". ++ "%4\$s\n"), ++ $from_profile->getBestName(), ++ $from->nickname, ++ common_local_url('all', array('nickname' => $to->nickname)), ++ common_config('site', 'name')); +hunk ./lib/mail.php 477 +- return mail_to_user($to, $subject, $body); ++ return mail_to_user($to, $subject, $body); +hunk ./lib/mail.php 480 +-function mail_notify_message($message, $from=NULL, $to=NULL) { ++/** ++ * send a message to notify a user of a direct message (DM) ++ * ++ * This function checks to see if the recipient wants notification ++ * of DMs and has a configured email address. ++ * ++ * @param Message $message message to notify about ++ * @param User $from user sending message; default to sender ++ * @param User $to user receiving message; default to recipient ++ * ++ * @return boolean success code ++ */ +hunk ./lib/mail.php 493 +- if (is_null($from)) { +- $from = User::staticGet('id', $message->from_profile); - } -- -- function get_message_profile($message) { -- return $message->getTo(); ++function mail_notify_message($message, $from=null, $to=null) ++{ ++ if (is_null($from)) { ++ $from = User::staticGet('id', $message->from_profile); ++ } +hunk ./lib/mail.php 499 +- if (is_null($to)) { +- $to = User::staticGet('id', $message->to_profile); - } -- -- function get_instructions() { -- return _('This is your outbox, which lists private messages you have sent.'); ++ if (is_null($to)) { ++ $to = User::staticGet('id', $message->to_profile); ++ } +hunk ./lib/mail.php 503 +- if (is_null($to->email) || !$to->emailnotifymsg) { +- return true; - } -- -+ function getInstructions() -+ { -+ return _('This is your outbox, which lists private messages you have sent.'); ++ if (is_null($to->email) || !$to->emailnotifymsg) { ++ return true; + } -hunk ./lib/mailbox.php 22 -- * @category Action -+ * @category Message -hunk ./lib/mailbox.php 41 -- * @category Action -+ * @category Message -hunk ./lib/mailbox.php 94 -- $this->show_page($user, $page); -+ $this->showPage($user, $page); -hunk ./lib/mailbox.php 106 -- function get_title($user, $page) -+ function getTitle($user, $page) -hunk ./lib/mailbox.php 117 -- function get_instructions() -+ function getInstructions() -hunk ./lib/mailbox.php 128 -- function show_top() -+ function showTop() -hunk ./lib/mailbox.php 146 -- function show_page($user, $page) -+ function showPage($user, $page) -hunk ./lib/mailbox.php 148 -- common_show_header($this->get_title($user, $page), -+ common_show_header($this->getTitle($user, $page), -hunk ./lib/mailbox.php 150 -- array($this, 'show_top')); -+ array($this, 'showTop')); -hunk ./lib/mailbox.php 152 -- $this->show_box($user, $page); -+ $this->showBox($user, $page); -hunk ./lib/mailbox.php 157 -+ /** -+ * retrieve the messages appropriate for this mailbox -+ * -+ * Does a query for the right messages -+ * -+ * @param User $user The current user -+ * @param int $page The page the user is on -+ * -+ * @return Message data object with stream for messages -+ */ +hunk ./lib/mail.php 508 +- $subject = sprintf(_('New private message from %s'), $from->nickname); ++ $subject = sprintf(_('New private message from %s'), $from->nickname); +hunk ./lib/mail.php 510 +- $from_profile = $from->getProfile(); ++ $from_profile = $from->getProfile(); +hunk ./lib/mail.php 512 +- $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". +- "------------------------------------------------------\n". +- "%3\$s\n". +- "------------------------------------------------------\n\n". +- "You can reply to their message here:\n\n". +- "%4\$s\n\n". +- "Don't reply to this email; it won't get to them.\n\n". +- "With kind regards,\n". +- "%5\$s\n"), +- $from_profile->getBestName(), +- $from->nickname, +- $message->content, +- common_local_url('newmessage', array('to' => $from->id)), +- common_config('site', 'name')); ++ $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". ++ "------------------------------------------------------\n". ++ "%3\$s\n". ++ "------------------------------------------------------\n\n". ++ "You can reply to their message here:\n\n". ++ "%4\$s\n\n". ++ "Don't reply to this email; it won't get to them.\n\n". ++ "With kind regards,\n". ++ "%5\$s\n"), ++ $from_profile->getBestName(), ++ $from->nickname, ++ $message->content, ++ common_local_url('newmessage', array('to' => $from->id)), ++ common_config('site', 'name')); +hunk ./lib/mail.php 528 +- return mail_to_user($to, $subject, $body); ++ return mail_to_user($to, $subject, $body); +hunk ./lib/mail.php 531 +-function mail_notify_fave($other, $user, $notice) { ++/** ++ * notify a user that one of their notices has been chosen as a 'fave' ++ * ++ * Doesn't check that the user has an email address nor if they ++ * want to receive notification of faves. Maybe this happens higher ++ * up the stack...? ++ * ++ * @param User $other The user whose notice was faved ++ * @param User $user The user who faved the notice ++ * @param Notice $notice The notice that was faved ++ * ++ * @return void ++ */ + -+ function getMessages($user, $page) -+ { -+ return null; -+ } ++function mail_notify_fave($other, $user, $notice) ++{ ++ $profile = $user->getProfile(); ++ ++ $bestname = $profile->getBestName(); +hunk ./lib/mail.php 551 +- $profile = $user->getProfile(); +- $bestname = $profile->getBestName(); +hunk ./lib/mail.php 552 +- $subject = sprintf(_('%s added your notice as a favorite'), $bestname); +- $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . +- "In case you forgot, you can see the text of your notice here:\n\n" . +- "%3\$s\n\n" . +- "You can see the list of %1\$s's favorites here:\n\n" . +- "%4\$s\n\n" . +- "Faithfully yours,\n" . +- "%5\$s\n"), +- $bestname, +- common_exact_date($notice->created), +- common_local_url('shownotice', array('notice' => $notice->id)), +- common_local_url('showfavorites', array('nickname' => $user->nickname)), +- common_config('site', 'name')); ++ ++ $subject = sprintf(_('%s added your notice as a favorite'), $bestname); + -hunk ./lib/mailbox.php 184 -- function show_box($user, $page) -+ function showBox($user, $page) -hunk ./lib/mailbox.php 186 -- $message = $this->get_messages($user, $page); -+ $message = $this->getMessages($user, $page); -hunk ./lib/mailbox.php 200 -- $this->show_message($message); -+ $this->showMessage($message); -hunk ./lib/mailbox.php 224 -- function get_message_profile($message) -+ function getMessageProfile($message) -hunk ./lib/mailbox.php 237 -- function show_message($message) -+ function showMessage($message) -hunk ./lib/mailbox.php 242 -- $profile = $this->get_message_profile($message); -+ $profile = $this->getMessageProfile($message); ++ $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" . ++ "%3\$s\n\n" . ++ "You can see the list of %1\$s's favorites here:\n\n" . ++ "%4\$s\n\n" . ++ "Faithfully yours,\n" . ++ "%5\$s\n"), ++ $bestname, ++ common_exact_date($notice->created), ++ common_local_url('shownotice', ++ array('notice' => $notice->id)), ++ common_local_url('showfavorites', ++ array('nickname' => $user->nickname)), ++ common_config('site', 'name')); +hunk ./lib/mail.php 573 +- mail_to_user($other, $subject, $body); ++ mail_to_user($other, $subject, $body); diff --git a/lib/mail.php b/lib/mail.php index c90140d3c..5638ae9bf 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -1,9 +1,12 @@ . + * + * @category Mail + * @package Laconica + * @author Evan Prodromou + * @author Zach Copley + * @author Robin Millette + * @author Sarven Capadisli + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} -require_once('Mail.php'); +require_once 'Mail.php'; -function mail_backend() { - static $backend = NULL; +/** + * return the configured mail backend + * + * Uses the $config array to make a mail backend. Cached so it is safe to call + * more than once. + * + * @return Mail backend + */ - if (!$backend) { - global $config; - $backend = Mail::factory($config['mail']['backend'], - ($config['mail']['params']) ? $config['mail']['params'] : array()); - if (PEAR::isError($backend)) { - common_server_error($backend->getMessage(), 500); - } - } - return $backend; +function mail_backend() +{ + static $backend = null; + + if (!$backend) { + global $config; + $backend = Mail::factory($config['mail']['backend'], + ($config['mail']['params']) ? + $config['mail']['params'] : + array()); + if (PEAR::isError($backend)) { + common_server_error($backend->getMessage(), 500); + } + } + return $backend; } -# XXX: use Mail_Queue... maybe +/** + * send an email to one or more recipients + * + * @param array $recipients array of strings with email addresses of recipients + * @param array $headers array mapping strings to strings for email headers + * @param string $body body of the email + * + * @return boolean success flag + */ -function mail_send($recipients, $headers, $body) { - $backend = mail_backend(); +function mail_send($recipients, $headers, $body) +{ + // XXX: use Mail_Queue... maybe + $backend = mail_backend(); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/plain; charset=UTF-8'; } - assert($backend); # throws an error if it's bad - $sent = $backend->send($recipients, $headers, $body); - if (PEAR::isError($sent)) { - common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); - return false; - } - return true; + assert($backend); // throws an error if it's bad + $sent = $backend->send($recipients, $headers, $body); + if (PEAR::isError($sent)) { + common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); + return false; + } + return true; } -function mail_domain() { - $maildomain = common_config('mail', 'domain'); - if (!$maildomain) { - $maildomain = common_config('site', 'server'); - } - return $maildomain; -} +/** + * returns the configured mail domain + * + * Defaults to the server name. + * + * @return string mail domain, suitable for making email addresses. + */ -function mail_notify_from() { - $notifyfrom = common_config('mail', 'notifyfrom'); - if (!$notifyfrom) { - $domain = mail_domain(); - $notifyfrom = common_config('site', 'name') .' '; - } - return $notifyfrom; +function mail_domain() +{ + $maildomain = common_config('mail', 'domain'); + if (!$maildomain) { + $maildomain = common_config('site', 'server'); + } + return $maildomain; } -function mail_to_user(&$user, $subject, $body, $address=NULL) { - if (!$address) { - $address = $user->email; - } +/** + * returns a good address for sending email from this server + * + * Uses either the configured value or a faked-up value made + * from the mail domain. + * + * @return string notify from address + */ + +function mail_notify_from() +{ + $notifyfrom = common_config('mail', 'notifyfrom'); - $recipients = $address; - $profile = $user->getProfile(); + if (!$notifyfrom) { - $headers['From'] = mail_notify_from(); - $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; - $headers['Subject'] = $subject; + $domain = mail_domain(); - return mail_send($recipients, $headers, $body); + $notifyfrom = common_config('site', 'name') .' '; + } + + return $notifyfrom; } -# For confirming a Jabber address +/** + * sends email to a user + * + * @param User &$user user to send email to + * @param string $subject subject of the email + * @param string $body body of the email + * @param string $address optional specification of email address + * + * @return boolean success flag + */ -function mail_confirm_address($user, $code, $nickname, $address) { +function mail_to_user(&$user, $subject, $body, $address=null) +{ + if (!$address) { + $address = $user->email; + } - $subject = _('Email address confirmation'); + $recipients = $address; + $profile = $user->getProfile(); - $body = sprintf(_("Hey, %s.\n\nSomeone just entered this email address on %s.\n\n" . - "If it was you, and you want to confirm your entry, use the URL below:\n\n\t%s\n\n" . - "If not, just ignore this message.\n\nThanks for your time, \n%s\n") - , $nickname, common_config('site', 'name') - , common_local_url('confirmaddress', array('code' => $code)), common_config('site', 'name')); - return mail_to_user($user, $subject, $body, $address); + $headers['From'] = mail_notify_from(); + $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; + $headers['Subject'] = $subject; + + return mail_send($recipients, $headers, $body); } -function mail_subscribe_notify($listenee, $listener) { - $other = $listener->getProfile(); - mail_subscribe_notify_profile($listenee, $other); +/** + * Send an email to confirm a user's control of an email address + * + * @param User $user User claiming the email address + * @param string $code Confirmation code + * @param string $nickname Nickname of user + * @param string $address email address to confirm + * + * @see common_confirmation_code() + * + * @return success flag + */ + +function mail_confirm_address($user, $code, $nickname, $address) +{ + $subject = _('Email address confirmation'); + + $body = sprintf(_("Hey, %s.\n\n". + "Someone just entered this email address on %s.\n\n" . + "If it was you, and you want to confirm your entry, ". + "use the URL below:\n\n\t%s\n\n" . + "If not, just ignore this message.\n\n". + "Thanks for your time, \n%s\n"), + $nickname, common_config('site', 'name'), + common_local_url('confirmaddress', array('code' => $code)), + common_config('site', 'name')); + return mail_to_user($user, $subject, $body, $address); +} + +/** + * notify a user of subscription by another user + * + * This is just a wrapper around the profile-based version. + * + * @param User $listenee user who is being subscribed to + * @param User $listener user who is subscribing + * + * @see mail_subscribe_notify_profile() + * + * @return void + */ + +function mail_subscribe_notify($listenee, $listener) +{ + $other = $listener->getProfile(); + mail_subscribe_notify_profile($listenee, $other); } -function mail_subscribe_notify_profile($listenee, $other) { - if ($listenee->email && $listenee->emailnotifysub) { - // use the recipients localization +/** + * notify a user of subscription by a profile (remote or local) + * + * This function checks to see if the listenee has an email + * address and wants subscription notices. + * + * @param User $listenee user who's being subscribed to + * @param Profile $other profile of person who's listening + * + * @return void + */ + +function mail_subscribe_notify_profile($listenee, $other) +{ + if ($listenee->email && $listenee->emailnotifysub) { + + // use the recipient's localization common_init_locale($listenee->language); - $profile = $listenee->getProfile(); - $name = $profile->getBestName(); - $long_name = ($other->fullname) ? ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; - $recipients = $listenee->email; - $headers['From'] = mail_notify_from(); - $headers['To'] = $name . ' <' . $listenee->email . '>'; - $headers['Subject'] = sprintf(_('%1$s is now listening to your notices on %2$s.'), + + $profile = $listenee->getProfile(); + + $name = $profile->getBestName(); + + $long_name = ($other->fullname) ? + ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; + + $recipients = $listenee->email; + + $headers['From'] = mail_notify_from(); + $headers['To'] = $name . ' <' . $listenee->email . '>'; + $headers['Subject'] = sprintf(_('%1$s is now listening to '. + 'your notices on %2$s.'), $other->getBestName(), - common_config('site', 'name')); - $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". - "\t".'%3$s'."\n\n". - '%4$s'. - '%5$s'. - '%6$s'. - "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". - "----\n". - "Change your email address or notification options at %8$s"), - $long_name, - common_config('site', 'name'), - $other->profileurl, - ($other->location) ? sprintf(_("Location: %s\n"), $other->location) : '', - ($other->homepage) ? sprintf(_("Homepage: %s\n"), $other->homepage) : '', - ($other->bio) ? sprintf(_("Bio: %s\n\n"), $other->bio) : '', - common_config('site', 'name'), - common_local_url('emailsettings')); + common_config('site', 'name')); + + $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". + "\t".'%3$s'."\n\n". + '%4$s'. + '%5$s'. + '%6$s'. + "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". + "----\n". + "Change your email address or ". + "notification options at %8$s\n"), + $long_name, + common_config('site', 'name'), + $other->profileurl, + ($other->location) ? + sprintf(_("Location: %s\n"), $other->location) : '', + ($other->homepage) ? + sprintf(_("Homepage: %s\n"), $other->homepage) : '', + ($other->bio) ? + sprintf(_("Bio: %s\n\n"), $other->bio) : '', + common_config('site', 'name'), + common_local_url('emailsettings')); + // reset localization common_init_locale(); - mail_send($recipients, $headers, $body); - } + mail_send($recipients, $headers, $body); + } } -function mail_new_incoming_notify($user) { +/** + * notify a user of their new incoming email address + * + * User's email and incoming fields should already be updated. + * + * @param User $user user with the new address + * + * @return void + */ + +function mail_new_incoming_notify($user) +{ + $profile = $user->getProfile(); - $profile = $user->getProfile(); - $name = $profile->getBestName(); + $name = $profile->getBestName(); - $headers['From'] = $user->incomingemail; - $headers['To'] = $name . ' <' . $user->email . '>'; - $headers['Subject'] = sprintf(_('New email address for posting to %s'), - common_config('site', 'name')); + $headers['From'] = $user->incomingemail; + $headers['To'] = $name . ' <' . $user->email . '>'; + $headers['Subject'] = sprintf(_('New email address for posting to %s'), + common_config('site', 'name')); - $body = sprintf(_("You have a new posting address on %1\$s.\n\n". - "Send email to %2\$s to post new messages.\n\n". - "More email instructions at %3\$s.\n\n". - "Faithfully yours,\n%4\$s"), - common_config('site', 'name'), - $user->incomingemail, - common_local_url('doc', array('title' => 'email')), - common_config('site', 'name')); + $body = sprintf(_("You have a new posting address on %1\$s.\n\n". + "Send email to %2\$s to post new messages.\n\n". + "More email instructions at %3\$s.\n\n". + "Faithfully yours,\n%4\$s"), + common_config('site', 'name'), + $user->incomingemail, + common_local_url('doc', array('title' => 'email')), + common_config('site', 'name')); - mail_send($user->email, $headers, $body); + mail_send($user->email, $headers, $body); } -function mail_new_incoming_address() { - $prefix = common_confirmation_code(64); - $suffix = mail_domain(); - return $prefix . '@' . $suffix; +/** + * generate a new address for incoming messages + * + * @todo check the database for uniqueness + * + * @return string new email address for incoming messages + */ + +function mail_new_incoming_address() +{ + $prefix = common_confirmation_code(64); + $suffix = mail_domain(); + return $prefix . '@' . $suffix; } -function mail_broadcast_notice_sms($notice) { +/** + * broadcast a notice to all subscribers with SMS notification on + * + * This function sends SMS messages to all users who have sms addresses; + * have sms notification on; and have sms enabled for this particular + * subscription. + * + * @param Notice $notice The notice to broadcast + * + * @return success flag + */ - # Now, get users subscribed to this profile +function mail_broadcast_notice_sms($notice) +{ + // Now, get users subscribed to this profile - $user = new User(); + $user = new User(); - $user->query('SELECT nickname, smsemail, incomingemail ' . - 'FROM user JOIN subscription ' . - 'ON user.id = subscription.subscriber ' . - 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . - 'AND user.smsemail IS NOT NULL ' . - 'AND user.smsnotify = 1 ' . + $user->query('SELECT nickname, smsemail, incomingemail ' . + 'FROM user JOIN subscription ' . + 'ON user.id = subscription.subscriber ' . + 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . + 'AND user.smsemail IS NOT null ' . + 'AND user.smsnotify = 1 ' . 'AND subscription.sms = 1 '); - while ($user->fetch()) { - common_log(LOG_INFO, - 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, - __FILE__); - $success = mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); - if (!$success) { - # XXX: Not sure, but I think that's the right thing to do - common_log(LOG_WARNING, - 'Sending notice ' . $notice->id . ' to ' . $user->smsemail . ' FAILED, cancelling.', - __FILE__); - return false; - } - } - - $user->free(); - unset($user); - - return true; + while ($user->fetch()) { + common_log(LOG_INFO, + 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, + __FILE__); + $success = mail_send_sms_notice_address($notice, + $user->smsemail, + $user->incomingemail); + if (!$success) { + // XXX: Not sure, but I think that's the right thing to do + common_log(LOG_WARNING, + 'Sending notice ' . $notice->id . ' to ' . + $user->smsemail . ' FAILED, cancelling.', + __FILE__); + return false; + } + } + + $user->free(); + unset($user); + + return true; } -function mail_send_sms_notice($notice, $user) { - return mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); +/** + * send a notice to a user via SMS + * + * A convenience wrapper around mail_send_sms_notice_address() + * + * @param Notice $notice notice to send + * @param User $user user to receive notice + * + * @see mail_send_sms_notice_address() + * + * @return boolean success flag + */ + +function mail_send_sms_notice($notice, $user) +{ + return mail_send_sms_notice_address($notice, + $user->smsemail, + $user->incomingemail); } -function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) { +/** + * send a notice to an SMS email address from a given address + * + * We use the user's incoming email address as the "From" address to make + * replying to notices easier. + * + * @param Notice $notice notice to send + * @param string $smsemail email address to send to + * @param string $incomingemail email address to set as 'from' + * + * @return boolean success flag + */ - $to = $nickname . ' <' . $smsemail . '>'; - $other = $notice->getProfile(); +function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) +{ + $to = $nickname . ' <' . $smsemail . '>'; - common_log(LOG_INFO, "Sending notice " . $notice->id . " to " . $smsemail, __FILE__); + $other = $notice->getProfile(); - $headers = array(); - $headers['From'] = (isset($incomingemail)) ? $incomingemail : mail_notify_from(); - $headers['To'] = $to; - $headers['Subject'] = sprintf(_('%s status'), - $other->getBestName()); - $body = $notice->content; + common_log(LOG_INFO, 'Sending notice ' . $notice->id . + ' to ' . $smsemail, __FILE__); - return mail_send($smsemail, $headers, $body); + $headers = array(); + + $headers['From'] = ($incomingemail) ? $incomingemail : mail_notify_from(); + $headers['To'] = $to; + $headers['Subject'] = sprintf(_('%s status'), + $other->getBestName()); + + $body = $notice->content; + + return mail_send($smsemail, $headers, $body); } -function mail_confirm_sms($code, $nickname, $address) { +/** + * send a message to confirm a claim for an SMS number + * + * @param string $code confirmation code + * @param string $nickname nickname of user claiming number + * @param string $address email address to send the confirmation to + * + * @see common_confirmation_code() + * + * @return void + */ - $recipients = $address; +function mail_confirm_sms($code, $nickname, $address) +{ + $recipients = $address; - $headers['From'] = mail_notify_from(); - $headers['To'] = $nickname . ' <' . $address . '>'; - $headers['Subject'] = _('SMS confirmation'); + $headers['From'] = mail_notify_from(); + $headers['To'] = $nickname . ' <' . $address . '>'; + $headers['Subject'] = _('SMS confirmation'); - $body = "$nickname: confirm you own this phone number with this code:"; - $body .= "\n\n"; - $body .= $code; - $body .= "\n\n"; + // FIXME: I18N - mail_send($recipients, $headers, $body); + $body = "$nickname: confirm you own this phone number with this code:"; + $body .= "\n\n"; + $body .= $code; + $body .= "\n\n"; + + mail_send($recipients, $headers, $body); } -function mail_notify_nudge($from, $to) { +/** + * send a mail message to notify a user of a 'nudge' + * + * @param User $from user nudging + * @param User $to user being nudged + * + * @return boolean success flag + */ + +function mail_notify_nudge($from, $to) +{ common_init_locale($to->language); - $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); - - $from_profile = $from->getProfile(); - - $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to these days and is inviting you to post some news.\n\n". - "So let's hear from you :)\n\n". - "%3\$s\n\n". - "Don't reply to this email; it won't get to them.\n\n". - "With kind regards,\n". - "%4\$s\n"), - $from_profile->getBestName(), - $from->nickname, - common_local_url('all', array('nickname' => $to->nickname)), - common_config('site', 'name')); + $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); + + $from_profile = $from->getProfile(); + + $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ". + "these days and is inviting you to post some news.\n\n". + "So let's hear from you :)\n\n". + "%3\$s\n\n". + "Don't reply to this email; it won't get to them.\n\n". + "With kind regards,\n". + "%4\$s\n"), + $from_profile->getBestName(), + $from->nickname, + common_local_url('all', array('nickname' => $to->nickname)), + common_config('site', 'name')); common_init_locale(); - return mail_to_user($to, $subject, $body); + return mail_to_user($to, $subject, $body); } -function mail_notify_message($message, $from=NULL, $to=NULL) { +/** + * send a message to notify a user of a direct message (DM) + * + * This function checks to see if the recipient wants notification + * of DMs and has a configured email address. + * + * @param Message $message message to notify about + * @param User $from user sending message; default to sender + * @param User $to user receiving message; default to recipient + * + * @return boolean success code + */ - if (is_null($from)) { - $from = User::staticGet('id', $message->from_profile); - } +function mail_notify_message($message, $from=null, $to=null) +{ + if (is_null($from)) { + $from = User::staticGet('id', $message->from_profile); + } - if (is_null($to)) { - $to = User::staticGet('id', $message->to_profile); - } + if (is_null($to)) { + $to = User::staticGet('id', $message->to_profile); + } - if (is_null($to->email) || !$to->emailnotifymsg) { - return true; - } + if (is_null($to->email) || !$to->emailnotifymsg) { + return true; + } common_init_locale($to->language); - $subject = sprintf(_('New private message from %s'), $from->nickname); - - $from_profile = $from->getProfile(); - - $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". - "------------------------------------------------------\n". - "%3\$s\n". - "------------------------------------------------------\n\n". - "You can reply to their message here:\n\n". - "%4\$s\n\n". - "Don't reply to this email; it won't get to them.\n\n". - "With kind regards,\n". - "%5\$s\n"), - $from_profile->getBestName(), - $from->nickname, - $message->content, - common_local_url('newmessage', array('to' => $from->id)), - common_config('site', 'name')); + $subject = sprintf(_('New private message from %s'), $from->nickname); + + $from_profile = $from->getProfile(); + + $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". + "------------------------------------------------------\n". + "%3\$s\n". + "------------------------------------------------------\n\n". + "You can reply to their message here:\n\n". + "%4\$s\n\n". + "Don't reply to this email; it won't get to them.\n\n". + "With kind regards,\n". + "%5\$s\n"), + $from_profile->getBestName(), + $from->nickname, + $message->content, + common_local_url('newmessage', array('to' => $from->id)), + common_config('site', 'name')); common_init_locale(); - return mail_to_user($to, $subject, $body); + return mail_to_user($to, $subject, $body); } -function mail_notify_fave($other, $user, $notice) { +/** + * notify a user that one of their notices has been chosen as a 'fave' + * + * Doesn't check that the user has an email address nor if they + * want to receive notification of faves. Maybe this happens higher + * up the stack...? + * + * @param User $other The user whose notice was faved + * @param User $user The user who faved the notice + * @param Notice $notice The notice that was faved + * + * @return void + */ + +function mail_notify_fave($other, $user, $notice) +{ + $profile = $user->getProfile(); + + $bestname = $profile->getBestName(); - $profile = $user->getProfile(); - $bestname = $profile->getBestName(); common_init_locale($other->language); - $subject = sprintf(_('%s added your notice as a favorite'), $bestname); - $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . - "In case you forgot, you can see the text of your notice here:\n\n" . - "%3\$s\n\n" . - "You can see the list of %1\$s's favorites here:\n\n" . - "%4\$s\n\n" . - "Faithfully yours,\n" . - "%5\$s\n"), - $bestname, - common_exact_date($notice->created), - common_local_url('shownotice', array('notice' => $notice->id)), - common_local_url('showfavorites', array('nickname' => $user->nickname)), - common_config('site', 'name')); + + $subject = sprintf(_('%s added your notice as a favorite'), $bestname); + + $body = sprintf(_("%1\$s just added your notice from %2\$s". + " as one of their favorites.\n\n" . + "In case you forgot, you can see the text". + " of your notice here:\n\n" . + "%3\$s\n\n" . + "You can see the list of %1\$s's favorites here:\n\n" . + "%4\$s\n\n" . + "Faithfully yours,\n" . + "%5\$s\n"), + $bestname, + common_exact_date($notice->created), + common_local_url('shownotice', + array('notice' => $notice->id)), + common_local_url('showfavorites', + array('nickname' => $user->nickname)), + common_config('site', 'name')); common_init_locale(); - mail_to_user($other, $subject, $body); + mail_to_user($other, $subject, $body); } -- cgit v1.2.3-54-g00ecf From 20af1927967592e56189f48d88d82fad989870ca Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Tue, 23 Dec 2008 14:08:51 -0500 Subject: bring lib/noticelist.php into line with PEAR code standards darcs-hash:20081223190851-84dde-ecad63595159aca2ae014325c9af29a9ace21c3d.gz --- _darcs/inventory | 4 +- ...dde-ecad63595159aca2ae014325c9af29a9ace21c3d.gz | Bin 0 -> 4424 bytes _darcs/pristine/actions/showstream.php | 4 +- _darcs/pristine/lib/noticelist.php | 567 ++++++--- _darcs/tentative_pristine | 1228 +++++++++----------- actions/showstream.php | 4 +- lib/noticelist.php | 567 ++++++--- 7 files changed, 1340 insertions(+), 1034 deletions(-) create mode 100644 _darcs/patches/20081223190851-84dde-ecad63595159aca2ae014325c9af29a9ace21c3d.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index 167d793d7..b1d1b1e70 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -45,4 +45,6 @@ Evan Prodromou **20081222201304 ] [reformat and document lib/mail.php for phpcs conformance -Evan Prodromou **20081223173330] \ No newline at end of file +Evan Prodromou **20081223173330] +[bring lib/noticelist.php into line with PEAR code standards +Evan Prodromou **20081223190851] \ No newline at end of file diff --git a/_darcs/patches/20081223190851-84dde-ecad63595159aca2ae014325c9af29a9ace21c3d.gz b/_darcs/patches/20081223190851-84dde-ecad63595159aca2ae014325c9af29a9ace21c3d.gz new file mode 100644 index 000000000..7f3254cbb Binary files /dev/null and b/_darcs/patches/20081223190851-84dde-ecad63595159aca2ae014325c9af29a9ace21c3d.gz differ diff --git a/_darcs/pristine/actions/showstream.php b/_darcs/pristine/actions/showstream.php index 6d6225661..61fdec3fe 100644 --- a/_darcs/pristine/actions/showstream.php +++ b/_darcs/pristine/actions/showstream.php @@ -438,13 +438,13 @@ class ShowstreamAction extends StreamAction { # We don't show the author for a profile, since we already know who it is! class ProfileNoticeList extends NoticeList { - function new_list_item($notice) { + function newListItem($notice) { return new ProfileNoticeListItem($notice); } } class ProfileNoticeListItem extends NoticeListItem { - function show_author() { + function showAuthor() { return; } } diff --git a/_darcs/pristine/lib/noticelist.php b/_darcs/pristine/lib/noticelist.php index 415c062e4..c9344a716 100644 --- a/_darcs/pristine/lib/noticelist.php +++ b/_darcs/pristine/lib/noticelist.php @@ -1,173 +1,366 @@ . + * along with this program. If not, see . + * + * @category UI + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} + +/** + * widget for displaying a list of notices + * + * There are a number of actions that display a list of notices, in + * reverse chronological order. This widget abstracts out most of the + * code for UI for notice lists. It's overridden to hide some + * data for e.g. the profile page. + * + * @category UI + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see Notice + * @see StreamAction + * @see NoticeListItem + * @see ProfileNoticeList + */ -class NoticeList { +class NoticeList +{ + /** the current stream of notices being displayed. */ - var $notice = NULL; + var $notice = null; - function __construct($notice) { + /** + * constructor + * + * @param Notice $notice stream of notices from DB_DataObject + */ + + function __construct($notice) + { $this->notice = $notice; } - function show() { + /** + * show the list of notices + * + * "Uses up" the stream by looping through it. So, probably can't + * be called twice on the same list. + * + * @return int count of notices listed. + */ - common_element_start('ul', array('id' => 'notices')); + function show() + { + common_element_start('ul', array('id' => 'notices')); - $cnt = 0; + $cnt = 0; - while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { - $cnt++; + while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { + $cnt++; - if ($cnt > NOTICES_PER_PAGE) { - break; - } + if ($cnt > NOTICES_PER_PAGE) { + break; + } - $item = $this->new_list_item($this->notice); + $item = $this->newListItem($this->notice); $item->show(); - } + } - common_element_end('ul'); + common_element_end('ul'); return $cnt; - } + } - function new_list_item($notice) { + /** + * returns a new list item for the current notice + * + * Recipe (factory?) method; overridden by sub-classes to give + * a different list item class. + * + * @param Notice $notice the current notice + * + * @return NoticeListItem a list item for displaying the notice + */ + + function newListItem($notice) + { return new NoticeListItem($notice); } } -class NoticeListItem { +/** + * widget for displaying a single notice + * + * This widget has the core smarts for showing a single notice: what to display, + * where, and under which circumstances. Its key method is show(); this is a recipe + * that calls all the other show*() methods to build up a single notice. The + * ProfileNoticeListItem subclass, for example, overrides showAuthor() to skip + * author info (since that's implicit by the data in the page). + * + * @category UI + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see NoticeList + * @see ProfileNoticeListItem + */ + +class NoticeListItem +{ + /** The notice this item will show. */ - var $notice = NULL; - var $profile = NULL; + var $notice = null; - function __construct($notice) { - $this->notice = $notice; - $this->profile = $notice->getProfile(); - } - - function show() { - $this->show_start(); - $this->show_fave_form(); - $this->show_author(); - $this->show_content(); - $this->show_start_time_section(); - $this->show_notice_link(); - $this->show_notice_source(); - $this->show_reply_to(); - $this->show_reply_link(); - $this->show_delete_link(); - $this->show_end_time_section(); - $this->show_end(); - } - - function show_start() { - # XXX: RDFa - common_element_start('li', array('class' => 'notice_single hentry', - 'id' => 'notice-' . $this->notice->id)); - } - - function show_fave_form() { + /** The profile of the author of the notice, extracted once for convenience. */ + + var $profile = null; + + /** + * constructor + * + * Also initializes the profile attribute. + * + * @param Notice $notice The notice we'll display + */ + + function __construct($notice) + { + $this->notice = $notice; + $this->profile = $notice->getProfile(); + } + + /** + * recipe function for displaying a single notice. + * + * This uses all the other methods to correctly display a notice. Override + * it or one of the others to fine-tune the output. + * + * @return void + */ + + function show() + { + $this->showStart(); + $this->showFaveForm(); + $this->showAuthor(); + $this->showContent(); + $this->startTimeSection(); + $this->showNoticeLink(); + $this->showNoticeSource(); + $this->showReplyTo(); + $this->showReplyLink(); + $this->showDeleteLink(); + $this->endTimeSection(); + $this->showEnd(); + } + + /** + * start a single notice. + * + * @return void + */ + + function showStart() + { + // XXX: RDFa + common_element_start('li', array('class' => 'notice_single hentry', + 'id' => 'notice-' . $this->notice->id)); + } + + /** + * show the "favorite" form + * + * @return void + */ + + function showFaveForm() + { $user = common_current_user(); - if ($user) { - if ($user->hasFave($this->notice)) { - common_disfavor_form($this->notice); - } else { - common_favor_form($this->notice); - } - } - } - - function show_author() { - common_element_start('span', 'vcard author'); - $this->show_avatar(); - $this->show_nickname(); - common_element_end('span'); - } - - function show_avatar() { - $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); - common_element_start('a', array('href' => $this->profile->profileurl)); - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), - 'class' => 'avatar stream photo', - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'alt' => - ($this->profile->fullname) ? $this->profile->fullname : - $this->profile->nickname)); - common_element_end('a'); - } - - function show_nickname() { - common_element('a', array('href' => $this->profile->profileurl, - 'class' => 'nickname fn url'), - $this->profile->nickname); - } - - function show_content() { - # FIXME: URL, image, video, audio - common_element_start('p', array('class' => 'content entry-title')); - if ($this->notice->rendered) { - common_raw($this->notice->rendered); - } else { - # XXX: may be some uncooked notices in the DB, - # we cook them right now. This should probably disappear in future - # versions (>> 0.4.x) - common_raw(common_render_content($this->notice->content, $this->notice)); - } - common_element_end('p'); - } - - function show_start_time_section() { - common_element_start('p', 'time'); - } - - function show_notice_link() { - $noticeurl = common_local_url('shownotice', array('notice' => $this->notice->id)); - # XXX: we need to figure this out better. Is this right? - if (strcmp($this->notice->uri, $noticeurl) != 0 && preg_match('/^http/', $this->notice->uri)) { - $noticeurl = $this->notice->uri; - } - common_element_start('a', array('class' => 'permalink', - 'rel' => 'bookmark', - 'href' => $noticeurl)); - common_element('abbr', array('class' => 'published', - 'title' => common_date_iso8601($this->notice->created)), - common_date_string($this->notice->created)); - common_element_end('a'); - } - - function show_notice_source() { - if ($this->notice->source) { - common_element('span', null, _(' from ')); + if ($user) { + if ($user->hasFave($this->notice)) { + common_disfavor_form($this->notice); + } else { + common_favor_form($this->notice); + } + } + } + + /** + * show the author of a notice + * + * By default, this shows the avatar and (linked) nickname of the author. + * + * @return void + */ + + function showAuthor() + { + common_element_start('span', 'vcard author'); + $this->showAvatar(); + $this->showNickname(); + common_element_end('span'); + } + + /** + * show the avatar of the notice's author + * + * This will use the default avatar if no avatar is assigned for the author. + * It makes a link to the author's profile. + * + * @return void + */ + + function showAvatar() + { + $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); + common_element_start('a', array('href' => $this->profile->profileurl)); + common_element('img', array('src' => ($avatar) ? + common_avatar_display_url($avatar) : + common_default_avatar(AVATAR_STREAM_SIZE), + 'class' => 'avatar stream photo', + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'alt' => + ($this->profile->fullname) ? + $this->profile->fullname : + $this->profile->nickname)); + common_element_end('a'); + } + + /** + * show the nickname of the author + * + * Links to the author's profile page + * + * @return void + */ + + function showNickname() + { + common_element('a', array('href' => $this->profile->profileurl, + 'class' => 'nickname fn url'), + $this->profile->nickname); + } + + /** + * show the content of the notice + * + * Shows the content of the notice. This is pre-rendered for efficiency + * at save time. Some very old notices might not be pre-rendered, so + * they're rendered on the spot. + * + * @return void + */ + + function showContent() + { + // FIXME: URL, image, video, audio + common_element_start('p', array('class' => 'content entry-title')); + if ($this->notice->rendered) { + common_raw($this->notice->rendered); + } else { + // XXX: may be some uncooked notices in the DB, + // we cook them right now. This should probably disappear in future + // versions (>> 0.4.x) + common_raw(common_render_content($this->notice->content, $this->notice)); + } + common_element_end('p'); + } + + /** + * show the "time" section of a notice + * + * This is the greyed-out section that appears beneath the content, including + * links to delete or reply to the notice. Probably should be called something + * else. + * + * @return void + */ + + function startTimeSection() + { + common_element_start('p', 'time'); + } + + /** + * show the link to the main page for the notice + * + * Displays a link to the page for a notice, with "relative" time. Tries to + * get remote notice URLs correct, but doesn't always succeed. + * + * @return void + */ + + function showNoticeLink() + { + $noticeurl = common_local_url('shownotice', + array('notice' => $this->notice->id)); + // XXX: we need to figure this out better. Is this right? + if (strcmp($this->notice->uri, $noticeurl) != 0 && + preg_match('/^http/', $this->notice->uri)) { + $noticeurl = $this->notice->uri; + } + common_element_start('a', array('class' => 'permalink', + 'rel' => 'bookmark', + 'href' => $noticeurl)); + $dt = common_date_iso8601($this->notice->created); + common_element('abbr', array('class' => 'published', + 'title' => $dt), + common_date_string($this->notice->created)); + common_element_end('a'); + } + + /** + * 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. + * + * @return void + */ + + function showNoticeSource() + { + if ($this->notice->source) { + common_element('span', null, _(' from ')); $source_name = _($this->notice->source); switch ($this->notice->source) { - case 'web': - case 'xmpp': - case 'mail': - case 'omb': - case 'api': + case 'web': + case 'xmpp': + case 'mail': + case 'omb': + case 'api': common_element('span', 'noticesource', $source_name); break; - default: + default: $ns = Notice_source::staticGet($this->notice->source); if ($ns) { common_element('a', array('href' => $ns->url), @@ -177,48 +370,98 @@ class NoticeListItem { } break; } - } + } } - function show_reply_to() { - if ($this->notice->reply_to) { - $replyurl = common_local_url('shownotice', array('notice' => $this->notice->reply_to)); - common_text(' ('); - common_element('a', array('class' => 'inreplyto', - 'href' => $replyurl), - _('in reply to...')); - common_text(')'); - } + /** + * show link to notice this notice is a reply to + * + * If this notice is a reply, show a link to the notice it is replying to. The + * heavy lifting for figuring out replies happens at save time. + * + * @return void + */ + + function showReplyTo() + { + if ($this->notice->reply_to) { + $replyurl = common_local_url('shownotice', + array('notice' => $this->notice->reply_to)); + common_text(' ('); + common_element('a', array('class' => 'inreplyto', + 'href' => $replyurl), + _('in reply to...')); + common_text(')'); + } } - function show_reply_link() { - common_element_start('a', - array('href' => common_local_url('newnotice', - array('replyto' => $this->profile->nickname)), - 'onclick' => 'return doreply("'.$this->profile->nickname.'", '.$this->notice->id.');', - 'title' => _('reply'), - 'class' => 'replybutton')); - common_raw(' →'); - common_element_end('a'); + /** + * show a link to reply to the current notice + * + * Should either do the reply in the current notice form (if available), or + * link out to the notice-posting form. A little flakey, doesn't always work. + * + * @return void + */ + + function showReplyLink() + { + $reply_url = common_local_url('newnotice', + array('replyto' => $this->profile->nickname)); + + $reply_js = + 'return doreply("'.$this->profile->nickname.'",'.$this->notice->id.');'; + + common_element_start('a', + array('href' => $reply_url, + 'onclick' => $reply_js, + 'title' => _('reply'), + 'class' => 'replybutton')); + common_raw(' →'); + common_element_end('a'); } - function show_delete_link() { + /** + * if the user is the author, let them delete the notice + * + * @return void + */ + + function showDeleteLink() + { $user = common_current_user(); - if ($user && $this->notice->profile_id == $user->id) { - $deleteurl = common_local_url('deletenotice', array('notice' => $this->notice->id)); - common_element_start('a', array('class' => 'deletenotice', - 'href' => $deleteurl, - 'title' => _('delete'))); - common_raw(' ×'); - common_element_end('a'); - } + if ($user && $this->notice->profile_id == $user->id) { + $deleteurl = common_local_url('deletenotice', + array('notice' => $this->notice->id)); + common_element_start('a', array('class' => 'deletenotice', + 'href' => $deleteurl, + 'title' => _('delete'))); + common_raw(' ×'); + common_element_end('a'); + } } - function show_end_time_section() { - common_element_end('p'); + /** + * end the time section + * + * @return void + */ + + function endTimeSection() + { + common_element_end('p'); } - function show_end() { - common_element_end('li'); + /** + * finish the notice + * + * Close the last elements in the notice list item + * + * @return void + */ + + function showEnd() + { + common_element_end('li'); } } diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index 8ce5499a9..e7d3612c8 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,758 +1,576 @@ -hunk ./lib/mail.php 2 +hunk ./actions/showstream.php 441 +- function new_list_item($notice) { ++ function newListItem($notice) { +hunk ./actions/showstream.php 447 +- function show_author() { ++ function showAuthor() { +hunk ./lib/noticelist.php 2 -/* - * Laconica - a distributed open-source microblogging tool - * Copyright (C) 2008, Controlez-Vous, Inc. +/** + * Laconica, the distributed open-source microblogging tool -hunk ./lib/mail.php 5 +hunk ./lib/noticelist.php 5 - * This program is free software: you can redistribute it and/or modify + * utilities for sending email + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./lib/mail.php 21 -+ * -+ * @category Mail +hunk ./lib/noticelist.php 16 +- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +hunk ./lib/noticelist.php 20 +- * along with this program. If not, see . ++ * along with this program. If not, see . ++ * ++ * @category UI + * @package Laconica + * @author Evan Prodromou -+ * @author Zach Copley -+ * @author Robin Millette -+ * @author Sarven Capadisli + * @copyright 2008 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/ -hunk ./lib/mail.php 33 --if (!defined('LACONICA')) { exit(1); } ++ */ ++ +if (!defined('LACONICA')) { + exit(1); +} -hunk ./lib/mail.php 37 --require_once('Mail.php'); -+require_once 'Mail.php'; + +/** -+ * return the configured mail backend -+ * -+ * Uses the $config array to make a mail backend. Cached so it is safe to call -+ * more than once. -+ * -+ * @return Mail backend -+ */ -hunk ./lib/mail.php 48 --function mail_backend() { -- static $backend = NULL; -+function mail_backend() ++ * widget for displaying a list of notices ++ * ++ * There are a number of actions that display a list of notices, in ++ * reverse chronological order. This widget abstracts out most of the ++ * code for UI for notice lists. It's overridden to hide some ++ * data for e.g. the profile page. ++ * ++ * @category UI ++ * @package Laconica ++ * @author Evan Prodromou ++ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 ++ * @link http://laconi.ca/ ++ * @see Notice ++ * @see StreamAction ++ * @see NoticeListItem ++ * @see ProfileNoticeList +hunk ./lib/noticelist.php 53 +-if (!defined('LACONICA')) { exit(1); } ++class NoticeList +{ -+ static $backend = null; -hunk ./lib/mail.php 52 -- if (!$backend) { -- global $config; -- $backend = Mail::factory($config['mail']['backend'], -- ($config['mail']['params']) ? $config['mail']['params'] : array()); -- if (PEAR::isError($backend)) { -- common_server_error($backend->getMessage(), 500); ++ /** the current stream of notices being displayed. */ +hunk ./lib/noticelist.php 57 +-class NoticeList { ++ var $notice = null; +hunk ./lib/noticelist.php 59 +- var $notice = NULL; ++ /** ++ * constructor ++ * ++ * @param Notice $notice stream of notices from DB_DataObject ++ */ +hunk ./lib/noticelist.php 65 +- function __construct($notice) { ++ function __construct($notice) ++ { +hunk ./lib/noticelist.php 70 +- function show() { ++ /** ++ * show the list of notices ++ * ++ * "Uses up" the stream by looping through it. So, probably can't ++ * be called twice on the same list. ++ * ++ * @return int count of notices listed. ++ */ +hunk ./lib/noticelist.php 79 +- common_element_start('ul', array('id' => 'notices')); ++ function show() ++ { ++ common_element_start('ul', array('id' => 'notices')); +hunk ./lib/noticelist.php 83 +- $cnt = 0; ++ $cnt = 0; +hunk ./lib/noticelist.php 85 +- while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { +- $cnt++; ++ while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { ++ $cnt++; +hunk ./lib/noticelist.php 88 +- if ($cnt > NOTICES_PER_PAGE) { +- break; +- } ++ if ($cnt > NOTICES_PER_PAGE) { ++ break; ++ } +hunk ./lib/noticelist.php 92 +- $item = $this->new_list_item($this->notice); ++ $item = $this->newListItem($this->notice); +hunk ./lib/noticelist.php 94 - } -- } -- return $backend; -+ if (!$backend) { -+ global $config; -+ $backend = Mail::factory($config['mail']['backend'], -+ ($config['mail']['params']) ? -+ $config['mail']['params'] : -+ array()); -+ if (PEAR::isError($backend)) { -+ common_server_error($backend->getMessage(), 500); + } -+ } -+ return $backend; -hunk ./lib/mail.php 65 --# XXX: use Mail_Queue... maybe -+/** -+ * send an email to one or more recipients -+ * -+ * @param array $recipients array of strings with email addresses of recipients -+ * @param array $headers array mapping strings to strings for email headers -+ * @param string $body body of the email -+ * -+ * @return boolean success flag -+ */ -hunk ./lib/mail.php 75 --function mail_send($recipients, $headers, $body) { -- $backend = mail_backend(); -+function mail_send($recipients, $headers, $body) -+{ -+ // XXX: use Mail_Queue... maybe -+ $backend = mail_backend(); -hunk ./lib/mail.php 82 -- assert($backend); # throws an error if it's bad -- $sent = $backend->send($recipients, $headers, $body); -- if (PEAR::isError($sent)) { -- common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); -- return false; -- } -- return true; -+ assert($backend); // throws an error if it's bad -+ $sent = $backend->send($recipients, $headers, $body); -+ if (PEAR::isError($sent)) { -+ common_log(LOG_ERR, 'Email error: ' . $sent->getMessage()); -+ return false; -+ } -+ return true; -hunk ./lib/mail.php 91 --function mail_domain() { -- $maildomain = common_config('mail', 'domain'); -- if (!$maildomain) { -- $maildomain = common_config('site', 'server'); +hunk ./lib/noticelist.php 96 +- common_element_end('ul'); ++ common_element_end('ul'); +hunk ./lib/noticelist.php 99 - } -- return $maildomain; --} -+/** -+ * returns the configured mail domain -+ * -+ * Defaults to the server name. -+ * -+ * @return string mail domain, suitable for making email addresses. -+ */ -hunk ./lib/mail.php 99 --function mail_notify_from() { -- $notifyfrom = common_config('mail', 'notifyfrom'); -- if (!$notifyfrom) { -- $domain = mail_domain(); -- $notifyfrom = common_config('site', 'name') .' '; -- } -- return $notifyfrom; -+function mail_domain() -+{ -+ $maildomain = common_config('mail', 'domain'); -+ if (!$maildomain) { -+ $maildomain = common_config('site', 'server'); -+ } -+ return $maildomain; -hunk ./lib/mail.php 108 --function mail_to_user(&$user, $subject, $body, $address=NULL) { -- if (!$address) { -- $address = $user->email; -- } -+/** -+ * returns a good address for sending email from this server -+ * -+ * Uses either the configured value or a faked-up value made -+ * from the mail domain. -+ * -+ * @return string notify from address -+ */ -hunk ./lib/mail.php 117 -- $recipients = $address; -- $profile = $user->getProfile(); -+function mail_notify_from() -+{ -+ $notifyfrom = common_config('mail', 'notifyfrom'); -hunk ./lib/mail.php 121 -- $headers['From'] = mail_notify_from(); -- $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; -- $headers['Subject'] = $subject; -+ if (!$notifyfrom) { -hunk ./lib/mail.php 123 -- return mail_send($recipients, $headers, $body); -+ $domain = mail_domain(); -+ -+ $notifyfrom = common_config('site', 'name') .' '; + } + -+ return $notifyfrom; -hunk ./lib/mail.php 131 --# For confirming a Jabber address ++ /** ++ * returns a new list item for the current notice ++ * ++ * Recipe (factory?) method; overridden by sub-classes to give ++ * a different list item class. ++ * ++ * @param Notice $notice the current notice ++ * ++ * @return NoticeListItem a list item for displaying the notice ++ */ +hunk ./lib/noticelist.php 112 +- function new_list_item($notice) { ++ function newListItem($notice) ++ { +hunk ./lib/noticelist.php 118 +-class NoticeListItem { +/** -+ * sends email to a user -+ * -+ * @param User &$user user to send email to -+ * @param string $subject subject of the email -+ * @param string $body body of the email -+ * @param string $address optional specification of email address -+ * -+ * @return boolean success flag ++ * widget for displaying a single notice ++ * ++ * This widget has the core smarts for showing a single notice: what to display, ++ * where, and under which circumstances. Its key method is show(); this is a recipe ++ * that calls all the other show*() methods to build up a single notice. The ++ * ProfileNoticeListItem subclass, for example, overrides showAuthor() to skip ++ * author info (since that's implicit by the data in the page). ++ * ++ * @category UI ++ * @package Laconica ++ * @author Evan Prodromou ++ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 ++ * @link http://laconi.ca/ ++ * @see NoticeList ++ * @see ProfileNoticeListItem + */ + -+function mail_to_user(&$user, $subject, $body, $address=null) ++class NoticeListItem +{ -+ if (!$address) { -+ $address = $user->email; -+ } -hunk ./lib/mail.php 148 --function mail_confirm_address($user, $code, $nickname, $address) { -+ $recipients = $address; -+ $profile = $user->getProfile(); -hunk ./lib/mail.php 151 -- $subject = _('Email address confirmation'); -+ $headers['From'] = mail_notify_from(); -+ $headers['To'] = $profile->getBestName() . ' <' . $address . '>'; -+ $headers['Subject'] = $subject; -hunk ./lib/mail.php 155 -- $body = sprintf(_("Hey, %s.\n\nSomeone just entered this email address on %s.\n\n" . -- "If it was you, and you want to confirm your entry, use the URL below:\n\n\t%s\n\n" . -- "If not, just ignore this message.\n\nThanks for your time, \n%s\n") -- , $nickname, common_config('site', 'name') -- , common_local_url('confirmaddress', array('code' => $code)), common_config('site', 'name')); -- return mail_to_user($user, $subject, $body, $address); -+ return mail_send($recipients, $headers, $body); -hunk ./lib/mail.php 158 --function mail_subscribe_notify($listenee, $listener) { -- $other = $listener->getProfile(); -- mail_subscribe_notify_profile($listenee, $other); -+/** -+ * Send an email to confirm a user's control of an email address -+ * -+ * @param User $user User claiming the email address -+ * @param string $code Confirmation code -+ * @param string $nickname Nickname of user -+ * @param string $address email address to confirm -+ * -+ * @see common_confirmation_code() -+ * -+ * @return success flag -+ */ ++ /** The notice this item will show. */ +hunk ./lib/noticelist.php 140 +- var $notice = NULL; +- var $profile = NULL; ++ var $notice = null; +hunk ./lib/noticelist.php 142 +- function __construct($notice) { +- $this->notice = $notice; +- $this->profile = $notice->getProfile(); ++ /** The profile of the author of the notice, extracted once for convenience. */ + -+function mail_confirm_address($user, $code, $nickname, $address) -+{ -+ $subject = _('Email address confirmation'); ++ var $profile = null; + -+ $body = sprintf(_("Hey, %s.\n\n". -+ "Someone just entered this email address on %s.\n\n" . -+ "If it was you, and you want to confirm your entry, ". -+ "use the URL below:\n\n\t%s\n\n" . -+ "If not, just ignore this message.\n\n". -+ "Thanks for your time, \n%s\n"), -+ $nickname, common_config('site', 'name'), -+ common_local_url('confirmaddress', array('code' => $code)), -+ common_config('site', 'name')); -+ return mail_to_user($user, $subject, $body, $address); -hunk ./lib/mail.php 187 --function mail_subscribe_notify_profile($listenee, $other) { -- if ($listenee->email && $listenee->emailnotifysub) { -- // use the recipients localization -+/** -+ * notify a user of subscription by another user -+ * -+ * This is just a wrapper around the profile-based version. -+ * -+ * @param User $listenee user who is being subscribed to -+ * @param User $listener user who is subscribing -+ * -+ * @see mail_subscribe_notify_profile() -+ * -+ * @return void -+ */ -+ -+function mail_subscribe_notify($listenee, $listener) -+{ -+ $other = $listener->getProfile(); -+ mail_subscribe_notify_profile($listenee, $other); -+} ++ /** ++ * constructor ++ * ++ * Also initializes the profile attribute. ++ * ++ * @param Notice $notice The notice we'll display ++ */ + -+/** -+ * notify a user of subscription by a profile (remote or local) -+ * -+ * This function checks to see if the listenee has an email -+ * address and wants subscription notices. -+ * -+ * @param User $listenee user who's being subscribed to -+ * @param Profile $other profile of person who's listening -+ * -+ * @return void -+ */ -+ -+function mail_subscribe_notify_profile($listenee, $other) -+{ -+ if ($listenee->email && $listenee->emailnotifysub) { ++ function __construct($notice) ++ { ++ $this->notice = $notice; ++ $this->profile = $notice->getProfile(); +hunk ./lib/noticelist.php 160 +- function show() { +- $this->show_start(); +- $this->show_fave_form(); +- $this->show_author(); +- $this->show_content(); +- $this->show_start_time_section(); +- $this->show_notice_link(); +- $this->show_notice_source(); +- $this->show_reply_to(); +- $this->show_reply_link(); +- $this->show_delete_link(); +- $this->show_end_time_section(); +- $this->show_end(); +- } ++ /** ++ * recipe function for displaying a single notice. ++ * ++ * This uses all the other methods to correctly display a notice. Override ++ * it or one of the others to fine-tune the output. ++ * ++ * @return void ++ */ +hunk ./lib/noticelist.php 169 +- function show_start() { +- # XXX: RDFa +- common_element_start('li', array('class' => 'notice_single hentry', +- 'id' => 'notice-' . $this->notice->id)); ++ function show() ++ { ++ $this->showStart(); ++ $this->showFaveForm(); ++ $this->showAuthor(); ++ $this->showContent(); ++ $this->startTimeSection(); ++ $this->showNoticeLink(); ++ $this->showNoticeSource(); ++ $this->showReplyTo(); ++ $this->showReplyLink(); ++ $this->showDeleteLink(); ++ $this->endTimeSection(); ++ $this->showEnd(); +hunk ./lib/noticelist.php 185 +- function show_fave_form() { ++ /** ++ * start a single notice. ++ * ++ * @return void ++ */ + -+ // use the recipient's localization -hunk ./lib/mail.php 224 -- $profile = $listenee->getProfile(); -- $name = $profile->getBestName(); -- $long_name = ($other->fullname) ? ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; -- $recipients = $listenee->email; -- $headers['From'] = mail_notify_from(); -- $headers['To'] = $name . ' <' . $listenee->email . '>'; -- $headers['Subject'] = sprintf(_('%1$s is now listening to your notices on %2$s.'), ++ function showStart() ++ { ++ // XXX: RDFa ++ common_element_start('li', array('class' => 'notice_single hentry', ++ 'id' => 'notice-' . $this->notice->id)); ++ } + -+ $profile = $listenee->getProfile(); ++ /** ++ * show the "favorite" form ++ * ++ * @return void ++ */ + -+ $name = $profile->getBestName(); ++ function showFaveForm() ++ { +hunk ./lib/noticelist.php 207 +- if ($user) { +- if ($user->hasFave($this->notice)) { +- common_disfavor_form($this->notice); +- } else { +- common_favor_form($this->notice); +- } +- } ++ if ($user) { ++ if ($user->hasFave($this->notice)) { ++ common_disfavor_form($this->notice); ++ } else { ++ common_favor_form($this->notice); ++ } ++ } +hunk ./lib/noticelist.php 216 +- function show_author() { +- common_element_start('span', 'vcard author'); +- $this->show_avatar(); +- $this->show_nickname(); +- common_element_end('span'); ++ /** ++ * show the author of a notice ++ * ++ * By default, this shows the avatar and (linked) nickname of the author. ++ * ++ * @return void ++ */ + -+ $long_name = ($other->fullname) ? -+ ($other->fullname . ' (' . $other->nickname . ')') : $other->nickname; ++ function showAuthor() ++ { ++ common_element_start('span', 'vcard author'); ++ $this->showAvatar(); ++ $this->showNickname(); ++ common_element_end('span'); +hunk ./lib/noticelist.php 232 +- function show_avatar() { +- $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); +- common_element_start('a', array('href' => $this->profile->profileurl)); +- common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), +- 'class' => 'avatar stream photo', +- 'width' => AVATAR_STREAM_SIZE, +- 'height' => AVATAR_STREAM_SIZE, +- 'alt' => +- ($this->profile->fullname) ? $this->profile->fullname : +- $this->profile->nickname)); +- common_element_end('a'); ++ /** ++ * show the avatar of the notice's author ++ * ++ * This will use the default avatar if no avatar is assigned for the author. ++ * It makes a link to the author's profile. ++ * ++ * @return void ++ */ + -+ $recipients = $listenee->email; ++ function showAvatar() ++ { ++ $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); ++ common_element_start('a', array('href' => $this->profile->profileurl)); ++ common_element('img', array('src' => ($avatar) ? ++ common_avatar_display_url($avatar) : ++ common_default_avatar(AVATAR_STREAM_SIZE), ++ 'class' => 'avatar stream photo', ++ 'width' => AVATAR_STREAM_SIZE, ++ 'height' => AVATAR_STREAM_SIZE, ++ 'alt' => ++ ($this->profile->fullname) ? ++ $this->profile->fullname : ++ $this->profile->nickname)); ++ common_element_end('a'); +hunk ./lib/noticelist.php 258 +- function show_nickname() { +- common_element('a', array('href' => $this->profile->profileurl, +- 'class' => 'nickname fn url'), +- $this->profile->nickname); ++ /** ++ * show the nickname of the author ++ * ++ * Links to the author's profile page ++ * ++ * @return void ++ */ + -+ $headers['From'] = mail_notify_from(); -+ $headers['To'] = $name . ' <' . $listenee->email . '>'; -+ $headers['Subject'] = sprintf(_('%1$s is now listening to '. -+ 'your notices on %2$s.'), -hunk ./lib/mail.php 239 -- common_config('site', 'name')); -- $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". -- "\t".'%3$s'."\n\n". -- '%4$s'. -- '%5$s'. -- '%6$s'. -- "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". -- "----\n". -- "Change your email address or notification options at %8$s"), -- $long_name, -- common_config('site', 'name'), -- $other->profileurl, -- ($other->location) ? sprintf(_("Location: %s\n"), $other->location) : '', -- ($other->homepage) ? sprintf(_("Homepage: %s\n"), $other->homepage) : '', -- ($other->bio) ? sprintf(_("Bio: %s\n\n"), $other->bio) : '', -- common_config('site', 'name'), -- common_local_url('emailsettings')); -+ common_config('site', 'name')); ++ function showNickname() ++ { ++ common_element('a', array('href' => $this->profile->profileurl, ++ 'class' => 'nickname fn url'), ++ $this->profile->nickname); +hunk ./lib/noticelist.php 273 +- function show_content() { +- # FIXME: URL, image, video, audio +- common_element_start('p', array('class' => 'content entry-title')); +- if ($this->notice->rendered) { +- common_raw($this->notice->rendered); +- } else { +- # XXX: may be some uncooked notices in the DB, +- # we cook them right now. This should probably disappear in future +- # versions (>> 0.4.x) +- common_raw(common_render_content($this->notice->content, $this->notice)); +- } +- common_element_end('p'); ++ /** ++ * show the content of the notice ++ * ++ * Shows the content of the notice. This is pre-rendered for efficiency ++ * at save time. Some very old notices might not be pre-rendered, so ++ * they're rendered on the spot. ++ * ++ * @return void ++ */ + -+ $body = sprintf(_('%1$s is now listening to your notices on %2$s.'."\n\n". -+ "\t".'%3$s'."\n\n". -+ '%4$s'. -+ '%5$s'. -+ '%6$s'. -+ "\n".'Faithfully yours,'."\n".'%7$s.'."\n\n". -+ "----\n". -+ "Change your email address or ". -+ "notification options at %8$s\n"), -+ $long_name, -+ common_config('site', 'name'), -+ $other->profileurl, -+ ($other->location) ? -+ sprintf(_("Location: %s\n"), $other->location) : '', -+ ($other->homepage) ? -+ sprintf(_("Homepage: %s\n"), $other->homepage) : '', -+ ($other->bio) ? -+ sprintf(_("Bio: %s\n\n"), $other->bio) : '', -+ common_config('site', 'name'), -+ common_local_url('emailsettings')); ++ function showContent() ++ { ++ // FIXME: URL, image, video, audio ++ common_element_start('p', array('class' => 'content entry-title')); ++ if ($this->notice->rendered) { ++ common_raw($this->notice->rendered); ++ } else { ++ // XXX: may be some uncooked notices in the DB, ++ // we cook them right now. This should probably disappear in future ++ // versions (>> 0.4.x) ++ common_raw(common_render_content($this->notice->content, $this->notice)); ++ } ++ common_element_end('p'); +hunk ./lib/noticelist.php 298 +- function show_start_time_section() { +- common_element_start('p', 'time'); ++ /** ++ * show the "time" section of a notice ++ * ++ * This is the greyed-out section that appears beneath the content, including ++ * links to delete or reply to the notice. Probably should be called something ++ * else. ++ * ++ * @return void ++ */ + -hunk ./lib/mail.php 264 -- mail_send($recipients, $headers, $body); -- } -+ mail_send($recipients, $headers, $body); -+ } -hunk ./lib/mail.php 268 --function mail_new_incoming_notify($user) { -+/** -+ * notify a user of their new incoming email address -+ * -+ * User's email and incoming fields should already be updated. -+ * -+ * @param User $user user with the new address -+ * -+ * @return void -+ */ ++ function startTimeSection() ++ { ++ common_element_start('p', 'time'); +hunk ./lib/noticelist.php 313 +- function show_notice_link() { +- $noticeurl = common_local_url('shownotice', array('notice' => $this->notice->id)); +- # XXX: we need to figure this out better. Is this right? +- if (strcmp($this->notice->uri, $noticeurl) != 0 && preg_match('/^http/', $this->notice->uri)) { +- $noticeurl = $this->notice->uri; +- } +- common_element_start('a', array('class' => 'permalink', +- 'rel' => 'bookmark', +- 'href' => $noticeurl)); +- common_element('abbr', array('class' => 'published', +- 'title' => common_date_iso8601($this->notice->created)), +- common_date_string($this->notice->created)); +- common_element_end('a'); ++ /** ++ * show the link to the main page for the notice ++ * ++ * Displays a link to the page for a notice, with "relative" time. Tries to ++ * get remote notice URLs correct, but doesn't always succeed. ++ * ++ * @return void ++ */ + -+function mail_new_incoming_notify($user) -+{ -+ $profile = $user->getProfile(); -hunk ./lib/mail.php 282 -- $profile = $user->getProfile(); -- $name = $profile->getBestName(); -+ $name = $profile->getBestName(); -hunk ./lib/mail.php 284 -- $headers['From'] = $user->incomingemail; -- $headers['To'] = $name . ' <' . $user->email . '>'; -- $headers['Subject'] = sprintf(_('New email address for posting to %s'), -- common_config('site', 'name')); -+ $headers['From'] = $user->incomingemail; -+ $headers['To'] = $name . ' <' . $user->email . '>'; -+ $headers['Subject'] = sprintf(_('New email address for posting to %s'), -+ common_config('site', 'name')); -hunk ./lib/mail.php 289 -- $body = sprintf(_("You have a new posting address on %1\$s.\n\n". -- "Send email to %2\$s to post new messages.\n\n". -- "More email instructions at %3\$s.\n\n". -- "Faithfully yours,\n%4\$s"), -- common_config('site', 'name'), -- $user->incomingemail, -- common_local_url('doc', array('title' => 'email')), -- common_config('site', 'name')); -+ $body = sprintf(_("You have a new posting address on %1\$s.\n\n". -+ "Send email to %2\$s to post new messages.\n\n". -+ "More email instructions at %3\$s.\n\n". -+ "Faithfully yours,\n%4\$s"), -+ common_config('site', 'name'), -+ $user->incomingemail, -+ common_local_url('doc', array('title' => 'email')), -+ common_config('site', 'name')); -hunk ./lib/mail.php 298 -- mail_send($user->email, $headers, $body); -+ mail_send($user->email, $headers, $body); -hunk ./lib/mail.php 301 --function mail_new_incoming_address() { -- $prefix = common_confirmation_code(64); -- $suffix = mail_domain(); -- return $prefix . '@' . $suffix; -+/** -+ * generate a new address for incoming messages -+ * -+ * @todo check the database for uniqueness -+ * -+ * @return string new email address for incoming messages -+ */ ++ function showNoticeLink() ++ { ++ $noticeurl = common_local_url('shownotice', ++ array('notice' => $this->notice->id)); ++ // XXX: we need to figure this out better. Is this right? ++ if (strcmp($this->notice->uri, $noticeurl) != 0 && ++ preg_match('/^http/', $this->notice->uri)) { ++ $noticeurl = $this->notice->uri; ++ } ++ common_element_start('a', array('class' => 'permalink', ++ 'rel' => 'bookmark', ++ 'href' => $noticeurl)); ++ $dt = common_date_iso8601($this->notice->created); ++ common_element('abbr', array('class' => 'published', ++ 'title' => $dt), ++ common_date_string($this->notice->created)); ++ common_element_end('a'); +hunk ./lib/noticelist.php 341 +- function show_notice_source() { +- if ($this->notice->source) { +- common_element('span', null, _(' from ')); ++ /** ++ * 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. ++ * ++ * @return void ++ */ + -+function mail_new_incoming_address() -+{ -+ $prefix = common_confirmation_code(64); -+ $suffix = mail_domain(); -+ return $prefix . '@' . $suffix; -hunk ./lib/mail.php 316 --function mail_broadcast_notice_sms($notice) { -+/** -+ * broadcast a notice to all subscribers with SMS notification on -+ * -+ * This function sends SMS messages to all users who have sms addresses; -+ * have sms notification on; and have sms enabled for this particular -+ * subscription. -+ * -+ * @param Notice $notice The notice to broadcast -+ * -+ * @return success flag -+ */ -hunk ./lib/mail.php 328 -- # Now, get users subscribed to this profile -+function mail_broadcast_notice_sms($notice) -+{ -+ // Now, get users subscribed to this profile -hunk ./lib/mail.php 332 -- $user = new User(); -+ $user = new User(); -hunk ./lib/mail.php 334 -- $user->query('SELECT nickname, smsemail, incomingemail ' . -- 'FROM user JOIN subscription ' . -- 'ON user.id = subscription.subscriber ' . -- 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . -- 'AND user.smsemail IS NOT NULL ' . -- 'AND user.smsnotify = 1 ' . -+ $user->query('SELECT nickname, smsemail, incomingemail ' . -+ 'FROM user JOIN subscription ' . -+ 'ON user.id = subscription.subscriber ' . -+ 'WHERE subscription.subscribed = ' . $notice->profile_id . ' ' . -+ 'AND user.smsemail IS NOT null ' . -+ 'AND user.smsnotify = 1 ' . -hunk ./lib/mail.php 342 -- while ($user->fetch()) { -- common_log(LOG_INFO, -- 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, -- __FILE__); -- $success = mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); -- if (!$success) { -- # XXX: Not sure, but I think that's the right thing to do -- common_log(LOG_WARNING, -- 'Sending notice ' . $notice->id . ' to ' . $user->smsemail . ' FAILED, cancelling.', -- __FILE__); -- return false; ++ function showNoticeSource() ++ { ++ if ($this->notice->source) { ++ common_element('span', null, _(' from ')); +hunk ./lib/noticelist.php 356 +- case 'web': +- case 'xmpp': +- case 'mail': +- case 'omb': +- case 'api': ++ case 'web': ++ case 'xmpp': ++ case 'mail': ++ case 'omb': ++ case 'api': +hunk ./lib/noticelist.php 363 +- default: ++ default: +hunk ./lib/noticelist.php 373 - } -- } -+ while ($user->fetch()) { -+ common_log(LOG_INFO, -+ 'Sending notice ' . $notice->id . ' to ' . $user->smsemail, -+ __FILE__); -+ $success = mail_send_sms_notice_address($notice, -+ $user->smsemail, -+ $user->incomingemail); -+ if (!$success) { -+ // XXX: Not sure, but I think that's the right thing to do -+ common_log(LOG_WARNING, -+ 'Sending notice ' . $notice->id . ' to ' . -+ $user->smsemail . ' FAILED, cancelling.', -+ __FILE__); -+ return false; + } -+ } -hunk ./lib/mail.php 359 -- $user->free(); -- unset($user); -+ $user->free(); -+ unset($user); -hunk ./lib/mail.php 362 -- return true; -+ return true; -hunk ./lib/mail.php 365 --function mail_send_sms_notice($notice, $user) { -- return mail_send_sms_notice_address($notice, $user->smsemail, $user->incomingemail); -+/** -+ * send a notice to a user via SMS -+ * -+ * A convenience wrapper around mail_send_sms_notice_address() -+ * -+ * @param Notice $notice notice to send -+ * @param User $user user to receive notice -+ * -+ * @see mail_send_sms_notice_address() -+ * -+ * @return boolean success flag -+ */ -+ -+function mail_send_sms_notice($notice, $user) -+{ -+ return mail_send_sms_notice_address($notice, -+ $user->smsemail, -+ $user->incomingemail); -hunk ./lib/mail.php 385 --function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) { -+/** -+ * send a notice to an SMS email address from a given address -+ * -+ * We use the user's incoming email address as the "From" address to make -+ * replying to notices easier. -+ * -+ * @param Notice $notice notice to send -+ * @param string $smsemail email address to send to -+ * @param string $incomingemail email address to set as 'from' -+ * -+ * @return boolean success flag -+ */ -+ -+function mail_send_sms_notice_address($notice, $smsemail, $incomingemail) -+{ -+ $to = $nickname . ' <' . $smsemail . '>'; -+ -+ $other = $notice->getProfile(); -hunk ./lib/mail.php 404 -- $to = $nickname . ' <' . $smsemail . '>'; -- $other = $notice->getProfile(); -+ common_log(LOG_INFO, 'Sending notice ' . $notice->id . -+ ' to ' . $smsemail, __FILE__); -hunk ./lib/mail.php 407 -- common_log(LOG_INFO, "Sending notice " . $notice->id . " to " . $smsemail, __FILE__); -+ $headers = array(); -hunk ./lib/mail.php 409 -- $headers = array(); -- $headers['From'] = (isset($incomingemail)) ? $incomingemail : mail_notify_from(); -- $headers['To'] = $to; -- $headers['Subject'] = sprintf(_('%s status'), -- $other->getBestName()); -- $body = $notice->content; -+ $headers['From'] = ($incomingemail) ? $incomingemail : mail_notify_from(); -+ $headers['To'] = $to; -+ $headers['Subject'] = sprintf(_('%s status'), -+ $other->getBestName()); -hunk ./lib/mail.php 414 -- return mail_send($smsemail, $headers, $body); -+ $body = $notice->content; +hunk ./lib/noticelist.php 376 +- function show_reply_to() { +- if ($this->notice->reply_to) { +- $replyurl = common_local_url('shownotice', array('notice' => $this->notice->reply_to)); +- common_text(' ('); +- common_element('a', array('class' => 'inreplyto', +- 'href' => $replyurl), +- _('in reply to...')); +- common_text(')'); +- } ++ /** ++ * show link to notice this notice is a reply to ++ * ++ * If this notice is a reply, show a link to the notice it is replying to. The ++ * heavy lifting for figuring out replies happens at save time. ++ * ++ * @return void ++ */ + -+ return mail_send($smsemail, $headers, $body); -hunk ./lib/mail.php 419 --function mail_confirm_sms($code, $nickname, $address) { -+/** -+ * send a message to confirm a claim for an SMS number -+ * -+ * @param string $code confirmation code -+ * @param string $nickname nickname of user claiming number -+ * @param string $address email address to send the confirmation to -+ * -+ * @see common_confirmation_code() -+ * -+ * @return void -+ */ ++ function showReplyTo() ++ { ++ if ($this->notice->reply_to) { ++ $replyurl = common_local_url('shownotice', ++ array('notice' => $this->notice->reply_to)); ++ common_text(' ('); ++ common_element('a', array('class' => 'inreplyto', ++ 'href' => $replyurl), ++ _('in reply to...')); ++ common_text(')'); ++ } +hunk ./lib/noticelist.php 398 +- function show_reply_link() { +- common_element_start('a', +- array('href' => common_local_url('newnotice', +- array('replyto' => $this->profile->nickname)), +- 'onclick' => 'return doreply("'.$this->profile->nickname.'", '.$this->notice->id.');', +- 'title' => _('reply'), +- 'class' => 'replybutton')); +- common_raw(' →'); +- common_element_end('a'); ++ /** ++ * show a link to reply to the current notice ++ * ++ * Should either do the reply in the current notice form (if available), or ++ * link out to the notice-posting form. A little flakey, doesn't always work. ++ * ++ * @return void ++ */ + -+function mail_confirm_sms($code, $nickname, $address) -+{ -+ $recipients = $address; -hunk ./lib/mail.php 435 -- $recipients = $address; -+ $headers['From'] = mail_notify_from(); -+ $headers['To'] = $nickname . ' <' . $address . '>'; -+ $headers['Subject'] = _('SMS confirmation'); -hunk ./lib/mail.php 439 -- $headers['From'] = mail_notify_from(); -- $headers['To'] = $nickname . ' <' . $address . '>'; -- $headers['Subject'] = _('SMS confirmation'); -+ // FIXME: I18N -hunk ./lib/mail.php 441 -- $body = "$nickname: confirm you own this phone number with this code:"; -- $body .= "\n\n"; -- $body .= $code; -- $body .= "\n\n"; -+ $body = "$nickname: confirm you own this phone number with this code:"; -+ $body .= "\n\n"; -+ $body .= $code; -+ $body .= "\n\n"; -hunk ./lib/mail.php 446 -- mail_send($recipients, $headers, $body); -+ mail_send($recipients, $headers, $body); -hunk ./lib/mail.php 449 --function mail_notify_nudge($from, $to) { -+/** -+ * send a mail message to notify a user of a 'nudge' -+ * -+ * @param User $from user nudging -+ * @param User $to user being nudged -+ * -+ * @return boolean success flag -+ */ ++ function showReplyLink() ++ { ++ $reply_url = common_local_url('newnotice', ++ array('replyto' => $this->profile->nickname)); + -+function mail_notify_nudge($from, $to) -+{ -hunk ./lib/mail.php 461 -- $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); -+ $subject = sprintf(_('You\'ve been nudged by %s'), $from->nickname); -hunk ./lib/mail.php 463 -- $from_profile = $from->getProfile(); -+ $from_profile = $from->getProfile(); -hunk ./lib/mail.php 465 -- $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to these days and is inviting you to post some news.\n\n". -- "So let's hear from you :)\n\n". -- "%3\$s\n\n". -- "Don't reply to this email; it won't get to them.\n\n". -- "With kind regards,\n". -- "%4\$s\n"), -- $from_profile->getBestName(), -- $from->nickname, -- common_local_url('all', array('nickname' => $to->nickname)), -- common_config('site', 'name')); -+ $body = sprintf(_("%1\$s (%2\$s) is wondering what you are up to ". -+ "these days and is inviting you to post some news.\n\n". -+ "So let's hear from you :)\n\n". -+ "%3\$s\n\n". -+ "Don't reply to this email; it won't get to them.\n\n". -+ "With kind regards,\n". -+ "%4\$s\n"), -+ $from_profile->getBestName(), -+ $from->nickname, -+ common_local_url('all', array('nickname' => $to->nickname)), -+ common_config('site', 'name')); -hunk ./lib/mail.php 477 -- return mail_to_user($to, $subject, $body); -+ return mail_to_user($to, $subject, $body); -hunk ./lib/mail.php 480 --function mail_notify_message($message, $from=NULL, $to=NULL) { -+/** -+ * send a message to notify a user of a direct message (DM) -+ * -+ * This function checks to see if the recipient wants notification -+ * of DMs and has a configured email address. -+ * -+ * @param Message $message message to notify about -+ * @param User $from user sending message; default to sender -+ * @param User $to user receiving message; default to recipient -+ * -+ * @return boolean success code -+ */ -hunk ./lib/mail.php 493 -- if (is_null($from)) { -- $from = User::staticGet('id', $message->from_profile); -- } -+function mail_notify_message($message, $from=null, $to=null) -+{ -+ if (is_null($from)) { -+ $from = User::staticGet('id', $message->from_profile); -+ } -hunk ./lib/mail.php 499 -- if (is_null($to)) { -- $to = User::staticGet('id', $message->to_profile); -- } -+ if (is_null($to)) { -+ $to = User::staticGet('id', $message->to_profile); -+ } -hunk ./lib/mail.php 503 -- if (is_null($to->email) || !$to->emailnotifymsg) { -- return true; -- } -+ if (is_null($to->email) || !$to->emailnotifymsg) { -+ return true; -+ } -hunk ./lib/mail.php 508 -- $subject = sprintf(_('New private message from %s'), $from->nickname); -+ $subject = sprintf(_('New private message from %s'), $from->nickname); -hunk ./lib/mail.php 510 -- $from_profile = $from->getProfile(); -+ $from_profile = $from->getProfile(); -hunk ./lib/mail.php 512 -- $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". -- "------------------------------------------------------\n". -- "%3\$s\n". -- "------------------------------------------------------\n\n". -- "You can reply to their message here:\n\n". -- "%4\$s\n\n". -- "Don't reply to this email; it won't get to them.\n\n". -- "With kind regards,\n". -- "%5\$s\n"), -- $from_profile->getBestName(), -- $from->nickname, -- $message->content, -- common_local_url('newmessage', array('to' => $from->id)), -- common_config('site', 'name')); -+ $body = sprintf(_("%1\$s (%2\$s) sent you a private message:\n\n". -+ "------------------------------------------------------\n". -+ "%3\$s\n". -+ "------------------------------------------------------\n\n". -+ "You can reply to their message here:\n\n". -+ "%4\$s\n\n". -+ "Don't reply to this email; it won't get to them.\n\n". -+ "With kind regards,\n". -+ "%5\$s\n"), -+ $from_profile->getBestName(), -+ $from->nickname, -+ $message->content, -+ common_local_url('newmessage', array('to' => $from->id)), -+ common_config('site', 'name')); -hunk ./lib/mail.php 528 -- return mail_to_user($to, $subject, $body); -+ return mail_to_user($to, $subject, $body); -hunk ./lib/mail.php 531 --function mail_notify_fave($other, $user, $notice) { -+/** -+ * notify a user that one of their notices has been chosen as a 'fave' -+ * -+ * Doesn't check that the user has an email address nor if they -+ * want to receive notification of faves. Maybe this happens higher -+ * up the stack...? -+ * -+ * @param User $other The user whose notice was faved -+ * @param User $user The user who faved the notice -+ * @param Notice $notice The notice that was faved -+ * -+ * @return void -+ */ ++ $reply_js = ++ 'return doreply("'.$this->profile->nickname.'",'.$this->notice->id.');'; + -+function mail_notify_fave($other, $user, $notice) -+{ -+ $profile = $user->getProfile(); ++ common_element_start('a', ++ array('href' => $reply_url, ++ 'onclick' => $reply_js, ++ 'title' => _('reply'), ++ 'class' => 'replybutton')); ++ common_raw(' →'); ++ common_element_end('a'); +hunk ./lib/noticelist.php 424 +- function show_delete_link() { ++ /** ++ * if the user is the author, let them delete the notice ++ * ++ * @return void ++ */ + -+ $bestname = $profile->getBestName(); -hunk ./lib/mail.php 551 -- $profile = $user->getProfile(); -- $bestname = $profile->getBestName(); -hunk ./lib/mail.php 552 -- $subject = sprintf(_('%s added your notice as a favorite'), $bestname); -- $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . -- "In case you forgot, you can see the text of your notice here:\n\n" . -- "%3\$s\n\n" . -- "You can see the list of %1\$s's favorites here:\n\n" . -- "%4\$s\n\n" . -- "Faithfully yours,\n" . -- "%5\$s\n"), -- $bestname, -- common_exact_date($notice->created), -- common_local_url('shownotice', array('notice' => $notice->id)), -- common_local_url('showfavorites', array('nickname' => $user->nickname)), -- common_config('site', 'name')); ++ function showDeleteLink() ++ { +hunk ./lib/noticelist.php 433 +- if ($user && $this->notice->profile_id == $user->id) { +- $deleteurl = common_local_url('deletenotice', array('notice' => $this->notice->id)); +- common_element_start('a', array('class' => 'deletenotice', +- 'href' => $deleteurl, +- 'title' => _('delete'))); +- common_raw(' ×'); +- common_element_end('a'); +- } ++ if ($user && $this->notice->profile_id == $user->id) { ++ $deleteurl = common_local_url('deletenotice', ++ array('notice' => $this->notice->id)); ++ common_element_start('a', array('class' => 'deletenotice', ++ 'href' => $deleteurl, ++ 'title' => _('delete'))); ++ common_raw(' ×'); ++ common_element_end('a'); ++ } +hunk ./lib/noticelist.php 444 +- function show_end_time_section() { +- common_element_end('p'); ++ /** ++ * end the time section ++ * ++ * @return void ++ */ + -+ $subject = sprintf(_('%s added your notice as a favorite'), $bestname); ++ function endTimeSection() ++ { ++ common_element_end('p'); +hunk ./lib/noticelist.php 455 +- function show_end() { +- common_element_end('li'); ++ /** ++ * finish the notice ++ * ++ * Close the last elements in the notice list item ++ * ++ * @return void ++ */ + -+ $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" . -+ "%3\$s\n\n" . -+ "You can see the list of %1\$s's favorites here:\n\n" . -+ "%4\$s\n\n" . -+ "Faithfully yours,\n" . -+ "%5\$s\n"), -+ $bestname, -+ common_exact_date($notice->created), -+ common_local_url('shownotice', -+ array('notice' => $notice->id)), -+ common_local_url('showfavorites', -+ array('nickname' => $user->nickname)), -+ common_config('site', 'name')); -hunk ./lib/mail.php 573 -- mail_to_user($other, $subject, $body); -+ mail_to_user($other, $subject, $body); ++ function showEnd() ++ { ++ common_element_end('li'); diff --git a/actions/showstream.php b/actions/showstream.php index 6d6225661..61fdec3fe 100644 --- a/actions/showstream.php +++ b/actions/showstream.php @@ -438,13 +438,13 @@ class ShowstreamAction extends StreamAction { # We don't show the author for a profile, since we already know who it is! class ProfileNoticeList extends NoticeList { - function new_list_item($notice) { + function newListItem($notice) { return new ProfileNoticeListItem($notice); } } class ProfileNoticeListItem extends NoticeListItem { - function show_author() { + function showAuthor() { return; } } diff --git a/lib/noticelist.php b/lib/noticelist.php index 415c062e4..c9344a716 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -1,173 +1,366 @@ . + * along with this program. If not, see . + * + * @category UI + * @package Laconica + * @author Evan Prodromou + * @copyright 2008 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); } +if (!defined('LACONICA')) { + exit(1); +} + +/** + * widget for displaying a list of notices + * + * There are a number of actions that display a list of notices, in + * reverse chronological order. This widget abstracts out most of the + * code for UI for notice lists. It's overridden to hide some + * data for e.g. the profile page. + * + * @category UI + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see Notice + * @see StreamAction + * @see NoticeListItem + * @see ProfileNoticeList + */ -class NoticeList { +class NoticeList +{ + /** the current stream of notices being displayed. */ - var $notice = NULL; + var $notice = null; - function __construct($notice) { + /** + * constructor + * + * @param Notice $notice stream of notices from DB_DataObject + */ + + function __construct($notice) + { $this->notice = $notice; } - function show() { + /** + * show the list of notices + * + * "Uses up" the stream by looping through it. So, probably can't + * be called twice on the same list. + * + * @return int count of notices listed. + */ - common_element_start('ul', array('id' => 'notices')); + function show() + { + common_element_start('ul', array('id' => 'notices')); - $cnt = 0; + $cnt = 0; - while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { - $cnt++; + while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { + $cnt++; - if ($cnt > NOTICES_PER_PAGE) { - break; - } + if ($cnt > NOTICES_PER_PAGE) { + break; + } - $item = $this->new_list_item($this->notice); + $item = $this->newListItem($this->notice); $item->show(); - } + } - common_element_end('ul'); + common_element_end('ul'); return $cnt; - } + } - function new_list_item($notice) { + /** + * returns a new list item for the current notice + * + * Recipe (factory?) method; overridden by sub-classes to give + * a different list item class. + * + * @param Notice $notice the current notice + * + * @return NoticeListItem a list item for displaying the notice + */ + + function newListItem($notice) + { return new NoticeListItem($notice); } } -class NoticeListItem { +/** + * widget for displaying a single notice + * + * This widget has the core smarts for showing a single notice: what to display, + * where, and under which circumstances. Its key method is show(); this is a recipe + * that calls all the other show*() methods to build up a single notice. The + * ProfileNoticeListItem subclass, for example, overrides showAuthor() to skip + * author info (since that's implicit by the data in the page). + * + * @category UI + * @package Laconica + * @author Evan Prodromou + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * @see NoticeList + * @see ProfileNoticeListItem + */ + +class NoticeListItem +{ + /** The notice this item will show. */ - var $notice = NULL; - var $profile = NULL; + var $notice = null; - function __construct($notice) { - $this->notice = $notice; - $this->profile = $notice->getProfile(); - } - - function show() { - $this->show_start(); - $this->show_fave_form(); - $this->show_author(); - $this->show_content(); - $this->show_start_time_section(); - $this->show_notice_link(); - $this->show_notice_source(); - $this->show_reply_to(); - $this->show_reply_link(); - $this->show_delete_link(); - $this->show_end_time_section(); - $this->show_end(); - } - - function show_start() { - # XXX: RDFa - common_element_start('li', array('class' => 'notice_single hentry', - 'id' => 'notice-' . $this->notice->id)); - } - - function show_fave_form() { + /** The profile of the author of the notice, extracted once for convenience. */ + + var $profile = null; + + /** + * constructor + * + * Also initializes the profile attribute. + * + * @param Notice $notice The notice we'll display + */ + + function __construct($notice) + { + $this->notice = $notice; + $this->profile = $notice->getProfile(); + } + + /** + * recipe function for displaying a single notice. + * + * This uses all the other methods to correctly display a notice. Override + * it or one of the others to fine-tune the output. + * + * @return void + */ + + function show() + { + $this->showStart(); + $this->showFaveForm(); + $this->showAuthor(); + $this->showContent(); + $this->startTimeSection(); + $this->showNoticeLink(); + $this->showNoticeSource(); + $this->showReplyTo(); + $this->showReplyLink(); + $this->showDeleteLink(); + $this->endTimeSection(); + $this->showEnd(); + } + + /** + * start a single notice. + * + * @return void + */ + + function showStart() + { + // XXX: RDFa + common_element_start('li', array('class' => 'notice_single hentry', + 'id' => 'notice-' . $this->notice->id)); + } + + /** + * show the "favorite" form + * + * @return void + */ + + function showFaveForm() + { $user = common_current_user(); - if ($user) { - if ($user->hasFave($this->notice)) { - common_disfavor_form($this->notice); - } else { - common_favor_form($this->notice); - } - } - } - - function show_author() { - common_element_start('span', 'vcard author'); - $this->show_avatar(); - $this->show_nickname(); - common_element_end('span'); - } - - function show_avatar() { - $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); - common_element_start('a', array('href' => $this->profile->profileurl)); - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), - 'class' => 'avatar stream photo', - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'alt' => - ($this->profile->fullname) ? $this->profile->fullname : - $this->profile->nickname)); - common_element_end('a'); - } - - function show_nickname() { - common_element('a', array('href' => $this->profile->profileurl, - 'class' => 'nickname fn url'), - $this->profile->nickname); - } - - function show_content() { - # FIXME: URL, image, video, audio - common_element_start('p', array('class' => 'content entry-title')); - if ($this->notice->rendered) { - common_raw($this->notice->rendered); - } else { - # XXX: may be some uncooked notices in the DB, - # we cook them right now. This should probably disappear in future - # versions (>> 0.4.x) - common_raw(common_render_content($this->notice->content, $this->notice)); - } - common_element_end('p'); - } - - function show_start_time_section() { - common_element_start('p', 'time'); - } - - function show_notice_link() { - $noticeurl = common_local_url('shownotice', array('notice' => $this->notice->id)); - # XXX: we need to figure this out better. Is this right? - if (strcmp($this->notice->uri, $noticeurl) != 0 && preg_match('/^http/', $this->notice->uri)) { - $noticeurl = $this->notice->uri; - } - common_element_start('a', array('class' => 'permalink', - 'rel' => 'bookmark', - 'href' => $noticeurl)); - common_element('abbr', array('class' => 'published', - 'title' => common_date_iso8601($this->notice->created)), - common_date_string($this->notice->created)); - common_element_end('a'); - } - - function show_notice_source() { - if ($this->notice->source) { - common_element('span', null, _(' from ')); + if ($user) { + if ($user->hasFave($this->notice)) { + common_disfavor_form($this->notice); + } else { + common_favor_form($this->notice); + } + } + } + + /** + * show the author of a notice + * + * By default, this shows the avatar and (linked) nickname of the author. + * + * @return void + */ + + function showAuthor() + { + common_element_start('span', 'vcard author'); + $this->showAvatar(); + $this->showNickname(); + common_element_end('span'); + } + + /** + * show the avatar of the notice's author + * + * This will use the default avatar if no avatar is assigned for the author. + * It makes a link to the author's profile. + * + * @return void + */ + + function showAvatar() + { + $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); + common_element_start('a', array('href' => $this->profile->profileurl)); + common_element('img', array('src' => ($avatar) ? + common_avatar_display_url($avatar) : + common_default_avatar(AVATAR_STREAM_SIZE), + 'class' => 'avatar stream photo', + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'alt' => + ($this->profile->fullname) ? + $this->profile->fullname : + $this->profile->nickname)); + common_element_end('a'); + } + + /** + * show the nickname of the author + * + * Links to the author's profile page + * + * @return void + */ + + function showNickname() + { + common_element('a', array('href' => $this->profile->profileurl, + 'class' => 'nickname fn url'), + $this->profile->nickname); + } + + /** + * show the content of the notice + * + * Shows the content of the notice. This is pre-rendered for efficiency + * at save time. Some very old notices might not be pre-rendered, so + * they're rendered on the spot. + * + * @return void + */ + + function showContent() + { + // FIXME: URL, image, video, audio + common_element_start('p', array('class' => 'content entry-title')); + if ($this->notice->rendered) { + common_raw($this->notice->rendered); + } else { + // XXX: may be some uncooked notices in the DB, + // we cook them right now. This should probably disappear in future + // versions (>> 0.4.x) + common_raw(common_render_content($this->notice->content, $this->notice)); + } + common_element_end('p'); + } + + /** + * show the "time" section of a notice + * + * This is the greyed-out section that appears beneath the content, including + * links to delete or reply to the notice. Probably should be called something + * else. + * + * @return void + */ + + function startTimeSection() + { + common_element_start('p', 'time'); + } + + /** + * show the link to the main page for the notice + * + * Displays a link to the page for a notice, with "relative" time. Tries to + * get remote notice URLs correct, but doesn't always succeed. + * + * @return void + */ + + function showNoticeLink() + { + $noticeurl = common_local_url('shownotice', + array('notice' => $this->notice->id)); + // XXX: we need to figure this out better. Is this right? + if (strcmp($this->notice->uri, $noticeurl) != 0 && + preg_match('/^http/', $this->notice->uri)) { + $noticeurl = $this->notice->uri; + } + common_element_start('a', array('class' => 'permalink', + 'rel' => 'bookmark', + 'href' => $noticeurl)); + $dt = common_date_iso8601($this->notice->created); + common_element('abbr', array('class' => 'published', + 'title' => $dt), + common_date_string($this->notice->created)); + common_element_end('a'); + } + + /** + * 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. + * + * @return void + */ + + function showNoticeSource() + { + if ($this->notice->source) { + common_element('span', null, _(' from ')); $source_name = _($this->notice->source); switch ($this->notice->source) { - case 'web': - case 'xmpp': - case 'mail': - case 'omb': - case 'api': + case 'web': + case 'xmpp': + case 'mail': + case 'omb': + case 'api': common_element('span', 'noticesource', $source_name); break; - default: + default: $ns = Notice_source::staticGet($this->notice->source); if ($ns) { common_element('a', array('href' => $ns->url), @@ -177,48 +370,98 @@ class NoticeListItem { } break; } - } + } } - function show_reply_to() { - if ($this->notice->reply_to) { - $replyurl = common_local_url('shownotice', array('notice' => $this->notice->reply_to)); - common_text(' ('); - common_element('a', array('class' => 'inreplyto', - 'href' => $replyurl), - _('in reply to...')); - common_text(')'); - } + /** + * show link to notice this notice is a reply to + * + * If this notice is a reply, show a link to the notice it is replying to. The + * heavy lifting for figuring out replies happens at save time. + * + * @return void + */ + + function showReplyTo() + { + if ($this->notice->reply_to) { + $replyurl = common_local_url('shownotice', + array('notice' => $this->notice->reply_to)); + common_text(' ('); + common_element('a', array('class' => 'inreplyto', + 'href' => $replyurl), + _('in reply to...')); + common_text(')'); + } } - function show_reply_link() { - common_element_start('a', - array('href' => common_local_url('newnotice', - array('replyto' => $this->profile->nickname)), - 'onclick' => 'return doreply("'.$this->profile->nickname.'", '.$this->notice->id.');', - 'title' => _('reply'), - 'class' => 'replybutton')); - common_raw(' →'); - common_element_end('a'); + /** + * show a link to reply to the current notice + * + * Should either do the reply in the current notice form (if available), or + * link out to the notice-posting form. A little flakey, doesn't always work. + * + * @return void + */ + + function showReplyLink() + { + $reply_url = common_local_url('newnotice', + array('replyto' => $this->profile->nickname)); + + $reply_js = + 'return doreply("'.$this->profile->nickname.'",'.$this->notice->id.');'; + + common_element_start('a', + array('href' => $reply_url, + 'onclick' => $reply_js, + 'title' => _('reply'), + 'class' => 'replybutton')); + common_raw(' →'); + common_element_end('a'); } - function show_delete_link() { + /** + * if the user is the author, let them delete the notice + * + * @return void + */ + + function showDeleteLink() + { $user = common_current_user(); - if ($user && $this->notice->profile_id == $user->id) { - $deleteurl = common_local_url('deletenotice', array('notice' => $this->notice->id)); - common_element_start('a', array('class' => 'deletenotice', - 'href' => $deleteurl, - 'title' => _('delete'))); - common_raw(' ×'); - common_element_end('a'); - } + if ($user && $this->notice->profile_id == $user->id) { + $deleteurl = common_local_url('deletenotice', + array('notice' => $this->notice->id)); + common_element_start('a', array('class' => 'deletenotice', + 'href' => $deleteurl, + 'title' => _('delete'))); + common_raw(' ×'); + common_element_end('a'); + } } - function show_end_time_section() { - common_element_end('p'); + /** + * end the time section + * + * @return void + */ + + function endTimeSection() + { + common_element_end('p'); } - function show_end() { - common_element_end('li'); + /** + * finish the notice + * + * Close the last elements in the notice list item + * + * @return void + */ + + function showEnd() + { + common_element_end('li'); } } -- cgit v1.2.3-54-g00ecf From 17ece0777b22b15c60b27b32f0f7e24ecc447661 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Tue, 23 Dec 2008 14:14:30 -0500 Subject: incorrect label on notice list file comment darcs-hash:20081223191430-84dde-7f50fbf9c39c3f397196ffca318d51de6624d7c9.gz --- _darcs/inventory | 4 +- ...dde-7f50fbf9c39c3f397196ffca318d51de6624d7c9.gz | Bin 0 -> 173 bytes _darcs/pristine/lib/noticelist.php | 2 +- _darcs/tentative_pristine | 575 +-------------------- lib/noticelist.php | 2 +- 5 files changed, 6 insertions(+), 577 deletions(-) create mode 100644 _darcs/patches/20081223191430-84dde-7f50fbf9c39c3f397196ffca318d51de6624d7c9.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index b1d1b1e70..c66eff2b7 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -47,4 +47,6 @@ Evan Prodromou **20081222201304 [reformat and document lib/mail.php for phpcs conformance Evan Prodromou **20081223173330] [bring lib/noticelist.php into line with PEAR code standards -Evan Prodromou **20081223190851] \ No newline at end of file +Evan Prodromou **20081223190851] +[incorrect label on notice list file comment +Evan Prodromou **20081223191430] \ No newline at end of file diff --git a/_darcs/patches/20081223191430-84dde-7f50fbf9c39c3f397196ffca318d51de6624d7c9.gz b/_darcs/patches/20081223191430-84dde-7f50fbf9c39c3f397196ffca318d51de6624d7c9.gz new file mode 100644 index 000000000..1d39cc7a1 Binary files /dev/null and b/_darcs/patches/20081223191430-84dde-7f50fbf9c39c3f397196ffca318d51de6624d7c9.gz differ diff --git a/_darcs/pristine/lib/noticelist.php b/_darcs/pristine/lib/noticelist.php index c9344a716..71db067d0 100644 --- a/_darcs/pristine/lib/noticelist.php +++ b/_darcs/pristine/lib/noticelist.php @@ -2,7 +2,7 @@ /** * Laconica, the distributed open-source microblogging tool * - * utilities for sending email + * widget for displaying a list of notices * * PHP version 5 * diff --git a/_darcs/tentative_pristine b/_darcs/tentative_pristine index e7d3612c8..e09c8fa72 100644 --- a/_darcs/tentative_pristine +++ b/_darcs/tentative_pristine @@ -1,576 +1,3 @@ -hunk ./actions/showstream.php 441 -- function new_list_item($notice) { -+ function newListItem($notice) { -hunk ./actions/showstream.php 447 -- function show_author() { -+ function showAuthor() { -hunk ./lib/noticelist.php 2 --/* -- * Laconica - a distributed open-source microblogging tool -- * Copyright (C) 2008, Controlez-Vous, Inc. -+/** -+ * Laconica, the distributed open-source microblogging tool hunk ./lib/noticelist.php 5 -- * This program is free software: you can redistribute it and/or modify -+ * utilities for sending email -+ * -+ * PHP version 5 -+ * -+ * LICENCE: This program is free software: you can redistribute it and/or modify -hunk ./lib/noticelist.php 16 -- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -hunk ./lib/noticelist.php 20 -- * along with this program. If not, see . -+ * along with this program. If not, see . -+ * -+ * @category UI -+ * @package Laconica -+ * @author Evan Prodromou -+ * @copyright 2008 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); -+} -+ -+/** +- * utilities for sending email + * widget for displaying a list of notices -+ * -+ * There are a number of actions that display a list of notices, in -+ * reverse chronological order. This widget abstracts out most of the -+ * code for UI for notice lists. It's overridden to hide some -+ * data for e.g. the profile page. -+ * -+ * @category UI -+ * @package Laconica -+ * @author Evan Prodromou -+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 -+ * @link http://laconi.ca/ -+ * @see Notice -+ * @see StreamAction -+ * @see NoticeListItem -+ * @see ProfileNoticeList -hunk ./lib/noticelist.php 53 --if (!defined('LACONICA')) { exit(1); } -+class NoticeList -+{ -+ /** the current stream of notices being displayed. */ -hunk ./lib/noticelist.php 57 --class NoticeList { -+ var $notice = null; -hunk ./lib/noticelist.php 59 -- var $notice = NULL; -+ /** -+ * constructor -+ * -+ * @param Notice $notice stream of notices from DB_DataObject -+ */ -hunk ./lib/noticelist.php 65 -- function __construct($notice) { -+ function __construct($notice) -+ { -hunk ./lib/noticelist.php 70 -- function show() { -+ /** -+ * show the list of notices -+ * -+ * "Uses up" the stream by looping through it. So, probably can't -+ * be called twice on the same list. -+ * -+ * @return int count of notices listed. -+ */ -hunk ./lib/noticelist.php 79 -- common_element_start('ul', array('id' => 'notices')); -+ function show() -+ { -+ common_element_start('ul', array('id' => 'notices')); -hunk ./lib/noticelist.php 83 -- $cnt = 0; -+ $cnt = 0; -hunk ./lib/noticelist.php 85 -- while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { -- $cnt++; -+ while ($this->notice->fetch() && $cnt <= NOTICES_PER_PAGE) { -+ $cnt++; -hunk ./lib/noticelist.php 88 -- if ($cnt > NOTICES_PER_PAGE) { -- break; -- } -+ if ($cnt > NOTICES_PER_PAGE) { -+ break; -+ } -hunk ./lib/noticelist.php 92 -- $item = $this->new_list_item($this->notice); -+ $item = $this->newListItem($this->notice); -hunk ./lib/noticelist.php 94 -- } -+ } -hunk ./lib/noticelist.php 96 -- common_element_end('ul'); -+ common_element_end('ul'); -hunk ./lib/noticelist.php 99 -- } -+ } -+ -+ /** -+ * returns a new list item for the current notice -+ * -+ * Recipe (factory?) method; overridden by sub-classes to give -+ * a different list item class. -+ * -+ * @param Notice $notice the current notice -+ * -+ * @return NoticeListItem a list item for displaying the notice -+ */ -hunk ./lib/noticelist.php 112 -- function new_list_item($notice) { -+ function newListItem($notice) -+ { -hunk ./lib/noticelist.php 118 --class NoticeListItem { -+/** -+ * widget for displaying a single notice -+ * -+ * This widget has the core smarts for showing a single notice: what to display, -+ * where, and under which circumstances. Its key method is show(); this is a recipe -+ * that calls all the other show*() methods to build up a single notice. The -+ * ProfileNoticeListItem subclass, for example, overrides showAuthor() to skip -+ * author info (since that's implicit by the data in the page). -+ * -+ * @category UI -+ * @package Laconica -+ * @author Evan Prodromou -+ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 -+ * @link http://laconi.ca/ -+ * @see NoticeList -+ * @see ProfileNoticeListItem -+ */ -+ -+class NoticeListItem -+{ -+ /** The notice this item will show. */ -hunk ./lib/noticelist.php 140 -- var $notice = NULL; -- var $profile = NULL; -+ var $notice = null; -hunk ./lib/noticelist.php 142 -- function __construct($notice) { -- $this->notice = $notice; -- $this->profile = $notice->getProfile(); -+ /** The profile of the author of the notice, extracted once for convenience. */ -+ -+ var $profile = null; -+ -+ /** -+ * constructor -+ * -+ * Also initializes the profile attribute. -+ * -+ * @param Notice $notice The notice we'll display -+ */ -+ -+ function __construct($notice) -+ { -+ $this->notice = $notice; -+ $this->profile = $notice->getProfile(); -hunk ./lib/noticelist.php 160 -- function show() { -- $this->show_start(); -- $this->show_fave_form(); -- $this->show_author(); -- $this->show_content(); -- $this->show_start_time_section(); -- $this->show_notice_link(); -- $this->show_notice_source(); -- $this->show_reply_to(); -- $this->show_reply_link(); -- $this->show_delete_link(); -- $this->show_end_time_section(); -- $this->show_end(); -- } -+ /** -+ * recipe function for displaying a single notice. -+ * -+ * This uses all the other methods to correctly display a notice. Override -+ * it or one of the others to fine-tune the output. -+ * -+ * @return void -+ */ -hunk ./lib/noticelist.php 169 -- function show_start() { -- # XXX: RDFa -- common_element_start('li', array('class' => 'notice_single hentry', -- 'id' => 'notice-' . $this->notice->id)); -+ function show() -+ { -+ $this->showStart(); -+ $this->showFaveForm(); -+ $this->showAuthor(); -+ $this->showContent(); -+ $this->startTimeSection(); -+ $this->showNoticeLink(); -+ $this->showNoticeSource(); -+ $this->showReplyTo(); -+ $this->showReplyLink(); -+ $this->showDeleteLink(); -+ $this->endTimeSection(); -+ $this->showEnd(); -hunk ./lib/noticelist.php 185 -- function show_fave_form() { -+ /** -+ * start a single notice. -+ * -+ * @return void -+ */ -+ -+ function showStart() -+ { -+ // XXX: RDFa -+ common_element_start('li', array('class' => 'notice_single hentry', -+ 'id' => 'notice-' . $this->notice->id)); -+ } -+ -+ /** -+ * show the "favorite" form -+ * -+ * @return void -+ */ -+ -+ function showFaveForm() -+ { -hunk ./lib/noticelist.php 207 -- if ($user) { -- if ($user->hasFave($this->notice)) { -- common_disfavor_form($this->notice); -- } else { -- common_favor_form($this->notice); -- } -- } -+ if ($user) { -+ if ($user->hasFave($this->notice)) { -+ common_disfavor_form($this->notice); -+ } else { -+ common_favor_form($this->notice); -+ } -+ } -hunk ./lib/noticelist.php 216 -- function show_author() { -- common_element_start('span', 'vcard author'); -- $this->show_avatar(); -- $this->show_nickname(); -- common_element_end('span'); -+ /** -+ * show the author of a notice -+ * -+ * By default, this shows the avatar and (linked) nickname of the author. -+ * -+ * @return void -+ */ -+ -+ function showAuthor() -+ { -+ common_element_start('span', 'vcard author'); -+ $this->showAvatar(); -+ $this->showNickname(); -+ common_element_end('span'); -hunk ./lib/noticelist.php 232 -- function show_avatar() { -- $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); -- common_element_start('a', array('href' => $this->profile->profileurl)); -- common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), -- 'class' => 'avatar stream photo', -- 'width' => AVATAR_STREAM_SIZE, -- 'height' => AVATAR_STREAM_SIZE, -- 'alt' => -- ($this->profile->fullname) ? $this->profile->fullname : -- $this->profile->nickname)); -- common_element_end('a'); -+ /** -+ * show the avatar of the notice's author -+ * -+ * This will use the default avatar if no avatar is assigned for the author. -+ * It makes a link to the author's profile. -+ * -+ * @return void -+ */ -+ -+ function showAvatar() -+ { -+ $avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); -+ common_element_start('a', array('href' => $this->profile->profileurl)); -+ common_element('img', array('src' => ($avatar) ? -+ common_avatar_display_url($avatar) : -+ common_default_avatar(AVATAR_STREAM_SIZE), -+ 'class' => 'avatar stream photo', -+ 'width' => AVATAR_STREAM_SIZE, -+ 'height' => AVATAR_STREAM_SIZE, -+ 'alt' => -+ ($this->profile->fullname) ? -+ $this->profile->fullname : -+ $this->profile->nickname)); -+ common_element_end('a'); -hunk ./lib/noticelist.php 258 -- function show_nickname() { -- common_element('a', array('href' => $this->profile->profileurl, -- 'class' => 'nickname fn url'), -- $this->profile->nickname); -+ /** -+ * show the nickname of the author -+ * -+ * Links to the author's profile page -+ * -+ * @return void -+ */ -+ -+ function showNickname() -+ { -+ common_element('a', array('href' => $this->profile->profileurl, -+ 'class' => 'nickname fn url'), -+ $this->profile->nickname); -hunk ./lib/noticelist.php 273 -- function show_content() { -- # FIXME: URL, image, video, audio -- common_element_start('p', array('class' => 'content entry-title')); -- if ($this->notice->rendered) { -- common_raw($this->notice->rendered); -- } else { -- # XXX: may be some uncooked notices in the DB, -- # we cook them right now. This should probably disappear in future -- # versions (>> 0.4.x) -- common_raw(common_render_content($this->notice->content, $this->notice)); -- } -- common_element_end('p'); -+ /** -+ * show the content of the notice -+ * -+ * Shows the content of the notice. This is pre-rendered for efficiency -+ * at save time. Some very old notices might not be pre-rendered, so -+ * they're rendered on the spot. -+ * -+ * @return void -+ */ -+ -+ function showContent() -+ { -+ // FIXME: URL, image, video, audio -+ common_element_start('p', array('class' => 'content entry-title')); -+ if ($this->notice->rendered) { -+ common_raw($this->notice->rendered); -+ } else { -+ // XXX: may be some uncooked notices in the DB, -+ // we cook them right now. This should probably disappear in future -+ // versions (>> 0.4.x) -+ common_raw(common_render_content($this->notice->content, $this->notice)); -+ } -+ common_element_end('p'); -hunk ./lib/noticelist.php 298 -- function show_start_time_section() { -- common_element_start('p', 'time'); -+ /** -+ * show the "time" section of a notice -+ * -+ * This is the greyed-out section that appears beneath the content, including -+ * links to delete or reply to the notice. Probably should be called something -+ * else. -+ * -+ * @return void -+ */ -+ -+ function startTimeSection() -+ { -+ common_element_start('p', 'time'); -hunk ./lib/noticelist.php 313 -- function show_notice_link() { -- $noticeurl = common_local_url('shownotice', array('notice' => $this->notice->id)); -- # XXX: we need to figure this out better. Is this right? -- if (strcmp($this->notice->uri, $noticeurl) != 0 && preg_match('/^http/', $this->notice->uri)) { -- $noticeurl = $this->notice->uri; -- } -- common_element_start('a', array('class' => 'permalink', -- 'rel' => 'bookmark', -- 'href' => $noticeurl)); -- common_element('abbr', array('class' => 'published', -- 'title' => common_date_iso8601($this->notice->created)), -- common_date_string($this->notice->created)); -- common_element_end('a'); -+ /** -+ * show the link to the main page for the notice -+ * -+ * Displays a link to the page for a notice, with "relative" time. Tries to -+ * get remote notice URLs correct, but doesn't always succeed. -+ * -+ * @return void -+ */ -+ -+ function showNoticeLink() -+ { -+ $noticeurl = common_local_url('shownotice', -+ array('notice' => $this->notice->id)); -+ // XXX: we need to figure this out better. Is this right? -+ if (strcmp($this->notice->uri, $noticeurl) != 0 && -+ preg_match('/^http/', $this->notice->uri)) { -+ $noticeurl = $this->notice->uri; -+ } -+ common_element_start('a', array('class' => 'permalink', -+ 'rel' => 'bookmark', -+ 'href' => $noticeurl)); -+ $dt = common_date_iso8601($this->notice->created); -+ common_element('abbr', array('class' => 'published', -+ 'title' => $dt), -+ common_date_string($this->notice->created)); -+ common_element_end('a'); -hunk ./lib/noticelist.php 341 -- function show_notice_source() { -- if ($this->notice->source) { -- common_element('span', null, _(' from ')); -+ /** -+ * 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. -+ * -+ * @return void -+ */ -+ -+ function showNoticeSource() -+ { -+ if ($this->notice->source) { -+ common_element('span', null, _(' from ')); -hunk ./lib/noticelist.php 356 -- case 'web': -- case 'xmpp': -- case 'mail': -- case 'omb': -- case 'api': -+ case 'web': -+ case 'xmpp': -+ case 'mail': -+ case 'omb': -+ case 'api': -hunk ./lib/noticelist.php 363 -- default: -+ default: -hunk ./lib/noticelist.php 373 -- } -+ } -hunk ./lib/noticelist.php 376 -- function show_reply_to() { -- if ($this->notice->reply_to) { -- $replyurl = common_local_url('shownotice', array('notice' => $this->notice->reply_to)); -- common_text(' ('); -- common_element('a', array('class' => 'inreplyto', -- 'href' => $replyurl), -- _('in reply to...')); -- common_text(')'); -- } -+ /** -+ * show link to notice this notice is a reply to -+ * -+ * If this notice is a reply, show a link to the notice it is replying to. The -+ * heavy lifting for figuring out replies happens at save time. -+ * -+ * @return void -+ */ -+ -+ function showReplyTo() -+ { -+ if ($this->notice->reply_to) { -+ $replyurl = common_local_url('shownotice', -+ array('notice' => $this->notice->reply_to)); -+ common_text(' ('); -+ common_element('a', array('class' => 'inreplyto', -+ 'href' => $replyurl), -+ _('in reply to...')); -+ common_text(')'); -+ } -hunk ./lib/noticelist.php 398 -- function show_reply_link() { -- common_element_start('a', -- array('href' => common_local_url('newnotice', -- array('replyto' => $this->profile->nickname)), -- 'onclick' => 'return doreply("'.$this->profile->nickname.'", '.$this->notice->id.');', -- 'title' => _('reply'), -- 'class' => 'replybutton')); -- common_raw(' →'); -- common_element_end('a'); -+ /** -+ * show a link to reply to the current notice -+ * -+ * Should either do the reply in the current notice form (if available), or -+ * link out to the notice-posting form. A little flakey, doesn't always work. -+ * -+ * @return void -+ */ -+ -+ function showReplyLink() -+ { -+ $reply_url = common_local_url('newnotice', -+ array('replyto' => $this->profile->nickname)); -+ -+ $reply_js = -+ 'return doreply("'.$this->profile->nickname.'",'.$this->notice->id.');'; -+ -+ common_element_start('a', -+ array('href' => $reply_url, -+ 'onclick' => $reply_js, -+ 'title' => _('reply'), -+ 'class' => 'replybutton')); -+ common_raw(' →'); -+ common_element_end('a'); -hunk ./lib/noticelist.php 424 -- function show_delete_link() { -+ /** -+ * if the user is the author, let them delete the notice -+ * -+ * @return void -+ */ -+ -+ function showDeleteLink() -+ { -hunk ./lib/noticelist.php 433 -- if ($user && $this->notice->profile_id == $user->id) { -- $deleteurl = common_local_url('deletenotice', array('notice' => $this->notice->id)); -- common_element_start('a', array('class' => 'deletenotice', -- 'href' => $deleteurl, -- 'title' => _('delete'))); -- common_raw(' ×'); -- common_element_end('a'); -- } -+ if ($user && $this->notice->profile_id == $user->id) { -+ $deleteurl = common_local_url('deletenotice', -+ array('notice' => $this->notice->id)); -+ common_element_start('a', array('class' => 'deletenotice', -+ 'href' => $deleteurl, -+ 'title' => _('delete'))); -+ common_raw(' ×'); -+ common_element_end('a'); -+ } -hunk ./lib/noticelist.php 444 -- function show_end_time_section() { -- common_element_end('p'); -+ /** -+ * end the time section -+ * -+ * @return void -+ */ -+ -+ function endTimeSection() -+ { -+ common_element_end('p'); -hunk ./lib/noticelist.php 455 -- function show_end() { -- common_element_end('li'); -+ /** -+ * finish the notice -+ * -+ * Close the last elements in the notice list item -+ * -+ * @return void -+ */ -+ -+ function showEnd() -+ { -+ common_element_end('li'); diff --git a/lib/noticelist.php b/lib/noticelist.php index c9344a716..71db067d0 100644 --- a/lib/noticelist.php +++ b/lib/noticelist.php @@ -2,7 +2,7 @@ /** * Laconica, the distributed open-source microblogging tool * - * utilities for sending email + * widget for displaying a list of notices * * PHP version 5 * -- cgit v1.2.3-54-g00ecf From edbc0c665cc65875b4d14b79939233b1c9c06bb6 Mon Sep 17 00:00:00 2001 From: Evan Prodromou Date: Tue, 23 Dec 2008 14:19:07 -0500 Subject: replace all tabs with four spaces The PEAR coding standards decree: no tabs, but indent by four spaces. I've done a global search-and-replace on all tabs, replacing them by four spaces. This is a huge change, but it will go a long way to getting us towards phpcs-compliance. And that means better code readability, and that means more participation. darcs-hash:20081223191907-84dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz --- _darcs/inventory | 12 +- ...dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz | Bin 0 -> 157972 bytes _darcs/pristine/actions/accesstoken.php | 34 +- _darcs/pristine/actions/all.php | 94 +- _darcs/pristine/actions/allrss.php | 84 +- _darcs/pristine/actions/api.php | 322 +- _darcs/pristine/actions/avatarbynickname.php | 76 +- _darcs/pristine/actions/block.php | 12 +- _darcs/pristine/actions/confirmaddress.php | 38 +- _darcs/pristine/actions/deletenotice.php | 136 +- _darcs/pristine/actions/deleteprofile.php | 246 +- _darcs/pristine/actions/disfavor.php | 94 +- _darcs/pristine/actions/doc.php | 28 +- _darcs/pristine/actions/emailsettings.php | 590 +- _darcs/pristine/actions/facebookhome.php | 140 +- _darcs/pristine/actions/facebookinvite.php | 26 +- _darcs/pristine/actions/facebookremove.php | 58 +- _darcs/pristine/actions/facebooksettings.php | 34 +- _darcs/pristine/actions/favor.php | 134 +- _darcs/pristine/actions/favorited.php | 102 +- _darcs/pristine/actions/favoritesrss.php | 72 +- _darcs/pristine/actions/featured.php | 108 +- _darcs/pristine/actions/finishaddopenid.php | 154 +- _darcs/pristine/actions/finishimmediate.php | 62 +- _darcs/pristine/actions/finishopenidlogin.php | 742 +- _darcs/pristine/actions/finishremotesubscribe.php | 402 +- _darcs/pristine/actions/foaf.php | 348 +- _darcs/pristine/actions/imsettings.php | 468 +- _darcs/pristine/actions/invite.php | 342 +- _darcs/pristine/actions/login.php | 236 +- _darcs/pristine/actions/logout.php | 32 +- _darcs/pristine/actions/microsummary.php | 38 +- _darcs/pristine/actions/newmessage.php | 224 +- _darcs/pristine/actions/newnotice.php | 254 +- _darcs/pristine/actions/noticesearch.php | 244 +- _darcs/pristine/actions/noticesearchrss.php | 56 +- _darcs/pristine/actions/nudge.php | 86 +- _darcs/pristine/actions/openidlogin.php | 122 +- _darcs/pristine/actions/openidsettings.php | 258 +- _darcs/pristine/actions/opensearch.php | 70 +- _darcs/pristine/actions/othersettings.php | 228 +- _darcs/pristine/actions/peoplesearch.php | 76 +- _darcs/pristine/actions/peopletag.php | 132 +- _darcs/pristine/actions/postnotice.php | 114 +- _darcs/pristine/actions/profilesettings.php | 824 +- _darcs/pristine/actions/public.php | 136 +- _darcs/pristine/actions/publicrss.php | 58 +- _darcs/pristine/actions/publicxrds.php | 82 +- _darcs/pristine/actions/recoverpassword.php | 590 +- _darcs/pristine/actions/register.php | 474 +- _darcs/pristine/actions/remotesubscribe.php | 604 +- _darcs/pristine/actions/replies.php | 96 +- _darcs/pristine/actions/repliesrss.php | 84 +- _darcs/pristine/actions/requesttoken.php | 34 +- _darcs/pristine/actions/showfavorites.php | 102 +- _darcs/pristine/actions/showmessage.php | 140 +- _darcs/pristine/actions/shownotice.php | 132 +- _darcs/pristine/actions/showstream.php | 736 +- _darcs/pristine/actions/smssettings.php | 590 +- _darcs/pristine/actions/subedit.php | 10 +- _darcs/pristine/actions/subscribe.php | 76 +- _darcs/pristine/actions/subscribers.php | 48 +- _darcs/pristine/actions/subscriptions.php | 44 +- _darcs/pristine/actions/sup.php | 110 +- _darcs/pristine/actions/tag.php | 270 +- _darcs/pristine/actions/tagother.php | 330 +- _darcs/pristine/actions/tagrss.php | 58 +- _darcs/pristine/actions/twitapiaccount.php | 104 +- _darcs/pristine/actions/twitapiblocks.php | 28 +- _darcs/pristine/actions/twitapidirect_messages.php | 516 +- _darcs/pristine/actions/twitapifavorites.php | 296 +- _darcs/pristine/actions/twitapifriendships.php | 192 +- _darcs/pristine/actions/twitapihelp.php | 50 +- _darcs/pristine/actions/twitapinotifications.php | 16 +- _darcs/pristine/actions/twitapistatuses.php | 1042 +- _darcs/pristine/actions/twitapiusers.php | 44 +- _darcs/pristine/actions/twittersettings.php | 596 +- _darcs/pristine/actions/unblock.php | 10 +- _darcs/pristine/actions/unsubscribe.php | 72 +- _darcs/pristine/actions/updateprofile.php | 286 +- _darcs/pristine/actions/userauthorization.php | 1104 +- _darcs/pristine/actions/userbyid.php | 30 +- _darcs/pristine/actions/userrss.php | 108 +- _darcs/pristine/actions/xrds.php | 212 +- _darcs/pristine/classes/Avatar.php | 106 +- _darcs/pristine/classes/Channel.php | 316 +- _darcs/pristine/classes/Command.php | 584 +- _darcs/pristine/classes/CommandInterpreter.php | 334 +- _darcs/pristine/classes/Fave.php | 28 +- _darcs/pristine/classes/Foreign_link.php | 86 +- _darcs/pristine/classes/Foreign_user.php | 86 +- _darcs/pristine/classes/Memcached_DataObject.php | 274 +- _darcs/pristine/classes/Message.php | 78 +- _darcs/pristine/classes/Notice.php | 804 +- _darcs/pristine/classes/NoticeWrapper.php | 42 +- _darcs/pristine/classes/Notice_tag.php | 34 +- _darcs/pristine/classes/Profile.php | 216 +- _darcs/pristine/classes/Profile_tag.php | 152 +- _darcs/pristine/classes/Queue_item.php | 60 +- _darcs/pristine/classes/Sms_carrier.php | 8 +- _darcs/pristine/classes/Subscription.php | 8 +- _darcs/pristine/classes/User.php | 592 +- _darcs/pristine/lib/common.php | 162 +- _darcs/pristine/lib/deleteaction.php | 74 +- _darcs/pristine/lib/facebookaction.php | 516 +- _darcs/pristine/lib/oauthstore.php | 218 +- _darcs/pristine/lib/omb.php | 378 +- _darcs/pristine/lib/openid.php | 316 +- _darcs/pristine/lib/personal.php | 366 +- _darcs/pristine/lib/profilelist.php | 260 +- _darcs/pristine/lib/queuehandler.php | 194 +- _darcs/pristine/lib/rssaction.php | 322 +- _darcs/pristine/lib/search_engines.php | 4 +- _darcs/pristine/lib/searchaction.php | 154 +- _darcs/pristine/lib/settingsaction.php | 100 +- _darcs/pristine/lib/stream.php | 34 +- _darcs/pristine/lib/subs.php | 122 +- _darcs/pristine/lib/theme.php | 18 +- _darcs/pristine/lib/twitter.php | 216 +- _darcs/pristine/lib/twitterapi.php | 1224 +- _darcs/pristine/lib/xmppqueuehandler.php | 112 +- _darcs/pristine/scripts/enjitqueuehandler.php | 86 +- _darcs/pristine/scripts/fixup_hashtags.php | 12 +- _darcs/pristine/scripts/fixup_inboxes.php | 58 +- _darcs/pristine/scripts/fixup_notices_rendered.php | 20 +- _darcs/pristine/scripts/getpiddir.php | 4 +- _darcs/pristine/scripts/inbox_users.php | 122 +- _darcs/pristine/scripts/jabberqueuehandler.php | 28 +- _darcs/pristine/scripts/maildaemon.php | 344 +- _darcs/pristine/scripts/ombqueuehandler.php | 52 +- _darcs/pristine/scripts/publicqueuehandler.php | 30 +- _darcs/pristine/scripts/sitemap.php | 538 +- _darcs/pristine/scripts/smsqueuehandler.php | 32 +- _darcs/pristine/scripts/synctwitterfriends.php | 28 +- _darcs/pristine/scripts/update_translations.php | 98 +- _darcs/pristine/scripts/xmppconfirmhandler.php | 192 +- _darcs/pristine/scripts/xmppdaemon.php | 504 +- _darcs/tentative_pristine | 28060 ++++++++++++++++++- actions/accesstoken.php | 34 +- actions/all.php | 94 +- actions/allrss.php | 84 +- actions/api.php | 322 +- actions/avatarbynickname.php | 76 +- actions/block.php | 12 +- actions/confirmaddress.php | 38 +- actions/deletenotice.php | 136 +- actions/deleteprofile.php | 246 +- actions/disfavor.php | 94 +- actions/doc.php | 28 +- actions/emailsettings.php | 590 +- actions/facebookhome.php | 140 +- actions/facebookinvite.php | 26 +- actions/facebookremove.php | 58 +- actions/facebooksettings.php | 34 +- actions/favor.php | 134 +- actions/favorited.php | 102 +- actions/favoritesrss.php | 72 +- actions/featured.php | 108 +- actions/finishaddopenid.php | 154 +- actions/finishimmediate.php | 62 +- actions/finishopenidlogin.php | 742 +- actions/finishremotesubscribe.php | 402 +- actions/foaf.php | 348 +- actions/imsettings.php | 468 +- actions/invite.php | 342 +- actions/login.php | 236 +- actions/logout.php | 32 +- actions/microsummary.php | 38 +- actions/newmessage.php | 224 +- actions/newnotice.php | 254 +- actions/noticesearch.php | 244 +- actions/noticesearchrss.php | 56 +- actions/nudge.php | 86 +- actions/openidlogin.php | 122 +- actions/openidsettings.php | 258 +- actions/opensearch.php | 70 +- actions/othersettings.php | 228 +- actions/peoplesearch.php | 76 +- actions/peopletag.php | 132 +- actions/postnotice.php | 114 +- actions/profilesettings.php | 824 +- actions/public.php | 136 +- actions/publicrss.php | 58 +- actions/publicxrds.php | 82 +- actions/recoverpassword.php | 590 +- actions/register.php | 474 +- actions/remotesubscribe.php | 604 +- actions/replies.php | 96 +- actions/repliesrss.php | 84 +- actions/requesttoken.php | 34 +- actions/showfavorites.php | 102 +- actions/showmessage.php | 140 +- actions/shownotice.php | 132 +- actions/showstream.php | 736 +- actions/smssettings.php | 590 +- actions/subedit.php | 10 +- actions/subscribe.php | 76 +- actions/subscribers.php | 48 +- actions/subscriptions.php | 44 +- actions/sup.php | 110 +- actions/tag.php | 270 +- actions/tagother.php | 330 +- actions/tagrss.php | 58 +- actions/twitapiaccount.php | 104 +- actions/twitapiblocks.php | 28 +- actions/twitapidirect_messages.php | 516 +- actions/twitapifavorites.php | 296 +- actions/twitapifriendships.php | 192 +- actions/twitapihelp.php | 50 +- actions/twitapinotifications.php | 16 +- actions/twitapistatuses.php | 1042 +- actions/twitapiusers.php | 44 +- actions/twittersettings.php | 596 +- actions/unblock.php | 10 +- actions/unsubscribe.php | 72 +- actions/updateprofile.php | 286 +- actions/userauthorization.php | 1104 +- actions/userbyid.php | 30 +- actions/userrss.php | 108 +- actions/xrds.php | 212 +- classes/Avatar.php | 106 +- classes/Channel.php | 316 +- classes/Command.php | 584 +- classes/CommandInterpreter.php | 334 +- classes/Fave.php | 28 +- classes/Foreign_link.php | 86 +- classes/Foreign_user.php | 86 +- classes/Memcached_DataObject.php | 274 +- classes/Message.php | 78 +- classes/Notice.php | 804 +- classes/NoticeWrapper.php | 42 +- classes/Notice_tag.php | 34 +- classes/Profile.php | 216 +- classes/Profile_tag.php | 152 +- classes/Queue_item.php | 60 +- classes/Sms_carrier.php | 8 +- classes/Subscription.php | 8 +- classes/User.php | 592 +- lib/common.php | 162 +- lib/deleteaction.php | 74 +- lib/facebookaction.php | 516 +- lib/oauthstore.php | 218 +- lib/omb.php | 378 +- lib/openid.php | 316 +- lib/personal.php | 366 +- lib/profilelist.php | 260 +- lib/queuehandler.php | 194 +- lib/rssaction.php | 322 +- lib/search_engines.php | 4 +- lib/searchaction.php | 154 +- lib/settingsaction.php | 100 +- lib/stream.php | 34 +- lib/subs.php | 122 +- lib/theme.php | 18 +- lib/twitter.php | 216 +- lib/twitterapi.php | 1224 +- lib/xmppqueuehandler.php | 112 +- scripts/enjitqueuehandler.php | 86 +- scripts/fixup_hashtags.php | 12 +- scripts/fixup_inboxes.php | 58 +- scripts/fixup_notices_rendered.php | 20 +- scripts/getpiddir.php | 4 +- scripts/inbox_users.php | 122 +- scripts/jabberqueuehandler.php | 28 +- scripts/maildaemon.php | 344 +- scripts/ombqueuehandler.php | 52 +- scripts/publicqueuehandler.php | 30 +- scripts/sitemap.php | 538 +- scripts/smsqueuehandler.php | 32 +- scripts/synctwitterfriends.php | 28 +- scripts/update_translations.php | 98 +- scripts/xmppconfirmhandler.php | 192 +- scripts/xmppdaemon.php | 504 +- 273 files changed, 56264 insertions(+), 28200 deletions(-) create mode 100644 _darcs/patches/20081223191907-84dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz (limited to 'lib') diff --git a/_darcs/inventory b/_darcs/inventory index c66eff2b7..f49b758ab 100644 --- a/_darcs/inventory +++ b/_darcs/inventory @@ -49,4 +49,14 @@ Evan Prodromou **20081223173330] [bring lib/noticelist.php into line with PEAR code standards Evan Prodromou **20081223190851] [incorrect label on notice list file comment -Evan Prodromou **20081223191430] \ No newline at end of file +Evan Prodromou **20081223191430] +[replace all tabs with four spaces +Evan Prodromou **20081223191907 + + The PEAR coding standards decree: no tabs, but indent by four spaces. + I've done a global search-and-replace on all tabs, replacing them by + four spaces. This is a huge change, but it will go a long way to + getting us towards phpcs-compliance. And that means better code + readability, and that means more participation. + +] \ No newline at end of file diff --git a/_darcs/patches/20081223191907-84dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz b/_darcs/patches/20081223191907-84dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz new file mode 100644 index 000000000..0ce001299 Binary files /dev/null and b/_darcs/patches/20081223191907-84dde-21e8efe210e6d5d54e935a22d0cee5c7bbfc007d.gz differ diff --git a/_darcs/pristine/actions/accesstoken.php b/_darcs/pristine/actions/accesstoken.php index 4907749ce..a468c33a6 100644 --- a/_darcs/pristine/actions/accesstoken.php +++ b/_darcs/pristine/actions/accesstoken.php @@ -22,21 +22,21 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/omb.php'); class AccesstokenAction extends Action { - function handle($args) { - parent::handle($args); - try { - common_debug('getting request from env variables', __FILE__); - common_remove_magic_from_request(); - $req = OAuthRequest::from_request(); - common_debug('getting a server', __FILE__); - $server = omb_oauth_server(); - common_debug('fetching the access token', __FILE__); - $token = $server->fetch_access_token($req); - common_debug('got this token: "'.print_r($token,TRUE).'"', __FILE__); - common_debug('printing the access token', __FILE__); - print $token; - } catch (OAuthException $e) { - common_server_error($e->getMessage()); - } - } + function handle($args) { + parent::handle($args); + try { + common_debug('getting request from env variables', __FILE__); + common_remove_magic_from_request(); + $req = OAuthRequest::from_request(); + common_debug('getting a server', __FILE__); + $server = omb_oauth_server(); + common_debug('fetching the access token', __FILE__); + $token = $server->fetch_access_token($req); + common_debug('got this token: "'.print_r($token,TRUE).'"', __FILE__); + common_debug('printing the access token', __FILE__); + print $token; + } catch (OAuthException $e) { + common_server_error($e->getMessage()); + } + } } diff --git a/_darcs/pristine/actions/all.php b/_darcs/pristine/actions/all.php index 2a26e48d4..066ee77bf 100644 --- a/_darcs/pristine/actions/all.php +++ b/_darcs/pristine/actions/all.php @@ -23,71 +23,71 @@ require_once(INSTALLDIR.'/actions/showstream.php'); class AllAction extends StreamAction { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); + $nickname = common_canonical_nickname($this->arg('nickname')); + $user = User::staticGet('nickname', $nickname); - if (!$user) { - $this->client_error(_('No such user.')); - return; - } + if (!$user) { + $this->client_error(_('No such user.')); + return; + } - $profile = $user->getProfile(); + $profile = $user->getProfile(); - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } - # Looks like we're good; show the header + # Looks like we're good; show the header - common_show_header(sprintf(_("%s and friends"), $profile->nickname), - array($this, 'show_header'), $user, - array($this, 'show_top')); + common_show_header(sprintf(_("%s and friends"), $profile->nickname), + array($this, 'show_header'), $user, + array($this, 'show_top')); - $this->show_notices($user); + $this->show_notices($user); - common_show_footer(); - } + common_show_footer(); + } - function show_header($user) { - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('allrss', array('nickname' => - $user->nickname)), - 'type' => 'application/rss+xml', - 'title' => sprintf(_('Feed for friends of %s'), $user->nickname))); - } + function show_header($user) { + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('allrss', array('nickname' => + $user->nickname)), + 'type' => 'application/rss+xml', + 'title' => sprintf(_('Feed for friends of %s'), $user->nickname))); + } - function show_top($user) { - $cur = common_current_user(); + function show_top($user) { + $cur = common_current_user(); - if ($cur && $cur->id == $user->id) { - common_notice_form('all'); - } + if ($cur && $cur->id == $user->id) { + common_notice_form('all'); + } - $this->views_menu(); + $this->views_menu(); - $this->show_feeds_list(array(0=>array('href'=>common_local_url('allrss', array('nickname' => $user->nickname)), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'allrss'))); - } + $this->show_feeds_list(array(0=>array('href'=>common_local_url('allrss', array('nickname' => $user->nickname)), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'allrss'))); + } - function show_notices($user) { + function show_notices($user) { - $page = $this->trimmed('page'); - if (!$page) { - $page = 1; - } + $page = $this->trimmed('page'); + if (!$page) { + $page = 1; + } - $notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); + $notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $cnt = $this->show_notice_list($notice); - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'all', array('nickname' => $user->nickname)); - } + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'all', array('nickname' => $user->nickname)); + } } diff --git a/_darcs/pristine/actions/allrss.php b/_darcs/pristine/actions/allrss.php index e49ac5540..d28fcea49 100644 --- a/_darcs/pristine/actions/allrss.php +++ b/_darcs/pristine/actions/allrss.php @@ -25,53 +25,53 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class AllrssAction extends Rss10Action { - var $user = NULL; + var $user = NULL; - function init() { - $nickname = $this->trimmed('nickname'); - $this->user = User::staticGet('nickname', $nickname); + function init() { + $nickname = $this->trimmed('nickname'); + $this->user = User::staticGet('nickname', $nickname); - if (!$this->user) { - common_user_error(_('No such user.')); - return false; - } else { - return true; - } - } + if (!$this->user) { + common_user_error(_('No such user.')); + return false; + } else { + return true; + } + } - function get_notices($limit=0) { + function get_notices($limit=0) { - $user = $this->user; - - $notice = $user->noticesWithFriends(0, $limit); - - while ($notice->fetch()) { - $notices[] = clone($notice); - } + $user = $this->user; + + $notice = $user->noticesWithFriends(0, $limit); + + while ($notice->fetch()) { + $notices[] = clone($notice); + } - return $notices; - } + return $notices; + } - function get_channel() { - $user = $this->user; - $c = array('url' => common_local_url('allrss', - array('nickname' => - $user->nickname)), - 'title' => sprintf(_('%s and friends'), $user->nickname), - 'link' => common_local_url('all', - array('nickname' => - $user->nickname)), - 'description' => sprintf(_('Feed for friends of %s'), $user->nickname)); - return $c; - } + function get_channel() { + $user = $this->user; + $c = array('url' => common_local_url('allrss', + array('nickname' => + $user->nickname)), + 'title' => sprintf(_('%s and friends'), $user->nickname), + 'link' => common_local_url('all', + array('nickname' => + $user->nickname)), + 'description' => sprintf(_('Feed for friends of %s'), $user->nickname)); + return $c; + } - function get_image() { - $user = $this->user; - $profile = $user->getProfile(); - if (!$profile) { - return NULL; - } - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - return ($avatar) ? $avatar->url : NULL; - } + function get_image() { + $user = $this->user; + $profile = $user->getProfile(); + if (!$profile) { + return NULL; + } + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + return ($avatar) ? $avatar->url : NULL; + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/api.php b/_darcs/pristine/actions/api.php index 919a515ce..e03961e21 100644 --- a/_darcs/pristine/actions/api.php +++ b/_darcs/pristine/actions/api.php @@ -10,115 +10,115 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } class ApiAction extends Action { - var $user; - var $content_type; - var $api_arg; - var $api_method; - var $api_action; - - function handle($args) { - parent::handle($args); - - $this->api_action = $this->arg('apiaction'); - $method = $this->arg('method'); - $argument = $this->arg('argument'); - - if (isset($argument)) { - $cmdext = explode('.', $argument); - $this->api_arg = $cmdext[0]; - $this->api_method = $method; - $this->content_type = strtolower($cmdext[1]); - } else { - - # Requested format / content-type will be an extension on the method - $cmdext = explode('.', $method); - $this->api_method = $cmdext[0]; - $this->content_type = strtolower($cmdext[1]); - } - - if ($this->requires_auth()) { - if (!isset($_SERVER['PHP_AUTH_USER'])) { - - # This header makes basic auth go - header('WWW-Authenticate: Basic realm="Laconica API"'); - - # If the user hits cancel -- bam! - $this->show_basic_auth_error(); - } else { - $nickname = $_SERVER['PHP_AUTH_USER']; - $password = $_SERVER['PHP_AUTH_PW']; - $user = common_check_user($nickname, $password); - - if ($user) { - $this->user = $user; - $this->process_command(); - } else { - # basic authentication failed - $this->show_basic_auth_error(); - } - } - } else { - - # Look for the user in the session - if (common_logged_in()) { - $this->user = common_current_user(); - } - - $this->process_command(); - } - } - - function process_command() { - $action = "twitapi$this->api_action"; - $actionfile = INSTALLDIR."/actions/$action.php"; - - if (file_exists($actionfile)) { - require_once($actionfile); - $action_class = ucfirst($action)."Action"; - $action_obj = new $action_class(); + var $user; + var $content_type; + var $api_arg; + var $api_method; + var $api_action; + + function handle($args) { + parent::handle($args); + + $this->api_action = $this->arg('apiaction'); + $method = $this->arg('method'); + $argument = $this->arg('argument'); + + if (isset($argument)) { + $cmdext = explode('.', $argument); + $this->api_arg = $cmdext[0]; + $this->api_method = $method; + $this->content_type = strtolower($cmdext[1]); + } else { + + # Requested format / content-type will be an extension on the method + $cmdext = explode('.', $method); + $this->api_method = $cmdext[0]; + $this->content_type = strtolower($cmdext[1]); + } + + if ($this->requires_auth()) { + if (!isset($_SERVER['PHP_AUTH_USER'])) { + + # This header makes basic auth go + header('WWW-Authenticate: Basic realm="Laconica API"'); + + # If the user hits cancel -- bam! + $this->show_basic_auth_error(); + } else { + $nickname = $_SERVER['PHP_AUTH_USER']; + $password = $_SERVER['PHP_AUTH_PW']; + $user = common_check_user($nickname, $password); + + if ($user) { + $this->user = $user; + $this->process_command(); + } else { + # basic authentication failed + $this->show_basic_auth_error(); + } + } + } else { + + # Look for the user in the session + if (common_logged_in()) { + $this->user = common_current_user(); + } + + $this->process_command(); + } + } + + function process_command() { + $action = "twitapi$this->api_action"; + $actionfile = INSTALLDIR."/actions/$action.php"; + + if (file_exists($actionfile)) { + require_once($actionfile); + $action_class = ucfirst($action)."Action"; + $action_obj = new $action_class(); if (!$action_obj->prepare($this->args)) { return; } - if (method_exists($action_obj, $this->api_method)) { - $apidata = array( 'content-type' => $this->content_type, - 'api_method' => $this->api_method, - 'api_arg' => $this->api_arg, - 'user' => $this->user); - - call_user_func(array($action_obj, $this->api_method), $_REQUEST, $apidata); - } else { - common_user_error("API method not found!", $code=404); - } - } else { - common_user_error("API method not found!", $code=404); - } - } - - # Whitelist of API methods that don't need authentication - function requires_auth() { - static $noauth = array( 'statuses/public_timeline', - 'statuses/show', - 'users/show', - 'help/test', - 'help/downtime_schedule'); - - static $bareauth = array('statuses/user_timeline', - 'statuses/friends', - 'statuses/followers', - 'favorites/favorites'); + if (method_exists($action_obj, $this->api_method)) { + $apidata = array( 'content-type' => $this->content_type, + 'api_method' => $this->api_method, + 'api_arg' => $this->api_arg, + 'user' => $this->user); + + call_user_func(array($action_obj, $this->api_method), $_REQUEST, $apidata); + } else { + common_user_error("API method not found!", $code=404); + } + } else { + common_user_error("API method not found!", $code=404); + } + } + + # Whitelist of API methods that don't need authentication + function requires_auth() { + static $noauth = array( 'statuses/public_timeline', + 'statuses/show', + 'users/show', + 'help/test', + 'help/downtime_schedule'); + + static $bareauth = array('statuses/user_timeline', + 'statuses/friends', + 'statuses/followers', + 'favorites/favorites'); # If the site is "private", all API methods need authentication @@ -126,71 +126,71 @@ class ApiAction extends Action { return true; } - $fullname = "$this->api_action/$this->api_method"; - - if (in_array($fullname, $bareauth)) { - # bareauth: only needs auth if without an argument - if ($this->api_arg) { - return false; - } else { - return true; - } - } else if (in_array($fullname, $noauth)) { - # noauth: never needs auth - return false; - } else { - # everybody else needs auth - return true; - } - } - - function show_basic_auth_error() { - header('HTTP/1.1 401 Unauthorized'); - $msg = 'Could not authenticate you.'; - - if ($this->content_type == 'xml') { - header('Content-Type: application/xml; charset=utf-8'); - common_start_xml(); - common_element_start('hash'); - common_element('error', NULL, $msg); - common_element('request', NULL, $_SERVER['REQUEST_URI']); - common_element_end('hash'); - common_end_xml(); - } else if ($this->content_type == 'json') { - header('Content-Type: application/json; charset=utf-8'); - $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); - print(json_encode($error_array)); - } else { - header('Content-type: text/plain'); - print "$msg\n"; - } - } - - function is_readonly() { - # NOTE: before handle(), can't use $this->arg - $apiaction = $_REQUEST['apiaction']; - $method = $_REQUEST['method']; - list($cmdtext, $fmt) = explode('.', $method); - - static $write_methods = array( - 'account' => array('update_location', 'update_delivery_device', 'end_session'), - 'blocks' => array('create', 'destroy'), - 'direct_messages' => array('create', 'destroy'), - 'favorites' => array('create', 'destroy'), - 'friendships' => array('create', 'destroy'), - 'help' => array(), - 'notifications' => array('follow', 'leave'), - 'statuses' => array('update', 'destroy'), - 'users' => array() - ); - - if (array_key_exists($apiaction, $write_methods)) { - if (!in_array($cmdtext, $write_methods[$apiaction])) { - return true; - } - } - - return false; - } + $fullname = "$this->api_action/$this->api_method"; + + if (in_array($fullname, $bareauth)) { + # bareauth: only needs auth if without an argument + if ($this->api_arg) { + return false; + } else { + return true; + } + } else if (in_array($fullname, $noauth)) { + # noauth: never needs auth + return false; + } else { + # everybody else needs auth + return true; + } + } + + function show_basic_auth_error() { + header('HTTP/1.1 401 Unauthorized'); + $msg = 'Could not authenticate you.'; + + if ($this->content_type == 'xml') { + header('Content-Type: application/xml; charset=utf-8'); + common_start_xml(); + common_element_start('hash'); + common_element('error', NULL, $msg); + common_element('request', NULL, $_SERVER['REQUEST_URI']); + common_element_end('hash'); + common_end_xml(); + } else if ($this->content_type == 'json') { + header('Content-Type: application/json; charset=utf-8'); + $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']); + print(json_encode($error_array)); + } else { + header('Content-type: text/plain'); + print "$msg\n"; + } + } + + function is_readonly() { + # NOTE: before handle(), can't use $this->arg + $apiaction = $_REQUEST['apiaction']; + $method = $_REQUEST['method']; + list($cmdtext, $fmt) = explode('.', $method); + + static $write_methods = array( + 'account' => array('update_location', 'update_delivery_device', 'end_session'), + 'blocks' => array('create', 'destroy'), + 'direct_messages' => array('create', 'destroy'), + 'favorites' => array('create', 'destroy'), + 'friendships' => array('create', 'destroy'), + 'help' => array(), + 'notifications' => array('follow', 'leave'), + 'statuses' => array('update', 'destroy'), + 'users' => array() + ); + + if (array_key_exists($apiaction, $write_methods)) { + if (!in_array($cmdtext, $write_methods[$apiaction])) { + return true; + } + } + + return false; + } } diff --git a/_darcs/pristine/actions/avatarbynickname.php b/_darcs/pristine/actions/avatarbynickname.php index b33cababf..2ca861a66 100644 --- a/_darcs/pristine/actions/avatarbynickname.php +++ b/_darcs/pristine/actions/avatarbynickname.php @@ -24,45 +24,45 @@ class AvatarbynicknameAction extends Action { parent::handle($args); $nickname = $this->trimmed('nickname'); if (!$nickname) { - $this->client_error(_('No nickname.')); - return; - } - $size = $this->trimmed('size'); + $this->client_error(_('No nickname.')); + return; + } + $size = $this->trimmed('size'); if (!$size) { - $this->client_error(_('No size.')); - return; - } - $size = strtolower($size); - if (!in_array($size, array('original', '96', '48', '24'))) { - $this->client_error(_('Invalid size.')); - return; - } + $this->client_error(_('No size.')); + return; + } + $size = strtolower($size); + if (!in_array($size, array('original', '96', '48', '24'))) { + $this->client_error(_('Invalid size.')); + return; + } - $user = User::staticGet('nickname', $nickname); - if (!$user) { - $this->client_error(_('No such user.')); - return; - } - $profile = $user->getProfile(); - if (!$profile) { - $this->client_error(_('User has no profile.')); - return; - } - if ($size == 'original') { - $avatar = $profile->getOriginal(); - } else { - $avatar = $profile->getAvatar($size+0); - } + $user = User::staticGet('nickname', $nickname); + if (!$user) { + $this->client_error(_('No such user.')); + return; + } + $profile = $user->getProfile(); + if (!$profile) { + $this->client_error(_('User has no profile.')); + return; + } + if ($size == 'original') { + $avatar = $profile->getOriginal(); + } else { + $avatar = $profile->getAvatar($size+0); + } - if ($avatar) { - $url = $avatar->url; - } else { - if ($size == 'original') { - $url = common_default_avatar(AVATAR_PROFILE_SIZE); - } else { - $url = common_default_avatar($size+0); - } - } - common_redirect($url, 302); - } + if ($avatar) { + $url = $avatar->url; + } else { + if ($size == 'original') { + $url = common_default_avatar(AVATAR_PROFILE_SIZE); + } else { + $url = common_default_avatar($size+0); + } + } + common_redirect($url, 302); + } } diff --git a/_darcs/pristine/actions/block.php b/_darcs/pristine/actions/block.php index e6d2b7e49..20ba81edb 100644 --- a/_darcs/pristine/actions/block.php +++ b/_darcs/pristine/actions/block.php @@ -32,12 +32,12 @@ class BlockAction extends Action { return false; } - $token = $this->trimmed('token'); + $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } $id = $this->trimmed('blockto'); @@ -75,7 +75,7 @@ class BlockAction extends Action { $id = $this->profile->id; - common_show_header(_('Block user')); + common_show_header(_('Block user')); common_element('p', NULL, _('Are you sure you want to block this user? '. diff --git a/_darcs/pristine/actions/confirmaddress.php b/_darcs/pristine/actions/confirmaddress.php index 44280e08a..9d97c8205 100644 --- a/_darcs/pristine/actions/confirmaddress.php +++ b/_darcs/pristine/actions/confirmaddress.php @@ -43,44 +43,44 @@ class ConfirmaddressAction extends Action { $this->client_error(_('That confirmation code is not for you!')); return; } - $type = $confirm->address_type; - if (!in_array($type, array('email', 'jabber', 'sms'))) { - $this->server_error(sprintf(_('Unrecognized address type %s'), $type)); - return; - } + $type = $confirm->address_type; + if (!in_array($type, array('email', 'jabber', 'sms'))) { + $this->server_error(sprintf(_('Unrecognized address type %s'), $type)); + return; + } if ($cur->$type == $confirm->address) { $this->client_error(_('That address has already been confirmed.')); - return; - } + return; + } $cur->query('BEGIN'); $orig_user = clone($cur); - $cur->$type = $confirm->address; + $cur->$type = $confirm->address; - if ($type == 'sms') { - $cur->carrier = ($confirm->address_extra)+0; - $carrier = Sms_carrier::staticGet($cur->carrier); - $cur->smsemail = $carrier->toEmailAddress($cur->sms); - } + if ($type == 'sms') { + $cur->carrier = ($confirm->address_extra)+0; + $carrier = Sms_carrier::staticGet($cur->carrier); + $cur->smsemail = $carrier->toEmailAddress($cur->sms); + } - $result = $cur->updateKeys($orig_user); + $result = $cur->updateKeys($orig_user); if (!$result) { - common_log_db_error($cur, 'UPDATE', __FILE__); + common_log_db_error($cur, 'UPDATE', __FILE__); $this->server_error(_('Couldn\'t update user.')); return; } - if ($type == 'email') { - $cur->emailChanged(); - } + if ($type == 'email') { + $cur->emailChanged(); + } $result = $confirm->delete(); if (!$result) { - common_log_db_error($confirm, 'DELETE', __FILE__); + common_log_db_error($confirm, 'DELETE', __FILE__); $this->server_error(_('Couldn\'t delete email confirmation.')); return; } diff --git a/_darcs/pristine/actions/deletenotice.php b/_darcs/pristine/actions/deletenotice.php index 64746283a..ba348c5fa 100644 --- a/_darcs/pristine/actions/deletenotice.php +++ b/_darcs/pristine/actions/deletenotice.php @@ -22,80 +22,80 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/deleteaction.php'); class DeletenoticeAction extends DeleteAction { - function handle($args) { - parent::handle($args); - # XXX: Ajax! + function handle($args) { + parent::handle($args); + # XXX: Ajax! - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->delete_notice(); - } else if ($_SERVER['REQUEST_METHOD'] == 'GET') { - $this->show_form(); - } - } + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->delete_notice(); + } else if ($_SERVER['REQUEST_METHOD'] == 'GET') { + $this->show_form(); + } + } - function get_instructions() { - return _('You are about to permanently delete a notice. Once this is done, it cannot be undone.'); - } + function get_instructions() { + return _('You are about to permanently delete a notice. Once this is done, it cannot be undone.'); + } - function get_title() { - return _('Delete notice'); - } + function get_title() { + return _('Delete notice'); + } - function show_form($error=NULL) { - $user = common_current_user(); + function show_form($error=NULL) { + $user = common_current_user(); - common_show_header($this->get_title(), array($this, 'show_header'), $error, - array($this, 'show_top')); - common_element_start('form', array('id' => 'notice_delete_form', - 'method' => 'post', - 'action' => common_local_url('deletenotice'))); - common_hidden('token', common_session_token()); - common_hidden('notice', $this->trimmed('notice')); - common_element_start('p'); - common_element('span', array('id' => 'confirmation_text'), _('Are you sure you want to delete this notice?')); + common_show_header($this->get_title(), array($this, 'show_header'), $error, + array($this, 'show_top')); + common_element_start('form', array('id' => 'notice_delete_form', + 'method' => 'post', + 'action' => common_local_url('deletenotice'))); + common_hidden('token', common_session_token()); + common_hidden('notice', $this->trimmed('notice')); + common_element_start('p'); + common_element('span', array('id' => 'confirmation_text'), _('Are you sure you want to delete this notice?')); - common_element('input', array('id' => 'submit_no', - 'name' => 'submit', - 'type' => 'submit', - 'value' => _('No'))); - common_element('input', array('id' => 'submit_yes', - 'name' => 'submit', - 'type' => 'submit', - 'value' => _('Yes'))); - common_element_end('p'); - common_element_end('form'); - common_show_footer(); - } + common_element('input', array('id' => 'submit_no', + 'name' => 'submit', + 'type' => 'submit', + 'value' => _('No'))); + common_element('input', array('id' => 'submit_yes', + 'name' => 'submit', + 'type' => 'submit', + 'value' => _('Yes'))); + common_element_end('p'); + common_element_end('form'); + common_show_footer(); + } - function delete_notice() { - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - $url = common_get_returnto(); - $confirmed = $this->trimmed('submit'); - if ($confirmed == _('Yes')) { - $user = common_current_user(); - $notice_id = $this->trimmed('notice'); - $notice = Notice::staticGet($notice_id); - $replies = new Reply; - $replies->get('notice_id', $notice_id); + function delete_notice() { + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + $url = common_get_returnto(); + $confirmed = $this->trimmed('submit'); + if ($confirmed == _('Yes')) { + $user = common_current_user(); + $notice_id = $this->trimmed('notice'); + $notice = Notice::staticGet($notice_id); + $replies = new Reply; + $replies->get('notice_id', $notice_id); - common_dequeue_notice($notice); - if (common_config('memcached', 'enabled')) { - $notice->blowSubsCache(); - } - $replies->delete(); - $notice->delete(); - } else { - if ($url) { - common_set_returnto(NULL); - } else { - $url = common_local_url('public'); - } - } - common_redirect($url); - } + common_dequeue_notice($notice); + if (common_config('memcached', 'enabled')) { + $notice->blowSubsCache(); + } + $replies->delete(); + $notice->delete(); + } else { + if ($url) { + common_set_returnto(NULL); + } else { + $url = common_local_url('public'); + } + } + common_redirect($url); + } } diff --git a/_darcs/pristine/actions/deleteprofile.php b/_darcs/pristine/actions/deleteprofile.php index 418ac998d..29797bc76 100644 --- a/_darcs/pristine/actions/deleteprofile.php +++ b/_darcs/pristine/actions/deleteprofile.php @@ -32,101 +32,101 @@ class DeleteprofileAction extends Action { } } - function get_instructions() { - return _('Export and delete your user information.'); - } - - function form_header($title, $msg=NULL, $success=false) { - common_show_header($title, - NULL, - array($msg, $success), - array($this, 'show_top')); - } - - function show_feeds_list($feeds) { - common_element_start('div', array('class' => 'feedsdel')); - common_element('p', null, 'Feeds:'); - common_element_start('ul', array('class' => 'xoxo')); - - foreach ($feeds as $key => $value) { - $this->common_feed_item($feeds[$key]); - } - common_element_end('ul'); - common_element_end('div'); - } + function get_instructions() { + return _('Export and delete your user information.'); + } + + function form_header($title, $msg=NULL, $success=false) { + common_show_header($title, + NULL, + array($msg, $success), + array($this, 'show_top')); + } + + function show_feeds_list($feeds) { + common_element_start('div', array('class' => 'feedsdel')); + common_element('p', null, 'Feeds:'); + common_element_start('ul', array('class' => 'xoxo')); + + foreach ($feeds as $key => $value) { + $this->common_feed_item($feeds[$key]); + } + common_element_end('ul'); + common_element_end('div'); + } //TODO move to common.php (and retrace its origin) - function common_feed_item($feed) { + function common_feed_item($feed) { + $user = common_current_user(); + $nickname = $user->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 'foaf': + $feed_classname = "foaf"; + $feed_mimetype = "application/".$feed['type']."+xml"; + $feed_title = "$nickname's FOAF file"; + $feed['textContent'] = "FOAF"; + break; + } + common_element_start('li'); + common_element('a', array('href' => $feed['href'], + 'class' => $feed_classname, + 'type' => $feed_mimetype, + 'title' => $feed_title), + $feed['textContent']); + common_element_end('li'); + } + + function show_form($msg=NULL, $success=false) { + $this->form_header(_('Delete my account'), $msg, $success); + common_element('h2', NULL, _('Delete my account confirmation')); + $this->show_confirm_delete_form(); + common_show_footer(); + } + + function show_confirm_delete_form() { $user = common_current_user(); - $nickname = $user->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 'foaf': - $feed_classname = "foaf"; - $feed_mimetype = "application/".$feed['type']."+xml"; - $feed_title = "$nickname's FOAF file"; - $feed['textContent'] = "FOAF"; - break; - } - common_element_start('li'); - common_element('a', array('href' => $feed['href'], - 'class' => $feed_classname, - 'type' => $feed_mimetype, - 'title' => $feed_title), - $feed['textContent']); - common_element_end('li'); - } - - function show_form($msg=NULL, $success=false) { - $this->form_header(_('Delete my account'), $msg, $success); - common_element('h2', NULL, _('Delete my account confirmation')); - $this->show_confirm_delete_form(); - common_show_footer(); - } - - function show_confirm_delete_form() { - $user = common_current_user(); $notices = DB_DataObject::factory('notice'); $notices->profile_id = $user->id; $notice_count = (int) $notices->count(); - common_element_start('form', array('method' => 'POST', - 'id' => 'delete', - 'action' => - common_local_url('deleteprofile'))); + common_element_start('form', array('method' => 'POST', + 'id' => 'delete', + 'action' => + common_local_url('deleteprofile'))); - common_hidden('token', common_session_token()); + common_hidden('token', common_session_token()); common_element('p', null, "Last chance to copy your notices and contacts by saving the two links below before deleting your account. Be careful, this operation cannot be undone."); - $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'notices'), - 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), - 'type' => 'rdf', - 'version' => 'FOAF', - 'item' => 'foaf'))); + $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'notices'), + 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), + 'type' => 'rdf', + 'version' => 'FOAF', + 'item' => 'foaf'))); common_checkbox('confirmation', _('Check if you are sure you want to delete your account.')); - common_submit('deleteaccount', _('Delete my account')); - common_element_end('form'); + common_submit('deleteaccount', _('Delete my account')); + common_element_end('form'); } - function handle_post() { - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } + function handle_post() { + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } if ($this->arg('deleteaccount') && $this->arg('confirmation')) { $this->delete_account(); @@ -134,9 +134,9 @@ class DeleteprofileAction extends Action { $this->show_form(); } - function delete_account() { - $user = common_current_user(); - assert(!is_null($user)); # should already be checked + function delete_account() { + $user = common_current_user(); + assert(!is_null($user)); # should already be checked // deleted later through the profile /* @@ -219,53 +219,53 @@ class DeleteprofileAction extends Action { common_redirect(common_local_url('public')); } - function show_top($arr) { - $msg = $arr[0]; - $success = $arr[1]; - if ($msg) { - $this->message($msg, $success); - } else { - $inst = $this->get_instructions(); - $output = common_markup_to_html($inst); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - } - $this->settings_menu(); - } + function show_top($arr) { + $msg = $arr[0]; + $success = $arr[1]; + if ($msg) { + $this->message($msg, $success); + } else { + $inst = $this->get_instructions(); + $output = common_markup_to_html($inst); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + } + $this->settings_menu(); + } function settings_menu() { # action => array('prompt', 'title') - $menu = - array('profilesettings' => - array(_('Profile'), - _('Change your profile settings')), - 'emailsettings' => - array(_('Email'), - _('Change email handling')), - 'openidsettings' => - array(_('OpenID'), - _('Add or remove OpenIDs')), - 'smssettings' => - array(_('SMS'), - _('Updates by SMS')), - 'imsettings' => - array(_('IM'), - _('Updates by instant messenger (IM)')), - 'twittersettings' => - array(_('Twitter'), - _('Twitter integration options')), - 'othersettings' => - array(_('Other'), - _('Other options'))); + $menu = + array('profilesettings' => + array(_('Profile'), + _('Change your profile settings')), + 'emailsettings' => + array(_('Email'), + _('Change email handling')), + 'openidsettings' => + array(_('OpenID'), + _('Add or remove OpenIDs')), + 'smssettings' => + array(_('SMS'), + _('Updates by SMS')), + 'imsettings' => + array(_('IM'), + _('Updates by instant messenger (IM)')), + 'twittersettings' => + array(_('Twitter'), + _('Twitter integration options')), + 'othersettings' => + array(_('Other'), + _('Other options'))); $action = $this->trimmed('action'); common_element_start('ul', array('id' => 'nav_views')); foreach ($menu as $menuaction => $menudesc) { - if ($menuaction == 'imsettings' && - !common_config('xmpp', 'enabled')) { - continue; - } + if ($menuaction == 'imsettings' && + !common_config('xmpp', 'enabled')) { + continue; + } common_menu_item(common_local_url($menuaction), $menudesc[0], $menudesc[1], diff --git a/_darcs/pristine/actions/disfavor.php b/_darcs/pristine/actions/disfavor.php index be208f65a..e47e68a8c 100644 --- a/_darcs/pristine/actions/disfavor.php +++ b/_darcs/pristine/actions/disfavor.php @@ -21,63 +21,63 @@ if (!defined('LACONICA')) { exit(1); } class DisfavorAction extends Action { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - return; - } + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + return; + } - $user = common_current_user(); + $user = common_current_user(); - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname))); - return; - } + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname))); + return; + } - $id = $this->trimmed('notice'); + $id = $this->trimmed('notice'); - $notice = Notice::staticGet($id); + $notice = Notice::staticGet($id); - $token = $this->trimmed('token-'.$notice->id); + $token = $this->trimmed('token-'.$notice->id); - if (!$token || $token != common_session_token()) { - $this->client_error(_("There was a problem with your session token. Try again, please.")); - return; - } + if (!$token || $token != common_session_token()) { + $this->client_error(_("There was a problem with your session token. Try again, please.")); + return; + } - $fave = new Fave(); - $fave->user_id = $this->id; - $fave->notice_id = $notice->id; - if (!$fave->find(true)) { - $this->client_error(_('This notice is not a favorite!')); - return; - } + $fave = new Fave(); + $fave->user_id = $this->id; + $fave->notice_id = $notice->id; + if (!$fave->find(true)) { + $this->client_error(_('This notice is not a favorite!')); + return; + } - $result = $fave->delete(); + $result = $fave->delete(); - if (!$result) { - common_log_db_error($fave, 'DELETE', __FILE__); - $this->server_error(_('Could not delete favorite.')); - return; - } - - $user->blowFavesCache(); + if (!$result) { + common_log_db_error($fave, 'DELETE', __FILE__); + $this->server_error(_('Could not delete favorite.')); + return; + } + + $user->blowFavesCache(); - if ($this->boolean('ajax')) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Add to favorites')); - common_element_end('head'); - common_element_start('body'); - common_favor_form($notice); - common_element_end('body'); - common_element_end('html'); - } else { - common_redirect(common_local_url('showfavorites', - array('nickname' => $user->nickname))); - } - } + if ($this->boolean('ajax')) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Add to favorites')); + common_element_end('head'); + common_element_start('body'); + common_favor_form($notice); + common_element_end('body'); + common_element_end('html'); + } else { + common_redirect(common_local_url('showfavorites', + array('nickname' => $user->nickname))); + } + } } diff --git a/_darcs/pristine/actions/doc.php b/_darcs/pristine/actions/doc.php index f3327048f..0cf665d68 100644 --- a/_darcs/pristine/actions/doc.php +++ b/_darcs/pristine/actions/doc.php @@ -21,18 +21,18 @@ if (!defined('LACONICA')) { exit(1); } class DocAction extends Action { - function handle($args) { - parent::handle($args); - $title = $this->trimmed('title'); - $filename = INSTALLDIR.'/doc/'.$title; - if (!file_exists($filename)) { - common_user_error(_('No such document.')); - return; - } - $c = file_get_contents($filename); - $output = common_markup_to_html($c); - common_show_header(_(ucfirst($title))); - common_raw($output); - common_show_footer(); - } + function handle($args) { + parent::handle($args); + $title = $this->trimmed('title'); + $filename = INSTALLDIR.'/doc/'.$title; + if (!file_exists($filename)) { + common_user_error(_('No such document.')); + return; + } + $c = file_get_contents($filename); + $output = common_markup_to_html($c); + common_show_header(_(ucfirst($title))); + common_raw($output); + common_show_footer(); + } } diff --git a/_darcs/pristine/actions/emailsettings.php b/_darcs/pristine/actions/emailsettings.php index b35b4d28e..b77817c8e 100644 --- a/_darcs/pristine/actions/emailsettings.php +++ b/_darcs/pristine/actions/emailsettings.php @@ -23,308 +23,308 @@ require_once(INSTALLDIR.'/lib/settingsaction.php'); class EmailsettingsAction extends SettingsAction { - function get_instructions() { - return _('Manage how you get email from %%site.name%%.'); - } - - function show_form($msg=NULL, $success=false) { - $user = common_current_user(); - $this->form_header(_('Email Settings'), $msg, $success); - common_element_start('form', array('method' => 'post', - 'id' => 'emailsettings', - 'action' => - common_local_url('emailsettings'))); - common_hidden('token', common_session_token()); - - common_element('h2', NULL, _('Address')); - - if ($user->email) { - common_element_start('p'); - common_element('span', 'address confirmed', $user->email); - common_element('span', 'input_instructions', - _('Current confirmed email address.')); - common_hidden('email', $user->email); - common_element_end('p'); - common_submit('remove', _('Remove')); - } else { - $confirm = $this->get_confirmation(); - if ($confirm) { - common_element_start('p'); - common_element('span', 'address unconfirmed', $confirm->address); - common_element('span', 'input_instructions', - _('Awaiting confirmation on this address. Check your inbox (and spam box!) for a message with further instructions.')); - common_hidden('email', $confirm->address); - common_element_end('p'); - common_submit('cancel', _('Cancel')); - } else { - common_input('email', _('Email Address'), - ($this->arg('email')) ? $this->arg('email') : NULL, - _('Email address, like "UserName@example.org"')); - common_submit('add', _('Add')); - } - } - - if ($user->email) { - common_element('h2', NULL, _('Incoming email')); - - if ($user->incomingemail) { - common_element_start('p'); - common_element('span', 'address', $user->incomingemail); - common_element('span', 'input_instructions', - _('Send email to this address to post new notices.')); - common_element_end('p'); - common_submit('removeincoming', _('Remove')); - } - - common_element_start('p'); - common_element('span', 'input_instructions', - _('Make a new email address for posting to; cancels the old one.')); - common_element_end('p'); - common_submit('newincoming', _('New')); - } - - common_element('h2', NULL, _('Preferences')); - - common_checkbox('emailnotifysub', - _('Send me notices of new subscriptions through email.'), - $user->emailnotifysub); - common_checkbox('emailnotifyfav', - _('Send me email when someone adds my notice as a favorite.'), - $user->emailnotifyfav); - common_checkbox('emailnotifymsg', - _('Send me email when someone sends me a private message.'), - $user->emailnotifymsg); - common_checkbox('emailnotifynudge', - _('Allow friends to nudge me and send me an email.'), - $user->emailnotifynudge); - common_checkbox('emailpost', - _('I want to post notices by email.'), - $user->emailpost); - common_checkbox('emailmicroid', - _('Publish a MicroID for my email address.'), - $user->emailmicroid); - - common_submit('save', _('Save')); - - common_element_end('form'); - common_show_footer(); - } - - function get_confirmation() { - $user = common_current_user(); - $confirm = new Confirm_address(); - $confirm->user_id = $user->id; - $confirm->address_type = 'email'; - if ($confirm->find(TRUE)) { - return $confirm; - } else { - return NULL; - } - } - - function handle_post() { - - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - if ($this->arg('save')) { - $this->save_preferences(); - } else if ($this->arg('add')) { - $this->add_address(); - } else if ($this->arg('cancel')) { - $this->cancel_confirmation(); - } else if ($this->arg('remove')) { - $this->remove_address(); - } else if ($this->arg('removeincoming')) { - $this->remove_incoming(); - } else if ($this->arg('newincoming')) { - $this->new_incoming(); - } else { - $this->show_form(_('Unexpected form submission.')); - } - } - - function save_preferences() { - - $emailnotifysub = $this->boolean('emailnotifysub'); - $emailnotifyfav = $this->boolean('emailnotifyfav'); - $emailnotifymsg = $this->boolean('emailnotifymsg'); - $emailnotifynudge = $this->boolean('emailnotifynudge'); - $emailmicroid = $this->boolean('emailmicroid'); - $emailpost = $this->boolean('emailpost'); - - $user = common_current_user(); - - assert(!is_null($user)); # should already be checked - - $user->query('BEGIN'); - - $original = clone($user); - - $user->emailnotifysub = $emailnotifysub; - $user->emailnotifyfav = $emailnotifyfav; - $user->emailnotifymsg = $emailnotifymsg; - $user->emailnotifynudge = $emailnotifynudge; - $user->emailmicroid = $emailmicroid; - $user->emailpost = $emailpost; - - $result = $user->update($original); - - if ($result === FALSE) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } - - $user->query('COMMIT'); - - $this->show_form(_('Preferences saved.'), true); - } - - function add_address() { - - $user = common_current_user(); - - $email = $this->trimmed('email'); - - # Some validation - - if (!$email) { - $this->show_form(_('No email address.')); - return; - } - - $email = common_canonical_email($email); - - if (!$email) { - $this->show_form(_('Cannot normalize that email address')); - return; - } - if (!Validate::email($email, true)) { - $this->show_form(_('Not a valid email address')); - return; - } else if ($user->email == $email) { - $this->show_form(_('That is already your email address.')); - return; - } else if ($this->email_exists($email)) { - $this->show_form(_('That email address already belongs to another user.')); - return; - } - - $confirm = new Confirm_address(); - $confirm->address = $email; - $confirm->address_type = 'email'; - $confirm->user_id = $user->id; - $confirm->code = common_confirmation_code(64); - - $result = $confirm->insert(); - - if ($result === FALSE) { - common_log_db_error($confirm, 'INSERT', __FILE__); - common_server_error(_('Couldn\'t insert confirmation code.')); - return; - } - - mail_confirm_address($user, $confirm->code, $user->nickname, $email); - - $msg = _('A confirmation code was sent to the email address you added. Check your inbox (and spam box!) for the code and instructions on how to use it.'); - - $this->show_form($msg, TRUE); - } - - function cancel_confirmation() { - $email = $this->arg('email'); - $confirm = $this->get_confirmation(); - if (!$confirm) { - $this->show_form(_('No pending confirmation to cancel.')); - return; - } - if ($confirm->address != $email) { - $this->show_form(_('That is the wrong IM address.')); - return; - } + function get_instructions() { + return _('Manage how you get email from %%site.name%%.'); + } + + function show_form($msg=NULL, $success=false) { + $user = common_current_user(); + $this->form_header(_('Email Settings'), $msg, $success); + common_element_start('form', array('method' => 'post', + 'id' => 'emailsettings', + 'action' => + common_local_url('emailsettings'))); + common_hidden('token', common_session_token()); + + common_element('h2', NULL, _('Address')); + + if ($user->email) { + common_element_start('p'); + common_element('span', 'address confirmed', $user->email); + common_element('span', 'input_instructions', + _('Current confirmed email address.')); + common_hidden('email', $user->email); + common_element_end('p'); + common_submit('remove', _('Remove')); + } else { + $confirm = $this->get_confirmation(); + if ($confirm) { + common_element_start('p'); + common_element('span', 'address unconfirmed', $confirm->address); + common_element('span', 'input_instructions', + _('Awaiting confirmation on this address. Check your inbox (and spam box!) for a message with further instructions.')); + common_hidden('email', $confirm->address); + common_element_end('p'); + common_submit('cancel', _('Cancel')); + } else { + common_input('email', _('Email Address'), + ($this->arg('email')) ? $this->arg('email') : NULL, + _('Email address, like "UserName@example.org"')); + common_submit('add', _('Add')); + } + } + + if ($user->email) { + common_element('h2', NULL, _('Incoming email')); + + if ($user->incomingemail) { + common_element_start('p'); + common_element('span', 'address', $user->incomingemail); + common_element('span', 'input_instructions', + _('Send email to this address to post new notices.')); + common_element_end('p'); + common_submit('removeincoming', _('Remove')); + } + + common_element_start('p'); + common_element('span', 'input_instructions', + _('Make a new email address for posting to; cancels the old one.')); + common_element_end('p'); + common_submit('newincoming', _('New')); + } + + common_element('h2', NULL, _('Preferences')); + + common_checkbox('emailnotifysub', + _('Send me notices of new subscriptions through email.'), + $user->emailnotifysub); + common_checkbox('emailnotifyfav', + _('Send me email when someone adds my notice as a favorite.'), + $user->emailnotifyfav); + common_checkbox('emailnotifymsg', + _('Send me email when someone sends me a private message.'), + $user->emailnotifymsg); + common_checkbox('emailnotifynudge', + _('Allow friends to nudge me and send me an email.'), + $user->emailnotifynudge); + common_checkbox('emailpost', + _('I want to post notices by email.'), + $user->emailpost); + common_checkbox('emailmicroid', + _('Publish a MicroID for my email address.'), + $user->emailmicroid); + + common_submit('save', _('Save')); + + common_element_end('form'); + common_show_footer(); + } + + function get_confirmation() { + $user = common_current_user(); + $confirm = new Confirm_address(); + $confirm->user_id = $user->id; + $confirm->address_type = 'email'; + if ($confirm->find(TRUE)) { + return $confirm; + } else { + return NULL; + } + } + + function handle_post() { + + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + if ($this->arg('save')) { + $this->save_preferences(); + } else if ($this->arg('add')) { + $this->add_address(); + } else if ($this->arg('cancel')) { + $this->cancel_confirmation(); + } else if ($this->arg('remove')) { + $this->remove_address(); + } else if ($this->arg('removeincoming')) { + $this->remove_incoming(); + } else if ($this->arg('newincoming')) { + $this->new_incoming(); + } else { + $this->show_form(_('Unexpected form submission.')); + } + } + + function save_preferences() { + + $emailnotifysub = $this->boolean('emailnotifysub'); + $emailnotifyfav = $this->boolean('emailnotifyfav'); + $emailnotifymsg = $this->boolean('emailnotifymsg'); + $emailnotifynudge = $this->boolean('emailnotifynudge'); + $emailmicroid = $this->boolean('emailmicroid'); + $emailpost = $this->boolean('emailpost'); + + $user = common_current_user(); + + assert(!is_null($user)); # should already be checked + + $user->query('BEGIN'); + + $original = clone($user); + + $user->emailnotifysub = $emailnotifysub; + $user->emailnotifyfav = $emailnotifyfav; + $user->emailnotifymsg = $emailnotifymsg; + $user->emailnotifynudge = $emailnotifynudge; + $user->emailmicroid = $emailmicroid; + $user->emailpost = $emailpost; + + $result = $user->update($original); + + if ($result === FALSE) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } + + $user->query('COMMIT'); + + $this->show_form(_('Preferences saved.'), true); + } + + function add_address() { + + $user = common_current_user(); + + $email = $this->trimmed('email'); + + # Some validation + + if (!$email) { + $this->show_form(_('No email address.')); + return; + } + + $email = common_canonical_email($email); + + if (!$email) { + $this->show_form(_('Cannot normalize that email address')); + return; + } + if (!Validate::email($email, true)) { + $this->show_form(_('Not a valid email address')); + return; + } else if ($user->email == $email) { + $this->show_form(_('That is already your email address.')); + return; + } else if ($this->email_exists($email)) { + $this->show_form(_('That email address already belongs to another user.')); + return; + } + + $confirm = new Confirm_address(); + $confirm->address = $email; + $confirm->address_type = 'email'; + $confirm->user_id = $user->id; + $confirm->code = common_confirmation_code(64); + + $result = $confirm->insert(); + + if ($result === FALSE) { + common_log_db_error($confirm, 'INSERT', __FILE__); + common_server_error(_('Couldn\'t insert confirmation code.')); + return; + } + + mail_confirm_address($user, $confirm->code, $user->nickname, $email); + + $msg = _('A confirmation code was sent to the email address you added. Check your inbox (and spam box!) for the code and instructions on how to use it.'); + + $this->show_form($msg, TRUE); + } + + function cancel_confirmation() { + $email = $this->arg('email'); + $confirm = $this->get_confirmation(); + if (!$confirm) { + $this->show_form(_('No pending confirmation to cancel.')); + return; + } + if ($confirm->address != $email) { + $this->show_form(_('That is the wrong IM address.')); + return; + } $result = $confirm->delete(); if (!$result) { - common_log_db_error($confirm, 'DELETE', __FILE__); + common_log_db_error($confirm, 'DELETE', __FILE__); $this->server_error(_('Couldn\'t delete email confirmation.')); return; } $this->show_form(_('Confirmation cancelled.'), TRUE); - } - - function remove_address() { - - $user = common_current_user(); - $email = $this->arg('email'); - - # Maybe an old tab open...? - - if ($user->email != $email) { - $this->show_form(_('That is not your email address.')); - return; - } - - $user->query('BEGIN'); - $original = clone($user); - $user->email = NULL; - $result = $user->updateKeys($original); - if (!$result) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } - $user->query('COMMIT'); - - $this->show_form(_('The address was removed.'), TRUE); - } - - function remove_incoming() { - $user = common_current_user(); - - if (!$user->incomingemail) { - $this->show_form(_('No incoming email address.')); - return; - } - - $orig = clone($user); - $user->incomingemail = NULL; - - if (!$user->updateKeys($orig)) { - common_log_db_error($user, 'UPDATE', __FILE__); - $this->server_error(_("Couldn't update user record.")); - } - - $this->show_form(_('Incoming email address removed.'), TRUE); - } - - function new_incoming() { - $user = common_current_user(); - - $orig = clone($user); - $user->incomingemail = mail_new_incoming_address(); - - if (!$user->updateKeys($orig)) { - common_log_db_error($user, 'UPDATE', __FILE__); - $this->server_error(_("Couldn't update user record.")); - } - - $this->show_form(_('New incoming email address added.'), TRUE); - } - - function email_exists($email) { - $user = common_current_user(); - $other = User::staticGet('email', $email); - if (!$other) { - return false; - } else { - return $other->id != $user->id; - } - } + } + + function remove_address() { + + $user = common_current_user(); + $email = $this->arg('email'); + + # Maybe an old tab open...? + + if ($user->email != $email) { + $this->show_form(_('That is not your email address.')); + return; + } + + $user->query('BEGIN'); + $original = clone($user); + $user->email = NULL; + $result = $user->updateKeys($original); + if (!$result) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } + $user->query('COMMIT'); + + $this->show_form(_('The address was removed.'), TRUE); + } + + function remove_incoming() { + $user = common_current_user(); + + if (!$user->incomingemail) { + $this->show_form(_('No incoming email address.')); + return; + } + + $orig = clone($user); + $user->incomingemail = NULL; + + if (!$user->updateKeys($orig)) { + common_log_db_error($user, 'UPDATE', __FILE__); + $this->server_error(_("Couldn't update user record.")); + } + + $this->show_form(_('Incoming email address removed.'), TRUE); + } + + function new_incoming() { + $user = common_current_user(); + + $orig = clone($user); + $user->incomingemail = mail_new_incoming_address(); + + if (!$user->updateKeys($orig)) { + common_log_db_error($user, 'UPDATE', __FILE__); + $this->server_error(_("Couldn't update user record.")); + } + + $this->show_form(_('New incoming email address added.'), TRUE); + } + + function email_exists($email) { + $user = common_current_user(); + $other = User::staticGet('email', $email); + if (!$other) { + return false; + } else { + return $other->id != $user->id; + } + } } diff --git a/_darcs/pristine/actions/facebookhome.php b/_darcs/pristine/actions/facebookhome.php index 8ee2d4cd3..c964f451a 100644 --- a/_darcs/pristine/actions/facebookhome.php +++ b/_darcs/pristine/actions/facebookhome.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,110 +23,110 @@ require_once(INSTALLDIR.'/lib/facebookaction.php'); class FacebookhomeAction extends FacebookAction { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $this->login(); - } + $this->login(); + } - function login() { + function login() { - $user = null; + $user = null; - $facebook = $this->get_facebook(); - $fbuid = $facebook->require_login(); + $facebook = $this->get_facebook(); + $fbuid = $facebook->require_login(); - # check to see whether there's already a Facebook link for this user - $flink = Foreign_link::getByForeignID($fbuid, 2); // 2 == Facebook + # check to see whether there's already a Facebook link for this user + $flink = Foreign_link::getByForeignID($fbuid, 2); // 2 == Facebook - if ($flink) { + if ($flink) { - $user = $flink->getUser(); - $this->show_home($facebook, $fbuid, $user); + $user = $flink->getUser(); + $this->show_home($facebook, $fbuid, $user); - } else { + } else { - # Make the user put in her Laconica creds - $nickname = common_canonical_nickname($this->trimmed('nickname')); - $password = $this->arg('password'); + # Make the user put in her Laconica creds + $nickname = common_canonical_nickname($this->trimmed('nickname')); + $password = $this->arg('password'); - if ($nickname) { + if ($nickname) { - if (common_check_user($nickname, $password)) { + if (common_check_user($nickname, $password)) { - $user = User::staticGet('nickname', $nickname); + $user = User::staticGet('nickname', $nickname); - if (!$user) { - echo ''; - $this->show_login_form(); - } + if (!$user) { + echo ''; + $this->show_login_form(); + } - $flink = DB_DataObject::factory('foreign_link'); - $flink->user_id = $user->id; - $flink->foreign_id = $fbuid; - $flink->service = 2; # Facebook - $flink->created = common_sql_now(); + $flink = DB_DataObject::factory('foreign_link'); + $flink->user_id = $user->id; + $flink->foreign_id = $fbuid; + $flink->service = 2; # Facebook + $flink->created = common_sql_now(); - # $this->set_flags($flink, $noticesync, $replysync, $friendsync); + # $this->set_flags($flink, $noticesync, $replysync, $friendsync); - $flink_id = $flink->insert(); + $flink_id = $flink->insert(); - if ($flink_id) { - echo ''; - } + if ($flink_id) { + echo ''; + } - $this->show_home($facebook, $fbuid, $user); + $this->show_home($facebook, $fbuid, $user); - return; - } else { - echo ''; - } - } + return; + } else { + echo ''; + } + } - $this->show_login_form(); - } + $this->show_login_form(); + } - } + } - function show_home($facebook, $fbuid, $user) { + function show_home($facebook, $fbuid, $user) { - $this->show_header('Home'); + $this->show_header('Home'); - echo $this->show_notices($user); - $this->update_profile_box($facebook, $fbuid, $user); + echo $this->show_notices($user); + $this->update_profile_box($facebook, $fbuid, $user); - $this->show_footer(); - } + $this->show_footer(); + } - function show_notices($user) { + function show_notices($user) { - $page = $this->trimmed('page'); - if (!$page) { - $page = 1; - } + $page = $this->trimmed('page'); + if (!$page) { + $page = 1; + } - $notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); + $notice = $user->noticesWithFriends(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); - echo '
    '; + echo '
      '; - $cnt = 0; + $cnt = 0; - while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) { - $cnt++; + while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) { + $cnt++; - if ($cnt > NOTICES_PER_PAGE) { - break; - } + if ($cnt > NOTICES_PER_PAGE) { + break; + } - echo $this->render_notice($notice); - } + echo $this->render_notice($notice); + } - echo '
        '; + echo '
          '; - $this->pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'index.php', array('nickname' => $user->nickname)); + $this->pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'index.php', array('nickname' => $user->nickname)); - } + } } diff --git a/_darcs/pristine/actions/facebookinvite.php b/_darcs/pristine/actions/facebookinvite.php index 68b351fb9..3a85a7c5c 100644 --- a/_darcs/pristine/actions/facebookinvite.php +++ b/_darcs/pristine/actions/facebookinvite.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,24 +23,24 @@ require_once(INSTALLDIR.'/lib/facebookaction.php'); class FacebookinviteAction extends FacebookAction { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $this->display(); - } + $this->display(); + } - function display() { + function display() { - $facebook = $this->get_facebook(); + $facebook = $this->get_facebook(); - $fbuid = $facebook->require_login(); + $fbuid = $facebook->require_login(); - $this->show_header('Invite'); + $this->show_header('Invite'); - echo '

          Coming soon...

          '; + echo '

          Coming soon...

          '; - $this->show_footer(); + $this->show_footer(); - } + } } diff --git a/_darcs/pristine/actions/facebookremove.php b/_darcs/pristine/actions/facebookremove.php index 2a7bdd03e..1215f6622 100644 --- a/_darcs/pristine/actions/facebookremove.php +++ b/_darcs/pristine/actions/facebookremove.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,43 +23,43 @@ require_once(INSTALLDIR.'/lib/facebookaction.php'); class FacebookremoveAction extends FacebookAction { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $secret = common_config('facebook', 'secret'); + $secret = common_config('facebook', 'secret'); - $sig = ''; + $sig = ''; - ksort($_POST); + ksort($_POST); - foreach ($_POST as $key => $val) { - if (substr($key, 0, 7) == 'fb_sig_') { - $sig .= substr($key, 7) . '=' . $val; - } - } + foreach ($_POST as $key => $val) { + if (substr($key, 0, 7) == 'fb_sig_') { + $sig .= substr($key, 7) . '=' . $val; + } + } - $sig .= $secret; - $verify = md5($sig); + $sig .= $secret; + $verify = md5($sig); - if ($verify == $this->arg('fb_sig')) { + if ($verify == $this->arg('fb_sig')) { - $flink = Foreign_link::getByForeignID($this->arg('fb_sig_user'), 2); + $flink = Foreign_link::getByForeignID($this->arg('fb_sig_user'), 2); - common_debug("Removing foreign link to Facebook - local user ID: $flink->user_id, Facebook ID: $flink->foreign_id"); + common_debug("Removing foreign link to Facebook - local user ID: $flink->user_id, Facebook ID: $flink->foreign_id"); - $result = $flink->delete(); + $result = $flink->delete(); - if (!$result) { - common_log_db_error($flink, 'DELETE', __FILE__); - common_server_error(_('Couldn\'t remove Facebook user.')); - return; - } + if (!$result) { + common_log_db_error($flink, 'DELETE', __FILE__); + common_server_error(_('Couldn\'t remove Facebook user.')); + return; + } - } else { - # Someone bad tried to remove facebook link? - common_log(LOG_ERR, "Someone from $_SERVER[REMOTE_ADDR] " . - 'unsuccessfully tried to remove a foreign link to Facebook!'); - } - } + } else { + # Someone bad tried to remove facebook link? + common_log(LOG_ERR, "Someone from $_SERVER[REMOTE_ADDR] " . + 'unsuccessfully tried to remove a foreign link to Facebook!'); + } + } } diff --git a/_darcs/pristine/actions/facebooksettings.php b/_darcs/pristine/actions/facebooksettings.php index 4d7000d60..a5ad9d07a 100644 --- a/_darcs/pristine/actions/facebooksettings.php +++ b/_darcs/pristine/actions/facebooksettings.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/facebookaction.php'); class FacebooksettingsAction extends FacebookAction { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $this->display(); - } + $this->display(); + } - function display() { + function display() { - $facebook = $this->get_facebook(); + $facebook = $this->get_facebook(); - $fbuid = $facebook->require_login(); + $fbuid = $facebook->require_login(); - $fbml = '' - .'

          Add an Identi.ca box to your profile!

          ' - .'' - .'
          '; + $fbml = '' + .'

          Add an Identi.ca box to your profile!

          ' + .'' + .'
          '; - $this->show_header('Settings'); + $this->show_header('Settings'); - echo $fbml; + echo $fbml; - $this->show_footer(); + $this->show_footer(); - } + } } diff --git a/_darcs/pristine/actions/favor.php b/_darcs/pristine/actions/favor.php index aede32902..c0b0324b5 100644 --- a/_darcs/pristine/actions/favor.php +++ b/_darcs/pristine/actions/favor.php @@ -23,72 +23,72 @@ require_once(INSTALLDIR.'/lib/mail.php'); class FavorAction extends Action { - function handle($args) { - parent::handle($args); - - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - return; - } - - $user = common_current_user(); - - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname))); - return; - } - - $id = $this->trimmed('notice'); - - $notice = Notice::staticGet($id); - - # CSRF protection - - $token = $this->trimmed('token-'.$notice->id); - if (!$token || $token != common_session_token()) { - $this->client_error(_("There was a problem with your session token. Try again, please.")); - return; - } - - if ($user->hasFave($notice)) { - $this->client_error(_('This notice is already a favorite!')); - return; - } - - $fave = Fave::addNew($user, $notice); - - if (!$fave) { - $this->server_error(_('Could not create favorite.')); - return; - } - - $this->notify($fave, $notice, $user); - $user->blowFavesCache(); - - if ($this->boolean('ajax')) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Disfavor favorite')); - common_element_end('head'); - common_element_start('body'); - common_disfavor_form($notice); - common_element_end('body'); - common_element_end('html'); - } else { - common_redirect(common_local_url('showfavorites', - array('nickname' => $user->nickname))); - } - } - - function notify($fave, $notice, $user) { - $other = User::staticGet('id', $notice->profile_id); - if ($other && $other->id != $user->id) { - if ($other->email && $other->emailnotifyfav) { - mail_notify_fave($other, $user, $notice); - } - # XXX: notify by IM - # XXX: notify by SMS - } - } + function handle($args) { + parent::handle($args); + + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + return; + } + + $user = common_current_user(); + + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + common_redirect(common_local_url('showfavorites', array('nickname' => $user->nickname))); + return; + } + + $id = $this->trimmed('notice'); + + $notice = Notice::staticGet($id); + + # CSRF protection + + $token = $this->trimmed('token-'.$notice->id); + if (!$token || $token != common_session_token()) { + $this->client_error(_("There was a problem with your session token. Try again, please.")); + return; + } + + if ($user->hasFave($notice)) { + $this->client_error(_('This notice is already a favorite!')); + return; + } + + $fave = Fave::addNew($user, $notice); + + if (!$fave) { + $this->server_error(_('Could not create favorite.')); + return; + } + + $this->notify($fave, $notice, $user); + $user->blowFavesCache(); + + if ($this->boolean('ajax')) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Disfavor favorite')); + common_element_end('head'); + common_element_start('body'); + common_disfavor_form($notice); + common_element_end('body'); + common_element_end('html'); + } else { + common_redirect(common_local_url('showfavorites', + array('nickname' => $user->nickname))); + } + } + + function notify($fave, $notice, $user) { + $other = User::staticGet('id', $notice->profile_id); + if ($other && $other->id != $user->id) { + if ($other->email && $other->emailnotifyfav) { + mail_notify_fave($other, $user, $notice); + } + # XXX: notify by IM + # XXX: notify by SMS + } + } } diff --git a/_darcs/pristine/actions/favorited.php b/_darcs/pristine/actions/favorited.php index dc8070d06..6a465df96 100644 --- a/_darcs/pristine/actions/favorited.php +++ b/_darcs/pristine/actions/favorited.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,77 +23,77 @@ require_once(INSTALLDIR.'/lib/stream.php'); class FavoritedAction extends StreamAction { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - common_show_header(_('Popular notices'), - array($this, 'show_header'), NULL, - array($this, 'show_top')); + common_show_header(_('Popular notices'), + array($this, 'show_header'), NULL, + array($this, 'show_top')); - $this->show_notices($page); + $this->show_notices($page); - common_show_footer(); - } + common_show_footer(); + } - function show_top() { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - $this->public_views_menu(); - } + function show_top() { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + $this->public_views_menu(); + } - function show_header() { + function show_header() { return; - } + } - function get_instructions() { - return _('Showing recently popular notices'); - } + function get_instructions() { + return _('Showing recently popular notices'); + } - function show_notices($page) { + function show_notices($page) { - $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'; + $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'; - $offset = ($page - 1) * NOTICES_PER_PAGE; - $limit = NOTICES_PER_PAGE + 1; + $offset = ($page - 1) * NOTICES_PER_PAGE; + $limit = NOTICES_PER_PAGE + 1; - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; - } + if (common_config('db','type') == 'pgsql') { + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $qry .= ' LIMIT ' . $offset . ', ' . $limit; + } - # Figure out how to cache this query + # Figure out how to cache this query - $notice = new Notice; - $notice->query(sprintf($qry, common_config('popular', 'dropoff'))); + $notice = new Notice; + $notice->query(sprintf($qry, common_config('popular', 'dropoff'))); - common_element_start('ul', array('id' => 'notices')); + common_element_start('ul', array('id' => 'notices')); - $cnt = 0; + $cnt = 0; - while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) { - $cnt++; + while ($notice->fetch() && $cnt <= NOTICES_PER_PAGE) { + $cnt++; - if ($cnt > NOTICES_PER_PAGE) { - break; - } + if ($cnt > NOTICES_PER_PAGE) { + break; + } $item = new NoticeListItem($notice); $item->show(); - } + } - common_element_end('ul'); + common_element_end('ul'); - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'favorited'); - } + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'favorited'); + } } diff --git a/_darcs/pristine/actions/favoritesrss.php b/_darcs/pristine/actions/favoritesrss.php index 25dd3861f..642d4f880 100644 --- a/_darcs/pristine/actions/favoritesrss.php +++ b/_darcs/pristine/actions/favoritesrss.php @@ -25,49 +25,49 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class FavoritesrssAction extends Rss10Action { - var $user = NULL; - - function init() { - $nickname = $this->trimmed('nickname'); - $this->user = User::staticGet('nickname', $nickname); + var $user = NULL; + + function init() { + $nickname = $this->trimmed('nickname'); + $this->user = User::staticGet('nickname', $nickname); - if (!$this->user) { - common_user_error(_('No such user.')); - return false; - } else { - return true; - } - } + if (!$this->user) { + common_user_error(_('No such user.')); + return false; + } else { + return true; + } + } - function get_notices($limit=0) { + function get_notices($limit=0) { - $user = $this->user; + $user = $this->user; - $notice = $user->favoriteNotices(0, $limit); + $notice = $user->favoriteNotices(0, $limit); - $notices = array(); + $notices = array(); - while ($notice->fetch()) { - $notices[] = clone($notice); - } + while ($notice->fetch()) { + $notices[] = clone($notice); + } - return $notices; - } + return $notices; + } - function get_channel() { - $user = $this->user; - $c = array('url' => common_local_url('favoritesrss', - array('nickname' => - $user->nickname)), - 'title' => sprintf(_("%s favorite notices"), $user->nickname), - 'link' => common_local_url('showfavorites', - array('nickname' => - $user->nickname)), - 'description' => sprintf(_('Feed of favorite notices of %s'), $user->nickname)); - return $c; - } + function get_channel() { + $user = $this->user; + $c = array('url' => common_local_url('favoritesrss', + array('nickname' => + $user->nickname)), + 'title' => sprintf(_("%s favorite notices"), $user->nickname), + 'link' => common_local_url('showfavorites', + array('nickname' => + $user->nickname)), + 'description' => sprintf(_('Feed of favorite notices of %s'), $user->nickname)); + return $c; + } - function get_image() { - return NULL; - } + function get_image() { + return NULL; + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/featured.php b/_darcs/pristine/actions/featured.php index 96fbd89ab..2ff4f7745 100644 --- a/_darcs/pristine/actions/featured.php +++ b/_darcs/pristine/actions/featured.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -24,79 +24,79 @@ require_once(INSTALLDIR.'/lib/profilelist.php'); class FeaturedAction extends StreamAction { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - common_show_header(_('Featured users'), - array($this, 'show_header'), NULL, - array($this, 'show_top')); + common_show_header(_('Featured users'), + array($this, 'show_header'), NULL, + array($this, 'show_top')); - $this->show_notices($page); + $this->show_notices($page); - common_show_footer(); - } + common_show_footer(); + } - function show_top() { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - $this->public_views_menu(); - } + function show_top() { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + $this->public_views_menu(); + } - function show_header() { - } + function show_header() { + } - function get_instructions() { - return _('Featured users'); - } + function get_instructions() { + return _('Featured users'); + } - function show_notices($page) { + function show_notices($page) { - // XXX: Note I'm doing it this two-stage way because a raw query - // with a JOIN was *not* working. --Zach + // XXX: Note I'm doing it this two-stage way because a raw query + // with a JOIN was *not* working. --Zach - $featured_nicks = common_config('nickname', 'featured'); + $featured_nicks = common_config('nickname', 'featured'); - if (count($featured_nicks) > 0) { + if (count($featured_nicks) > 0) { - $quoted = array(); + $quoted = array(); - foreach ($featured_nicks as $nick) { - $quoted[] = "'$nick'"; - } + foreach ($featured_nicks as $nick) { + $quoted[] = "'$nick'"; + } - $user = new User; - $user->whereAdd(sprintf('nickname IN (%s)', implode(',', $quoted))); - $user->limit(($page - 1) * PROFILES_PER_PAGE, PROFILES_PER_PAGE + 1); - $user->orderBy('user.nickname ASC'); + $user = new User; + $user->whereAdd(sprintf('nickname IN (%s)', implode(',', $quoted))); + $user->limit(($page - 1) * PROFILES_PER_PAGE, PROFILES_PER_PAGE + 1); + $user->orderBy('user.nickname ASC'); - $user->find(); + $user->find(); - $profile_ids = array(); + $profile_ids = array(); - while ($user->fetch()) { - $profile_ids[] = $user->id; - } + while ($user->fetch()) { + $profile_ids[] = $user->id; + } - $profile = new Profile; - $profile->whereAdd(sprintf('profile.id IN (%s)', implode(',', $profile_ids))); - $profile->orderBy('nickname ASC'); + $profile = new Profile; + $profile->whereAdd(sprintf('profile.id IN (%s)', implode(',', $profile_ids))); + $profile->orderBy('nickname ASC'); - $cnt = $profile->find(); + $cnt = $profile->find(); - if ($cnt > 0) { - $featured = new ProfileList($profile); - $featured->show_list(); - } + if ($cnt > 0) { + $featured = new ProfileList($profile); + $featured->show_list(); + } - $profile->free(); + $profile->free(); - common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, $page, 'featured'); - } - } + common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, $page, 'featured'); + } + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/finishaddopenid.php b/_darcs/pristine/actions/finishaddopenid.php index 54d81b0b4..07024e091 100644 --- a/_darcs/pristine/actions/finishaddopenid.php +++ b/_darcs/pristine/actions/finishaddopenid.php @@ -23,81 +23,81 @@ require_once(INSTALLDIR.'/lib/openid.php'); class FinishaddopenidAction extends Action { - function handle($args) { - parent::handle($args); - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - } else { - $this->try_login(); - } - } - - function try_login() { - - $consumer =& oid_consumer(); - - $response = $consumer->complete(common_local_url('finishaddopenid')); - - if ($response->status == Auth_OpenID_CANCEL) { - $this->message(_('OpenID authentication cancelled.')); - return; - } else if ($response->status == Auth_OpenID_FAILURE) { - // Authentication failed; display the error message. - $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message)); - } else if ($response->status == Auth_OpenID_SUCCESS) { - - $display = $response->getDisplayIdentifier(); - $canonical = ($response->endpoint && $response->endpoint->canonicalID) ? - $response->endpoint->canonicalID : $display; - - $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); - - if ($sreg_resp) { - $sreg = $sreg_resp->contents(); - } - - $cur =& common_current_user(); - $other = oid_get_user($canonical); - - if ($other) { - if ($other->id == $cur->id) { - $this->message(_('You already have this OpenID!')); - } else { - $this->message(_('Someone else already has this OpenID.')); - } - return; - } - - # start a transaction - - $cur->query('BEGIN'); - - $result = oid_link_user($cur->id, $canonical, $display); - - if (!$result) { - $this->message(_('Error connecting user.')); - return; - } - if ($sreg) { - if (!oid_update_user($cur, $sreg)) { - $this->message(_('Error updating profile')); - return; - } - } - - # success! - - $cur->query('COMMIT'); - - oid_set_last($display); - - common_redirect(common_local_url('openidsettings')); - } - } - - function message($msg) { - common_show_header(_('OpenID Login')); - common_element('p', NULL, $msg); - common_show_footer(); - } + function handle($args) { + parent::handle($args); + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + } else { + $this->try_login(); + } + } + + function try_login() { + + $consumer =& oid_consumer(); + + $response = $consumer->complete(common_local_url('finishaddopenid')); + + if ($response->status == Auth_OpenID_CANCEL) { + $this->message(_('OpenID authentication cancelled.')); + return; + } else if ($response->status == Auth_OpenID_FAILURE) { + // Authentication failed; display the error message. + $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message)); + } else if ($response->status == Auth_OpenID_SUCCESS) { + + $display = $response->getDisplayIdentifier(); + $canonical = ($response->endpoint && $response->endpoint->canonicalID) ? + $response->endpoint->canonicalID : $display; + + $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); + + if ($sreg_resp) { + $sreg = $sreg_resp->contents(); + } + + $cur =& common_current_user(); + $other = oid_get_user($canonical); + + if ($other) { + if ($other->id == $cur->id) { + $this->message(_('You already have this OpenID!')); + } else { + $this->message(_('Someone else already has this OpenID.')); + } + return; + } + + # start a transaction + + $cur->query('BEGIN'); + + $result = oid_link_user($cur->id, $canonical, $display); + + if (!$result) { + $this->message(_('Error connecting user.')); + return; + } + if ($sreg) { + if (!oid_update_user($cur, $sreg)) { + $this->message(_('Error updating profile')); + return; + } + } + + # success! + + $cur->query('COMMIT'); + + oid_set_last($display); + + common_redirect(common_local_url('openidsettings')); + } + } + + function message($msg) { + common_show_header(_('OpenID Login')); + common_element('p', NULL, $msg); + common_show_footer(); + } } diff --git a/_darcs/pristine/actions/finishimmediate.php b/_darcs/pristine/actions/finishimmediate.php index 6dbaa3d1c..ea711f5c5 100644 --- a/_darcs/pristine/actions/finishimmediate.php +++ b/_darcs/pristine/actions/finishimmediate.php @@ -23,43 +23,43 @@ require_once(INSTALLDIR.'/lib/openid.php'); class FinishimmediateAction extends Action { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - $consumer = oid_consumer(); + $consumer = oid_consumer(); - $response = $consumer->complete(common_local_url('finishimmediate')); + $response = $consumer->complete(common_local_url('finishimmediate')); - if ($response->status == Auth_OpenID_SUCCESS) { - $display = $response->getDisplayIdentifier(); - $canonical = ($response->endpoint->canonicalID) ? - $response->endpoint->canonicalID : $response->getDisplayIdentifier(); + if ($response->status == Auth_OpenID_SUCCESS) { + $display = $response->getDisplayIdentifier(); + $canonical = ($response->endpoint->canonicalID) ? + $response->endpoint->canonicalID : $response->getDisplayIdentifier(); - $user = oid_get_user($canonical); + $user = oid_get_user($canonical); - if ($user) { - oid_update_user($user, $sreg); - oid_set_last($display); # refresh for another year - common_set_user($user->nickname); - $this->go_backto(); - return; - } - } + if ($user) { + oid_update_user($user, $sreg); + oid_set_last($display); # refresh for another year + common_set_user($user->nickname); + $this->go_backto(); + return; + } + } - # Failure! Clear openid so we don't try it again + # Failure! Clear openid so we don't try it again - oid_clear_last(); - $this->go_backto(); - return; - } + oid_clear_last(); + $this->go_backto(); + return; + } - function go_backto() { - common_ensure_session(); - $backto = $_SESSION['openid_immediate_backto']; - if (!$backto) { - # gar. Well, push them to the public page - $backto = common_local_url('public'); - } - common_redirect($backto); - } + function go_backto() { + common_ensure_session(); + $backto = $_SESSION['openid_immediate_backto']; + if (!$backto) { + # gar. Well, push them to the public page + $backto = common_local_url('public'); + } + common_redirect($backto); + } } diff --git a/_darcs/pristine/actions/finishopenidlogin.php b/_darcs/pristine/actions/finishopenidlogin.php index 766a08b20..a2a778f31 100644 --- a/_darcs/pristine/actions/finishopenidlogin.php +++ b/_darcs/pristine/actions/finishopenidlogin.php @@ -23,414 +23,414 @@ require_once(INSTALLDIR.'/lib/openid.php'); class FinishopenidloginAction extends Action { - function handle($args) { - parent::handle($args); - if (common_logged_in()) { - common_user_error(_('Already logged in.')); - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - if ($this->arg('create')) { - if (!$this->boolean('license')) { - $this->show_form(_('You can\'t register if you don\'t agree to the license.'), - $this->trimmed('newname')); - return; - } - $this->create_new_user(); - } else if ($this->arg('connect')) { - $this->connect_user(); - } else { - common_debug(print_r($this->args, true), __FILE__); - $this->show_form(_('Something weird happened.'), - $this->trimmed('newname')); - } - } else { - $this->try_login(); - } - } - - function show_top($error=NULL) { - if ($error) { - common_element('div', array('class' => 'error'), $error); - } else { - global $config; - common_element('div', 'instructions', - sprintf(_('This is the first time you\'ve logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), $config['site']['name'])); - } - } - - function show_form($error=NULL, $username=NULL) { - common_show_header(_('OpenID Account Setup'), NULL, $error, - array($this, 'show_top')); - - common_element_start('form', array('method' => 'post', - 'id' => 'account_connect', - 'action' => common_local_url('finishopenidlogin'))); - common_hidden('token', common_session_token()); - common_element('h2', NULL, - _('Create new account')); - common_element('p', NULL, - _('Create a new user with this nickname.')); - common_input('newname', _('New nickname'), - ($username) ? $username : '', - _('1-64 lowercase letters or numbers, no punctuation or spaces')); - common_element_start('p'); - common_element('input', array('type' => 'checkbox', - 'id' => 'license', - 'name' => 'license', - 'value' => 'true')); - common_text(_('My text and files are available under ')); - common_element('a', array(href => common_config('license', 'url')), - common_config('license', 'title')); - common_text(_(' except this private data: password, email address, IM address, phone number.')); - common_element_end('p'); - common_submit('create', _('Create')); - common_element('h2', NULL, - _('Connect existing account')); - common_element('p', NULL, - _('If you already have an account, login with your username and password to connect it to your OpenID.')); - common_input('nickname', _('Existing nickname')); - common_password('password', _('Password')); - common_submit('connect', _('Connect')); - common_element_end('form'); - common_show_footer(); - } - - function try_login() { - - $consumer = oid_consumer(); - - $response = $consumer->complete(common_local_url('finishopenidlogin')); - - if ($response->status == Auth_OpenID_CANCEL) { - $this->message(_('OpenID authentication cancelled.')); - return; - } else if ($response->status == Auth_OpenID_FAILURE) { - // Authentication failed; display the error message. - $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message)); - } else if ($response->status == Auth_OpenID_SUCCESS) { - // This means the authentication succeeded; extract the - // identity URL and Simple Registration data (if it was - // returned). - $display = $response->getDisplayIdentifier(); - $canonical = ($response->endpoint->canonicalID) ? - $response->endpoint->canonicalID : $response->getDisplayIdentifier(); - - $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); - - if ($sreg_resp) { - $sreg = $sreg_resp->contents(); - } - - $user = oid_get_user($canonical); - - if ($user) { - oid_set_last($display); - # XXX: commented out at @edd's request until better - # control over how data flows from OpenID provider. - # oid_update_user($user, $sreg); - common_set_user($user); - common_real_login(true); - if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { - common_rememberme($user); - } + function handle($args) { + parent::handle($args); + if (common_logged_in()) { + common_user_error(_('Already logged in.')); + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + if ($this->arg('create')) { + if (!$this->boolean('license')) { + $this->show_form(_('You can\'t register if you don\'t agree to the license.'), + $this->trimmed('newname')); + return; + } + $this->create_new_user(); + } else if ($this->arg('connect')) { + $this->connect_user(); + } else { + common_debug(print_r($this->args, true), __FILE__); + $this->show_form(_('Something weird happened.'), + $this->trimmed('newname')); + } + } else { + $this->try_login(); + } + } + + function show_top($error=NULL) { + if ($error) { + common_element('div', array('class' => 'error'), $error); + } else { + global $config; + common_element('div', 'instructions', + sprintf(_('This is the first time you\'ve logged into %s so we must connect your OpenID to a local account. You can either create a new account, or connect with your existing account, if you have one.'), $config['site']['name'])); + } + } + + function show_form($error=NULL, $username=NULL) { + common_show_header(_('OpenID Account Setup'), NULL, $error, + array($this, 'show_top')); + + common_element_start('form', array('method' => 'post', + 'id' => 'account_connect', + 'action' => common_local_url('finishopenidlogin'))); + common_hidden('token', common_session_token()); + common_element('h2', NULL, + _('Create new account')); + common_element('p', NULL, + _('Create a new user with this nickname.')); + common_input('newname', _('New nickname'), + ($username) ? $username : '', + _('1-64 lowercase letters or numbers, no punctuation or spaces')); + common_element_start('p'); + common_element('input', array('type' => 'checkbox', + 'id' => 'license', + 'name' => 'license', + 'value' => 'true')); + common_text(_('My text and files are available under ')); + common_element('a', array(href => common_config('license', 'url')), + common_config('license', 'title')); + common_text(_(' except this private data: password, email address, IM address, phone number.')); + common_element_end('p'); + common_submit('create', _('Create')); + common_element('h2', NULL, + _('Connect existing account')); + common_element('p', NULL, + _('If you already have an account, login with your username and password to connect it to your OpenID.')); + common_input('nickname', _('Existing nickname')); + common_password('password', _('Password')); + common_submit('connect', _('Connect')); + common_element_end('form'); + common_show_footer(); + } + + function try_login() { + + $consumer = oid_consumer(); + + $response = $consumer->complete(common_local_url('finishopenidlogin')); + + if ($response->status == Auth_OpenID_CANCEL) { + $this->message(_('OpenID authentication cancelled.')); + return; + } else if ($response->status == Auth_OpenID_FAILURE) { + // Authentication failed; display the error message. + $this->message(sprintf(_('OpenID authentication failed: %s'), $response->message)); + } else if ($response->status == Auth_OpenID_SUCCESS) { + // This means the authentication succeeded; extract the + // identity URL and Simple Registration data (if it was + // returned). + $display = $response->getDisplayIdentifier(); + $canonical = ($response->endpoint->canonicalID) ? + $response->endpoint->canonicalID : $response->getDisplayIdentifier(); + + $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response); + + if ($sreg_resp) { + $sreg = $sreg_resp->contents(); + } + + $user = oid_get_user($canonical); + + if ($user) { + oid_set_last($display); + # XXX: commented out at @edd's request until better + # control over how data flows from OpenID provider. + # oid_update_user($user, $sreg); + common_set_user($user); + common_real_login(true); + if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { + common_rememberme($user); + } unset($_SESSION['openid_rememberme']); - $this->go_home($user->nickname); - } else { - $this->save_values($display, $canonical, $sreg); - $this->show_form(NULL, $this->best_new_nickname($display, $sreg)); - } - } - } - - function message($msg) { - common_show_header(_('OpenID Login')); - common_element('p', NULL, $msg); - common_show_footer(); - } - - function save_values($display, $canonical, $sreg) { - common_ensure_session(); - $_SESSION['openid_display'] = $display; - $_SESSION['openid_canonical'] = $canonical; - $_SESSION['openid_sreg'] = $sreg; - } - - function get_saved_values() { - return array($_SESSION['openid_display'], - $_SESSION['openid_canonical'], - $_SESSION['openid_sreg']); - } - - function create_new_user() { + $this->go_home($user->nickname); + } else { + $this->save_values($display, $canonical, $sreg); + $this->show_form(NULL, $this->best_new_nickname($display, $sreg)); + } + } + } + + function message($msg) { + common_show_header(_('OpenID Login')); + common_element('p', NULL, $msg); + common_show_footer(); + } + + function save_values($display, $canonical, $sreg) { + common_ensure_session(); + $_SESSION['openid_display'] = $display; + $_SESSION['openid_canonical'] = $canonical; + $_SESSION['openid_sreg'] = $sreg; + } + + function get_saved_values() { + return array($_SESSION['openid_display'], + $_SESSION['openid_canonical'], + $_SESSION['openid_sreg']); + } + + function create_new_user() { # FIXME: save invite code before redirect, and check here - if (common_config('site', 'closed') || common_config('site', 'inviteonly')) { - common_user_error(_('Registration not allowed.')); + if (common_config('site', 'closed') || common_config('site', 'inviteonly')) { + common_user_error(_('Registration not allowed.')); return; } - $nickname = $this->trimmed('newname'); + $nickname = $this->trimmed('newname'); - if (!Validate::string($nickname, array('min_length' => 1, - 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { - $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); - return; - } + if (!Validate::string($nickname, array('min_length' => 1, + 'max_length' => 64, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); + return; + } - if (!User::allowed_nickname($nickname)) { - $this->show_form(_('Nickname not allowed.')); - return; - } + if (!User::allowed_nickname($nickname)) { + $this->show_form(_('Nickname not allowed.')); + return; + } - if (User::staticGet('nickname', $nickname)) { - $this->show_form(_('Nickname already in use. Try another one.')); - return; - } + if (User::staticGet('nickname', $nickname)) { + $this->show_form(_('Nickname already in use. Try another one.')); + return; + } - list($display, $canonical, $sreg) = $this->get_saved_values(); + list($display, $canonical, $sreg) = $this->get_saved_values(); - if (!$display || !$canonical) { - common_server_error(_('Stored OpenID not found.')); - return; - } + if (!$display || !$canonical) { + common_server_error(_('Stored OpenID not found.')); + return; + } - # Possible race condition... let's be paranoid + # Possible race condition... let's be paranoid - $other = oid_get_user($canonical); + $other = oid_get_user($canonical); - if ($other) { - common_server_error(_('Creating new account for OpenID that already has a user.')); - return; - } + if ($other) { + common_server_error(_('Creating new account for OpenID that already has a user.')); + return; + } - if ($sreg['country']) { - if ($sreg['postcode']) { - # XXX: use postcode to get city and region - # XXX: also, store postcode somewhere -- it's valuable! - $location = $sreg['postcode'] . ', ' . $sreg['country']; - } else { - $location = $sreg['country']; - } - } + if ($sreg['country']) { + if ($sreg['postcode']) { + # XXX: use postcode to get city and region + # XXX: also, store postcode somewhere -- it's valuable! + $location = $sreg['postcode'] . ', ' . $sreg['country']; + } else { + $location = $sreg['country']; + } + } - if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) { - $fullname = $sreg['fullname']; - } + if ($sreg['fullname'] && strlen($sreg['fullname']) <= 255) { + $fullname = $sreg['fullname']; + } - if ($sreg['email'] && Validate::email($sreg['email'], true)) { - $email = $sreg['email']; - } + if ($sreg['email'] && Validate::email($sreg['email'], true)) { + $email = $sreg['email']; + } - # XXX: add language - # XXX: add timezone + # XXX: add language + # XXX: add timezone - $user = User::register(array('nickname' => $nickname, - 'email' => $email, - 'fullname' => $fullname, - 'location' => $location)); + $user = User::register(array('nickname' => $nickname, + 'email' => $email, + 'fullname' => $fullname, + 'location' => $location)); - $result = oid_link_user($user->id, $canonical, $display); + $result = oid_link_user($user->id, $canonical, $display); - oid_set_last($display); - common_set_user($user); - common_real_login(true); + oid_set_last($display); + common_set_user($user); + common_real_login(true); if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { - common_rememberme($user); - } + common_rememberme($user); + } unset($_SESSION['openid_rememberme']); - common_redirect(common_local_url('showstream', array('nickname' => $user->nickname))); - } + common_redirect(common_local_url('showstream', array('nickname' => $user->nickname))); + } - function connect_user() { + function connect_user() { - $nickname = $this->trimmed('nickname'); - $password = $this->trimmed('password'); + $nickname = $this->trimmed('nickname'); + $password = $this->trimmed('password'); - if (!common_check_user($nickname, $password)) { - $this->show_form(_('Invalid username or password.')); - return; - } + if (!common_check_user($nickname, $password)) { + $this->show_form(_('Invalid username or password.')); + return; + } - # They're legit! + # They're legit! - $user = User::staticGet('nickname', $nickname); + $user = User::staticGet('nickname', $nickname); - list($display, $canonical, $sreg) = $this->get_saved_values(); + list($display, $canonical, $sreg) = $this->get_saved_values(); - if (!$display || !$canonical) { - common_server_error(_('Stored OpenID not found.')); - return; - } + if (!$display || !$canonical) { + common_server_error(_('Stored OpenID not found.')); + return; + } - $result = oid_link_user($user->id, $canonical, $display); + $result = oid_link_user($user->id, $canonical, $display); - if (!$result) { - common_server_error(_('Error connecting user to OpenID.')); - return; - } + if (!$result) { + common_server_error(_('Error connecting user to OpenID.')); + return; + } - oid_update_user($user, $sreg); - oid_set_last($display); - common_set_user($user); - common_real_login(true); + oid_update_user($user, $sreg); + oid_set_last($display); + common_set_user($user); + common_real_login(true); if (isset($_SESSION['openid_rememberme']) && $_SESSION['openid_rememberme']) { - common_rememberme($user); - } - unset($_SESSION['openid_rememberme']); - $this->go_home($user->nickname); - } - - function go_home($nickname) { - $url = common_get_returnto(); - if ($url) { - # We don't have to return to it again - common_set_returnto(NULL); - } else { - $url = common_local_url('all', - array('nickname' => - $nickname)); - } - common_redirect($url); - } - - function best_new_nickname($display, $sreg) { - - # Try the passed-in nickname - - if ($sreg['nickname']) { - $nickname = $this->nicknamize($sreg['nickname']); - if ($this->is_new_nickname($nickname)) { - return $nickname; - } - } - - # Try the full name - - if ($sreg['fullname']) { - $fullname = $this->nicknamize($sreg['fullname']); - if ($this->is_new_nickname($fullname)) { - return $fullname; - } - } - - # Try the URL - - $from_url = $this->openid_to_nickname($display); - - if ($from_url && $this->is_new_nickname($from_url)) { - return $from_url; - } - - # XXX: others? - - return NULL; - } - - function is_new_nickname($str) { - if (!Validate::string($str, array('min_length' => 1, - 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { - return false; - } - if (!User::allowed_nickname($str)) { - return false; - } - if (User::staticGet('nickname', $str)) { - return false; - } - return true; - } - - function openid_to_nickname($openid) { + common_rememberme($user); + } + unset($_SESSION['openid_rememberme']); + $this->go_home($user->nickname); + } + + function go_home($nickname) { + $url = common_get_returnto(); + if ($url) { + # We don't have to return to it again + common_set_returnto(NULL); + } else { + $url = common_local_url('all', + array('nickname' => + $nickname)); + } + common_redirect($url); + } + + function best_new_nickname($display, $sreg) { + + # Try the passed-in nickname + + if ($sreg['nickname']) { + $nickname = $this->nicknamize($sreg['nickname']); + if ($this->is_new_nickname($nickname)) { + return $nickname; + } + } + + # Try the full name + + if ($sreg['fullname']) { + $fullname = $this->nicknamize($sreg['fullname']); + if ($this->is_new_nickname($fullname)) { + return $fullname; + } + } + + # Try the URL + + $from_url = $this->openid_to_nickname($display); + + if ($from_url && $this->is_new_nickname($from_url)) { + return $from_url; + } + + # XXX: others? + + return NULL; + } + + function is_new_nickname($str) { + if (!Validate::string($str, array('min_length' => 1, + 'max_length' => 64, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + return false; + } + if (!User::allowed_nickname($str)) { + return false; + } + if (User::staticGet('nickname', $str)) { + return false; + } + return true; + } + + function openid_to_nickname($openid) { if (Auth_Yadis_identifierScheme($openid) == 'XRI') { - return $this->xri_to_nickname($openid); - } else { - return $this->url_to_nickname($openid); - } - } + return $this->xri_to_nickname($openid); + } else { + return $this->url_to_nickname($openid); + } + } - # We try to use an OpenID URL as a legal Laconica user name in this order - # 1. Plain hostname, like http://evanp.myopenid.com/ - # 2. One element in path, like http://profile.typekey.com/EvanProdromou/ - # or http://getopenid.com/evanprodromou + # We try to use an OpenID URL as a legal Laconica user name in this order + # 1. Plain hostname, like http://evanp.myopenid.com/ + # 2. One element in path, like http://profile.typekey.com/EvanProdromou/ + # or http://getopenid.com/evanprodromou function url_to_nickname($openid) { - static $bad = array('query', 'user', 'password', 'port', 'fragment'); - - $parts = parse_url($openid); - - # If any of these parts exist, this won't work - - foreach ($bad as $badpart) { - if (array_key_exists($badpart, $parts)) { - return NULL; - } - } - - # We just have host and/or path - - # If it's just a host... - if (array_key_exists('host', $parts) && - (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0)) - { - $hostparts = explode('.', $parts['host']); - - # Try to catch common idiom of nickname.service.tld - - if ((count($hostparts) > 2) && - (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au - (strcmp($hostparts[0], 'www') != 0)) - { - return $this->nicknamize($hostparts[0]); - } else { - # Do the whole hostname - return $this->nicknamize($parts['host']); - } - } else { - if (array_key_exists('path', $parts)) { - # Strip starting, ending slashes - $path = preg_replace('@/$@', '', $parts['path']); - $path = preg_replace('@^/@', '', $path); - if (strpos($path, '/') === false) { - return $this->nicknamize($path); - } - } - } - - return NULL; - } - - function xri_to_nickname($xri) { - $base = $this->xri_base($xri); - - if (!$base) { - return NULL; - } else { - # =evan.prodromou - # or @gratis*evan.prodromou - $parts = explode('*', substr($base, 1)); - return $this->nicknamize(array_pop($parts)); - } - } - - function xri_base($xri) { - if (substr($xri, 0, 6) == 'xri://') { - return substr($xri, 6); - } else { - return $xri; - } - } - - # Given a string, try to make it work as a nickname - - function nicknamize($str) { - $str = preg_replace('/\W/', '', $str); - return strtolower($str); - } + static $bad = array('query', 'user', 'password', 'port', 'fragment'); + + $parts = parse_url($openid); + + # If any of these parts exist, this won't work + + foreach ($bad as $badpart) { + if (array_key_exists($badpart, $parts)) { + return NULL; + } + } + + # We just have host and/or path + + # If it's just a host... + if (array_key_exists('host', $parts) && + (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0)) + { + $hostparts = explode('.', $parts['host']); + + # Try to catch common idiom of nickname.service.tld + + if ((count($hostparts) > 2) && + (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au + (strcmp($hostparts[0], 'www') != 0)) + { + return $this->nicknamize($hostparts[0]); + } else { + # Do the whole hostname + return $this->nicknamize($parts['host']); + } + } else { + if (array_key_exists('path', $parts)) { + # Strip starting, ending slashes + $path = preg_replace('@/$@', '', $parts['path']); + $path = preg_replace('@^/@', '', $path); + if (strpos($path, '/') === false) { + return $this->nicknamize($path); + } + } + } + + return NULL; + } + + function xri_to_nickname($xri) { + $base = $this->xri_base($xri); + + if (!$base) { + return NULL; + } else { + # =evan.prodromou + # or @gratis*evan.prodromou + $parts = explode('*', substr($base, 1)); + return $this->nicknamize(array_pop($parts)); + } + } + + function xri_base($xri) { + if (substr($xri, 0, 6) == 'xri://') { + return substr($xri, 6); + } else { + return $xri; + } + } + + # Given a string, try to make it work as a nickname + + function nicknamize($str) { + $str = preg_replace('/\W/', '', $str); + return strtolower($str); + } } diff --git a/_darcs/pristine/actions/finishremotesubscribe.php b/_darcs/pristine/actions/finishremotesubscribe.php index 58040683f..c3387cf02 100644 --- a/_darcs/pristine/actions/finishremotesubscribe.php +++ b/_darcs/pristine/actions/finishremotesubscribe.php @@ -23,174 +23,174 @@ require_once(INSTALLDIR.'/lib/omb.php'); class FinishremotesubscribeAction extends Action { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - if (common_logged_in()) { - common_user_error(_('You can use the local subscription!')); - return; - } + if (common_logged_in()) { + common_user_error(_('You can use the local subscription!')); + return; + } + + $omb = $_SESSION['oauth_authorization_request']; + + if (!$omb) { + common_user_error(_('Not expecting this response!')); + return; + } + + common_debug('stored request: '.print_r($omb,true), __FILE__); + + common_remove_magic_from_request(); + $req = OAuthRequest::from_request(); - $omb = $_SESSION['oauth_authorization_request']; + $token = $req->get_parameter('oauth_token'); - if (!$omb) { - common_user_error(_('Not expecting this response!')); - return; - } + # I think this is the success metric - common_debug('stored request: '.print_r($omb,true), __FILE__); + if ($token != $omb['token']) { + common_user_error(_('Not authorized.')); + return; + } - common_remove_magic_from_request(); - $req = OAuthRequest::from_request(); + $version = $req->get_parameter('omb_version'); + + if ($version != OMB_VERSION_01) { + common_user_error(_('Unknown version of OMB protocol.')); + return; + } - $token = $req->get_parameter('oauth_token'); + $nickname = $req->get_parameter('omb_listener_nickname'); - # I think this is the success metric + if (!$nickname) { + common_user_error(_('No nickname provided by remote server.')); + return; + } - if ($token != $omb['token']) { - common_user_error(_('Not authorized.')); - return; - } - - $version = $req->get_parameter('omb_version'); - - if ($version != OMB_VERSION_01) { - common_user_error(_('Unknown version of OMB protocol.')); - return; - } - - $nickname = $req->get_parameter('omb_listener_nickname'); - - if (!$nickname) { - common_user_error(_('No nickname provided by remote server.')); - return; - } - - $profile_url = $req->get_parameter('omb_listener_profile'); - - if (!$profile_url) { - common_user_error(_('No profile URL returned by server.')); - return; - } - - if (!Validate::uri($profile_url, array('allowed_schemes' => array('http', 'https')))) { - common_user_error(_('Invalid profile URL returned by server.')); - return; - } - - if ($profile_url == common_local_url('showstream', array('nickname' => $nickname))) { - common_user_error(_('You can use the local subscription!')); - return; - } - - common_debug('listenee: "'.$omb['listenee'].'"', __FILE__); - - $user = User::staticGet('nickname', $omb['listenee']); - - if (!$user) { - common_user_error(_('User being listened to doesn\'t exist.')); - return; - } - - $other = User::staticGet('uri', $omb['listener']); - - if ($other) { - common_user_error(_('You can use the local subscription!')); - return; - } - - $fullname = $req->get_parameter('omb_listener_fullname'); - $homepage = $req->get_parameter('omb_listener_homepage'); - $bio = $req->get_parameter('omb_listener_bio'); - $location = $req->get_parameter('omb_listener_location'); - $avatar_url = $req->get_parameter('omb_listener_avatar'); - - list($newtok, $newsecret) = $this->access_token($omb); - - if (!$newtok || !$newsecret) { - common_user_error(_('Couldn\'t convert request tokens to access tokens.')); - return; - } - - # XXX: possible attack point; subscribe and return someone else's profile URI - - $remote = Remote_profile::staticGet('uri', $omb['listener']); - - if ($remote) { - $exists = true; - $profile = Profile::staticGet($remote->id); - $orig_remote = clone($remote); - $orig_profile = clone($profile); - # XXX: compare current postNotice and updateProfile URLs to the ones - # stored in the DB to avoid (possibly...) above attack - } else { - $exists = false; - $remote = new Remote_profile(); - $remote->uri = $omb['listener']; - $profile = new Profile(); - } - - $profile->nickname = $nickname; - $profile->profileurl = $profile_url; - - if ($fullname) { - $profile->fullname = $fullname; - } - if ($homepage) { - $profile->homepage = $homepage; - } - if ($bio) { - $profile->bio = $bio; - } - if ($location) { - $profile->location = $location; - } - - if ($exists) { - $profile->update($orig_profile); - } else { - $profile->created = DB_DataObject_Cast::dateTime(); # current time - $id = $profile->insert(); - if (!$id) { - common_server_error(_('Error inserting new profile')); - return; - } - $remote->id = $id; - } - - if ($avatar_url) { - if (!$this->add_avatar($profile, $avatar_url)) { - common_server_error(_('Error inserting avatar')); - return; - } - } - - $remote->postnoticeurl = $omb['post_notice_url']; - $remote->updateprofileurl = $omb['update_profile_url']; - - if ($exists) { - if (!$remote->update($orig_remote)) { - common_server_error(_('Error updating remote profile')); - return; - } - } else { - $remote->created = DB_DataObject_Cast::dateTime(); # current time - if (!$remote->insert()) { - common_server_error(_('Error inserting remote profile')); - return; - } - } + $profile_url = $req->get_parameter('omb_listener_profile'); + + if (!$profile_url) { + common_user_error(_('No profile URL returned by server.')); + return; + } + + if (!Validate::uri($profile_url, array('allowed_schemes' => array('http', 'https')))) { + common_user_error(_('Invalid profile URL returned by server.')); + return; + } + + if ($profile_url == common_local_url('showstream', array('nickname' => $nickname))) { + common_user_error(_('You can use the local subscription!')); + return; + } + + common_debug('listenee: "'.$omb['listenee'].'"', __FILE__); + + $user = User::staticGet('nickname', $omb['listenee']); + + if (!$user) { + common_user_error(_('User being listened to doesn\'t exist.')); + return; + } + + $other = User::staticGet('uri', $omb['listener']); + + if ($other) { + common_user_error(_('You can use the local subscription!')); + return; + } + + $fullname = $req->get_parameter('omb_listener_fullname'); + $homepage = $req->get_parameter('omb_listener_homepage'); + $bio = $req->get_parameter('omb_listener_bio'); + $location = $req->get_parameter('omb_listener_location'); + $avatar_url = $req->get_parameter('omb_listener_avatar'); + + list($newtok, $newsecret) = $this->access_token($omb); + + if (!$newtok || !$newsecret) { + common_user_error(_('Couldn\'t convert request tokens to access tokens.')); + return; + } + + # XXX: possible attack point; subscribe and return someone else's profile URI + + $remote = Remote_profile::staticGet('uri', $omb['listener']); + + if ($remote) { + $exists = true; + $profile = Profile::staticGet($remote->id); + $orig_remote = clone($remote); + $orig_profile = clone($profile); + # XXX: compare current postNotice and updateProfile URLs to the ones + # stored in the DB to avoid (possibly...) above attack + } else { + $exists = false; + $remote = new Remote_profile(); + $remote->uri = $omb['listener']; + $profile = new Profile(); + } + + $profile->nickname = $nickname; + $profile->profileurl = $profile_url; + + if ($fullname) { + $profile->fullname = $fullname; + } + if ($homepage) { + $profile->homepage = $homepage; + } + if ($bio) { + $profile->bio = $bio; + } + if ($location) { + $profile->location = $location; + } + + if ($exists) { + $profile->update($orig_profile); + } else { + $profile->created = DB_DataObject_Cast::dateTime(); # current time + $id = $profile->insert(); + if (!$id) { + common_server_error(_('Error inserting new profile')); + return; + } + $remote->id = $id; + } + + if ($avatar_url) { + if (!$this->add_avatar($profile, $avatar_url)) { + common_server_error(_('Error inserting avatar')); + return; + } + } + + $remote->postnoticeurl = $omb['post_notice_url']; + $remote->updateprofileurl = $omb['update_profile_url']; + + if ($exists) { + if (!$remote->update($orig_remote)) { + common_server_error(_('Error updating remote profile')); + return; + } + } else { + $remote->created = DB_DataObject_Cast::dateTime(); # current time + if (!$remote->insert()) { + common_server_error(_('Error inserting remote profile')); + return; + } + } if ($user->hasBlocked($profile)) { $this->client_error(_('That user has blocked you from subscribing.')); return; } - $sub = new Subscription(); + $sub = new Subscription(); - $sub->subscriber = $remote->id; - $sub->subscribed = $user->id; + $sub->subscriber = $remote->id; + $sub->subscribed = $user->id; $sub_exists = false; @@ -202,8 +202,8 @@ class FinishremotesubscribeAction extends Action { $sub->created = DB_DataObject_Cast::dateTime(); # current time } - $sub->token = $newtok; - $sub->secret = $newsecret; + $sub->token = $newtok; + $sub->secret = $newsecret; if ($sub_exists) { $result = $sub->update($orig_sub); @@ -211,78 +211,78 @@ class FinishremotesubscribeAction extends Action { $result = $sub->insert(); } - if (!$result) { + if (!$result) { common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__); - common_user_error(_('Couldn\'t insert new subscription.')); - return; - } + common_user_error(_('Couldn\'t insert new subscription.')); + return; + } - # Notify user, if necessary + # Notify user, if necessary - mail_subscribe_notify_profile($user, $profile); + mail_subscribe_notify_profile($user, $profile); - # Clear the data - unset($_SESSION['oauth_authorization_request']); + # Clear the data + unset($_SESSION['oauth_authorization_request']); - # If we show subscriptions in reverse chron order, this should - # show up close to the top of the page + # If we show subscriptions in reverse chron order, this should + # show up close to the top of the page - common_redirect(common_local_url('subscribers', array('nickname' => - $user->nickname))); - } + common_redirect(common_local_url('subscribers', array('nickname' => + $user->nickname))); + } - function add_avatar($profile, $url) { - $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar'); - copy($url, $temp_filename); - return $profile->setOriginal($temp_filename); - } + function add_avatar($profile, $url) { + $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar'); + copy($url, $temp_filename); + return $profile->setOriginal($temp_filename); + } - function access_token($omb) { + function access_token($omb) { - common_debug('starting request for access token', __FILE__); + common_debug('starting request for access token', __FILE__); - $con = omb_oauth_consumer(); - $tok = new OAuthToken($omb['token'], $omb['secret']); + $con = omb_oauth_consumer(); + $tok = new OAuthToken($omb['token'], $omb['secret']); - common_debug('using request token "'.$tok.'"', __FILE__); + common_debug('using request token "'.$tok.'"', __FILE__); - $url = $omb['access_token_url']; + $url = $omb['access_token_url']; - common_debug('using access token url "'.$url.'"', __FILE__); + common_debug('using access token url "'.$url.'"', __FILE__); - # XXX: Is this the right thing to do? Strip off GET params and make them - # POST params? Seems wrong to me. + # XXX: Is this the right thing to do? Strip off GET params and make them + # POST params? Seems wrong to me. - $parsed = parse_url($url); - $params = array(); - parse_str($parsed['query'], $params); + $parsed = parse_url($url); + $params = array(); + parse_str($parsed['query'], $params); - $req = OAuthRequest::from_consumer_and_token($con, $tok, "POST", $url, $params); + $req = OAuthRequest::from_consumer_and_token($con, $tok, "POST", $url, $params); - $req->set_parameter('omb_version', OMB_VERSION_01); + $req->set_parameter('omb_version', OMB_VERSION_01); - # XXX: test to see if endpoint accepts this signature method + # XXX: test to see if endpoint accepts this signature method - $req->sign_request(omb_hmac_sha1(), $con, $tok); + $req->sign_request(omb_hmac_sha1(), $con, $tok); - # We re-use this tool's fetcher, since it's pretty good + # We re-use this tool's fetcher, since it's pretty good - common_debug('posting to access token url "'.$req->get_normalized_http_url().'"', __FILE__); - common_debug('posting request data "'.$req->to_postdata().'"', __FILE__); + common_debug('posting to access token url "'.$req->get_normalized_http_url().'"', __FILE__); + common_debug('posting request data "'.$req->to_postdata().'"', __FILE__); - $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); - $result = $fetcher->post($req->get_normalized_http_url(), - $req->to_postdata(), + $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); + $result = $fetcher->post($req->get_normalized_http_url(), + $req->to_postdata(), array('User-Agent' => 'Laconica/' . LACONICA_VERSION)); - common_debug('got result: "'.print_r($result,TRUE).'"', __FILE__); + common_debug('got result: "'.print_r($result,TRUE).'"', __FILE__); - if ($result->status != 200) { - return NULL; - } + if ($result->status != 200) { + return NULL; + } - parse_str($result->body, $return); + parse_str($result->body, $return); - return array($return['oauth_token'], $return['oauth_token_secret']); - } + return array($return['oauth_token'], $return['oauth_token_secret']); + } } diff --git a/_darcs/pristine/actions/foaf.php b/_darcs/pristine/actions/foaf.php index 6811fc05a..310ba2c19 100644 --- a/_darcs/pristine/actions/foaf.php +++ b/_darcs/pristine/actions/foaf.php @@ -25,178 +25,178 @@ define('BOTH', 0); class FoafAction extends Action { - function is_readonly() { - return true; - } - - function handle($args) { - parent::handle($args); - - $nickname = $this->trimmed('nickname'); - - $user = User::staticGet('nickname', $nickname); - - if (!$user) { - common_user_error(_('No such user.'), 404); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - common_server_error(_('User has no profile.'), 500); - return; - } - - header('Content-Type: application/rdf+xml'); - - common_start_xml(); - common_element_start('rdf:RDF', array('xmlns:rdf' => - 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', - 'xmlns:rdfs' => - 'http://www.w3.org/2000/01/rdf-schema#', - 'xmlns:geo' => - 'http://www.w3.org/2003/01/geo/wgs84_pos#', - 'xmlns' => 'http://xmlns.com/foaf/0.1/')); - - # This is the document about the user - - $this->show_ppd('', $user->uri); - - # XXX: might not be a person - common_element_start('Person', array('rdf:about' => - $user->uri)); - common_element('mbox_sha1sum', NULL, sha1('mailto:' . $user->email)); - if ($profile->fullname) { - common_element('name', NULL, $profile->fullname); - } - if ($profile->homepage) { - common_element('homepage', array('rdf:resource' => $profile->homepage)); - } - if ($profile->bio) { - common_element('rdfs:comment', NULL, $profile->bio); - } - # XXX: more structured location data - if ($profile->location) { - common_element_start('based_near'); - common_element_start('geo:SpatialThing'); - common_element('name', NULL, $profile->location); - common_element_end('geo:SpatialThing'); - common_element_end('based_near'); - } - - $this->show_microblogging_account($profile, common_root_url()); - - $avatar = $profile->getOriginalAvatar(); - - if ($avatar) { - common_element_start('img'); - common_element_start('Image', array('rdf:about' => $avatar->url)); - foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) { - $scaled = $profile->getAvatar($size); - if (!$scaled->original) { # sometimes the original has one of our scaled sizes - common_element_start('thumbnail'); - common_element('Image', array('rdf:about' => $scaled->url)); - common_element_end('thumbnail'); - } - } - common_element_end('Image'); - common_element_end('img'); - } - - # Get people user is subscribed to - - $person = array(); - - $sub = new Subscription(); - $sub->subscriber = $profile->id; - $sub->whereAdd('subscriber != subscribed'); - - if ($sub->find()) { - while ($sub->fetch()) { - if ($sub->token) { - $other = Remote_profile::staticGet('id', $sub->subscribed); - } else { - $other = User::staticGet('id', $sub->subscribed); - } - if (!$other) { - common_debug('Got a bad subscription: '.print_r($sub,TRUE)); - continue; - } - common_element('knows', array('rdf:resource' => $other->uri)); - $person[$other->uri] = array(LISTENEE, $other); - } - } - - # Get people who subscribe to user - - $sub = new Subscription(); - $sub->subscribed = $profile->id; - $sub->whereAdd('subscriber != subscribed'); - - if ($sub->find()) { - while ($sub->fetch()) { - if ($sub->token) { - $other = Remote_profile::staticGet('id', $sub->subscriber); - } else { - $other = User::staticGet('id', $sub->subscriber); - } - if (!$other) { - common_debug('Got a bad subscription: '.print_r($sub,TRUE)); - continue; - } - if (array_key_exists($other->uri, $person)) { - $person[$other->uri][0] = BOTH; - } else { - $person[$other->uri] = array(LISTENER, $other); - } - } - } - - common_element_end('Person'); - - foreach ($person as $uri => $p) { - $foaf_url = NULL; - if ($p[1] instanceof User) { - $foaf_url = common_local_url('foaf', array('nickname' => $p[1]->nickname)); - } - $profile = Profile::staticGet($p[1]->id); - common_element_start('Person', array('rdf:about' => $uri)); - if ($p[0] == LISTENER || $p[0] == BOTH) { - common_element('knows', array('rdf:resource' => $user->uri)); - } - $this->show_microblogging_account($profile, ($p[1] instanceof User) ? - common_root_url() : NULL); - if ($foaf_url) { - common_element('rdfs:seeAlso', array('rdf:resource' => $foaf_url)); - } - common_element_end('Person'); - if ($foaf_url) { - $this->show_ppd($foaf_url, $uri); - } - } - - common_element_end('rdf:RDF'); - } - - function show_ppd($foaf_url, $person_uri) { - common_element_start('PersonalProfileDocument', array('rdf:about' => $foaf_url)); - common_element('maker', array('rdf:resource' => $person_uri)); - common_element('primaryTopic', array('rdf:resource' => $person_uri)); - common_element_end('PersonalProfileDocument'); - } - - function show_microblogging_account($profile, $service=NULL) { - # Their account - common_element_start('holdsAccount'); - common_element_start('OnlineAccount'); - if ($service) { - common_element('accountServiceHomepage', array('rdf:resource' => - $service)); - } - common_element('accountName', NULL, $profile->nickname); - common_element('homepage', array('rdf:resource' => $profile->profileurl)); - common_element_end('OnlineAccount'); - common_element_end('holdsAccount'); - } + function is_readonly() { + return true; + } + + function handle($args) { + parent::handle($args); + + $nickname = $this->trimmed('nickname'); + + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + common_user_error(_('No such user.'), 404); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + common_server_error(_('User has no profile.'), 500); + return; + } + + header('Content-Type: application/rdf+xml'); + + common_start_xml(); + common_element_start('rdf:RDF', array('xmlns:rdf' => + 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', + 'xmlns:rdfs' => + 'http://www.w3.org/2000/01/rdf-schema#', + 'xmlns:geo' => + 'http://www.w3.org/2003/01/geo/wgs84_pos#', + 'xmlns' => 'http://xmlns.com/foaf/0.1/')); + + # This is the document about the user + + $this->show_ppd('', $user->uri); + + # XXX: might not be a person + common_element_start('Person', array('rdf:about' => + $user->uri)); + common_element('mbox_sha1sum', NULL, sha1('mailto:' . $user->email)); + if ($profile->fullname) { + common_element('name', NULL, $profile->fullname); + } + if ($profile->homepage) { + common_element('homepage', array('rdf:resource' => $profile->homepage)); + } + if ($profile->bio) { + common_element('rdfs:comment', NULL, $profile->bio); + } + # XXX: more structured location data + if ($profile->location) { + common_element_start('based_near'); + common_element_start('geo:SpatialThing'); + common_element('name', NULL, $profile->location); + common_element_end('geo:SpatialThing'); + common_element_end('based_near'); + } + + $this->show_microblogging_account($profile, common_root_url()); + + $avatar = $profile->getOriginalAvatar(); + + if ($avatar) { + common_element_start('img'); + common_element_start('Image', array('rdf:about' => $avatar->url)); + foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) { + $scaled = $profile->getAvatar($size); + if (!$scaled->original) { # sometimes the original has one of our scaled sizes + common_element_start('thumbnail'); + common_element('Image', array('rdf:about' => $scaled->url)); + common_element_end('thumbnail'); + } + } + common_element_end('Image'); + common_element_end('img'); + } + + # Get people user is subscribed to + + $person = array(); + + $sub = new Subscription(); + $sub->subscriber = $profile->id; + $sub->whereAdd('subscriber != subscribed'); + + if ($sub->find()) { + while ($sub->fetch()) { + if ($sub->token) { + $other = Remote_profile::staticGet('id', $sub->subscribed); + } else { + $other = User::staticGet('id', $sub->subscribed); + } + if (!$other) { + common_debug('Got a bad subscription: '.print_r($sub,TRUE)); + continue; + } + common_element('knows', array('rdf:resource' => $other->uri)); + $person[$other->uri] = array(LISTENEE, $other); + } + } + + # Get people who subscribe to user + + $sub = new Subscription(); + $sub->subscribed = $profile->id; + $sub->whereAdd('subscriber != subscribed'); + + if ($sub->find()) { + while ($sub->fetch()) { + if ($sub->token) { + $other = Remote_profile::staticGet('id', $sub->subscriber); + } else { + $other = User::staticGet('id', $sub->subscriber); + } + if (!$other) { + common_debug('Got a bad subscription: '.print_r($sub,TRUE)); + continue; + } + if (array_key_exists($other->uri, $person)) { + $person[$other->uri][0] = BOTH; + } else { + $person[$other->uri] = array(LISTENER, $other); + } + } + } + + common_element_end('Person'); + + foreach ($person as $uri => $p) { + $foaf_url = NULL; + if ($p[1] instanceof User) { + $foaf_url = common_local_url('foaf', array('nickname' => $p[1]->nickname)); + } + $profile = Profile::staticGet($p[1]->id); + common_element_start('Person', array('rdf:about' => $uri)); + if ($p[0] == LISTENER || $p[0] == BOTH) { + common_element('knows', array('rdf:resource' => $user->uri)); + } + $this->show_microblogging_account($profile, ($p[1] instanceof User) ? + common_root_url() : NULL); + if ($foaf_url) { + common_element('rdfs:seeAlso', array('rdf:resource' => $foaf_url)); + } + common_element_end('Person'); + if ($foaf_url) { + $this->show_ppd($foaf_url, $uri); + } + } + + common_element_end('rdf:RDF'); + } + + function show_ppd($foaf_url, $person_uri) { + common_element_start('PersonalProfileDocument', array('rdf:about' => $foaf_url)); + common_element('maker', array('rdf:resource' => $person_uri)); + common_element('primaryTopic', array('rdf:resource' => $person_uri)); + common_element_end('PersonalProfileDocument'); + } + + function show_microblogging_account($profile, $service=NULL) { + # Their account + common_element_start('holdsAccount'); + common_element_start('OnlineAccount'); + if ($service) { + common_element('accountServiceHomepage', array('rdf:resource' => + $service)); + } + common_element('accountName', NULL, $profile->nickname); + common_element('homepage', array('rdf:resource' => $profile->profileurl)); + common_element_end('OnlineAccount'); + common_element_end('holdsAccount'); + } } diff --git a/_darcs/pristine/actions/imsettings.php b/_darcs/pristine/actions/imsettings.php index 0aa7631dc..d0c47f7fd 100644 --- a/_darcs/pristine/actions/imsettings.php +++ b/_darcs/pristine/actions/imsettings.php @@ -24,247 +24,247 @@ require_once(INSTALLDIR.'/lib/jabber.php'); class ImsettingsAction extends SettingsAction { - function get_instructions() { - return _('You can send and receive notices through Jabber/GTalk [instant messages](%%doc.im%%). Configure your address and settings below.'); - } - - function show_form($msg=NULL, $success=false) { - $user = common_current_user(); - $this->form_header(_('IM Settings'), $msg, $success); - common_element_start('form', array('method' => 'post', - 'id' => 'imsettings', - 'action' => - common_local_url('imsettings'))); - common_hidden('token', common_session_token()); - - common_element('h2', NULL, _('Address')); - - if ($user->jabber) { - common_element_start('p'); - common_element('span', 'address confirmed', $user->jabber); - common_element('span', 'input_instructions', - _('Current confirmed Jabber/GTalk address.')); - common_hidden('jabber', $user->jabber); - common_element_end('p'); - common_submit('remove', _('Remove')); - } else { - $confirm = $this->get_confirmation(); - if ($confirm) { - common_element_start('p'); - common_element('span', 'address unconfirmed', $confirm->address); - common_element('span', 'input_instructions', - sprintf(_('Awaiting confirmation on this address. Check your Jabber/GTalk account for a message with further instructions. (Did you add %s to your buddy list?)'), jabber_daemon_address())); - common_hidden('jabber', $confirm->address); - common_element_end('p'); - common_submit('cancel', _('Cancel')); - } else { - common_input('jabber', _('IM Address'), - ($this->arg('jabber')) ? $this->arg('jabber') : NULL, - sprintf(_('Jabber or GTalk address, like "UserName@example.org". First, make sure to add %s to your buddy list in your IM client or on GTalk.'), jabber_daemon_address())); - common_submit('add', _('Add')); - } - } - - common_element('h2', NULL, _('Preferences')); - - common_checkbox('jabbernotify', - _('Send me notices through Jabber/GTalk.'), - $user->jabbernotify); - common_checkbox('updatefrompresence', - _('Post a notice when my Jabber/GTalk status changes.'), - $user->updatefrompresence); - common_checkbox('jabberreplies', - _('Send me replies through Jabber/GTalk from people I\'m not subscribed to.'), - $user->jabberreplies); - common_checkbox('jabbermicroid', - _('Publish a MicroID for my Jabber/GTalk address.'), - $user->jabbermicroid); - common_submit('save', _('Save')); - - common_element_end('form'); - common_show_footer(); - } - - function get_confirmation() { - $user = common_current_user(); - $confirm = new Confirm_address(); - $confirm->user_id = $user->id; - $confirm->address_type = 'jabber'; - if ($confirm->find(TRUE)) { - return $confirm; - } else { - return NULL; - } - } - - function handle_post() { - - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - if ($this->arg('save')) { - $this->save_preferences(); - } else if ($this->arg('add')) { - $this->add_address(); - } else if ($this->arg('cancel')) { - $this->cancel_confirmation(); - } else if ($this->arg('remove')) { - $this->remove_address(); - } else { - $this->show_form(_('Unexpected form submission.')); - } - } - - function save_preferences() { - - $jabbernotify = $this->boolean('jabbernotify'); - $updatefrompresence = $this->boolean('updatefrompresence'); - $jabberreplies = $this->boolean('jabberreplies'); - $jabbermicroid = $this->boolean('jabbermicroid'); - - $user = common_current_user(); - - assert(!is_null($user)); # should already be checked - - $user->query('BEGIN'); - - $original = clone($user); - - $user->jabbernotify = $jabbernotify; - $user->updatefrompresence = $updatefrompresence; - $user->jabberreplies = $jabberreplies; - $user->jabbermicroid = $jabbermicroid; - - $result = $user->update($original); - - if ($result === FALSE) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } - - $user->query('COMMIT'); - - $this->show_form(_('Preferences saved.'), true); - } - - function add_address() { - - $user = common_current_user(); - - $jabber = $this->trimmed('jabber'); - - # Some validation - - if (!$jabber) { - $this->show_form(_('No Jabber ID.')); - return; - } - - $jabber = jabber_normalize_jid($jabber); - - if (!$jabber) { - $this->show_form(_('Cannot normalize that Jabber ID')); - return; - } - if (!jabber_valid_base_jid($jabber)) { - $this->show_form(_('Not a valid Jabber ID')); - return; - } else if ($user->jabber == $jabber) { - $this->show_form(_('That is already your Jabber ID.')); - return; - } else if ($this->jabber_exists($jabber)) { - $this->show_form(_('Jabber ID already belongs to another user.')); - return; - } - - $confirm = new Confirm_address(); - $confirm->address = $jabber; - $confirm->address_type = 'jabber'; - $confirm->user_id = $user->id; - $confirm->code = common_confirmation_code(64); - - $result = $confirm->insert(); - - if ($result === FALSE) { - common_log_db_error($confirm, 'INSERT', __FILE__); - common_server_error(_('Couldn\'t insert confirmation code.')); - return; - } - - if (!common_config('queue', 'enabled')) { - jabber_confirm_address($confirm->code, - $user->nickname, - $jabber); - } - - $msg = sprintf(_('A confirmation code was sent to the IM address you added. You must approve %s for sending messages to you.'), jabber_daemon_address()); - - $this->show_form($msg, TRUE); - } - - function cancel_confirmation() { - $jabber = $this->arg('jabber'); - $confirm = $this->get_confirmation(); - if (!$confirm) { - $this->show_form(_('No pending confirmation to cancel.')); - return; - } - if ($confirm->address != $jabber) { - $this->show_form(_('That is the wrong IM address.')); - return; - } + function get_instructions() { + return _('You can send and receive notices through Jabber/GTalk [instant messages](%%doc.im%%). Configure your address and settings below.'); + } + + function show_form($msg=NULL, $success=false) { + $user = common_current_user(); + $this->form_header(_('IM Settings'), $msg, $success); + common_element_start('form', array('method' => 'post', + 'id' => 'imsettings', + 'action' => + common_local_url('imsettings'))); + common_hidden('token', common_session_token()); + + common_element('h2', NULL, _('Address')); + + if ($user->jabber) { + common_element_start('p'); + common_element('span', 'address confirmed', $user->jabber); + common_element('span', 'input_instructions', + _('Current confirmed Jabber/GTalk address.')); + common_hidden('jabber', $user->jabber); + common_element_end('p'); + common_submit('remove', _('Remove')); + } else { + $confirm = $this->get_confirmation(); + if ($confirm) { + common_element_start('p'); + common_element('span', 'address unconfirmed', $confirm->address); + common_element('span', 'input_instructions', + sprintf(_('Awaiting confirmation on this address. Check your Jabber/GTalk account for a message with further instructions. (Did you add %s to your buddy list?)'), jabber_daemon_address())); + common_hidden('jabber', $confirm->address); + common_element_end('p'); + common_submit('cancel', _('Cancel')); + } else { + common_input('jabber', _('IM Address'), + ($this->arg('jabber')) ? $this->arg('jabber') : NULL, + sprintf(_('Jabber or GTalk address, like "UserName@example.org". First, make sure to add %s to your buddy list in your IM client or on GTalk.'), jabber_daemon_address())); + common_submit('add', _('Add')); + } + } + + common_element('h2', NULL, _('Preferences')); + + common_checkbox('jabbernotify', + _('Send me notices through Jabber/GTalk.'), + $user->jabbernotify); + common_checkbox('updatefrompresence', + _('Post a notice when my Jabber/GTalk status changes.'), + $user->updatefrompresence); + common_checkbox('jabberreplies', + _('Send me replies through Jabber/GTalk from people I\'m not subscribed to.'), + $user->jabberreplies); + common_checkbox('jabbermicroid', + _('Publish a MicroID for my Jabber/GTalk address.'), + $user->jabbermicroid); + common_submit('save', _('Save')); + + common_element_end('form'); + common_show_footer(); + } + + function get_confirmation() { + $user = common_current_user(); + $confirm = new Confirm_address(); + $confirm->user_id = $user->id; + $confirm->address_type = 'jabber'; + if ($confirm->find(TRUE)) { + return $confirm; + } else { + return NULL; + } + } + + function handle_post() { + + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + if ($this->arg('save')) { + $this->save_preferences(); + } else if ($this->arg('add')) { + $this->add_address(); + } else if ($this->arg('cancel')) { + $this->cancel_confirmation(); + } else if ($this->arg('remove')) { + $this->remove_address(); + } else { + $this->show_form(_('Unexpected form submission.')); + } + } + + function save_preferences() { + + $jabbernotify = $this->boolean('jabbernotify'); + $updatefrompresence = $this->boolean('updatefrompresence'); + $jabberreplies = $this->boolean('jabberreplies'); + $jabbermicroid = $this->boolean('jabbermicroid'); + + $user = common_current_user(); + + assert(!is_null($user)); # should already be checked + + $user->query('BEGIN'); + + $original = clone($user); + + $user->jabbernotify = $jabbernotify; + $user->updatefrompresence = $updatefrompresence; + $user->jabberreplies = $jabberreplies; + $user->jabbermicroid = $jabbermicroid; + + $result = $user->update($original); + + if ($result === FALSE) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } + + $user->query('COMMIT'); + + $this->show_form(_('Preferences saved.'), true); + } + + function add_address() { + + $user = common_current_user(); + + $jabber = $this->trimmed('jabber'); + + # Some validation + + if (!$jabber) { + $this->show_form(_('No Jabber ID.')); + return; + } + + $jabber = jabber_normalize_jid($jabber); + + if (!$jabber) { + $this->show_form(_('Cannot normalize that Jabber ID')); + return; + } + if (!jabber_valid_base_jid($jabber)) { + $this->show_form(_('Not a valid Jabber ID')); + return; + } else if ($user->jabber == $jabber) { + $this->show_form(_('That is already your Jabber ID.')); + return; + } else if ($this->jabber_exists($jabber)) { + $this->show_form(_('Jabber ID already belongs to another user.')); + return; + } + + $confirm = new Confirm_address(); + $confirm->address = $jabber; + $confirm->address_type = 'jabber'; + $confirm->user_id = $user->id; + $confirm->code = common_confirmation_code(64); + + $result = $confirm->insert(); + + if ($result === FALSE) { + common_log_db_error($confirm, 'INSERT', __FILE__); + common_server_error(_('Couldn\'t insert confirmation code.')); + return; + } + + if (!common_config('queue', 'enabled')) { + jabber_confirm_address($confirm->code, + $user->nickname, + $jabber); + } + + $msg = sprintf(_('A confirmation code was sent to the IM address you added. You must approve %s for sending messages to you.'), jabber_daemon_address()); + + $this->show_form($msg, TRUE); + } + + function cancel_confirmation() { + $jabber = $this->arg('jabber'); + $confirm = $this->get_confirmation(); + if (!$confirm) { + $this->show_form(_('No pending confirmation to cancel.')); + return; + } + if ($confirm->address != $jabber) { + $this->show_form(_('That is the wrong IM address.')); + return; + } $result = $confirm->delete(); if (!$result) { - common_log_db_error($confirm, 'DELETE', __FILE__); + common_log_db_error($confirm, 'DELETE', __FILE__); $this->server_error(_('Couldn\'t delete email confirmation.')); return; } $this->show_form(_('Confirmation cancelled.'), TRUE); - } - - function remove_address() { - - $user = common_current_user(); - $jabber = $this->arg('jabber'); - - # Maybe an old tab open...? - - if ($user->jabber != $jabber) { - $this->show_form(_('That is not your Jabber ID.')); - return; - } - - $user->query('BEGIN'); - $original = clone($user); - $user->jabber = NULL; - $result = $user->updateKeys($original); - if (!$result) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } - $user->query('COMMIT'); - - # XXX: unsubscribe to the old address - - $this->show_form(_('The address was removed.'), TRUE); - } - - function jabber_exists($jabber) { - $user = common_current_user(); - $other = User::staticGet('jabber', $jabber); - if (!$other) { - return false; - } else { - return $other->id != $user->id; - } - } + } + + function remove_address() { + + $user = common_current_user(); + $jabber = $this->arg('jabber'); + + # Maybe an old tab open...? + + if ($user->jabber != $jabber) { + $this->show_form(_('That is not your Jabber ID.')); + return; + } + + $user->query('BEGIN'); + $original = clone($user); + $user->jabber = NULL; + $result = $user->updateKeys($original); + if (!$result) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } + $user->query('COMMIT'); + + # XXX: unsubscribe to the old address + + $this->show_form(_('The address was removed.'), TRUE); + } + + function jabber_exists($jabber) { + $user = common_current_user(); + $other = User::staticGet('jabber', $jabber); + if (!$other) { + return false; + } else { + return $other->id != $user->id; + } + } } diff --git a/_darcs/pristine/actions/invite.php b/_darcs/pristine/actions/invite.php index c7d92085c..e5cc6ad01 100644 --- a/_darcs/pristine/actions/invite.php +++ b/_darcs/pristine/actions/invite.php @@ -21,179 +21,179 @@ if (!defined('LACONICA')) { exit(1); } class InviteAction extends Action { - function is_readonly() { - return false; - } + function is_readonly() { + return false; + } function handle($args) { parent::handle($args); - if (!common_logged_in()) { - $this->client_error(sprintf(_('You must be logged in to invite other users to use %s'), - common_config('site', 'name'))); - return; - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->send_invitations(); - } else { - $this->show_form(); - } - } - - function send_invitations() { - - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - $user = common_current_user(); - $profile = $user->getProfile(); - - $bestname = $profile->getBestName(); - $sitename = common_config('site', 'name'); - $personal = $this->trimmed('personal'); - - $addresses = explode("\n", $this->trimmed('addresses')); - - foreach ($addresses as $email) { - $email = trim($email); - if (!Validate::email($email, true)) { - $this->show_form(sprintf(_('Invalid email address: %s'), $email)); - return; - } - } - - $already = array(); - $subbed = array(); - - foreach ($addresses as $email) { - $email = common_canonical_email($email); - $other = User::staticGet('email', $email); - if ($other) { - if ($user->isSubscribed($other)) { - $already[] = $other; - } else { - subs_subscribe_to($user, $other); - $subbed[] = $other; - } - } else { - $sent[] = $email; - $this->send_invitation($email, $user, $personal); - } - } - - common_show_header(_('Invitation(s) sent')); - if ($already) { - common_element('p', NULL, _('You are already subscribed to these users:')); - common_element_start('ul'); - foreach ($already as $other) { - common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email)); - } - common_element_end('ul'); - } - if ($subbed) { - common_element('p', NULL, _('These people are already users and you were automatically subscribed to them:')); - common_element_start('ul'); - foreach ($subbed as $other) { - common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email)); - } - common_element_end('ul'); - } - if ($sent) { - common_element('p', NULL, _('Invitation(s) sent to the following people:')); - common_element_start('ul'); - foreach ($sent as $other) { - common_element('li', NULL, $other); - } - common_element_end('ul'); - common_element('p', NULL, _('You will be notified when your invitees accept the invitation and register on the site. Thanks for growing the community!')); - } - common_show_footer(); - } - - function show_top($error=NULL) { - if ($error) { - common_element('p', 'error', $error); - } else { - common_element_start('div', 'instructions'); - common_element('p', NULL, - _('Use this form to invite your friends and colleagues to use this service.')); - common_element_end('div'); - } - } - - function show_form($error=NULL) { - - global $config; - - common_show_header(_('Invite new users'), NULL, $error, array($this, 'show_top')); - - common_element_start('form', array('method' => 'post', - 'id' => 'invite', - 'action' => common_local_url('invite'))); - common_hidden('token', common_session_token()); - - common_textarea('addresses', _('Email addresses'), - $this->trimmed('addresses'), - _('Addresses of friends to invite (one per line)')); - - common_textarea('personal', _('Personal message'), - $this->trimmed('personal'), - _('Optionally add a personal message to the invitation.')); - - common_submit('send', _('Send')); - - common_element_end('form'); - - common_show_footer(); - } - - function send_invitation($email, $user, $personal) { - - $profile = $user->getProfile(); - $bestname = $profile->getBestName(); - - $sitename = common_config('site', 'name'); - - $invite = new Invitation(); - - $invite->address = $email; - $invite->address_type = 'email'; - $invite->code = common_confirmation_code(128); - $invite->user_id = $user->id; - $invite->created = common_sql_now(); - - if (!$invite->insert()) { - common_log_db_error($invite, 'INSERT', __FILE__); - return false; - } - - $recipients = array($email); - - $headers['From'] = mail_notify_from(); - $headers['To'] = $email; - $headers['Subject'] = sprintf(_('%1$s has invited you to join them on %2$s'), $bestname, $sitename); - - $body = sprintf(_("%1\$s has invited you to join them on %2\$s (%3\$s).\n\n". - "%2\$s is a micro-blogging service that lets you keep up-to-date with people you know and people who interest you.\n\n". - "You can also share news about yourself, your thoughts, or your life online with people who know about you. ". - "It's also great for meeting new people who share your interests.\n\n". - "%1\$s said:\n\n%4\$s\n\n". - "You can see %1\$s's profile page on %2\$s here:\n\n". - "%5\$s\n\n". - "If you'd like to try the service, click on the link below to accept the invitation.\n\n". - "%6\$s\n\n". - "If not, you can ignore this message. Thanks for your patience and your time.\n\n". - "Sincerely, %2\$s\n"), - $bestname, - $sitename, - common_root_url(), - $personal, - common_local_url('showstream', array('nickname' => $user->nickname)), - common_local_url('register', array('code' => $invite->code))); - - mail_send($recipients, $headers, $body); - } + if (!common_logged_in()) { + $this->client_error(sprintf(_('You must be logged in to invite other users to use %s'), + common_config('site', 'name'))); + return; + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->send_invitations(); + } else { + $this->show_form(); + } + } + + function send_invitations() { + + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + $user = common_current_user(); + $profile = $user->getProfile(); + + $bestname = $profile->getBestName(); + $sitename = common_config('site', 'name'); + $personal = $this->trimmed('personal'); + + $addresses = explode("\n", $this->trimmed('addresses')); + + foreach ($addresses as $email) { + $email = trim($email); + if (!Validate::email($email, true)) { + $this->show_form(sprintf(_('Invalid email address: %s'), $email)); + return; + } + } + + $already = array(); + $subbed = array(); + + foreach ($addresses as $email) { + $email = common_canonical_email($email); + $other = User::staticGet('email', $email); + if ($other) { + if ($user->isSubscribed($other)) { + $already[] = $other; + } else { + subs_subscribe_to($user, $other); + $subbed[] = $other; + } + } else { + $sent[] = $email; + $this->send_invitation($email, $user, $personal); + } + } + + common_show_header(_('Invitation(s) sent')); + if ($already) { + common_element('p', NULL, _('You are already subscribed to these users:')); + common_element_start('ul'); + foreach ($already as $other) { + common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email)); + } + common_element_end('ul'); + } + if ($subbed) { + common_element('p', NULL, _('These people are already users and you were automatically subscribed to them:')); + common_element_start('ul'); + foreach ($subbed as $other) { + common_element('li', NULL, sprintf(_('%s (%s)'), $other->nickname, $other->email)); + } + common_element_end('ul'); + } + if ($sent) { + common_element('p', NULL, _('Invitation(s) sent to the following people:')); + common_element_start('ul'); + foreach ($sent as $other) { + common_element('li', NULL, $other); + } + common_element_end('ul'); + common_element('p', NULL, _('You will be notified when your invitees accept the invitation and register on the site. Thanks for growing the community!')); + } + common_show_footer(); + } + + function show_top($error=NULL) { + if ($error) { + common_element('p', 'error', $error); + } else { + common_element_start('div', 'instructions'); + common_element('p', NULL, + _('Use this form to invite your friends and colleagues to use this service.')); + common_element_end('div'); + } + } + + function show_form($error=NULL) { + + global $config; + + common_show_header(_('Invite new users'), NULL, $error, array($this, 'show_top')); + + common_element_start('form', array('method' => 'post', + 'id' => 'invite', + 'action' => common_local_url('invite'))); + common_hidden('token', common_session_token()); + + common_textarea('addresses', _('Email addresses'), + $this->trimmed('addresses'), + _('Addresses of friends to invite (one per line)')); + + common_textarea('personal', _('Personal message'), + $this->trimmed('personal'), + _('Optionally add a personal message to the invitation.')); + + common_submit('send', _('Send')); + + common_element_end('form'); + + common_show_footer(); + } + + function send_invitation($email, $user, $personal) { + + $profile = $user->getProfile(); + $bestname = $profile->getBestName(); + + $sitename = common_config('site', 'name'); + + $invite = new Invitation(); + + $invite->address = $email; + $invite->address_type = 'email'; + $invite->code = common_confirmation_code(128); + $invite->user_id = $user->id; + $invite->created = common_sql_now(); + + if (!$invite->insert()) { + common_log_db_error($invite, 'INSERT', __FILE__); + return false; + } + + $recipients = array($email); + + $headers['From'] = mail_notify_from(); + $headers['To'] = $email; + $headers['Subject'] = sprintf(_('%1$s has invited you to join them on %2$s'), $bestname, $sitename); + + $body = sprintf(_("%1\$s has invited you to join them on %2\$s (%3\$s).\n\n". + "%2\$s is a micro-blogging service that lets you keep up-to-date with people you know and people who interest you.\n\n". + "You can also share news about yourself, your thoughts, or your life online with people who know about you. ". + "It's also great for meeting new people who share your interests.\n\n". + "%1\$s said:\n\n%4\$s\n\n". + "You can see %1\$s's profile page on %2\$s here:\n\n". + "%5\$s\n\n". + "If you'd like to try the service, click on the link below to accept the invitation.\n\n". + "%6\$s\n\n". + "If not, you can ignore this message. Thanks for your patience and your time.\n\n". + "Sincerely, %2\$s\n"), + $bestname, + $sitename, + common_root_url(), + $personal, + common_local_url('showstream', array('nickname' => $user->nickname)), + common_local_url('register', array('code' => $invite->code))); + + mail_send($recipients, $headers, $body); + } } diff --git a/_darcs/pristine/actions/login.php b/_darcs/pristine/actions/login.php index ccec9cf8a..5e4d45149 100644 --- a/_darcs/pristine/actions/login.php +++ b/_darcs/pristine/actions/login.php @@ -21,132 +21,132 @@ if (!defined('LACONICA')) { exit(1); } class LoginAction extends Action { - function is_readonly() { - return true; - } + function is_readonly() { + return true; + } - function handle($args) { - parent::handle($args); - if (common_is_real_login()) { - common_user_error(_('Already logged in.')); - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->check_login(); - } else { - $this->show_form(); - } - } + function handle($args) { + parent::handle($args); + if (common_is_real_login()) { + common_user_error(_('Already logged in.')); + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->check_login(); + } else { + $this->show_form(); + } + } - function check_login() { - # XXX: login throttle + function check_login() { + # XXX: login throttle - # CSRF protection - token set in common_notice_form() - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + # CSRF protection - token set in common_notice_form() + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } - $nickname = common_canonical_nickname($this->trimmed('nickname')); - $password = $this->arg('password'); - if (common_check_user($nickname, $password)) { - # success! - if (!common_set_user($nickname)) { - common_server_error(_('Error setting user.')); - return; - } - common_real_login(true); - if ($this->boolean('rememberme')) { - common_debug('Adding rememberme cookie for ' . $nickname); - common_rememberme(); - } - # success! - $url = common_get_returnto(); - if ($url) { - # We don't have to return to it again - common_set_returnto(NULL); - } else { - $url = common_local_url('all', - array('nickname' => - $nickname)); - } - common_redirect($url); - } else { - $this->show_form(_('Incorrect username or password.')); - return; - } + $nickname = common_canonical_nickname($this->trimmed('nickname')); + $password = $this->arg('password'); + if (common_check_user($nickname, $password)) { + # success! + if (!common_set_user($nickname)) { + common_server_error(_('Error setting user.')); + return; + } + common_real_login(true); + if ($this->boolean('rememberme')) { + common_debug('Adding rememberme cookie for ' . $nickname); + common_rememberme(); + } + # success! + $url = common_get_returnto(); + if ($url) { + # We don't have to return to it again + common_set_returnto(NULL); + } else { + $url = common_local_url('all', + array('nickname' => + $nickname)); + } + common_redirect($url); + } else { + $this->show_form(_('Incorrect username or password.')); + return; + } - # success! - if (!common_set_user($user)) { - common_server_error(_('Error setting user.')); - return; - } + # success! + if (!common_set_user($user)) { + common_server_error(_('Error setting user.')); + return; + } - common_real_login(true); + common_real_login(true); - if ($this->boolean('rememberme')) { - common_debug('Adding rememberme cookie for ' . $nickname); - common_rememberme($user); - } - # success! - $url = common_get_returnto(); - if ($url) { - # We don't have to return to it again - common_set_returnto(NULL); - } else { - $url = common_local_url('all', - array('nickname' => - $nickname)); - } - common_redirect($url); - } + if ($this->boolean('rememberme')) { + common_debug('Adding rememberme cookie for ' . $nickname); + common_rememberme($user); + } + # success! + $url = common_get_returnto(); + if ($url) { + # We don't have to return to it again + common_set_returnto(NULL); + } else { + $url = common_local_url('all', + array('nickname' => + $nickname)); + } + common_redirect($url); + } - function show_form($error=NULL) { - common_show_header(_('Login'), NULL, $error, array($this, 'show_top')); - common_element_start('form', array('method' => 'post', - 'id' => 'login', - 'action' => common_local_url('login'))); - common_input('nickname', _('Nickname')); - common_password('password', _('Password')); - common_checkbox('rememberme', _('Remember me'), false, - _('Automatically login in the future; ' . - 'not for shared computers!')); - common_submit('submit', _('Login')); - common_hidden('token', common_session_token()); - common_element_end('form'); - common_element_start('p'); - common_element('a', array('href' => common_local_url('recoverpassword')), - _('Lost or forgotten password?')); - common_element_end('p'); - common_show_footer(); - } + function show_form($error=NULL) { + common_show_header(_('Login'), NULL, $error, array($this, 'show_top')); + common_element_start('form', array('method' => 'post', + 'id' => 'login', + 'action' => common_local_url('login'))); + common_input('nickname', _('Nickname')); + common_password('password', _('Password')); + common_checkbox('rememberme', _('Remember me'), false, + _('Automatically login in the future; ' . + 'not for shared computers!')); + common_submit('submit', _('Login')); + common_hidden('token', common_session_token()); + common_element_end('form'); + common_element_start('p'); + common_element('a', array('href' => common_local_url('recoverpassword')), + _('Lost or forgotten password?')); + common_element_end('p'); + common_show_footer(); + } - function get_instructions() { - if (common_logged_in() && - !common_is_real_login() && - common_get_returnto()) - { - # rememberme logins have to reauthenticate before - # changing any profile settings (cookie-stealing protection) - return _('For security reasons, please re-enter your ' . - 'user name and password ' . - 'before changing your settings.'); - } else { - return _('Login with your username and password. ' . - 'Don\'t have a username yet? ' . - '[Register](%%action.register%%) a new account, or ' . - 'try [OpenID](%%action.openidlogin%%). '); - } - } + function get_instructions() { + if (common_logged_in() && + !common_is_real_login() && + common_get_returnto()) + { + # rememberme logins have to reauthenticate before + # changing any profile settings (cookie-stealing protection) + return _('For security reasons, please re-enter your ' . + 'user name and password ' . + 'before changing your settings.'); + } else { + return _('Login with your username and password. ' . + 'Don\'t have a username yet? ' . + '[Register](%%action.register%%) a new account, or ' . + 'try [OpenID](%%action.openidlogin%%). '); + } + } - function show_top($error=NULL) { - if ($error) { - common_element('p', 'error', $error); - } else { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - } - } + function show_top($error=NULL) { + if ($error) { + common_element('p', 'error', $error); + } else { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + } + } } diff --git a/_darcs/pristine/actions/logout.php b/_darcs/pristine/actions/logout.php index f00fa0ba7..5f7b9d502 100644 --- a/_darcs/pristine/actions/logout.php +++ b/_darcs/pristine/actions/logout.php @@ -22,20 +22,20 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/openid.php'); class LogoutAction extends Action { - - function is_readonly() { - return true; - } - - function handle($args) { - parent::handle($args); - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - } else { - common_set_user(NULL); - common_real_login(false); # not logged in - common_forgetme(); # don't log back in! - common_redirect(common_local_url('public')); - } - } + + function is_readonly() { + return true; + } + + function handle($args) { + parent::handle($args); + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + } else { + common_set_user(NULL); + common_real_login(false); # not logged in + common_forgetme(); # don't log back in! + common_redirect(common_local_url('public')); + } + } } diff --git a/_darcs/pristine/actions/microsummary.php b/_darcs/pristine/actions/microsummary.php index 104467d29..ced4b0d1e 100644 --- a/_darcs/pristine/actions/microsummary.php +++ b/_darcs/pristine/actions/microsummary.php @@ -21,26 +21,26 @@ if (!defined('LACONICA')) { exit(1); } class MicrosummaryAction extends Action { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); + $nickname = common_canonical_nickname($this->arg('nickname')); + $user = User::staticGet('nickname', $nickname); - if (!$user) { - $this->client_error(_('No such user'), 404); - return; - } - - $notice = $user->getCurrentNotice(); - - if (!$notice) { - $this->client_error(_('No current status'), 404); - } - - header('Content-Type: text/plain'); - - print $user->nickname . ': ' . $notice->content; - } + if (!$user) { + $this->client_error(_('No such user'), 404); + return; + } + + $notice = $user->getCurrentNotice(); + + if (!$notice) { + $this->client_error(_('No current status'), 404); + } + + header('Content-Type: text/plain'); + + print $user->nickname . ': ' . $notice->content; + } } diff --git a/_darcs/pristine/actions/newmessage.php b/_darcs/pristine/actions/newmessage.php index da48fc7e7..121fc4246 100644 --- a/_darcs/pristine/actions/newmessage.php +++ b/_darcs/pristine/actions/newmessage.php @@ -20,116 +20,116 @@ if (!defined('LACONICA')) { exit(1); } class NewmessageAction extends Action { - - function handle($args) { - parent::handle($args); - - if (!common_logged_in()) { - $this->client_error(_('Not logged in.'), 403); - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->save_new_message(); - } else { - $this->show_form(); - } - } - - function save_new_message() { - $user = common_current_user(); - assert($user); # XXX: maybe an error instead... - - # CSRF protection - - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - $content = $this->trimmed('content'); - $to = $this->trimmed('to'); - - if (!$content) { - $this->show_form(_('No content!')); - return; - } else { - $content_shortened = common_shorten_links($content); - - if (mb_strlen($content_shortened) > 140) { - common_debug("Content = '$content_shortened'", __FILE__); - common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__); - $this->show_form(_('That\'s too long. Max message size is 140 chars.')); - return; - } - } - - $other = User::staticGet('id', $to); - - if (!$other) { - $this->show_form(_('No recipient specified.')); - return; - } else if (!$user->mutuallySubscribed($other)) { - $this->client_error(_('You can\'t send a message to this user.'), 404); - return; - } else if ($user->id == $other->id) { - $this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), 403); - return; - } - - $message = Message::saveNew($user->id, $other->id, $content, 'web'); - - if (is_string($message)) { - $this->show_form($message); - return; - } - - $this->notify($user, $other, $message); - - $url = common_local_url('outbox', array('nickname' => $user->nickname)); - - common_redirect($url, 303); - } - - function show_top($params) { - - list($content, $user, $to) = $params; - - assert(!is_null($user)); - - common_message_form($content, $user, $to); - } - - function show_form($msg=NULL) { - - $content = $this->trimmed('content'); - $user = common_current_user(); - - $to = $this->trimmed('to'); - - $other = User::staticGet('id', $to); - - if (!$other) { - $this->client_error(_('No such user'), 404); - return; - } - - if (!$user->mutuallySubscribed($other)) { - $this->client_error(_('You can\'t send a message to this user.'), 404); - return; - } - - common_show_header(_('New message'), NULL, - array($content, $user, $other), - array($this, 'show_top')); - - if ($msg) { - common_element('p', array('id'=>'error'), $msg); - } - - common_show_footer(); - } - - function notify($from, $to, $message) { - mail_notify_message($message, $from, $to); - # XXX: Jabber, SMS notifications... probably queued - } + + function handle($args) { + parent::handle($args); + + if (!common_logged_in()) { + $this->client_error(_('Not logged in.'), 403); + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->save_new_message(); + } else { + $this->show_form(); + } + } + + function save_new_message() { + $user = common_current_user(); + assert($user); # XXX: maybe an error instead... + + # CSRF protection + + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + $content = $this->trimmed('content'); + $to = $this->trimmed('to'); + + if (!$content) { + $this->show_form(_('No content!')); + return; + } else { + $content_shortened = common_shorten_links($content); + + if (mb_strlen($content_shortened) > 140) { + common_debug("Content = '$content_shortened'", __FILE__); + common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__); + $this->show_form(_('That\'s too long. Max message size is 140 chars.')); + return; + } + } + + $other = User::staticGet('id', $to); + + if (!$other) { + $this->show_form(_('No recipient specified.')); + return; + } else if (!$user->mutuallySubscribed($other)) { + $this->client_error(_('You can\'t send a message to this user.'), 404); + return; + } else if ($user->id == $other->id) { + $this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), 403); + return; + } + + $message = Message::saveNew($user->id, $other->id, $content, 'web'); + + if (is_string($message)) { + $this->show_form($message); + return; + } + + $this->notify($user, $other, $message); + + $url = common_local_url('outbox', array('nickname' => $user->nickname)); + + common_redirect($url, 303); + } + + function show_top($params) { + + list($content, $user, $to) = $params; + + assert(!is_null($user)); + + common_message_form($content, $user, $to); + } + + function show_form($msg=NULL) { + + $content = $this->trimmed('content'); + $user = common_current_user(); + + $to = $this->trimmed('to'); + + $other = User::staticGet('id', $to); + + if (!$other) { + $this->client_error(_('No such user'), 404); + return; + } + + if (!$user->mutuallySubscribed($other)) { + $this->client_error(_('You can\'t send a message to this user.'), 404); + return; + } + + common_show_header(_('New message'), NULL, + array($content, $user, $other), + array($this, 'show_top')); + + if ($msg) { + common_element('p', array('id'=>'error'), $msg); + } + + common_show_footer(); + } + + function notify($from, $to, $message) { + mail_notify_message($message, $from, $to); + # XXX: Jabber, SMS notifications... probably queued + } } diff --git a/_darcs/pristine/actions/newnotice.php b/_darcs/pristine/actions/newnotice.php index 42b48923f..7c3ad8815 100644 --- a/_darcs/pristine/actions/newnotice.php +++ b/_darcs/pristine/actions/newnotice.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,132 +23,132 @@ require_once INSTALLDIR . '/lib/noticelist.php'; class NewnoticeAction extends Action { - function handle($args) { - parent::handle($args); - - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - - # CSRF protection - token set in common_notice_form() - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } - - $this->save_new_notice(); - } else { - $this->show_form(); - } - } - - function save_new_notice() { - - $user = common_current_user(); - assert($user); # XXX: maybe an error instead... - $content = $this->trimmed('status_textarea'); - - if (!$content) { - $this->show_form(_('No content!')); - return; - } else { - $content_shortened = common_shorten_links($content); - - if (mb_strlen($content_shortened) > 140) { - common_debug("Content = '$content_shortened'", __FILE__); - common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__); - $this->show_form(_('That\'s too long. Max notice size is 140 chars.')); - return; - } - } - - $inter = new CommandInterpreter(); - - $cmd = $inter->handle_command($user, $content_shortened); - - if ($cmd) { - if ($this->boolean('ajax')) { - $cmd->execute(new AjaxWebChannel()); - } else { - $cmd->execute(new WebChannel()); - } - return; - } - - $replyto = $this->trimmed('inreplyto'); - - $notice = Notice::saveNew($user->id, $content, 'web', 1, ($replyto == 'false') ? NULL : $replyto); - - if (is_string($notice)) { - $this->show_form($notice); - return; - } - - common_broadcast_notice($notice); - - if ($this->boolean('ajax')) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Notice posted')); - common_element_end('head'); - common_element_start('body'); - $this->show_notice($notice); - common_element_end('body'); - common_element_end('html'); - } else { - $returnto = $this->trimmed('returnto'); - - if ($returnto) { - $url = common_local_url($returnto, - array('nickname' => $user->nickname)); - } else { - $url = common_local_url('shownotice', - array('notice' => $notice->id)); - } - common_redirect($url, 303); - } - } - - function ajax_error_msg($msg) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Ajax Error')); - common_element_end('head'); - common_element_start('body'); - common_element('p', array('id' => 'error'), $msg); - common_element_end('body'); - common_element_end('html'); - } - - function show_top($content=NULL) { - common_notice_form(NULL, $content); - } - - function show_form($msg=NULL) { - if ($msg && $this->boolean('ajax')) { - $this->ajax_error_msg($msg); - return; - } - $content = $this->trimmed('status_textarea'); - if (!$content) { - $replyto = $this->trimmed('replyto'); - $profile = Profile::staticGet('nickname', $replyto); - if ($profile) { - $content = '@' . $profile->nickname . ' '; - } - } - common_show_header(_('New notice'), NULL, $content, - array($this, 'show_top')); - if ($msg) { - common_element('p', array('id' => 'error'), $msg); - } - common_show_footer(); - } - - function show_notice($notice) { + function handle($args) { + parent::handle($args); + + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + + # CSRF protection - token set in common_notice_form() + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } + + $this->save_new_notice(); + } else { + $this->show_form(); + } + } + + function save_new_notice() { + + $user = common_current_user(); + assert($user); # XXX: maybe an error instead... + $content = $this->trimmed('status_textarea'); + + if (!$content) { + $this->show_form(_('No content!')); + return; + } else { + $content_shortened = common_shorten_links($content); + + if (mb_strlen($content_shortened) > 140) { + common_debug("Content = '$content_shortened'", __FILE__); + common_debug("mb_strlen(\$content) = " . mb_strlen($content_shortened), __FILE__); + $this->show_form(_('That\'s too long. Max notice size is 140 chars.')); + return; + } + } + + $inter = new CommandInterpreter(); + + $cmd = $inter->handle_command($user, $content_shortened); + + if ($cmd) { + if ($this->boolean('ajax')) { + $cmd->execute(new AjaxWebChannel()); + } else { + $cmd->execute(new WebChannel()); + } + return; + } + + $replyto = $this->trimmed('inreplyto'); + + $notice = Notice::saveNew($user->id, $content, 'web', 1, ($replyto == 'false') ? NULL : $replyto); + + if (is_string($notice)) { + $this->show_form($notice); + return; + } + + common_broadcast_notice($notice); + + if ($this->boolean('ajax')) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Notice posted')); + common_element_end('head'); + common_element_start('body'); + $this->show_notice($notice); + common_element_end('body'); + common_element_end('html'); + } else { + $returnto = $this->trimmed('returnto'); + + if ($returnto) { + $url = common_local_url($returnto, + array('nickname' => $user->nickname)); + } else { + $url = common_local_url('shownotice', + array('notice' => $notice->id)); + } + common_redirect($url, 303); + } + } + + function ajax_error_msg($msg) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Ajax Error')); + common_element_end('head'); + common_element_start('body'); + common_element('p', array('id' => 'error'), $msg); + common_element_end('body'); + common_element_end('html'); + } + + function show_top($content=NULL) { + common_notice_form(NULL, $content); + } + + function show_form($msg=NULL) { + if ($msg && $this->boolean('ajax')) { + $this->ajax_error_msg($msg); + return; + } + $content = $this->trimmed('status_textarea'); + if (!$content) { + $replyto = $this->trimmed('replyto'); + $profile = Profile::staticGet('nickname', $replyto); + if ($profile) { + $content = '@' . $profile->nickname . ' '; + } + } + common_show_header(_('New notice'), NULL, $content, + array($this, 'show_top')); + if ($msg) { + common_element('p', array('id' => 'error'), $msg); + } + common_show_footer(); + } + + function show_notice($notice) { $nli = new NoticeListItem($notice); $nli->show(); - } + } } diff --git a/_darcs/pristine/actions/noticesearch.php b/_darcs/pristine/actions/noticesearch.php index 96e4d777f..53d78e199 100644 --- a/_darcs/pristine/actions/noticesearch.php +++ b/_darcs/pristine/actions/noticesearch.php @@ -25,140 +25,140 @@ require_once(INSTALLDIR.'/lib/searchaction.php'); class NoticesearchAction extends SearchAction { - function get_instructions() { - return _('Search for notices on %%site.name%% by their contents. Separate search terms by spaces; they must be 3 characters or more.'); - } + function get_instructions() { + return _('Search for notices on %%site.name%% by their contents. Separate search terms by spaces; they must be 3 characters or more.'); + } - function get_title() { - return _('Text search'); - } + function get_title() { + return _('Text search'); + } - function show_results($q, $page) { + function show_results($q, $page) { - $notice = new Notice(); + $notice = new Notice(); - # lcase it for comparison - $q = strtolower($q); + # lcase it for comparison + $q = strtolower($q); $search_engine = $notice->getSearchEngine('identica_notices'); $search_engine->set_sort_mode('chron'); - # Ask for an extra to see if there's more. - $search_engine->limit((($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1); + # Ask for an extra to see if there's more. + $search_engine->limit((($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1); if (false === $search_engine->query($q)) { $cnt = 0; } else { - $cnt = $notice->find(); + $cnt = $notice->find(); } - if ($cnt > 0) { - $terms = preg_split('/[\s,]+/', $q); - common_element_start('ul', array('id' => 'notices')); - for ($i = 0; $i < min($cnt, NOTICES_PER_PAGE); $i++) { - if ($notice->fetch()) { - $this->show_notice($notice, $terms); - } else { - // shouldn't happen! - break; - } - } - common_element_end('ul'); - } else { - common_element('p', 'error', _('No results')); - } - - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'noticesearch', array('q' => $q)); - } - - function show_header($arr) { - if ($arr) { - $q = $arr[0]; - } - if ($q) { - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('noticesearchrss', - array('q' => $q)), - 'type' => 'application/rss+xml', - 'title' => _('Search Stream Feed'))); - } - } - - # XXX: refactor and combine with StreamAction::show_notice() - - function show_notice($notice, $terms) { - $profile = $notice->getProfile(); - if (!$profile) { - common_log_db_error($notice, 'SELECT', __FILE__); - $this->server_error(_('Notice without matching profile')); - return; - } - # XXX: RDFa - common_element_start('li', array('class' => 'notice_single', - 'id' => 'notice-' . $notice->id)); - $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); - common_element_start('a', array('href' => $profile->profileurl)); - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), - 'class' => 'avatar stream', - 'width' => AVATAR_STREAM_SIZE, - 'height' => AVATAR_STREAM_SIZE, - 'alt' => - ($profile->fullname) ? $profile->fullname : - $profile->nickname)); - common_element_end('a'); - common_element('a', array('href' => $profile->profileurl, - 'class' => 'nickname'), - $profile->nickname); - # FIXME: URL, image, video, audio - common_element_start('p', array('class' => 'content')); - if ($notice->rendered) { - common_raw($this->highlight($notice->rendered, $terms)); - } else { - # XXX: may be some uncooked notices in the DB, - # we cook them right now. This should probably disappear in future - # versions (>> 0.4.x) - common_raw($this->highlight(common_render_content($notice->content, $notice), $terms)); - } - common_element_end('p'); - $noticeurl = common_local_url('shownotice', array('notice' => $notice->id)); - common_element_start('p', 'time'); - common_element('a', array('class' => 'permalink', - 'href' => $noticeurl, - 'title' => common_exact_date($notice->created)), - common_date_string($notice->created)); - if ($notice->reply_to) { - $replyurl = common_local_url('shownotice', array('notice' => $notice->reply_to)); - common_text(' ('); - common_element('a', array('class' => 'inreplyto', - 'href' => $replyurl), - _('in reply to...')); - common_text(')'); - } - common_element_start('a', - array('href' => common_local_url('newnotice', - array('replyto' => $profile->nickname)), - 'onclick' => 'doreply("'.$profile->nickname.'"); return false', - 'title' => _('reply'), - 'class' => 'replybutton')); - common_hidden('posttoken', common_session_token()); - - common_raw('→'); - common_element_end('a'); - common_element_end('p'); - common_element_end('li'); - } - - function highlight($text, $terms) { - /* Highligh serach terms */ - $pattern = '/('.implode('|',array_map('htmlspecialchars', $terms)).')/i'; - $result = preg_replace($pattern, '\\1', $text); - - /* Remove highlighting from inside links, loop incase multiple highlights in links */ - $pattern = '/(href="[^"]*)('.implode('|',array_map('htmlspecialchars', $terms)).')<\/strong>([^"]*")/iU'; - do { - $result = preg_replace($pattern, '\\1\\2\\3', $result, -1, $count); - } while ($count); - return $result; - } + if ($cnt > 0) { + $terms = preg_split('/[\s,]+/', $q); + common_element_start('ul', array('id' => 'notices')); + for ($i = 0; $i < min($cnt, NOTICES_PER_PAGE); $i++) { + if ($notice->fetch()) { + $this->show_notice($notice, $terms); + } else { + // shouldn't happen! + break; + } + } + common_element_end('ul'); + } else { + common_element('p', 'error', _('No results')); + } + + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'noticesearch', array('q' => $q)); + } + + function show_header($arr) { + if ($arr) { + $q = $arr[0]; + } + if ($q) { + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('noticesearchrss', + array('q' => $q)), + 'type' => 'application/rss+xml', + 'title' => _('Search Stream Feed'))); + } + } + + # XXX: refactor and combine with StreamAction::show_notice() + + function show_notice($notice, $terms) { + $profile = $notice->getProfile(); + if (!$profile) { + common_log_db_error($notice, 'SELECT', __FILE__); + $this->server_error(_('Notice without matching profile')); + return; + } + # XXX: RDFa + common_element_start('li', array('class' => 'notice_single', + 'id' => 'notice-' . $notice->id)); + $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); + common_element_start('a', array('href' => $profile->profileurl)); + common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_STREAM_SIZE), + 'class' => 'avatar stream', + 'width' => AVATAR_STREAM_SIZE, + 'height' => AVATAR_STREAM_SIZE, + 'alt' => + ($profile->fullname) ? $profile->fullname : + $profile->nickname)); + common_element_end('a'); + common_element('a', array('href' => $profile->profileurl, + 'class' => 'nickname'), + $profile->nickname); + # FIXME: URL, image, video, audio + common_element_start('p', array('class' => 'content')); + if ($notice->rendered) { + common_raw($this->highlight($notice->rendered, $terms)); + } else { + # XXX: may be some uncooked notices in the DB, + # we cook them right now. This should probably disappear in future + # versions (>> 0.4.x) + common_raw($this->highlight(common_render_content($notice->content, $notice), $terms)); + } + common_element_end('p'); + $noticeurl = common_local_url('shownotice', array('notice' => $notice->id)); + common_element_start('p', 'time'); + common_element('a', array('class' => 'permalink', + 'href' => $noticeurl, + 'title' => common_exact_date($notice->created)), + common_date_string($notice->created)); + if ($notice->reply_to) { + $replyurl = common_local_url('shownotice', array('notice' => $notice->reply_to)); + common_text(' ('); + common_element('a', array('class' => 'inreplyto', + 'href' => $replyurl), + _('in reply to...')); + common_text(')'); + } + common_element_start('a', + array('href' => common_local_url('newnotice', + array('replyto' => $profile->nickname)), + 'onclick' => 'doreply("'.$profile->nickname.'"); return false', + 'title' => _('reply'), + 'class' => 'replybutton')); + common_hidden('posttoken', common_session_token()); + + common_raw('→'); + common_element_end('a'); + common_element_end('p'); + common_element_end('li'); + } + + function highlight($text, $terms) { + /* Highligh serach terms */ + $pattern = '/('.implode('|',array_map('htmlspecialchars', $terms)).')/i'; + $result = preg_replace($pattern, '\\1', $text); + + /* Remove highlighting from inside links, loop incase multiple highlights in links */ + $pattern = '/(href="[^"]*)('.implode('|',array_map('htmlspecialchars', $terms)).')<\/strong>([^"]*")/iU'; + do { + $result = preg_replace($pattern, '\\1\\2\\3', $result, -1, $count); + } while ($count); + return $result; + } } diff --git a/_darcs/pristine/actions/noticesearchrss.php b/_darcs/pristine/actions/noticesearchrss.php index 0f38515a0..a7df62ca0 100644 --- a/_darcs/pristine/actions/noticesearchrss.php +++ b/_darcs/pristine/actions/noticesearchrss.php @@ -25,46 +25,46 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class NoticesearchrssAction extends Rss10Action { - function init() { - return true; - } + function init() { + return true; + } - function get_notices($limit=0) { + function get_notices($limit=0) { - $q = $this->trimmed('q'); - $notices = array(); + $q = $this->trimmed('q'); + $notices = array(); - $notice = new Notice(); + $notice = new Notice(); - # lcase it for comparison - $q = strtolower($q); + # lcase it for comparison + $q = strtolower($q); $search_engine = $notice->getSearchEngine('identica_notices'); $search_engine->set_sort_mode('chron'); - if (!$limit) $limit = 20; + if (!$limit) $limit = 20; $search_engine->limit(0, $limit, true); $search_engine->query($q); - $notice->find(); + $notice->find(); - while ($notice->fetch()) { - $notices[] = clone($notice); - } + while ($notice->fetch()) { + $notices[] = clone($notice); + } - return $notices; - } + return $notices; + } - function get_channel() { - global $config; - $q = $this->trimmed('q'); - $c = array('url' => common_local_url('noticesearchrss', array('q' => $q)), - 'title' => $config['site']['name'] . sprintf(_(' Search Stream for "%s"'), $q), - 'link' => common_local_url('noticesearch', array('q' => $q)), - 'description' => sprintf(_('All updates matching search term "%s"'), $q)); - return $c; - } + function get_channel() { + global $config; + $q = $this->trimmed('q'); + $c = array('url' => common_local_url('noticesearchrss', array('q' => $q)), + 'title' => $config['site']['name'] . sprintf(_(' Search Stream for "%s"'), $q), + 'link' => common_local_url('noticesearch', array('q' => $q)), + 'description' => sprintf(_('All updates matching search term "%s"'), $q)); + return $c; + } - function get_image() { - return NULL; - } + function get_image() { + return NULL; + } } diff --git a/_darcs/pristine/actions/nudge.php b/_darcs/pristine/actions/nudge.php index 677f58800..6f3b4c95c 100644 --- a/_darcs/pristine/actions/nudge.php +++ b/_darcs/pristine/actions/nudge.php @@ -23,62 +23,62 @@ require_once(INSTALLDIR.'/lib/mail.php'); class NudgeAction extends Action { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - if (!common_logged_in()) { - $this->client_error(_('Not logged in.')); - return; - } + if (!common_logged_in()) { + $this->client_error(_('Not logged in.')); + return; + } - $user = common_current_user(); - $other = User::staticGet('nickname', $this->arg('nickname')); + $user = common_current_user(); + $other = User::staticGet('nickname', $this->arg('nickname')); - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - common_redirect(common_local_url('showstream', array('nickname' => $other->nickname))); - return; - } + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + common_redirect(common_local_url('showstream', array('nickname' => $other->nickname))); + return; + } - # CSRF protection + # CSRF protection - $token = $this->trimmed('token'); - - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } if (!$other->email || !$other->emailnotifynudge) { $this->client_error(_('This user doesn\'t allow nudges or hasn\'t confirmed or set his email yet.')); return; } - $this->notify($user, $other); + $this->notify($user, $other); - if ($this->boolean('ajax')) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Nudge sent')); - common_element_end('head'); - common_element_start('body'); - common_nudge_response(); - common_element_end('body'); - common_element_end('html'); - } else { + if ($this->boolean('ajax')) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Nudge sent')); + common_element_end('head'); + common_element_start('body'); + common_nudge_response(); + common_element_end('body'); + common_element_end('html'); + } else { // display a confirmation to the user - common_redirect(common_local_url('showstream', - array('nickname' => $other->nickname))); - } - } + common_redirect(common_local_url('showstream', + array('nickname' => $other->nickname))); + } + } - function notify($user, $other) { - if ($other->id != $user->id) { - if ($other->email && $other->emailnotifynudge) { - mail_notify_nudge($user, $other); - } - # XXX: notify by IM - # XXX: notify by SMS - } - } + function notify($user, $other) { + if ($other->id != $user->id) { + if ($other->email && $other->emailnotifynudge) { + mail_notify_nudge($user, $other); + } + # XXX: notify by IM + # XXX: notify by SMS + } + } } diff --git a/_darcs/pristine/actions/openidlogin.php b/_darcs/pristine/actions/openidlogin.php index 1b289dbea..6192dfc34 100644 --- a/_darcs/pristine/actions/openidlogin.php +++ b/_darcs/pristine/actions/openidlogin.php @@ -23,70 +23,70 @@ require_once(INSTALLDIR.'/lib/openid.php'); class OpenidloginAction extends Action { - function handle($args) { - parent::handle($args); - if (common_logged_in()) { - common_user_error(_('Already logged in.')); - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $openid_url = $this->trimmed('openid_url'); + function handle($args) { + parent::handle($args); + if (common_logged_in()) { + common_user_error(_('Already logged in.')); + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $openid_url = $this->trimmed('openid_url'); - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.'), $openid_url); - return; - } + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.'), $openid_url); + return; + } - $rememberme = $this->boolean('rememberme'); - - common_ensure_session(); - - $_SESSION['openid_rememberme'] = $rememberme; - - $result = oid_authenticate($openid_url, - 'finishopenidlogin'); - - if (is_string($result)) { # error message - unset($_SESSION['openid_rememberme']); - $this->show_form($result, $openid_url); - } - } else { - $openid_url = oid_get_last(); - $this->show_form(NULL, $openid_url); - } - } + $rememberme = $this->boolean('rememberme'); + + common_ensure_session(); + + $_SESSION['openid_rememberme'] = $rememberme; + + $result = oid_authenticate($openid_url, + 'finishopenidlogin'); + + if (is_string($result)) { # error message + unset($_SESSION['openid_rememberme']); + $this->show_form($result, $openid_url); + } + } else { + $openid_url = oid_get_last(); + $this->show_form(NULL, $openid_url); + } + } - function get_instructions() { - return _('Login with an [OpenID](%%doc.openid%%) account.'); - } + function get_instructions() { + return _('Login with an [OpenID](%%doc.openid%%) account.'); + } - function show_top($error=NULL) { - if ($error) { - common_element('div', array('class' => 'error'), $error); - } else { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - } - } + function show_top($error=NULL) { + if ($error) { + common_element('div', array('class' => 'error'), $error); + } else { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + } + } - function show_form($error=NULL, $openid_url) { - common_show_header(_('OpenID Login'), NULL, $error, array($this, 'show_top')); - $formaction = common_local_url('openidlogin'); - common_element_start('form', array('method' => 'post', - 'id' => 'openidlogin', - 'action' => $formaction)); - common_hidden('token', common_session_token()); - common_input('openid_url', _('OpenID URL'), - $openid_url, - _('Your OpenID URL')); - common_checkbox('rememberme', _('Remember me'), false, - _('Automatically login in the future; ' . - 'not for shared computers!')); - common_submit('submit', _('Login')); - common_element_end('form'); - common_show_footer(); - } + function show_form($error=NULL, $openid_url) { + common_show_header(_('OpenID Login'), NULL, $error, array($this, 'show_top')); + $formaction = common_local_url('openidlogin'); + common_element_start('form', array('method' => 'post', + 'id' => 'openidlogin', + 'action' => $formaction)); + common_hidden('token', common_session_token()); + common_input('openid_url', _('OpenID URL'), + $openid_url, + _('Your OpenID URL')); + common_checkbox('rememberme', _('Remember me'), false, + _('Automatically login in the future; ' . + 'not for shared computers!')); + common_submit('submit', _('Login')); + common_element_end('form'); + common_show_footer(); + } } diff --git a/_darcs/pristine/actions/openidsettings.php b/_darcs/pristine/actions/openidsettings.php index f539d111f..dd575bb73 100644 --- a/_darcs/pristine/actions/openidsettings.php +++ b/_darcs/pristine/actions/openidsettings.php @@ -24,133 +24,133 @@ require_once(INSTALLDIR.'/lib/openid.php'); class OpenidsettingsAction extends SettingsAction { - function get_instructions() { - return _('[OpenID](%%doc.openid%%) lets you log into many sites ' . - ' with the same user account. '. - ' Manage your associated OpenIDs from here.'); - } - - function show_form($msg=NULL, $success=false) { - - $user = common_current_user(); - - $this->form_header(_('OpenID settings'), $msg, $success); - - common_element_start('form', array('method' => 'post', - 'id' => 'openidadd', - 'action' => - common_local_url('openidsettings'))); - common_hidden('token', common_session_token()); - common_element('h2', NULL, _('Add OpenID')); - common_element('p', NULL, - _('If you want to add an OpenID to your account, ' . - 'enter it in the box below and click "Add".')); - common_element_start('p'); - common_element('label', array('for' => 'openid_url'), - _('OpenID URL')); - common_element('input', array('name' => 'openid_url', - 'type' => 'text', - 'id' => 'openid_url')); - common_element('input', array('type' => 'submit', - 'id' => 'add', - 'name' => 'add', - 'class' => 'submit', - 'value' => _('Add'))); - common_element_end('p'); - common_element_end('form'); - - $oid = new User_openid(); - $oid->user_id = $user->id; - - $cnt = $oid->find(); - - if ($cnt > 0) { - - common_element('h2', NULL, _('Remove OpenID')); - - if ($cnt == 1 && !$user->password) { - - common_element('p', NULL, - _('Removing your only OpenID would make it impossible to log in! ' . - 'If you need to remove it, add another OpenID first.')); - - if ($oid->fetch()) { - common_element_start('p'); - common_element('a', array('href' => $oid->canonical), - $oid->display); - common_element_end('p'); - } - - } else { - - common_element('p', NULL, - _('You can remove an OpenID from your account '. - 'by clicking the button marked "Remove".')); - $idx = 0; - - while ($oid->fetch()) { - common_element_start('form', array('method' => 'POST', - 'id' => 'openiddelete' . $idx, - 'action' => - common_local_url('openidsettings'))); - common_element_start('p'); - common_hidden('token', common_session_token()); - common_element('a', array('href' => $oid->canonical), - $oid->display); - common_element('input', array('type' => 'hidden', - 'id' => 'openid_url'.$idx, - 'name' => 'openid_url', - 'value' => $oid->canonical)); - common_element('input', array('type' => 'submit', - 'id' => 'remove'.$idx, - 'name' => 'remove', - 'class' => 'submit', - 'value' => _('Remove'))); - common_element_end('p'); - common_element_end('form'); - $idx++; - } - } - } - - common_show_footer(); - } - - function handle_post() { - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - if ($this->arg('add')) { - $result = oid_authenticate($this->trimmed('openid_url'), 'finishaddopenid'); - if (is_string($result)) { # error message - $this->show_form($result); - } - } else if ($this->arg('remove')) { - $this->remove_openid(); - } else { - $this->show_form(_('Something weird happened.')); - } - } - - function remove_openid() { - - $openid_url = $this->trimmed('openid_url'); - $oid = User_openid::staticGet('canonical', $openid_url); - if (!$oid) { - $this->show_form(_('No such OpenID.')); - return; - } - $cur = common_current_user(); - if (!$cur || $oid->user_id != $cur->id) { - $this->show_form(_('That OpenID does not belong to you.')); - return; - } - $oid->delete(); - $this->show_form(_('OpenID removed.'), true); - return; - } + function get_instructions() { + return _('[OpenID](%%doc.openid%%) lets you log into many sites ' . + ' with the same user account. '. + ' Manage your associated OpenIDs from here.'); + } + + function show_form($msg=NULL, $success=false) { + + $user = common_current_user(); + + $this->form_header(_('OpenID settings'), $msg, $success); + + common_element_start('form', array('method' => 'post', + 'id' => 'openidadd', + 'action' => + common_local_url('openidsettings'))); + common_hidden('token', common_session_token()); + common_element('h2', NULL, _('Add OpenID')); + common_element('p', NULL, + _('If you want to add an OpenID to your account, ' . + 'enter it in the box below and click "Add".')); + common_element_start('p'); + common_element('label', array('for' => 'openid_url'), + _('OpenID URL')); + common_element('input', array('name' => 'openid_url', + 'type' => 'text', + 'id' => 'openid_url')); + common_element('input', array('type' => 'submit', + 'id' => 'add', + 'name' => 'add', + 'class' => 'submit', + 'value' => _('Add'))); + common_element_end('p'); + common_element_end('form'); + + $oid = new User_openid(); + $oid->user_id = $user->id; + + $cnt = $oid->find(); + + if ($cnt > 0) { + + common_element('h2', NULL, _('Remove OpenID')); + + if ($cnt == 1 && !$user->password) { + + common_element('p', NULL, + _('Removing your only OpenID would make it impossible to log in! ' . + 'If you need to remove it, add another OpenID first.')); + + if ($oid->fetch()) { + common_element_start('p'); + common_element('a', array('href' => $oid->canonical), + $oid->display); + common_element_end('p'); + } + + } else { + + common_element('p', NULL, + _('You can remove an OpenID from your account '. + 'by clicking the button marked "Remove".')); + $idx = 0; + + while ($oid->fetch()) { + common_element_start('form', array('method' => 'POST', + 'id' => 'openiddelete' . $idx, + 'action' => + common_local_url('openidsettings'))); + common_element_start('p'); + common_hidden('token', common_session_token()); + common_element('a', array('href' => $oid->canonical), + $oid->display); + common_element('input', array('type' => 'hidden', + 'id' => 'openid_url'.$idx, + 'name' => 'openid_url', + 'value' => $oid->canonical)); + common_element('input', array('type' => 'submit', + 'id' => 'remove'.$idx, + 'name' => 'remove', + 'class' => 'submit', + 'value' => _('Remove'))); + common_element_end('p'); + common_element_end('form'); + $idx++; + } + } + } + + common_show_footer(); + } + + function handle_post() { + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + if ($this->arg('add')) { + $result = oid_authenticate($this->trimmed('openid_url'), 'finishaddopenid'); + if (is_string($result)) { # error message + $this->show_form($result); + } + } else if ($this->arg('remove')) { + $this->remove_openid(); + } else { + $this->show_form(_('Something weird happened.')); + } + } + + function remove_openid() { + + $openid_url = $this->trimmed('openid_url'); + $oid = User_openid::staticGet('canonical', $openid_url); + if (!$oid) { + $this->show_form(_('No such OpenID.')); + return; + } + $cur = common_current_user(); + if (!$cur || $oid->user_id != $cur->id) { + $this->show_form(_('That OpenID does not belong to you.')); + return; + } + $oid->delete(); + $this->show_form(_('OpenID removed.'), true); + return; + } } diff --git a/_darcs/pristine/actions/opensearch.php b/_darcs/pristine/actions/opensearch.php index 0f366be4c..707e929fb 100644 --- a/_darcs/pristine/actions/opensearch.php +++ b/_darcs/pristine/actions/opensearch.php @@ -21,39 +21,39 @@ if (!defined('LACONICA')) { exit(1); } class OpensearchAction extends Action { - function handle($args) { - - parent::handle($args); - - $type = $this->trimmed('type'); - - $short_name = ''; - if ($type == 'people') { - $type = 'peoplesearch'; - $short_name = _('People Search'); - } else { - $short_name = _('Notice Search'); - $type = 'noticesearch'; - } - - header('Content-Type: text/html'); - - common_start_xml(); - common_element_start('OpenSearchDescription', array('xmlns' => 'http://a9.com/-/spec/opensearch/1.1/')); - - $short_name = common_config('site', 'name').' '.$short_name; - common_element('ShortName', NULL, $short_name); - common_element('Contact', NULL, common_config('site', 'email')); - common_element('Url', array('type' => 'text/html', 'method' => 'get', - 'template' => str_replace('---', '{searchTerms}', common_local_url($type, array('q' => '---'))))); - common_element('Image', array('height' => 16, 'width' => 16, 'type' => 'image/vnd.microsoft.icon'), common_path('favicon.ico')); - common_element('Image', array('height' => 50, 'width' => 50, 'type' => 'image/png'), theme_path('logo.png')); - common_element('AdultContent', NULL, 'false'); - common_element('Language', NULL, common_language()); - common_element('OutputEncoding', NULL, 'UTF-8'); - common_element('InputEncoding', NULL, 'UTF-8'); - - common_element_end('OpenSearchDescription'); - common_end_xml(); - } + function handle($args) { + + parent::handle($args); + + $type = $this->trimmed('type'); + + $short_name = ''; + if ($type == 'people') { + $type = 'peoplesearch'; + $short_name = _('People Search'); + } else { + $short_name = _('Notice Search'); + $type = 'noticesearch'; + } + + header('Content-Type: text/html'); + + common_start_xml(); + common_element_start('OpenSearchDescription', array('xmlns' => 'http://a9.com/-/spec/opensearch/1.1/')); + + $short_name = common_config('site', 'name').' '.$short_name; + common_element('ShortName', NULL, $short_name); + common_element('Contact', NULL, common_config('site', 'email')); + common_element('Url', array('type' => 'text/html', 'method' => 'get', + 'template' => str_replace('---', '{searchTerms}', common_local_url($type, array('q' => '---'))))); + common_element('Image', array('height' => 16, 'width' => 16, 'type' => 'image/vnd.microsoft.icon'), common_path('favicon.ico')); + common_element('Image', array('height' => 50, 'width' => 50, 'type' => 'image/png'), theme_path('logo.png')); + common_element('AdultContent', NULL, 'false'); + common_element('Language', NULL, common_language()); + common_element('OutputEncoding', NULL, 'UTF-8'); + common_element('InputEncoding', NULL, 'UTF-8'); + + common_element_end('OpenSearchDescription'); + common_end_xml(); + } } diff --git a/_darcs/pristine/actions/othersettings.php b/_darcs/pristine/actions/othersettings.php index eccf90e91..9b824cea2 100644 --- a/_darcs/pristine/actions/othersettings.php +++ b/_darcs/pristine/actions/othersettings.php @@ -23,159 +23,159 @@ require_once(INSTALLDIR.'/lib/settingsaction.php'); class OthersettingsAction extends SettingsAction { - function get_instructions() { - return _('Manage various other options.'); - } + function get_instructions() { + return _('Manage various other options.'); + } - function show_form($msg=NULL, $success=false) { - $user = common_current_user(); + function show_form($msg=NULL, $success=false) { + $user = common_current_user(); - $this->form_header(_('Other Settings'), $msg, $success); + $this->form_header(_('Other Settings'), $msg, $success); - common_element('h2', NULL, _('URL Auto-shortening')); - common_element_start('form', array('method' => 'post', - 'id' => 'othersettings', - 'action' => - common_local_url('othersettings'))); - common_hidden('token', common_session_token()); + common_element('h2', NULL, _('URL Auto-shortening')); + common_element_start('form', array('method' => 'post', + 'id' => 'othersettings', + 'action' => + common_local_url('othersettings'))); + common_hidden('token', common_session_token()); - $services = array( - '' => 'None', + $services = array( + '' => 'None', 'ur1.ca' => 'ur1.ca (free service)', '2tu.us' => '2tu.us (free service)', 'ptiturl.com' => 'ptiturl.com', 'bit.ly' => 'bit.ly', - 'tinyurl.com' => 'tinyurl.com', - 'is.gd' => 'is.gd', - 'snipr.com' => 'snipr.com', - 'metamark.net' => 'metamark.net' - ); + 'tinyurl.com' => 'tinyurl.com', + 'is.gd' => 'is.gd', + 'snipr.com' => 'snipr.com', + 'metamark.net' => 'metamark.net' + ); - common_dropdown('urlshorteningservice', _('Service'), $services, _('Automatic shortening service to use.'), FALSE, $user->urlshorteningservice); + common_dropdown('urlshorteningservice', _('Service'), $services, _('Automatic shortening service to use.'), FALSE, $user->urlshorteningservice); - common_submit('save', _('Save')); + common_submit('save', _('Save')); - common_element_end('form'); + common_element_end('form'); -// common_element('h2', NULL, _('Delete my account')); -// $this->show_delete_form(); +// common_element('h2', NULL, _('Delete my account')); +// $this->show_delete_form(); - common_show_footer(); - } + common_show_footer(); + } - function show_feeds_list($feeds) { - common_element_start('div', array('class' => 'feedsdel')); - common_element('p', null, 'Feeds:'); - common_element_start('ul', array('class' => 'xoxo')); + function show_feeds_list($feeds) { + common_element_start('div', array('class' => 'feedsdel')); + common_element('p', null, 'Feeds:'); + common_element_start('ul', array('class' => 'xoxo')); - foreach ($feeds as $key => $value) { - $this->common_feed_item($feeds[$key]); - } - common_element_end('ul'); - common_element_end('div'); - } + foreach ($feeds as $key => $value) { + $this->common_feed_item($feeds[$key]); + } + common_element_end('ul'); + common_element_end('div'); + } //TODO move to common.php (and retrace its origin) - function common_feed_item($feed) { + function common_feed_item($feed) { $user = common_current_user(); - $nickname = $user->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 'foaf': - $feed_classname = "foaf"; - $feed_mimetype = "application/".$feed['type']."+xml"; - $feed_title = "$nickname's FOAF file"; - $feed['textContent'] = "FOAF"; - break; - } - common_element_start('li'); - common_element('a', array('href' => $feed['href'], - 'class' => $feed_classname, - 'type' => $feed_mimetype, - 'title' => $feed_title), - $feed['textContent']); - common_element_end('li'); - } - -// function show_delete_form() { -// $user = common_current_user(); + $nickname = $user->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 'foaf': + $feed_classname = "foaf"; + $feed_mimetype = "application/".$feed['type']."+xml"; + $feed_title = "$nickname's FOAF file"; + $feed['textContent'] = "FOAF"; + break; + } + common_element_start('li'); + common_element('a', array('href' => $feed['href'], + 'class' => $feed_classname, + 'type' => $feed_mimetype, + 'title' => $feed_title), + $feed['textContent']); + common_element_end('li'); + } + +// function show_delete_form() { +// $user = common_current_user(); // $notices = DB_DataObject::factory('notice'); // $notices->profile_id = $user->id; // $notice_count = (int) $notices->count(); // -// common_element_start('form', array('method' => 'POST', -// 'id' => 'delete', -// 'action' => -// common_local_url('deleteprofile'))); +// common_element_start('form', array('method' => 'POST', +// 'id' => 'delete', +// 'action' => +// common_local_url('deleteprofile'))); // -// common_hidden('token', common_session_token()); +// common_hidden('token', common_session_token()); // common_element('p', null, "You can copy your notices and contacts by saving the two links below before deleting your account. Be careful, this operation cannot be undone."); // -// $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)), -// 'type' => 'rss', -// 'version' => 'RSS 1.0', -// 'item' => 'notices'), -// 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), -// 'type' => 'rdf', -// 'version' => 'FOAF', -// 'item' => 'foaf'))); +// $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('limit' => $notice_count, 'nickname' => $user->nickname)), +// 'type' => 'rss', +// 'version' => 'RSS 1.0', +// 'item' => 'notices'), +// 1=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), +// 'type' => 'rdf', +// 'version' => 'FOAF', +// 'item' => 'foaf'))); // -// common_submit('deleteaccount', _('Delete my account')); -// common_element_end('form'); -// } +// common_submit('deleteaccount', _('Delete my account')); +// common_element_end('form'); +// } - function handle_post() { + function handle_post() { - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } - if ($this->arg('save')) { - $this->save_preferences(); - }else { - $this->show_form(_('Unexpected form submission.')); - } - } + if ($this->arg('save')) { + $this->save_preferences(); + }else { + $this->show_form(_('Unexpected form submission.')); + } + } - function save_preferences() { + function save_preferences() { - $urlshorteningservice = $this->trimmed('urlshorteningservice'); + $urlshorteningservice = $this->trimmed('urlshorteningservice'); - if (!is_null($urlshorteningservice) && strlen($urlshorteningservice) > 50) { - $this->show_form(_('URL shortening service is too long (max 50 chars).')); - return; - } + if (!is_null($urlshorteningservice) && strlen($urlshorteningservice) > 50) { + $this->show_form(_('URL shortening service is too long (max 50 chars).')); + return; + } - $user = common_current_user(); + $user = common_current_user(); - assert(!is_null($user)); # should already be checked + assert(!is_null($user)); # should already be checked - $user->query('BEGIN'); + $user->query('BEGIN'); - $original = clone($user); + $original = clone($user); - $user->urlshorteningservice = $urlshorteningservice; + $user->urlshorteningservice = $urlshorteningservice; - $result = $user->update($original); + $result = $user->update($original); - if ($result === FALSE) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } + if ($result === FALSE) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } - $user->query('COMMIT'); + $user->query('COMMIT'); - $this->show_form(_('Preferences saved.'), true); - } + $this->show_form(_('Preferences saved.'), true); + } } diff --git a/_darcs/pristine/actions/peoplesearch.php b/_darcs/pristine/actions/peoplesearch.php index 2e54233ec..f89de53f7 100644 --- a/_darcs/pristine/actions/peoplesearch.php +++ b/_darcs/pristine/actions/peoplesearch.php @@ -24,61 +24,61 @@ require_once(INSTALLDIR.'/lib/profilelist.php'); class PeoplesearchAction extends SearchAction { - function get_instructions() { - return _('Search for people on %%site.name%% by their name, location, or interests. ' . - 'Separate the terms by spaces; they must be 3 characters or more.'); - } + function get_instructions() { + return _('Search for people on %%site.name%% by their name, location, or interests. ' . + 'Separate the terms by spaces; they must be 3 characters or more.'); + } - function get_title() { - return _('People search'); - } + function get_title() { + return _('People search'); + } - function show_results($q, $page) { + function show_results($q, $page) { - $profile = new Profile(); + $profile = new Profile(); - # lcase it for comparison - $q = strtolower($q); + # lcase it for comparison + $q = strtolower($q); $search_engine = $profile->getSearchEngine('identica_people'); $search_engine->set_sort_mode('chron'); - # Ask for an extra to see if there's more. + # Ask for an extra to see if there's more. $search_engine->limit((($page-1)*PROFILES_PER_PAGE), PROFILES_PER_PAGE + 1); if (false === $search_engine->query($q)) { $cnt = 0; } else { - $cnt = $profile->find(); + $cnt = $profile->find(); + } + if ($cnt > 0) { + $terms = preg_split('/[\s,]+/', $q); + $results = new PeopleSearchResults($profile, $terms); + $results->show_list(); + } else { + common_element('p', 'error', _('No results')); } - if ($cnt > 0) { - $terms = preg_split('/[\s,]+/', $q); - $results = new PeopleSearchResults($profile, $terms); - $results->show_list(); - } else { - common_element('p', 'error', _('No results')); - } - $profile->free(); - - common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, - $page, 'peoplesearch', array('q' => $q)); - } + $profile->free(); + + common_pagination($page > 1, $cnt > PROFILES_PER_PAGE, + $page, 'peoplesearch', array('q' => $q)); + } } class PeopleSearchResults extends ProfileList { - var $terms = NULL; - var $pattern = NULL; - - function __construct($profile, $terms) { - parent::__construct($profile); - $this->terms = array_map('preg_quote', - array_map('htmlspecialchars', $terms)); - $this->pattern = '/('.implode('|',$terms).')/i'; - } - - function highlight($text) { - return preg_replace($this->pattern, '\\1', htmlspecialchars($text)); - } + var $terms = NULL; + var $pattern = NULL; + + function __construct($profile, $terms) { + parent::__construct($profile); + $this->terms = array_map('preg_quote', + array_map('htmlspecialchars', $terms)); + $this->pattern = '/('.implode('|',$terms).')/i'; + } + + function highlight($text) { + return preg_replace($this->pattern, '\\1', htmlspecialchars($text)); + } } diff --git a/_darcs/pristine/actions/peopletag.php b/_darcs/pristine/actions/peopletag.php index c508e0594..f03a3c8af 100644 --- a/_darcs/pristine/actions/peopletag.php +++ b/_darcs/pristine/actions/peopletag.php @@ -22,82 +22,82 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/profilelist.php'); class PeopletagAction extends Action { - - function handle($args) { + + function handle($args) { - parent::handle($args); + parent::handle($args); - $tag = $this->trimmed('tag'); - - if (!common_valid_profile_tag($tag)) { - $this->client_error(sprintf(_('Not a valid people tag: %s'), $tag)); - return; - } + $tag = $this->trimmed('tag'); + + if (!common_valid_profile_tag($tag)) { + $this->client_error(sprintf(_('Not a valid people tag: %s'), $tag)); + return; + } - $page = $this->trimmed('page'); - - if (!$page) { - $page = 1; - } - - # Looks like we're good; show the header + $page = $this->trimmed('page'); + + if (!$page) { + $page = 1; + } + + # Looks like we're good; show the header - common_show_header(sprintf(_('Users self-tagged with %s - page %d'), $tag, $page), - NULL, $tag, array($this, 'show_top')); + common_show_header(sprintf(_('Users self-tagged with %s - page %d'), $tag, $page), + NULL, $tag, array($this, 'show_top')); - $this->show_people($tag, $page); + $this->show_people($tag, $page); - common_show_footer(); - } + common_show_footer(); + } - function show_people($tag, $page) { - - $profile = new Profile(); + function show_people($tag, $page) { + + $profile = new Profile(); - $offset = ($page-1)*PROFILES_PER_PAGE; - $limit = PROFILES_PER_PAGE + 1; - - if (common_config('db','type') == 'pgsql') { - $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $lim = ' LIMIT ' . $offset . ', ' . $limit; - } + $offset = ($page-1)*PROFILES_PER_PAGE; + $limit = PROFILES_PER_PAGE + 1; + + if (common_config('db','type') == 'pgsql') { + $lim = ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $lim = ' LIMIT ' . $offset . ', ' . $limit; + } - # XXX: memcached this - - $profile->query(sprintf('SELECT profile.* ' . - 'FROM profile JOIN profile_tag ' . - 'ON profile.id = profile_tag.tagger ' . - 'WHERE profile_tag.tagger = profile_tag.tagged ' . - 'AND tag = "%s" ' . - 'ORDER BY profile_tag.modified DESC ' . - $lim, $tag)); + # XXX: memcached this + + $profile->query(sprintf('SELECT profile.* ' . + 'FROM profile JOIN profile_tag ' . + 'ON profile.id = profile_tag.tagger ' . + 'WHERE profile_tag.tagger = profile_tag.tagged ' . + 'AND tag = "%s" ' . + 'ORDER BY profile_tag.modified DESC ' . + $lim, $tag)); - $pl = new ProfileList($profile); - $cnt = $pl->show_list(); - - common_pagination($page > 1, - $cnt > PROFILES_PER_PAGE, - $page, - $this->trimmed('action'), - array('tag' => $tag)); - } - - function show_top($tag) { - $instr = sprintf(_('These are users who have tagged themselves "%s" ' . - 'to show a common interest, characteristic, hobby or job.'), $tag); - common_element_start('div', 'instructions'); - common_element_start('p'); - common_text($instr); - common_element_end('p'); - common_element_end('div'); - } + $pl = new ProfileList($profile); + $cnt = $pl->show_list(); + + common_pagination($page > 1, + $cnt > PROFILES_PER_PAGE, + $page, + $this->trimmed('action'), + array('tag' => $tag)); + } + + function show_top($tag) { + $instr = sprintf(_('These are users who have tagged themselves "%s" ' . + 'to show a common interest, characteristic, hobby or job.'), $tag); + common_element_start('div', 'instructions'); + common_element_start('p'); + common_text($instr); + common_element_end('p'); + common_element_end('div'); + } - function get_title() { - return NULL; - } + function get_title() { + return NULL; + } - function show_header($arr) { - return; - } + function show_header($arr) { + return; + } } diff --git a/_darcs/pristine/actions/postnotice.php b/_darcs/pristine/actions/postnotice.php index 243081f12..66e4dc806 100644 --- a/_darcs/pristine/actions/postnotice.php +++ b/_darcs/pristine/actions/postnotice.php @@ -22,67 +22,67 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/omb.php'); class PostnoticeAction extends Action { - function handle($args) { - parent::handle($args); - try { - common_remove_magic_from_request(); - $req = OAuthRequest::from_request(); - # Note: server-to-server function! - $server = omb_oauth_server(); - list($consumer, $token) = $server->verify_request($req); - if ($this->save_notice($req, $consumer, $token)) { - print "omb_version=".OMB_VERSION_01; - } - } catch (OAuthException $e) { - common_server_error($e->getMessage()); - return; - } - } + function handle($args) { + parent::handle($args); + try { + common_remove_magic_from_request(); + $req = OAuthRequest::from_request(); + # Note: server-to-server function! + $server = omb_oauth_server(); + list($consumer, $token) = $server->verify_request($req); + if ($this->save_notice($req, $consumer, $token)) { + print "omb_version=".OMB_VERSION_01; + } + } catch (OAuthException $e) { + common_server_error($e->getMessage()); + return; + } + } - function save_notice(&$req, &$consumer, &$token) { - $version = $req->get_parameter('omb_version'); - if ($version != OMB_VERSION_01) { - common_user_error(_('Unsupported OMB version'), 400); - return false; - } - # First, check to see - $listenee = $req->get_parameter('omb_listenee'); - $remote_profile = Remote_profile::staticGet('uri', $listenee); - if (!$remote_profile) { - common_user_error(_('Profile unknown'), 403); - return false; - } - $sub = Subscription::staticGet('token', $token->key); - if (!$sub) { - common_user_error(_('No such subscription'), 403); - return false; - } - $content = $req->get_parameter('omb_notice_content'); + function save_notice(&$req, &$consumer, &$token) { + $version = $req->get_parameter('omb_version'); + if ($version != OMB_VERSION_01) { + common_user_error(_('Unsupported OMB version'), 400); + return false; + } + # First, check to see + $listenee = $req->get_parameter('omb_listenee'); + $remote_profile = Remote_profile::staticGet('uri', $listenee); + if (!$remote_profile) { + common_user_error(_('Profile unknown'), 403); + return false; + } + $sub = Subscription::staticGet('token', $token->key); + if (!$sub) { + common_user_error(_('No such subscription'), 403); + return false; + } + $content = $req->get_parameter('omb_notice_content'); $content_shortened = common_shorten_links($content); if (mb_strlen($content_shortened) > 140) { common_user_error(_('Invalid notice content'), 400); return false; } - $notice_uri = $req->get_parameter('omb_notice'); - if (!Validate::uri($notice_uri) && - !common_valid_tag($notice_uri)) { - common_user_error(_('Invalid notice uri'), 400); - return false; - } - $notice_url = $req->get_parameter('omb_notice_url'); - if ($notice_url && !common_valid_http_url($notice_url)) { - common_user_error(_('Invalid notice url'), 400); - return false; - } - $notice = Notice::staticGet('uri', $notice_uri); - if (!$notice) { - $notice = Notice::saveNew($remote_profile->id, $content, 'omb', false, 0, $notice_uri); - if (is_string($notice)) { - common_server_serror($notice, 500); - return false; - } - common_broadcast_notice($notice, true); - } - return true; - } + $notice_uri = $req->get_parameter('omb_notice'); + if (!Validate::uri($notice_uri) && + !common_valid_tag($notice_uri)) { + common_user_error(_('Invalid notice uri'), 400); + return false; + } + $notice_url = $req->get_parameter('omb_notice_url'); + if ($notice_url && !common_valid_http_url($notice_url)) { + common_user_error(_('Invalid notice url'), 400); + return false; + } + $notice = Notice::staticGet('uri', $notice_uri); + if (!$notice) { + $notice = Notice::saveNew($remote_profile->id, $content, 'omb', false, 0, $notice_uri); + if (is_string($notice)) { + common_server_serror($notice, 500); + return false; + } + common_broadcast_notice($notice, true); + } + return true; + } } diff --git a/_darcs/pristine/actions/profilesettings.php b/_darcs/pristine/actions/profilesettings.php index ed2623c9b..3d92161ab 100644 --- a/_darcs/pristine/actions/profilesettings.php +++ b/_darcs/pristine/actions/profilesettings.php @@ -23,417 +23,417 @@ require_once(INSTALLDIR.'/lib/settingsaction.php'); class ProfilesettingsAction extends SettingsAction { - function get_instructions() { - return _('You can update your personal profile info here '. - 'so people know more about you.'); - } - - function show_form($msg=NULL, $success=false) { - $this->form_header(_('Profile settings'), $msg, $success); - $this->show_settings_form(); - common_element('h2', NULL, _('Avatar')); - $this->show_avatar_form(); - common_element('h2', NULL, _('Change password')); - $this->show_password_form(); -// common_element('h2', NULL, _('Delete my account')); -// $this->show_delete_form(); - common_show_footer(); - } - - function handle_post() { - - # CSRF protection - - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - if ($this->arg('save')) { - $this->save_profile(); - } else if ($this->arg('upload')) { - $this->upload_avatar(); - } else if ($this->arg('changepass')) { - $this->change_password(); - } - - } - - function show_settings_form() { - - $user = common_current_user(); - $profile = $user->getProfile(); - - common_element_start('form', array('method' => 'POST', - 'id' => 'profilesettings', - 'action' => - common_local_url('profilesettings'))); - common_hidden('token', common_session_token()); - - # too much common patterns here... abstractable? - - common_input('nickname', _('Nickname'), - ($this->arg('nickname')) ? $this->arg('nickname') : $profile->nickname, - _('1-64 lowercase letters or numbers, no punctuation or spaces')); - common_input('fullname', _('Full name'), - ($this->arg('fullname')) ? $this->arg('fullname') : $profile->fullname); - common_input('homepage', _('Homepage'), - ($this->arg('homepage')) ? $this->arg('homepage') : $profile->homepage, - _('URL of your homepage, blog, or profile on another site')); - common_textarea('bio', _('Bio'), - ($this->arg('bio')) ? $this->arg('bio') : $profile->bio, - _('Describe yourself and your interests in 140 chars')); - common_input('location', _('Location'), - ($this->arg('location')) ? $this->arg('location') : $profile->location, - _('Where you are, like "City, State (or Region), Country"')); - common_input('tags', _('Tags'), - ($this->arg('tags')) ? $this->arg('tags') : implode(' ', $user->getSelfTags()), - _('Tags for yourself (letters, numbers, -, ., and _), comma- or space- separated')); - - $language = common_language(); - common_dropdown('language', _('Language'), get_nice_language_list(), _('Preferred language'), TRUE, $language); - $timezone = common_timezone(); - $timezones = array(); - foreach(DateTimeZone::listIdentifiers() as $k => $v) { - $timezones[$v] = $v; - } - common_dropdown('timezone', _('Timezone'), $timezones, _('What timezone are you normally in?'), TRUE, $timezone); - - common_checkbox('autosubscribe', _('Automatically subscribe to whoever subscribes to me (best for non-humans)'), - ($this->arg('autosubscribe')) ? $this->boolean('autosubscribe') : $user->autosubscribe); - - common_submit('save', _('Save')); - - common_element_end('form'); - - - } - - function show_avatar_form() { - - $user = common_current_user(); - $profile = $user->getProfile(); - - if (!$profile) { - common_log_db_error($user, 'SELECT', __FILE__); - $this->server_error(_('User without matching profile')); - return; - } - - $original = $profile->getOriginalAvatar(); - - - common_element_start('form', array('enctype' => 'multipart/form-data', - 'method' => 'POST', - 'id' => 'avatar', - 'action' => - common_local_url('profilesettings'))); - common_hidden('token', common_session_token()); - - if ($original) { - common_element('img', array('src' => $original->url, - 'class' => 'avatar original', - 'width' => $original->width, - 'height' => $original->height, - 'alt' => $user->nickname)); - } - - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - - if ($avatar) { - common_element('img', array('src' => $avatar->url, - 'class' => 'avatar profile', - 'width' => AVATAR_PROFILE_SIZE, - 'height' => AVATAR_PROFILE_SIZE, - 'alt' => $user->nickname)); - } - - - common_element('input', array('name' => 'MAX_FILE_SIZE', - 'type' => 'hidden', - 'id' => 'MAX_FILE_SIZE', - 'value' => MAX_AVATAR_SIZE)); - - common_element_start('p'); - - - common_element('input', array('name' => 'avatarfile', - 'type' => 'file', - 'id' => 'avatarfile')); - common_element_end('p'); - - common_submit('upload', _('Upload')); - common_element_end('form'); - - } - - function show_password_form() { - - $user = common_current_user(); - common_element_start('form', array('method' => 'POST', - 'id' => 'password', - 'action' => - common_local_url('profilesettings'))); - - common_hidden('token', common_session_token()); - - # Users who logged in with OpenID won't have a pwd - if ($user->password) { - common_password('oldpassword', _('Old password')); - } - common_password('newpassword', _('New password'), - _('6 or more characters')); - common_password('confirm', _('Confirm'), - _('same as password above')); - common_submit('changepass', _('Change')); - common_element_end('form'); - } - - function save_profile() { - $nickname = $this->trimmed('nickname'); - $fullname = $this->trimmed('fullname'); - $homepage = $this->trimmed('homepage'); - $bio = $this->trimmed('bio'); - $location = $this->trimmed('location'); - $autosubscribe = $this->boolean('autosubscribe'); - $language = $this->trimmed('language'); - $timezone = $this->trimmed('timezone'); - $tagstring = $this->trimmed('tags'); - - # Some validation - - if (!Validate::string($nickname, array('min_length' => 1, - 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { - $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); - return; - } else if (!User::allowed_nickname($nickname)) { - $this->show_form(_('Not a valid nickname.')); - return; - } else if (!is_null($homepage) && (strlen($homepage) > 0) && - !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { - $this->show_form(_('Homepage is not a valid URL.')); - return; - } else if (!is_null($fullname) && strlen($fullname) > 255) { - $this->show_form(_('Full name is too long (max 255 chars).')); - return; - } else if (!is_null($bio) && strlen($bio) > 140) { - $this->show_form(_('Bio is too long (max 140 chars).')); - return; - } else if (!is_null($location) && strlen($location) > 255) { - $this->show_form(_('Location is too long (max 255 chars).')); - return; - } else if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) { - $this->show_form(_('Timezone not selected.')); - return; - } else if ($this->nickname_exists($nickname)) { - $this->show_form(_('Nickname already in use. Try another one.')); - return; + function get_instructions() { + return _('You can update your personal profile info here '. + 'so people know more about you.'); + } + + function show_form($msg=NULL, $success=false) { + $this->form_header(_('Profile settings'), $msg, $success); + $this->show_settings_form(); + common_element('h2', NULL, _('Avatar')); + $this->show_avatar_form(); + common_element('h2', NULL, _('Change password')); + $this->show_password_form(); +// common_element('h2', NULL, _('Delete my account')); +// $this->show_delete_form(); + common_show_footer(); + } + + function handle_post() { + + # CSRF protection + + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + if ($this->arg('save')) { + $this->save_profile(); + } else if ($this->arg('upload')) { + $this->upload_avatar(); + } else if ($this->arg('changepass')) { + $this->change_password(); + } + + } + + function show_settings_form() { + + $user = common_current_user(); + $profile = $user->getProfile(); + + common_element_start('form', array('method' => 'POST', + 'id' => 'profilesettings', + 'action' => + common_local_url('profilesettings'))); + common_hidden('token', common_session_token()); + + # too much common patterns here... abstractable? + + common_input('nickname', _('Nickname'), + ($this->arg('nickname')) ? $this->arg('nickname') : $profile->nickname, + _('1-64 lowercase letters or numbers, no punctuation or spaces')); + common_input('fullname', _('Full name'), + ($this->arg('fullname')) ? $this->arg('fullname') : $profile->fullname); + common_input('homepage', _('Homepage'), + ($this->arg('homepage')) ? $this->arg('homepage') : $profile->homepage, + _('URL of your homepage, blog, or profile on another site')); + common_textarea('bio', _('Bio'), + ($this->arg('bio')) ? $this->arg('bio') : $profile->bio, + _('Describe yourself and your interests in 140 chars')); + common_input('location', _('Location'), + ($this->arg('location')) ? $this->arg('location') : $profile->location, + _('Where you are, like "City, State (or Region), Country"')); + common_input('tags', _('Tags'), + ($this->arg('tags')) ? $this->arg('tags') : implode(' ', $user->getSelfTags()), + _('Tags for yourself (letters, numbers, -, ., and _), comma- or space- separated')); + + $language = common_language(); + common_dropdown('language', _('Language'), get_nice_language_list(), _('Preferred language'), TRUE, $language); + $timezone = common_timezone(); + $timezones = array(); + foreach(DateTimeZone::listIdentifiers() as $k => $v) { + $timezones[$v] = $v; + } + common_dropdown('timezone', _('Timezone'), $timezones, _('What timezone are you normally in?'), TRUE, $timezone); + + common_checkbox('autosubscribe', _('Automatically subscribe to whoever subscribes to me (best for non-humans)'), + ($this->arg('autosubscribe')) ? $this->boolean('autosubscribe') : $user->autosubscribe); + + common_submit('save', _('Save')); + + common_element_end('form'); + + + } + + function show_avatar_form() { + + $user = common_current_user(); + $profile = $user->getProfile(); + + if (!$profile) { + common_log_db_error($user, 'SELECT', __FILE__); + $this->server_error(_('User without matching profile')); + return; + } + + $original = $profile->getOriginalAvatar(); + + + common_element_start('form', array('enctype' => 'multipart/form-data', + 'method' => 'POST', + 'id' => 'avatar', + 'action' => + common_local_url('profilesettings'))); + common_hidden('token', common_session_token()); + + if ($original) { + common_element('img', array('src' => $original->url, + 'class' => 'avatar original', + 'width' => $original->width, + 'height' => $original->height, + 'alt' => $user->nickname)); + } + + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + + if ($avatar) { + common_element('img', array('src' => $avatar->url, + 'class' => 'avatar profile', + 'width' => AVATAR_PROFILE_SIZE, + 'height' => AVATAR_PROFILE_SIZE, + 'alt' => $user->nickname)); + } + + + common_element('input', array('name' => 'MAX_FILE_SIZE', + 'type' => 'hidden', + 'id' => 'MAX_FILE_SIZE', + 'value' => MAX_AVATAR_SIZE)); + + common_element_start('p'); + + + common_element('input', array('name' => 'avatarfile', + 'type' => 'file', + 'id' => 'avatarfile')); + common_element_end('p'); + + common_submit('upload', _('Upload')); + common_element_end('form'); + + } + + function show_password_form() { + + $user = common_current_user(); + common_element_start('form', array('method' => 'POST', + 'id' => 'password', + 'action' => + common_local_url('profilesettings'))); + + common_hidden('token', common_session_token()); + + # Users who logged in with OpenID won't have a pwd + if ($user->password) { + common_password('oldpassword', _('Old password')); + } + common_password('newpassword', _('New password'), + _('6 or more characters')); + common_password('confirm', _('Confirm'), + _('same as password above')); + common_submit('changepass', _('Change')); + common_element_end('form'); + } + + function save_profile() { + $nickname = $this->trimmed('nickname'); + $fullname = $this->trimmed('fullname'); + $homepage = $this->trimmed('homepage'); + $bio = $this->trimmed('bio'); + $location = $this->trimmed('location'); + $autosubscribe = $this->boolean('autosubscribe'); + $language = $this->trimmed('language'); + $timezone = $this->trimmed('timezone'); + $tagstring = $this->trimmed('tags'); + + # Some validation + + if (!Validate::string($nickname, array('min_length' => 1, + 'max_length' => 64, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); + return; + } else if (!User::allowed_nickname($nickname)) { + $this->show_form(_('Not a valid nickname.')); + return; + } else if (!is_null($homepage) && (strlen($homepage) > 0) && + !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { + $this->show_form(_('Homepage is not a valid URL.')); + return; + } else if (!is_null($fullname) && strlen($fullname) > 255) { + $this->show_form(_('Full name is too long (max 255 chars).')); + return; + } else if (!is_null($bio) && strlen($bio) > 140) { + $this->show_form(_('Bio is too long (max 140 chars).')); + return; + } else if (!is_null($location) && strlen($location) > 255) { + $this->show_form(_('Location is too long (max 255 chars).')); + return; + } else if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) { + $this->show_form(_('Timezone not selected.')); + return; + } else if ($this->nickname_exists($nickname)) { + $this->show_form(_('Nickname already in use. Try another one.')); + return; } else if (!is_null($language) && strlen($language) > 50) { - $this->show_form(_('Language is too long (max 50 chars).')); - return; - } - - if ($tagstring) { - $tags = array_map('common_canonical_tag', preg_split('/[\s,]+/', $tagstring)); - } else { - $tags = array(); - } - - foreach ($tags as $tag) { - if (!common_valid_profile_tag($tag)) { - $this->show_form(sprintf(_('Invalid tag: "%s"'), $tag)); - return; - } - } - - $user = common_current_user(); - - $user->query('BEGIN'); - - if ($user->nickname != $nickname || - $user->language != $language || - $user->timezone != $timezone) { - - common_debug('Updating user nickname from ' . $user->nickname . ' to ' . $nickname, - __FILE__); - common_debug('Updating user language from ' . $user->language . ' to ' . $language, - __FILE__); - common_debug('Updating user timezone from ' . $user->timezone . ' to ' . $timezone, - __FILE__); - - $original = clone($user); - - $user->nickname = $nickname; - $user->language = $language; - $user->timezone = $timezone; - - $result = $user->updateKeys($original); - - if ($result === FALSE) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } else { - # Re-initialize language environment if it changed - common_init_language(); - } - } - - # XXX: XOR - - if ($user->autosubscribe ^ $autosubscribe) { - - $original = clone($user); - - $user->autosubscribe = $autosubscribe; - - $result = $user->update($original); - - if ($result === FALSE) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user for autosubscribe.')); - return; - } - } - - $profile = $user->getProfile(); - - $orig_profile = clone($profile); - - $profile->nickname = $user->nickname; - $profile->fullname = $fullname; - $profile->homepage = $homepage; - $profile->bio = $bio; - $profile->location = $location; - $profile->profileurl = common_profile_url($nickname); - - common_debug('Old profile: ' . common_log_objstring($orig_profile), __FILE__); - common_debug('New profile: ' . common_log_objstring($profile), __FILE__); - - $result = $profile->update($orig_profile); - - if (!$result) { - common_log_db_error($profile, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t save profile.')); - return; - } - - # Set the user tags - - $result = $user->setSelfTags($tags); - - if (!$result) { - common_server_error(_('Couldn\'t save tags.')); - return; - } - - $user->query('COMMIT'); - - common_broadcast_profile($profile); - - $this->show_form(_('Settings saved.'), TRUE); - } - - - function upload_avatar() { - switch ($_FILES['avatarfile']['error']) { - case UPLOAD_ERR_OK: # success, jump out - break; - case UPLOAD_ERR_INI_SIZE: - case UPLOAD_ERR_FORM_SIZE: - $this->show_form(_('That file is too big.')); - return; - case UPLOAD_ERR_PARTIAL: - @unlink($_FILES['avatarfile']['tmp_name']); - $this->show_form(_('Partial upload.')); - return; - default: - $this->show_form(_('System error uploading file.')); - return; - } - - $info = @getimagesize($_FILES['avatarfile']['tmp_name']); - - if (!$info) { - @unlink($_FILES['avatarfile']['tmp_name']); - $this->show_form(_('Not an image or corrupt file.')); - return; - } - - switch ($info[2]) { - case IMAGETYPE_GIF: - case IMAGETYPE_JPEG: - case IMAGETYPE_PNG: - break; - default: - $this->show_form(_('Unsupported image file format.')); - return; - } - - $user = common_current_user(); - $profile = $user->getProfile(); - - if ($profile->setOriginal($_FILES['avatarfile']['tmp_name'])) { - $this->show_form(_('Avatar updated.'), true); - } else { - $this->show_form(_('Failed updating avatar.')); - } - - @unlink($_FILES['avatarfile']['tmp_name']); - } - - function nickname_exists($nickname) { - $user = common_current_user(); - $other = User::staticGet('nickname', $nickname); - if (!$other) { - return false; - } else { - return $other->id != $user->id; - } - } - - function change_password() { - - $user = common_current_user(); - assert(!is_null($user)); # should already be checked - - # FIXME: scrub input - - $newpassword = $this->arg('newpassword'); - $confirm = $this->arg('confirm'); - $token = $this->arg('token'); - - if (0 != strcmp($newpassword, $confirm)) { - $this->show_form(_('Passwords don\'t match.')); - return; - } - - if ($user->password) { - $oldpassword = $this->arg('oldpassword'); - - if (!common_check_user($user->nickname, $oldpassword)) { - $this->show_form(_('Incorrect old password')); - return; - } - } - - $original = clone($user); - - $user->password = common_munge_password($newpassword, $user->id); - - $val = $user->validate(); - if ($val !== TRUE) { - $this->show_form(_('Error saving user; invalid.')); - return; - } - - if (!$user->update($original)) { - common_server_error(_('Can\'t save new password.')); - return; - } - - $this->show_form(_('Password saved.'), true); - } + $this->show_form(_('Language is too long (max 50 chars).')); + return; + } + + if ($tagstring) { + $tags = array_map('common_canonical_tag', preg_split('/[\s,]+/', $tagstring)); + } else { + $tags = array(); + } + + foreach ($tags as $tag) { + if (!common_valid_profile_tag($tag)) { + $this->show_form(sprintf(_('Invalid tag: "%s"'), $tag)); + return; + } + } + + $user = common_current_user(); + + $user->query('BEGIN'); + + if ($user->nickname != $nickname || + $user->language != $language || + $user->timezone != $timezone) { + + common_debug('Updating user nickname from ' . $user->nickname . ' to ' . $nickname, + __FILE__); + common_debug('Updating user language from ' . $user->language . ' to ' . $language, + __FILE__); + common_debug('Updating user timezone from ' . $user->timezone . ' to ' . $timezone, + __FILE__); + + $original = clone($user); + + $user->nickname = $nickname; + $user->language = $language; + $user->timezone = $timezone; + + $result = $user->updateKeys($original); + + if ($result === FALSE) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } else { + # Re-initialize language environment if it changed + common_init_language(); + } + } + + # XXX: XOR + + if ($user->autosubscribe ^ $autosubscribe) { + + $original = clone($user); + + $user->autosubscribe = $autosubscribe; + + $result = $user->update($original); + + if ($result === FALSE) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user for autosubscribe.')); + return; + } + } + + $profile = $user->getProfile(); + + $orig_profile = clone($profile); + + $profile->nickname = $user->nickname; + $profile->fullname = $fullname; + $profile->homepage = $homepage; + $profile->bio = $bio; + $profile->location = $location; + $profile->profileurl = common_profile_url($nickname); + + common_debug('Old profile: ' . common_log_objstring($orig_profile), __FILE__); + common_debug('New profile: ' . common_log_objstring($profile), __FILE__); + + $result = $profile->update($orig_profile); + + if (!$result) { + common_log_db_error($profile, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t save profile.')); + return; + } + + # Set the user tags + + $result = $user->setSelfTags($tags); + + if (!$result) { + common_server_error(_('Couldn\'t save tags.')); + return; + } + + $user->query('COMMIT'); + + common_broadcast_profile($profile); + + $this->show_form(_('Settings saved.'), TRUE); + } + + + function upload_avatar() { + switch ($_FILES['avatarfile']['error']) { + case UPLOAD_ERR_OK: # success, jump out + break; + case UPLOAD_ERR_INI_SIZE: + case UPLOAD_ERR_FORM_SIZE: + $this->show_form(_('That file is too big.')); + return; + case UPLOAD_ERR_PARTIAL: + @unlink($_FILES['avatarfile']['tmp_name']); + $this->show_form(_('Partial upload.')); + return; + default: + $this->show_form(_('System error uploading file.')); + return; + } + + $info = @getimagesize($_FILES['avatarfile']['tmp_name']); + + if (!$info) { + @unlink($_FILES['avatarfile']['tmp_name']); + $this->show_form(_('Not an image or corrupt file.')); + return; + } + + switch ($info[2]) { + case IMAGETYPE_GIF: + case IMAGETYPE_JPEG: + case IMAGETYPE_PNG: + break; + default: + $this->show_form(_('Unsupported image file format.')); + return; + } + + $user = common_current_user(); + $profile = $user->getProfile(); + + if ($profile->setOriginal($_FILES['avatarfile']['tmp_name'])) { + $this->show_form(_('Avatar updated.'), true); + } else { + $this->show_form(_('Failed updating avatar.')); + } + + @unlink($_FILES['avatarfile']['tmp_name']); + } + + function nickname_exists($nickname) { + $user = common_current_user(); + $other = User::staticGet('nickname', $nickname); + if (!$other) { + return false; + } else { + return $other->id != $user->id; + } + } + + function change_password() { + + $user = common_current_user(); + assert(!is_null($user)); # should already be checked + + # FIXME: scrub input + + $newpassword = $this->arg('newpassword'); + $confirm = $this->arg('confirm'); + $token = $this->arg('token'); + + if (0 != strcmp($newpassword, $confirm)) { + $this->show_form(_('Passwords don\'t match.')); + return; + } + + if ($user->password) { + $oldpassword = $this->arg('oldpassword'); + + if (!common_check_user($user->nickname, $oldpassword)) { + $this->show_form(_('Incorrect old password')); + return; + } + } + + $original = clone($user); + + $user->password = common_munge_password($newpassword, $user->id); + + $val = $user->validate(); + if ($val !== TRUE) { + $this->show_form(_('Error saving user; invalid.')); + return; + } + + if (!$user->update($original)) { + common_server_error(_('Can\'t save new password.')); + return; + } + + $this->show_form(_('Password saved.'), true); + } } diff --git a/_darcs/pristine/actions/public.php b/_darcs/pristine/actions/public.php index 218f80194..422e4bc98 100644 --- a/_darcs/pristine/actions/public.php +++ b/_darcs/pristine/actions/public.php @@ -23,77 +23,77 @@ require_once(INSTALLDIR.'/lib/stream.php'); class PublicAction extends StreamAction { - function handle($args) { - parent::handle($args); - - $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - - header('X-XRDS-Location: '. common_local_url('publicxrds')); - - common_show_header(_('Public timeline'), - array($this, 'show_header'), NULL, - array($this, 'show_top')); - - # XXX: Public sidebar here? - - $this->show_notices($page); - - common_show_footer(); - } - - function show_top() { - if (common_logged_in()) { - common_notice_form('public'); - } else { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - } - - $this->public_views_menu(); - - $this->show_feeds_list(array(0=>array('href'=>common_local_url('publicrss'), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'publicrss'), - 1=>array('href'=>common_local_url('publicatom'), - 'type' => 'atom', - 'version' => 'Atom 1.0', - 'item' => 'publicatom'))); - } - - function get_instructions() { - return _('This is %%site.name%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' . - 'based on the Free Software [Laconica](http://laconi.ca/) tool. ' . - '[Join now](%%action.register%%) to share notices about yourself with friends, family, and colleagues! ([Read more](%%doc.help%%))'); - } - - function show_header() { - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('publicrss'), - 'type' => 'application/rss+xml', - 'title' => _('Public Stream Feed'))); - # for client side of OpenID authentication - common_element('meta', array('http-equiv' => 'X-XRDS-Location', - 'content' => common_local_url('publicxrds'))); - } - - function show_notices($page) { - - $cnt = 0; - $notice = Notice::publicStream(($page-1)*NOTICES_PER_PAGE, - NOTICES_PER_PAGE + 1); - - if (!$notice) { + function handle($args) { + parent::handle($args); + + $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + header('X-XRDS-Location: '. common_local_url('publicxrds')); + + common_show_header(_('Public timeline'), + array($this, 'show_header'), NULL, + array($this, 'show_top')); + + # XXX: Public sidebar here? + + $this->show_notices($page); + + common_show_footer(); + } + + function show_top() { + if (common_logged_in()) { + common_notice_form('public'); + } else { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + } + + $this->public_views_menu(); + + $this->show_feeds_list(array(0=>array('href'=>common_local_url('publicrss'), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'publicrss'), + 1=>array('href'=>common_local_url('publicatom'), + 'type' => 'atom', + 'version' => 'Atom 1.0', + 'item' => 'publicatom'))); + } + + function get_instructions() { + return _('This is %%site.name%%, a [micro-blogging](http://en.wikipedia.org/wiki/Micro-blogging) service ' . + 'based on the Free Software [Laconica](http://laconi.ca/) tool. ' . + '[Join now](%%action.register%%) to share notices about yourself with friends, family, and colleagues! ([Read more](%%doc.help%%))'); + } + + function show_header() { + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('publicrss'), + 'type' => 'application/rss+xml', + 'title' => _('Public Stream Feed'))); + # for client side of OpenID authentication + common_element('meta', array('http-equiv' => 'X-XRDS-Location', + 'content' => common_local_url('publicxrds'))); + } + + function show_notices($page) { + + $cnt = 0; + $notice = Notice::publicStream(($page-1)*NOTICES_PER_PAGE, + NOTICES_PER_PAGE + 1); + + if (!$notice) { $this->server_error(_('Could not retrieve public stream.')); return; - } + } $cnt = $this->show_notice_list($notice); - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'public'); - } + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'public'); + } } diff --git a/_darcs/pristine/actions/publicrss.php b/_darcs/pristine/actions/publicrss.php index 1ab6a8be0..fa86de1d9 100644 --- a/_darcs/pristine/actions/publicrss.php +++ b/_darcs/pristine/actions/publicrss.php @@ -25,33 +25,33 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class PublicrssAction extends Rss10Action { - function init() { - return true; - } - - function get_notices($limit=0) { - - $notices = array(); - - $notice = Notice::publicStream(0, ($limit == 0) ? 48 : $limit); - - while ($notice->fetch()) { - $notices[] = clone($notice); - } - - return $notices; - } - - function get_channel() { - global $config; - $c = array('url' => common_local_url('publicrss'), - 'title' => sprintf(_('%s Public Stream'), $config['site']['name']), - 'link' => common_local_url('public'), - 'description' => sprintf(_('All updates for %s'), $config['site']['name'])); - return $c; - } - - function get_image() { - return NULL; - } + function init() { + return true; + } + + function get_notices($limit=0) { + + $notices = array(); + + $notice = Notice::publicStream(0, ($limit == 0) ? 48 : $limit); + + while ($notice->fetch()) { + $notices[] = clone($notice); + } + + return $notices; + } + + function get_channel() { + global $config; + $c = array('url' => common_local_url('publicrss'), + 'title' => sprintf(_('%s Public Stream'), $config['site']['name']), + 'link' => common_local_url('public'), + 'description' => sprintf(_('All updates for %s'), $config['site']['name'])); + return $c; + } + + function get_image() { + return NULL; + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/publicxrds.php b/_darcs/pristine/actions/publicxrds.php index 951434c87..ffd65c8c9 100644 --- a/_darcs/pristine/actions/publicxrds.php +++ b/_darcs/pristine/actions/publicxrds.php @@ -25,55 +25,55 @@ require_once(INSTALLDIR.'/lib/openid.php'); class PublicxrdsAction extends Action { - function is_readonly() { - return true; - } + function is_readonly() { + return true; + } - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - header('Content-Type: application/xrds+xml'); + header('Content-Type: application/xrds+xml'); - common_start_xml(); - common_element_start('XRDS', array('xmlns' => 'xri://$xrds')); + common_start_xml(); + common_element_start('XRDS', array('xmlns' => 'xri://$xrds')); - common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', - 'xmlns:simple' => 'http://xrds-simple.net/core/1.0', - 'version' => '2.0')); + common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', + 'xmlns:simple' => 'http://xrds-simple.net/core/1.0', + 'version' => '2.0')); - common_element('Type', NULL, 'xri://$xrds*simple'); + common_element('Type', NULL, 'xri://$xrds*simple'); - foreach (array('finishopenidlogin', 'finishaddopenid', 'finishimmediate') as $finish) { - $this->show_service(Auth_OpenID_RP_RETURN_TO_URL_TYPE, - common_local_url($finish)); - } + foreach (array('finishopenidlogin', 'finishaddopenid', 'finishimmediate') as $finish) { + $this->show_service(Auth_OpenID_RP_RETURN_TO_URL_TYPE, + common_local_url($finish)); + } - common_element_end('XRD'); + common_element_end('XRD'); - common_element_end('XRDS'); - common_end_xml(); - } + common_element_end('XRDS'); + common_end_xml(); + } - function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) { - common_element_start('Service'); - if ($uri) { - common_element('URI', NULL, $uri); - } - common_element('Type', NULL, $type); - if ($params) { - foreach ($params as $param) { - common_element('Type', NULL, $param); - } - } - if ($sigs) { - foreach ($sigs as $sig) { - common_element('Type', NULL, $sig); - } - } - if ($localId) { - common_element('LocalID', NULL, $localId); - } - common_element_end('Service'); - } + function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) { + common_element_start('Service'); + if ($uri) { + common_element('URI', NULL, $uri); + } + common_element('Type', NULL, $type); + if ($params) { + foreach ($params as $param) { + common_element('Type', NULL, $param); + } + } + if ($sigs) { + foreach ($sigs as $sig) { + common_element('Type', NULL, $sig); + } + } + if ($localId) { + common_element('LocalID', NULL, $localId); + } + common_element_end('Service'); + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/recoverpassword.php b/_darcs/pristine/actions/recoverpassword.php index 38c42f41d..1263fee9b 100644 --- a/_darcs/pristine/actions/recoverpassword.php +++ b/_darcs/pristine/actions/recoverpassword.php @@ -28,304 +28,304 @@ class RecoverpasswordAction extends Action { function handle($args) { parent::handle($args); if (common_logged_in()) { - $this->client_error(_('You are already logged in!')); + $this->client_error(_('You are already logged in!')); return; } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - if ($this->arg('recover')) { - $this->recover_password(); + if ($this->arg('recover')) { + $this->recover_password(); } else if ($this->arg('reset')) { - $this->reset_password(); - } else { - $this->client_error(_('Unexpected form submission.')); - } - } else { - if ($this->trimmed('code')) { - $this->check_code(); - } else { - $this->show_form(); - } - } - } - - function check_code() { - - $code = $this->trimmed('code'); - $confirm = Confirm_address::staticGet('code', $code); - - if (!$confirm) { - $this->client_error(_('No such recovery code.')); - return; - } - if ($confirm->address_type != 'recover') { - $this->client_error(_('Not a recovery code.')); - return; - } - - $user = User::staticGet($confirm->user_id); - - if (!$user) { - $this->server_error(_('Recovery code for unknown user.')); - return; - } - - $touched = strtotime($confirm->modified); - $email = $confirm->address; - - # Burn this code - - $result = $confirm->delete(); - - if (!$result) { - common_log_db_error($confirm, 'DELETE', __FILE__); - common_server_error(_('Error with confirmation code.')); - return; - } - - # These should be reaped, but for now we just check mod time - # Note: it's still deleted; let's avoid a second attempt! - - if ((time() - $touched) > MAX_RECOVERY_TIME) { - common_log(LOG_WARNING, - 'Attempted redemption on recovery code ' . - 'that is ' . $touched . ' seconds old. '); - $this->client_error(_('This confirmation code is too old. ' . - 'Please start again.')); - return; - } - - # If we used an outstanding confirmation to send the email, - # it's been confirmed at this point. - - if (!$user->email) { - $orig = clone($user); - $user->email = $email; - $result = $user->updateKeys($orig); - if (!$result) { - common_log_db_error($user, 'UPDATE', __FILE__); - $this->server_error(_('Could not update user with confirmed email address.')); - return; - } - } - - # Success! - - $this->set_temp_user($user); - $this->show_password_form(); - } - - function set_temp_user(&$user) { - common_ensure_session(); - $_SESSION['tempuser'] = $user->id; - } - - function get_temp_user() { - common_ensure_session(); - $user_id = $_SESSION['tempuser']; - if ($user_id) { - $user = User::staticGet($user_id); - } - return $user; - } - - function clear_temp_user() { - common_ensure_session(); - unset($_SESSION['tempuser']); - } - - function show_top($msg=NULL) { - if ($msg) { + $this->reset_password(); + } else { + $this->client_error(_('Unexpected form submission.')); + } + } else { + if ($this->trimmed('code')) { + $this->check_code(); + } else { + $this->show_form(); + } + } + } + + function check_code() { + + $code = $this->trimmed('code'); + $confirm = Confirm_address::staticGet('code', $code); + + if (!$confirm) { + $this->client_error(_('No such recovery code.')); + return; + } + if ($confirm->address_type != 'recover') { + $this->client_error(_('Not a recovery code.')); + return; + } + + $user = User::staticGet($confirm->user_id); + + if (!$user) { + $this->server_error(_('Recovery code for unknown user.')); + return; + } + + $touched = strtotime($confirm->modified); + $email = $confirm->address; + + # Burn this code + + $result = $confirm->delete(); + + if (!$result) { + common_log_db_error($confirm, 'DELETE', __FILE__); + common_server_error(_('Error with confirmation code.')); + return; + } + + # These should be reaped, but for now we just check mod time + # Note: it's still deleted; let's avoid a second attempt! + + if ((time() - $touched) > MAX_RECOVERY_TIME) { + common_log(LOG_WARNING, + 'Attempted redemption on recovery code ' . + 'that is ' . $touched . ' seconds old. '); + $this->client_error(_('This confirmation code is too old. ' . + 'Please start again.')); + return; + } + + # If we used an outstanding confirmation to send the email, + # it's been confirmed at this point. + + if (!$user->email) { + $orig = clone($user); + $user->email = $email; + $result = $user->updateKeys($orig); + if (!$result) { + common_log_db_error($user, 'UPDATE', __FILE__); + $this->server_error(_('Could not update user with confirmed email address.')); + return; + } + } + + # Success! + + $this->set_temp_user($user); + $this->show_password_form(); + } + + function set_temp_user(&$user) { + common_ensure_session(); + $_SESSION['tempuser'] = $user->id; + } + + function get_temp_user() { + common_ensure_session(); + $user_id = $_SESSION['tempuser']; + if ($user_id) { + $user = User::staticGet($user_id); + } + return $user; + } + + function clear_temp_user() { + common_ensure_session(); + unset($_SESSION['tempuser']); + } + + function show_top($msg=NULL) { + if ($msg) { common_element('div', 'error', $msg); - } else { - common_element_start('div', 'instructions'); - common_element('p', NULL, - _('If you\'ve forgotten or lost your' . - ' password, you can get a new one sent to' . - ' the email address you have stored ' . - ' in your account.')); - common_element_end('div'); - } - } - - function show_password_top($msg=NULL) { - if ($msg) { + } else { + common_element_start('div', 'instructions'); + common_element('p', NULL, + _('If you\'ve forgotten or lost your' . + ' password, you can get a new one sent to' . + ' the email address you have stored ' . + ' in your account.')); + common_element_end('div'); + } + } + + function show_password_top($msg=NULL) { + if ($msg) { common_element('div', 'error', $msg); - } else { - common_element('div', 'instructions', - _('You\'ve been identified. Enter a ' . - ' new password below. ')); - } - } - - function show_form($msg=NULL) { - - common_show_header(_('Recover password'), NULL, - $msg, array($this, 'show_top')); - - common_element_start('form', array('method' => 'post', - 'id' => 'recoverpassword', - 'action' => common_local_url('recoverpassword'))); - common_input('nicknameoremail', _('Nickname or email'), - $this->trimmed('nicknameoremail'), - _('Your nickname on this server, ' . - 'or your registered email address.')); - common_submit('recover', _('Recover')); - common_element_end('form'); - common_show_footer(); - } - - function show_password_form($msg=NULL) { - - common_show_header(_('Reset password'), NULL, - $msg, array($this, 'show_password_top')); - - common_element_start('form', array('method' => 'post', - 'id' => 'recoverpassword', - 'action' => common_local_url('recoverpassword'))); - common_hidden('token', common_session_token()); - common_password('newpassword', _('New password'), - _('6 or more characters, and don\'t forget it!')); - common_password('confirm', _('Confirm'), - _('Same as password above')); - common_submit('reset', _('Reset')); - common_element_end('form'); - common_show_footer(); - } - - function recover_password() { - $nore = $this->trimmed('nicknameoremail'); - if (!$nore) { - $this->show_form(_('Enter a nickname or email address.')); - return; - } - - $user = User::staticGet('email', common_canonical_email($nore)); - - if (!$user) { - $user = User::staticGet('nickname', common_canonical_nickname($nore)); - } - - # See if it's an unconfirmed email address - - if (!$user) { - $confirm_email = Confirm_address::staticGet('address', common_canonical_email($nore)); - if ($confirm_email && $confirm_email->address_type == 'email') { - $user = User::staticGet($confirm_email->user_id); - } - } - - if (!$user) { - $this->show_form(_('No user with that email address or username.')); - return; - } - - # Try to get an unconfirmed email address if they used a user name - - if (!$user->email && !$confirm_email) { - $confirm_email = Confirm_address::staticGet('user_id', $user->id); - if ($confirm_email && $confirm_email->address_type != 'email') { - # Skip non-email confirmations - $confirm_email = NULL; - } - } - - if (!$user->email && !$confirm_email) { - $this->client_error(_('No registered email address for that user.')); - return; - } - - # Success! We have a valid user and a confirmed or unconfirmed email address - - $confirm = new Confirm_address(); - $confirm->code = common_confirmation_code(128); - $confirm->address_type = 'recover'; - $confirm->user_id = $user->id; - $confirm->address = (isset($user->email)) ? $user->email : $confirm_email->address; - - if (!$confirm->insert()) { - common_log_db_error($confirm, 'INSERT', __FILE__); - $this->server_error(_('Error saving address confirmation.')); - return; - } - - $body = "Hey, $user->nickname."; - $body .= "\n\n"; - $body .= 'Someone just asked for a new password ' . - 'for this account on ' . common_config('site', 'name') . '.'; - $body .= "\n\n"; - $body .= 'If it was you, and you want to confirm, use the URL below:'; - $body .= "\n\n"; - $body .= "\t".common_local_url('recoverpassword', - array('code' => $confirm->code)); - $body .= "\n\n"; - $body .= 'If not, just ignore this message.'; - $body .= "\n\n"; - $body .= 'Thanks for your time, '; - $body .= "\n"; - $body .= common_config('site', 'name'); - $body .= "\n"; - - mail_to_user($user, _('Password recovery requested'), $body, $confirm->address); - - common_show_header(_('Password recovery requested')); - common_element('p', NULL, - _('Instructions for recovering your password ' . - 'have been sent to the email address registered to your ' . - 'account.')); - common_show_footer(); - } - - function reset_password() { - - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - $user = $this->get_temp_user(); - - if (!$user) { - $this->client_error(_('Unexpected password reset.')); - return; - } - - $newpassword = $this->trimmed('newpassword'); - $confirm = $this->trimmed('confirm'); - - if (!$newpassword || strlen($newpassword) < 6) { - $this->show_password_form(_('Password must be 6 chars or more.')); - return; - } - if ($newpassword != $confirm) { - $this->show_password_form(_('Password and confirmation do not match.')); - return; - } - - # OK, we're ready to go - - $original = clone($user); - - $user->password = common_munge_password($newpassword, $user->id); - - if (!$user->update($original)) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Can\'t save new password.')); - return; - } - - $this->clear_temp_user(); - - if (!common_set_user($user->nickname)) { - common_server_error(_('Error setting user.')); - return; - } - - common_real_login(true); - - common_show_header(_('Password saved.')); - common_element('p', NULL, _('New password successfully saved. ' . - 'You are now logged in.')); - common_show_footer(); - } + } else { + common_element('div', 'instructions', + _('You\'ve been identified. Enter a ' . + ' new password below. ')); + } + } + + function show_form($msg=NULL) { + + common_show_header(_('Recover password'), NULL, + $msg, array($this, 'show_top')); + + common_element_start('form', array('method' => 'post', + 'id' => 'recoverpassword', + 'action' => common_local_url('recoverpassword'))); + common_input('nicknameoremail', _('Nickname or email'), + $this->trimmed('nicknameoremail'), + _('Your nickname on this server, ' . + 'or your registered email address.')); + common_submit('recover', _('Recover')); + common_element_end('form'); + common_show_footer(); + } + + function show_password_form($msg=NULL) { + + common_show_header(_('Reset password'), NULL, + $msg, array($this, 'show_password_top')); + + common_element_start('form', array('method' => 'post', + 'id' => 'recoverpassword', + 'action' => common_local_url('recoverpassword'))); + common_hidden('token', common_session_token()); + common_password('newpassword', _('New password'), + _('6 or more characters, and don\'t forget it!')); + common_password('confirm', _('Confirm'), + _('Same as password above')); + common_submit('reset', _('Reset')); + common_element_end('form'); + common_show_footer(); + } + + function recover_password() { + $nore = $this->trimmed('nicknameoremail'); + if (!$nore) { + $this->show_form(_('Enter a nickname or email address.')); + return; + } + + $user = User::staticGet('email', common_canonical_email($nore)); + + if (!$user) { + $user = User::staticGet('nickname', common_canonical_nickname($nore)); + } + + # See if it's an unconfirmed email address + + if (!$user) { + $confirm_email = Confirm_address::staticGet('address', common_canonical_email($nore)); + if ($confirm_email && $confirm_email->address_type == 'email') { + $user = User::staticGet($confirm_email->user_id); + } + } + + if (!$user) { + $this->show_form(_('No user with that email address or username.')); + return; + } + + # Try to get an unconfirmed email address if they used a user name + + if (!$user->email && !$confirm_email) { + $confirm_email = Confirm_address::staticGet('user_id', $user->id); + if ($confirm_email && $confirm_email->address_type != 'email') { + # Skip non-email confirmations + $confirm_email = NULL; + } + } + + if (!$user->email && !$confirm_email) { + $this->client_error(_('No registered email address for that user.')); + return; + } + + # Success! We have a valid user and a confirmed or unconfirmed email address + + $confirm = new Confirm_address(); + $confirm->code = common_confirmation_code(128); + $confirm->address_type = 'recover'; + $confirm->user_id = $user->id; + $confirm->address = (isset($user->email)) ? $user->email : $confirm_email->address; + + if (!$confirm->insert()) { + common_log_db_error($confirm, 'INSERT', __FILE__); + $this->server_error(_('Error saving address confirmation.')); + return; + } + + $body = "Hey, $user->nickname."; + $body .= "\n\n"; + $body .= 'Someone just asked for a new password ' . + 'for this account on ' . common_config('site', 'name') . '.'; + $body .= "\n\n"; + $body .= 'If it was you, and you want to confirm, use the URL below:'; + $body .= "\n\n"; + $body .= "\t".common_local_url('recoverpassword', + array('code' => $confirm->code)); + $body .= "\n\n"; + $body .= 'If not, just ignore this message.'; + $body .= "\n\n"; + $body .= 'Thanks for your time, '; + $body .= "\n"; + $body .= common_config('site', 'name'); + $body .= "\n"; + + mail_to_user($user, _('Password recovery requested'), $body, $confirm->address); + + common_show_header(_('Password recovery requested')); + common_element('p', NULL, + _('Instructions for recovering your password ' . + 'have been sent to the email address registered to your ' . + 'account.')); + common_show_footer(); + } + + function reset_password() { + + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + $user = $this->get_temp_user(); + + if (!$user) { + $this->client_error(_('Unexpected password reset.')); + return; + } + + $newpassword = $this->trimmed('newpassword'); + $confirm = $this->trimmed('confirm'); + + if (!$newpassword || strlen($newpassword) < 6) { + $this->show_password_form(_('Password must be 6 chars or more.')); + return; + } + if ($newpassword != $confirm) { + $this->show_password_form(_('Password and confirmation do not match.')); + return; + } + + # OK, we're ready to go + + $original = clone($user); + + $user->password = common_munge_password($newpassword, $user->id); + + if (!$user->update($original)) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Can\'t save new password.')); + return; + } + + $this->clear_temp_user(); + + if (!common_set_user($user->nickname)) { + common_server_error(_('Error setting user.')); + return; + } + + common_real_login(true); + + common_show_header(_('Password saved.')); + common_element('p', NULL, _('New password successfully saved. ' . + 'You are now logged in.')); + common_show_footer(); + } } diff --git a/_darcs/pristine/actions/register.php b/_darcs/pristine/actions/register.php index a22ffca28..011aa3f09 100644 --- a/_darcs/pristine/actions/register.php +++ b/_darcs/pristine/actions/register.php @@ -21,242 +21,242 @@ if (!defined('LACONICA')) { exit(1); } class RegisterAction extends Action { - function handle($args) { - parent::handle($args); - - if (common_config('site', 'closed')) { - common_user_error(_('Registration not allowed.')); - } else if (common_logged_in()) { - common_user_error(_('Already logged in.')); - } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->try_register(); - } else { - $this->show_form(); - } - } - - function try_register() { - - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - $nickname = $this->trimmed('nickname'); - $email = $this->trimmed('email'); - $fullname = $this->trimmed('fullname'); - $homepage = $this->trimmed('homepage'); - $bio = $this->trimmed('bio'); - $location = $this->trimmed('location'); - - # We don't trim these... whitespace is OK in a password! - - $password = $this->arg('password'); - $confirm = $this->arg('confirm'); - - # invitation code, if any - - $code = $this->trimmed('code'); - - if ($code) { - $invite = Invitation::staticGet($code); - } - - if (common_config('site', 'inviteonly') && !($code && $invite)) { - $this->client_error(_('Sorry, only invited people can register.')); - return; - } - - # Input scrubbing - - $nickname = common_canonical_nickname($nickname); - $email = common_canonical_email($email); - - if (!$this->boolean('license')) { - $this->show_form(_('You can\'t register if you don\'t agree to the license.')); - } else if ($email && !Validate::email($email, true)) { - $this->show_form(_('Not a valid email address.')); - } else if (!Validate::string($nickname, array('min_length' => 1, - 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { - $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); - } else if ($this->nickname_exists($nickname)) { - $this->show_form(_('Nickname already in use. Try another one.')); - } else if (!User::allowed_nickname($nickname)) { - $this->show_form(_('Not a valid nickname.')); - } else if ($this->email_exists($email)) { - $this->show_form(_('Email address already exists.')); - } else if (!is_null($homepage) && (strlen($homepage) > 0) && - !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { - $this->show_form(_('Homepage is not a valid URL.')); - return; - } else if (!is_null($fullname) && strlen($fullname) > 255) { - $this->show_form(_('Full name is too long (max 255 chars).')); - return; - } else if (!is_null($bio) && strlen($bio) > 140) { - $this->show_form(_('Bio is too long (max 140 chars).')); - return; - } else if (!is_null($location) && strlen($location) > 255) { - $this->show_form(_('Location is too long (max 255 chars).')); - return; - } else if (strlen($password) < 6) { - $this->show_form(_('Password must be 6 or more characters.')); - return; - } else if ($password != $confirm) { - $this->show_form(_('Passwords don\'t match.')); - } else if ($user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, - 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, - 'location' => $location, 'code' => $code))) { - if (!$user) { - $this->show_form(_('Invalid username or password.')); - return; - } - # success! - if (!common_set_user($user)) { - common_server_error(_('Error setting user.')); - return; - } - # this is a real login - common_real_login(true); - if ($this->boolean('rememberme')) { - common_debug('Adding rememberme cookie for ' . $nickname); - common_rememberme($user); - } - # Re-init language env in case it changed (not yet, but soon) - common_init_language(); - $this->show_success(); - } else { - $this->show_form(_('Invalid username or password.')); - } - } - - # checks if *CANONICAL* nickname exists - - function nickname_exists($nickname) { - $user = User::staticGet('nickname', $nickname); - return ($user !== false); - } - - # checks if *CANONICAL* email exists - - function email_exists($email) { - $email = common_canonical_email($email); - if (!$email || strlen($email) == 0) { - return false; - } - $user = User::staticGet('email', $email); - return ($user !== false); - } - - function show_top($error=NULL) { - if ($error) { - common_element('p', 'error', $error); - } else { - $instr = common_markup_to_html(_('With this form you can create a new account. ' . - 'You can then post notices and link up to friends and colleagues. '. - '(Have an [OpenID](http://openid.net/)? ' . - 'Try our [OpenID registration](%%action.openidlogin%%)!)')); - - common_element_start('div', 'instructions'); - common_raw($instr); - common_element_end('div'); - } - } - - function show_form($error=NULL) { - global $config; - - $code = $this->trimmed('code'); - - if ($code) { - $invite = Invitation::staticGet($code); - } - - if (common_config('site', 'inviteonly') && !($code && $invite)) { - $this->client_error(_('Sorry, only invited people can register.')); - return; - } - - common_show_header(_('Register'), NULL, $error, array($this, 'show_top')); - common_element_start('form', array('method' => 'post', - 'id' => 'login', - 'action' => common_local_url('register'))); - - common_hidden('token', common_session_token()); - - if ($code) { - common_hidden('code', $code); - } - - common_input('nickname', _('Nickname'), $this->trimmed('nickname'), - _('1-64 lowercase letters or numbers, no punctuation or spaces. Required.')); - common_password('password', _('Password'), - _('6 or more characters. Required.')); - common_password('confirm', _('Confirm'), - _('Same as password above. Required.')); - if ($invite && $invite->address_type == 'email') { - common_input('email', _('Email'), $invite->address, - _('Used only for updates, announcements, and password recovery')); - } else { - common_input('email', _('Email'), $this->trimmed('email'), - _('Used only for updates, announcements, and password recovery')); - } - common_input('fullname', _('Full name'), - $this->trimmed('fullname'), - _('Longer name, preferably your "real" name')); - common_input('homepage', _('Homepage'), - $this->trimmed('homepage'), - _('URL of your homepage, blog, or profile on another site')); - common_textarea('bio', _('Bio'), - $this->trimmed('bio'), - _('Describe yourself and your interests in 140 chars')); - common_input('location', _('Location'), - $this->trimmed('location'), - _('Where you are, like "City, State (or Region), Country"')); - common_checkbox('rememberme', _('Remember me'), - $this->boolean('rememberme'), - _('Automatically login in the future; not for shared computers!')); - common_element_start('p'); - $attrs = array('type' => 'checkbox', - 'id' => 'license', - 'name' => 'license', - 'value' => 'true'); - if ($this->boolean('license')) { - $attrs['checked'] = 'checked'; - } - common_element('input', $attrs); - common_text(_('My text and files are available under ')); - common_element('a', array('href' => $config['license']['url']), - $config['license']['title']); - common_text(_(' except this private data: password, email address, IM address, phone number.')); - common_element_end('p'); - common_submit('submit', _('Register')); - common_element_end('form'); - common_show_footer(); - } - - function show_success() { - $nickname = $this->arg('nickname'); - common_show_header(_('Registration successful')); - common_element_start('div', 'success'); - $instr = sprintf(_('Congratulations, %s! And welcome to %%%%site.name%%%%. From here, you may want to...'. "\n\n" . - '* Go to [your profile](%s) and post your first message.' . "\n" . - '* Add a [Jabber/GTalk address](%%%%action.imsettings%%%%) so you can send notices through instant messages.' . "\n" . - '* [Search for people](%%%%action.peoplesearch%%%%) that you may know or that share your interests. ' . "\n" . - '* Update your [profile settings](%%%%action.profilesettings%%%%) to tell others more about you. ' . "\n" . - '* Read over the [online docs](%%%%doc.help%%%%) for features you may have missed. ' . "\n\n" . - 'Thanks for signing up and we hope you enjoy using this service.'), - $nickname, common_local_url('showstream', array('nickname' => $nickname))); - common_raw(common_markup_to_html($instr)); - $have_email = $this->trimmed('email'); - if ($have_email) { - $emailinstr = _('(You should receive a message by email momentarily, with ' . - 'instructions on how to confirm your email address.)'); - common_raw(common_markup_to_html($emailinstr)); - } - common_element_end('div'); - common_show_footer(); - } + function handle($args) { + parent::handle($args); + + if (common_config('site', 'closed')) { + common_user_error(_('Registration not allowed.')); + } else if (common_logged_in()) { + common_user_error(_('Already logged in.')); + } else if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->try_register(); + } else { + $this->show_form(); + } + } + + function try_register() { + + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + $nickname = $this->trimmed('nickname'); + $email = $this->trimmed('email'); + $fullname = $this->trimmed('fullname'); + $homepage = $this->trimmed('homepage'); + $bio = $this->trimmed('bio'); + $location = $this->trimmed('location'); + + # We don't trim these... whitespace is OK in a password! + + $password = $this->arg('password'); + $confirm = $this->arg('confirm'); + + # invitation code, if any + + $code = $this->trimmed('code'); + + if ($code) { + $invite = Invitation::staticGet($code); + } + + if (common_config('site', 'inviteonly') && !($code && $invite)) { + $this->client_error(_('Sorry, only invited people can register.')); + return; + } + + # Input scrubbing + + $nickname = common_canonical_nickname($nickname); + $email = common_canonical_email($email); + + if (!$this->boolean('license')) { + $this->show_form(_('You can\'t register if you don\'t agree to the license.')); + } else if ($email && !Validate::email($email, true)) { + $this->show_form(_('Not a valid email address.')); + } else if (!Validate::string($nickname, array('min_length' => 1, + 'max_length' => 64, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + $this->show_form(_('Nickname must have only lowercase letters and numbers and no spaces.')); + } else if ($this->nickname_exists($nickname)) { + $this->show_form(_('Nickname already in use. Try another one.')); + } else if (!User::allowed_nickname($nickname)) { + $this->show_form(_('Not a valid nickname.')); + } else if ($this->email_exists($email)) { + $this->show_form(_('Email address already exists.')); + } else if (!is_null($homepage) && (strlen($homepage) > 0) && + !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { + $this->show_form(_('Homepage is not a valid URL.')); + return; + } else if (!is_null($fullname) && strlen($fullname) > 255) { + $this->show_form(_('Full name is too long (max 255 chars).')); + return; + } else if (!is_null($bio) && strlen($bio) > 140) { + $this->show_form(_('Bio is too long (max 140 chars).')); + return; + } else if (!is_null($location) && strlen($location) > 255) { + $this->show_form(_('Location is too long (max 255 chars).')); + return; + } else if (strlen($password) < 6) { + $this->show_form(_('Password must be 6 or more characters.')); + return; + } else if ($password != $confirm) { + $this->show_form(_('Passwords don\'t match.')); + } else if ($user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, + 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, + 'location' => $location, 'code' => $code))) { + if (!$user) { + $this->show_form(_('Invalid username or password.')); + return; + } + # success! + if (!common_set_user($user)) { + common_server_error(_('Error setting user.')); + return; + } + # this is a real login + common_real_login(true); + if ($this->boolean('rememberme')) { + common_debug('Adding rememberme cookie for ' . $nickname); + common_rememberme($user); + } + # Re-init language env in case it changed (not yet, but soon) + common_init_language(); + $this->show_success(); + } else { + $this->show_form(_('Invalid username or password.')); + } + } + + # checks if *CANONICAL* nickname exists + + function nickname_exists($nickname) { + $user = User::staticGet('nickname', $nickname); + return ($user !== false); + } + + # checks if *CANONICAL* email exists + + function email_exists($email) { + $email = common_canonical_email($email); + if (!$email || strlen($email) == 0) { + return false; + } + $user = User::staticGet('email', $email); + return ($user !== false); + } + + function show_top($error=NULL) { + if ($error) { + common_element('p', 'error', $error); + } else { + $instr = common_markup_to_html(_('With this form you can create a new account. ' . + 'You can then post notices and link up to friends and colleagues. '. + '(Have an [OpenID](http://openid.net/)? ' . + 'Try our [OpenID registration](%%action.openidlogin%%)!)')); + + common_element_start('div', 'instructions'); + common_raw($instr); + common_element_end('div'); + } + } + + function show_form($error=NULL) { + global $config; + + $code = $this->trimmed('code'); + + if ($code) { + $invite = Invitation::staticGet($code); + } + + if (common_config('site', 'inviteonly') && !($code && $invite)) { + $this->client_error(_('Sorry, only invited people can register.')); + return; + } + + common_show_header(_('Register'), NULL, $error, array($this, 'show_top')); + common_element_start('form', array('method' => 'post', + 'id' => 'login', + 'action' => common_local_url('register'))); + + common_hidden('token', common_session_token()); + + if ($code) { + common_hidden('code', $code); + } + + common_input('nickname', _('Nickname'), $this->trimmed('nickname'), + _('1-64 lowercase letters or numbers, no punctuation or spaces. Required.')); + common_password('password', _('Password'), + _('6 or more characters. Required.')); + common_password('confirm', _('Confirm'), + _('Same as password above. Required.')); + if ($invite && $invite->address_type == 'email') { + common_input('email', _('Email'), $invite->address, + _('Used only for updates, announcements, and password recovery')); + } else { + common_input('email', _('Email'), $this->trimmed('email'), + _('Used only for updates, announcements, and password recovery')); + } + common_input('fullname', _('Full name'), + $this->trimmed('fullname'), + _('Longer name, preferably your "real" name')); + common_input('homepage', _('Homepage'), + $this->trimmed('homepage'), + _('URL of your homepage, blog, or profile on another site')); + common_textarea('bio', _('Bio'), + $this->trimmed('bio'), + _('Describe yourself and your interests in 140 chars')); + common_input('location', _('Location'), + $this->trimmed('location'), + _('Where you are, like "City, State (or Region), Country"')); + common_checkbox('rememberme', _('Remember me'), + $this->boolean('rememberme'), + _('Automatically login in the future; not for shared computers!')); + common_element_start('p'); + $attrs = array('type' => 'checkbox', + 'id' => 'license', + 'name' => 'license', + 'value' => 'true'); + if ($this->boolean('license')) { + $attrs['checked'] = 'checked'; + } + common_element('input', $attrs); + common_text(_('My text and files are available under ')); + common_element('a', array('href' => $config['license']['url']), + $config['license']['title']); + common_text(_(' except this private data: password, email address, IM address, phone number.')); + common_element_end('p'); + common_submit('submit', _('Register')); + common_element_end('form'); + common_show_footer(); + } + + function show_success() { + $nickname = $this->arg('nickname'); + common_show_header(_('Registration successful')); + common_element_start('div', 'success'); + $instr = sprintf(_('Congratulations, %s! And welcome to %%%%site.name%%%%. From here, you may want to...'. "\n\n" . + '* Go to [your profile](%s) and post your first message.' . "\n" . + '* Add a [Jabber/GTalk address](%%%%action.imsettings%%%%) so you can send notices through instant messages.' . "\n" . + '* [Search for people](%%%%action.peoplesearch%%%%) that you may know or that share your interests. ' . "\n" . + '* Update your [profile settings](%%%%action.profilesettings%%%%) to tell others more about you. ' . "\n" . + '* Read over the [online docs](%%%%doc.help%%%%) for features you may have missed. ' . "\n\n" . + 'Thanks for signing up and we hope you enjoy using this service.'), + $nickname, common_local_url('showstream', array('nickname' => $nickname))); + common_raw(common_markup_to_html($instr)); + $have_email = $this->trimmed('email'); + if ($have_email) { + $emailinstr = _('(You should receive a message by email momentarily, with ' . + 'instructions on how to confirm your email address.)'); + common_raw(common_markup_to_html($emailinstr)); + } + common_element_end('div'); + common_show_footer(); + } } diff --git a/_darcs/pristine/actions/remotesubscribe.php b/_darcs/pristine/actions/remotesubscribe.php index c3a09bcfc..14e8cb068 100644 --- a/_darcs/pristine/actions/remotesubscribe.php +++ b/_darcs/pristine/actions/remotesubscribe.php @@ -23,364 +23,364 @@ require_once(INSTALLDIR.'/lib/omb.php'); class RemotesubscribeAction extends Action { - function handle($args) { - - parent::handle($args); - - if (common_logged_in()) { - common_user_error(_('You can use the local subscription!')); - return; - } - - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - $this->remote_subscription(); - } else { - $this->show_form(); - } - } - - function get_instructions() { - return _('To subscribe, you can [login](%%action.login%%),' . - ' or [register](%%action.register%%) a new ' . - ' account. If you already have an account ' . - ' on a [compatible microblogging site](%%doc.openmublog%%), ' . - ' enter your profile URL below.'); - } - - function show_top($err=NULL) { - if ($err) { - common_element('div', 'error', $err); - } else { - $instructions = $this->get_instructions(); - $output = common_markup_to_html($instructions); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('p'); - } - } - - function show_form($err=NULL) { - $nickname = $this->trimmed('nickname'); - $profile = $this->trimmed('profile_url'); - common_show_header(_('Remote subscribe'), NULL, $err, - array($this, 'show_top')); - # id = remotesubscribe conflicts with the - # button on profile page - common_element_start('form', array('id' => 'remsub', 'method' => 'post', - 'action' => common_local_url('remotesubscribe'))); - common_hidden('token', common_session_token()); - common_input('nickname', _('User nickname'), $nickname, - _('Nickname of the user you want to follow')); - common_input('profile_url', _('Profile URL'), $profile, - _('URL of your profile on another compatible microblogging service')); - common_submit('submit', _('Subscribe')); - common_element_end('form'); - common_show_footer(); - } - - function remote_subscription() { - $user = $this->get_user(); - - if (!$user) { - $this->show_form(_('No such user.')); - return; - } - - $profile = $this->trimmed('profile_url'); - - if (!$profile) { - $this->show_form(_('No such user.')); - return; - } - - if (!Validate::uri($profile, array('allowed_schemes' => array('http', 'https')))) { - $this->show_form(_('Invalid profile URL (bad format)')); - return; - } - - $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); - $yadis = Auth_Yadis_Yadis::discover($profile, $fetcher); - - if (!$yadis || $yadis->failed) { - $this->show_form(_('Not a valid profile URL (no YADIS document).')); - return; - } - - # XXX: a little liberal for sites that accidentally put whitespace before the xml declaration + function handle($args) { + + parent::handle($args); + + if (common_logged_in()) { + common_user_error(_('You can use the local subscription!')); + return; + } + + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + $this->remote_subscription(); + } else { + $this->show_form(); + } + } + + function get_instructions() { + return _('To subscribe, you can [login](%%action.login%%),' . + ' or [register](%%action.register%%) a new ' . + ' account. If you already have an account ' . + ' on a [compatible microblogging site](%%doc.openmublog%%), ' . + ' enter your profile URL below.'); + } + + function show_top($err=NULL) { + if ($err) { + common_element('div', 'error', $err); + } else { + $instructions = $this->get_instructions(); + $output = common_markup_to_html($instructions); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('p'); + } + } + + function show_form($err=NULL) { + $nickname = $this->trimmed('nickname'); + $profile = $this->trimmed('profile_url'); + common_show_header(_('Remote subscribe'), NULL, $err, + array($this, 'show_top')); + # id = remotesubscribe conflicts with the + # button on profile page + common_element_start('form', array('id' => 'remsub', 'method' => 'post', + 'action' => common_local_url('remotesubscribe'))); + common_hidden('token', common_session_token()); + common_input('nickname', _('User nickname'), $nickname, + _('Nickname of the user you want to follow')); + common_input('profile_url', _('Profile URL'), $profile, + _('URL of your profile on another compatible microblogging service')); + common_submit('submit', _('Subscribe')); + common_element_end('form'); + common_show_footer(); + } + + function remote_subscription() { + $user = $this->get_user(); + + if (!$user) { + $this->show_form(_('No such user.')); + return; + } + + $profile = $this->trimmed('profile_url'); + + if (!$profile) { + $this->show_form(_('No such user.')); + return; + } + + if (!Validate::uri($profile, array('allowed_schemes' => array('http', 'https')))) { + $this->show_form(_('Invalid profile URL (bad format)')); + return; + } + + $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); + $yadis = Auth_Yadis_Yadis::discover($profile, $fetcher); + + if (!$yadis || $yadis->failed) { + $this->show_form(_('Not a valid profile URL (no YADIS document).')); + return; + } + + # XXX: a little liberal for sites that accidentally put whitespace before the xml declaration $xrds =& Auth_Yadis_XRDS::parseXRDS(trim($yadis->response_text)); - if (!$xrds) { - $this->show_form(_('Not a valid profile URL (no XRDS defined).')); - return; - } + if (!$xrds) { + $this->show_form(_('Not a valid profile URL (no XRDS defined).')); + return; + } - $omb = $this->getOmb($xrds); + $omb = $this->getOmb($xrds); - if (!$omb) { - $this->show_form(_('Not a valid profile URL (incorrect services).')); - return; - } + if (!$omb) { + $this->show_form(_('Not a valid profile URL (incorrect services).')); + return; + } - if (omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]) == - common_local_url('requesttoken')) - { - $this->show_form(_('That\'s a local profile! Login to subscribe.')); - return; - } - - if (User::staticGet('uri', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]))) { - $this->show_form(_('That\'s a local profile! Login to subscribe.')); - return; - } - - list($token, $secret) = $this->request_token($omb); - - if (!$token || !$secret) { - $this->show_form(_('Couldn\'t get a request token.')); - return; - } - - $this->request_authorization($user, $omb, $token, $secret); - } - - function get_user() { - $user = NULL; - $nickname = $this->trimmed('nickname'); - if ($nickname) { - $user = User::staticGet('nickname', $nickname); - } - return $user; - } - - function getOmb($xrds) { - - static $omb_endpoints = array(OMB_ENDPOINT_UPDATEPROFILE, OMB_ENDPOINT_POSTNOTICE); - static $oauth_endpoints = array(OAUTH_ENDPOINT_REQUEST, OAUTH_ENDPOINT_AUTHORIZE, - OAUTH_ENDPOINT_ACCESS); - $omb = array(); - - # XXX: the following code could probably be refactored to eliminate dupes - - $oauth_services = omb_get_services($xrds, OAUTH_DISCOVERY); - - if (!$oauth_services) { - return NULL; - } - - $oauth_service = $oauth_services[0]; - - $oauth_xrd = $this->getXRD($oauth_service, $xrds); + if (omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]) == + common_local_url('requesttoken')) + { + $this->show_form(_('That\'s a local profile! Login to subscribe.')); + return; + } + + if (User::staticGet('uri', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]))) { + $this->show_form(_('That\'s a local profile! Login to subscribe.')); + return; + } + + list($token, $secret) = $this->request_token($omb); + + if (!$token || !$secret) { + $this->show_form(_('Couldn\'t get a request token.')); + return; + } + + $this->request_authorization($user, $omb, $token, $secret); + } + + function get_user() { + $user = NULL; + $nickname = $this->trimmed('nickname'); + if ($nickname) { + $user = User::staticGet('nickname', $nickname); + } + return $user; + } + + function getOmb($xrds) { + + static $omb_endpoints = array(OMB_ENDPOINT_UPDATEPROFILE, OMB_ENDPOINT_POSTNOTICE); + static $oauth_endpoints = array(OAUTH_ENDPOINT_REQUEST, OAUTH_ENDPOINT_AUTHORIZE, + OAUTH_ENDPOINT_ACCESS); + $omb = array(); + + # XXX: the following code could probably be refactored to eliminate dupes + + $oauth_services = omb_get_services($xrds, OAUTH_DISCOVERY); + + if (!$oauth_services) { + return NULL; + } + + $oauth_service = $oauth_services[0]; + + $oauth_xrd = $this->getXRD($oauth_service, $xrds); - if (!$oauth_xrd) { - return NULL; - } + if (!$oauth_xrd) { + return NULL; + } - if (!$this->addServices($oauth_xrd, $oauth_endpoints, $omb)) { - return NULL; - } + if (!$this->addServices($oauth_xrd, $oauth_endpoints, $omb)) { + return NULL; + } - $omb_services = omb_get_services($xrds, OMB_NAMESPACE); + $omb_services = omb_get_services($xrds, OMB_NAMESPACE); - if (!$omb_services) { - return NULL; - } + if (!$omb_services) { + return NULL; + } - $omb_service = $omb_services[0]; + $omb_service = $omb_services[0]; - $omb_xrd = $this->getXRD($omb_service, $xrds); + $omb_xrd = $this->getXRD($omb_service, $xrds); - if (!$omb_xrd) { - return NULL; - } + if (!$omb_xrd) { + return NULL; + } - if (!$this->addServices($omb_xrd, $omb_endpoints, $omb)) { - return NULL; - } + if (!$this->addServices($omb_xrd, $omb_endpoints, $omb)) { + return NULL; + } - # XXX: check that we got all the services we needed + # XXX: check that we got all the services we needed - foreach (array_merge($omb_endpoints, $oauth_endpoints) as $type) { - if (!array_key_exists($type, $omb) || !$omb[$type]) { - return NULL; - } - } + foreach (array_merge($omb_endpoints, $oauth_endpoints) as $type) { + if (!array_key_exists($type, $omb) || !$omb[$type]) { + return NULL; + } + } - if (!omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])) { - return NULL; - } + if (!omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])) { + return NULL; + } - return $omb; - } + return $omb; + } - function getXRD($main_service, $main_xrds) { - $uri = omb_service_uri($main_service); - if (strpos($uri, "#") !== 0) { - # FIXME: more rigorous handling of external service definitions - return NULL; - } - $id = substr($uri, 1); - $nodes = $main_xrds->allXrdNodes; - $parser = $main_xrds->parser; - foreach ($nodes as $node) { - $attrs = $parser->attributes($node); - if (array_key_exists('xml:id', $attrs) && - $attrs['xml:id'] == $id) { - # XXX: trick the constructor into thinking this is the only node - $bogus_nodes = array($node); - return new Auth_Yadis_XRDS($parser, $bogus_nodes); - } - } - return NULL; - } + function getXRD($main_service, $main_xrds) { + $uri = omb_service_uri($main_service); + if (strpos($uri, "#") !== 0) { + # FIXME: more rigorous handling of external service definitions + return NULL; + } + $id = substr($uri, 1); + $nodes = $main_xrds->allXrdNodes; + $parser = $main_xrds->parser; + foreach ($nodes as $node) { + $attrs = $parser->attributes($node); + if (array_key_exists('xml:id', $attrs) && + $attrs['xml:id'] == $id) { + # XXX: trick the constructor into thinking this is the only node + $bogus_nodes = array($node); + return new Auth_Yadis_XRDS($parser, $bogus_nodes); + } + } + return NULL; + } - function addServices($xrd, $types, &$omb) { - foreach ($types as $type) { - $matches = omb_get_services($xrd, $type); - if ($matches) { - $omb[$type] = $matches[0]; - } else { - # no match for type - return false; - } - } - return true; - } + function addServices($xrd, $types, &$omb) { + foreach ($types as $type) { + $matches = omb_get_services($xrd, $type); + if ($matches) { + $omb[$type] = $matches[0]; + } else { + # no match for type + return false; + } + } + return true; + } - function request_token($omb) { - $con = omb_oauth_consumer(); + function request_token($omb) { + $con = omb_oauth_consumer(); - $url = omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]); + $url = omb_service_uri($omb[OAUTH_ENDPOINT_REQUEST]); - # XXX: Is this the right thing to do? Strip off GET params and make them - # POST params? Seems wrong to me. + # XXX: Is this the right thing to do? Strip off GET params and make them + # POST params? Seems wrong to me. - $parsed = parse_url($url); - $params = array(); - parse_str($parsed['query'], $params); + $parsed = parse_url($url); + $params = array(); + parse_str($parsed['query'], $params); - $req = OAuthRequest::from_consumer_and_token($con, NULL, "POST", $url, $params); + $req = OAuthRequest::from_consumer_and_token($con, NULL, "POST", $url, $params); - $listener = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]); + $listener = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]); - if (!$listener) { - return NULL; - } + if (!$listener) { + return NULL; + } - $req->set_parameter('omb_listener', $listener); - $req->set_parameter('omb_version', OMB_VERSION_01); + $req->set_parameter('omb_listener', $listener); + $req->set_parameter('omb_version', OMB_VERSION_01); - # XXX: test to see if endpoint accepts this signature method + # XXX: test to see if endpoint accepts this signature method - $req->sign_request(omb_hmac_sha1(), $con, NULL); + $req->sign_request(omb_hmac_sha1(), $con, NULL); - # We re-use this tool's fetcher, since it's pretty good + # We re-use this tool's fetcher, since it's pretty good - $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); + $fetcher = Auth_Yadis_Yadis::getHTTPFetcher(); - $result = $fetcher->post($req->get_normalized_http_url(), - $req->to_postdata(), + $result = $fetcher->post($req->get_normalized_http_url(), + $req->to_postdata(), array('User-Agent' => 'Laconica/' . LACONICA_VERSION)); - if ($result->status != 200) { - return NULL; - } + if ($result->status != 200) { + return NULL; + } - parse_str($result->body, $return); + parse_str($result->body, $return); - return array($return['oauth_token'], $return['oauth_token_secret']); - } + return array($return['oauth_token'], $return['oauth_token_secret']); + } - function request_authorization($user, $omb, $token, $secret) { - global $config; # for license URL + function request_authorization($user, $omb, $token, $secret) { + global $config; # for license URL - $con = omb_oauth_consumer(); - $tok = new OAuthToken($token, $secret); + $con = omb_oauth_consumer(); + $tok = new OAuthToken($token, $secret); - $url = omb_service_uri($omb[OAUTH_ENDPOINT_AUTHORIZE]); + $url = omb_service_uri($omb[OAUTH_ENDPOINT_AUTHORIZE]); - # XXX: Is this the right thing to do? Strip off GET params and make them - # POST params? Seems wrong to me. + # XXX: Is this the right thing to do? Strip off GET params and make them + # POST params? Seems wrong to me. - $parsed = parse_url($url); - $params = array(); - parse_str($parsed['query'], $params); + $parsed = parse_url($url); + $params = array(); + parse_str($parsed['query'], $params); - $req = OAuthRequest::from_consumer_and_token($con, $tok, 'GET', $url, $params); + $req = OAuthRequest::from_consumer_and_token($con, $tok, 'GET', $url, $params); - # We send over a ton of information. This lets the other - # server store info about our user, and it lets the current - # user decide if they really want to authorize the subscription. + # We send over a ton of information. This lets the other + # server store info about our user, and it lets the current + # user decide if they really want to authorize the subscription. - $req->set_parameter('omb_version', OMB_VERSION_01); - $req->set_parameter('omb_listener', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])); - $req->set_parameter('omb_listenee', $user->uri); - $req->set_parameter('omb_listenee_profile', common_profile_url($user->nickname)); - $req->set_parameter('omb_listenee_nickname', $user->nickname); - $req->set_parameter('omb_listenee_license', $config['license']['url']); + $req->set_parameter('omb_version', OMB_VERSION_01); + $req->set_parameter('omb_listener', omb_local_id($omb[OAUTH_ENDPOINT_REQUEST])); + $req->set_parameter('omb_listenee', $user->uri); + $req->set_parameter('omb_listenee_profile', common_profile_url($user->nickname)); + $req->set_parameter('omb_listenee_nickname', $user->nickname); + $req->set_parameter('omb_listenee_license', $config['license']['url']); - $profile = $user->getProfile(); - if (!$profile) { - common_log_db_error($user, 'SELECT', __FILE__); - $this->server_error(_('User without matching profile')); - return; - } + $profile = $user->getProfile(); + if (!$profile) { + common_log_db_error($user, 'SELECT', __FILE__); + $this->server_error(_('User without matching profile')); + return; + } - if ($profile->fullname) { - $req->set_parameter('omb_listenee_fullname', $profile->fullname); - } - if ($profile->homepage) { - $req->set_parameter('omb_listenee_homepage', $profile->homepage); - } - if ($profile->bio) { - $req->set_parameter('omb_listenee_bio', $profile->bio); - } - if ($profile->location) { - $req->set_parameter('omb_listenee_location', $profile->location); - } - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - if ($avatar) { - $req->set_parameter('omb_listenee_avatar', $avatar->url); - } + if ($profile->fullname) { + $req->set_parameter('omb_listenee_fullname', $profile->fullname); + } + if ($profile->homepage) { + $req->set_parameter('omb_listenee_homepage', $profile->homepage); + } + if ($profile->bio) { + $req->set_parameter('omb_listenee_bio', $profile->bio); + } + if ($profile->location) { + $req->set_parameter('omb_listenee_location', $profile->location); + } + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + if ($avatar) { + $req->set_parameter('omb_listenee_avatar', $avatar->url); + } - # XXX: add a nonce to prevent replay attacks + # XXX: add a nonce to prevent replay attacks - $req->set_parameter('oauth_callback', common_local_url('finishremotesubscribe')); + $req->set_parameter('oauth_callback', common_local_url('finishremotesubscribe')); - # XXX: test to see if endpoint accepts this signature method + # XXX: test to see if endpoint accepts this signature method - $req->sign_request(omb_hmac_sha1(), $con, $tok); + $req->sign_request(omb_hmac_sha1(), $con, $tok); - # store all our info here + # store all our info here - $omb['listenee'] = $user->nickname; - $omb['listener'] = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]); - $omb['token'] = $token; - $omb['secret'] = $secret; - # call doesn't work after bounce back so we cache; maybe serialization issue...? - $omb['access_token_url'] = omb_service_uri($omb[OAUTH_ENDPOINT_ACCESS]); - $omb['post_notice_url'] = omb_service_uri($omb[OMB_ENDPOINT_POSTNOTICE]); - $omb['update_profile_url'] = omb_service_uri($omb[OMB_ENDPOINT_UPDATEPROFILE]); + $omb['listenee'] = $user->nickname; + $omb['listener'] = omb_local_id($omb[OAUTH_ENDPOINT_REQUEST]); + $omb['token'] = $token; + $omb['secret'] = $secret; + # call doesn't work after bounce back so we cache; maybe serialization issue...? + $omb['access_token_url'] = omb_service_uri($omb[OAUTH_ENDPOINT_ACCESS]); + $omb['post_notice_url'] = omb_service_uri($omb[OMB_ENDPOINT_POSTNOTICE]); + $omb['update_profile_url'] = omb_service_uri($omb[OMB_ENDPOINT_UPDATEPROFILE]); - common_ensure_session(); + common_ensure_session(); - $_SESSION['oauth_authorization_request'] = $omb; + $_SESSION['oauth_authorization_request'] = $omb; - # Redirect to authorization service + # Redirect to authorization service - common_redirect($req->to_url()); - return; - } + common_redirect($req->to_url()); + return; + } - function make_nonce() { - return common_good_rand(16); - } + function make_nonce() { + return common_good_rand(16); + } } diff --git a/_darcs/pristine/actions/replies.php b/_darcs/pristine/actions/replies.php index 835871ffc..be80fae79 100644 --- a/_darcs/pristine/actions/replies.php +++ b/_darcs/pristine/actions/replies.php @@ -23,72 +23,72 @@ require_once(INSTALLDIR.'/actions/showstream.php'); class RepliesAction extends StreamAction { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); + $nickname = common_canonical_nickname($this->arg('nickname')); + $user = User::staticGet('nickname', $nickname); - if (!$user) { - $this->no_such_user(); - return; - } + if (!$user) { + $this->no_such_user(); + return; + } - $profile = $user->getProfile(); + $profile = $user->getProfile(); - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } - # Looks like we're good; show the header + # Looks like we're good; show the header - common_show_header(sprintf(_("Replies to %s"), $profile->nickname), - array($this, 'show_header'), $user, - array($this, 'show_top')); + common_show_header(sprintf(_("Replies to %s"), $profile->nickname), + array($this, 'show_header'), $user, + array($this, 'show_top')); - $this->show_replies($user); + $this->show_replies($user); - common_show_footer(); - } + common_show_footer(); + } - function no_such_user() { - common_user_error(_('No such user.')); - } + function no_such_user() { + common_user_error(_('No such user.')); + } - function show_header($user) { - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('repliesrss', array('nickname' => - $user->nickname)), - 'type' => 'application/rss+xml', - 'title' => sprintf(_('Feed for replies to %s'), $user->nickname))); - } + function show_header($user) { + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('repliesrss', array('nickname' => + $user->nickname)), + 'type' => 'application/rss+xml', + 'title' => sprintf(_('Feed for replies to %s'), $user->nickname))); + } - function show_top($user) { - $cur = common_current_user(); + function show_top($user) { + $cur = common_current_user(); - if ($cur && $cur->id == $user->id) { - common_notice_form('replies'); - } + if ($cur && $cur->id == $user->id) { + common_notice_form('replies'); + } - $this->views_menu(); + $this->views_menu(); - $this->show_feeds_list(array(0=>array('href'=>common_local_url('repliesrss', array('nickname' => $user->nickname)), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'repliesrss'))); - } + $this->show_feeds_list(array(0=>array('href'=>common_local_url('repliesrss', array('nickname' => $user->nickname)), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'repliesrss'))); + } - function show_replies($user) { + function show_replies($user) { - $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - $notice = $user->getReplies(($page-1) * NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); + $notice = $user->getReplies(($page-1) * NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); - $cnt = $this->show_notice_list($notice); + $cnt = $this->show_notice_list($notice); - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'replies', array('nickname' => $user->nickname)); - } + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'replies', array('nickname' => $user->nickname)); + } } diff --git a/_darcs/pristine/actions/repliesrss.php b/_darcs/pristine/actions/repliesrss.php index 7369db5e0..3689ea1f8 100644 --- a/_darcs/pristine/actions/repliesrss.php +++ b/_darcs/pristine/actions/repliesrss.php @@ -25,55 +25,55 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class RepliesrssAction extends Rss10Action { - var $user = NULL; + var $user = NULL; - function init() { - $nickname = $this->trimmed('nickname'); - $this->user = User::staticGet('nickname', $nickname); + function init() { + $nickname = $this->trimmed('nickname'); + $this->user = User::staticGet('nickname', $nickname); - if (!$this->user) { - common_user_error(_('No such user.')); - return false; - } else { - return true; - } - } + if (!$this->user) { + common_user_error(_('No such user.')); + return false; + } else { + return true; + } + } - function get_notices($limit=0) { + function get_notices($limit=0) { - $user = $this->user; + $user = $this->user; - $notice = $user->getReplies(0, ($limit == 0) ? 48 : $limit); + $notice = $user->getReplies(0, ($limit == 0) ? 48 : $limit); - $notices = array(); - - while ($notice->fetch()) { - $notices[] = clone($notice); - } + $notices = array(); + + while ($notice->fetch()) { + $notices[] = clone($notice); + } - return $notices; - } + return $notices; + } - function get_channel() { - $user = $this->user; - $c = array('url' => common_local_url('repliesrss', - array('nickname' => - $user->nickname)), - 'title' => sprintf(_("Replies to %s"), $user->nickname), - 'link' => common_local_url('replies', - array('nickname' => - $user->nickname)), - 'description' => sprintf(_('Feed for replies to %s'), $user->nickname)); - return $c; - } + function get_channel() { + $user = $this->user; + $c = array('url' => common_local_url('repliesrss', + array('nickname' => + $user->nickname)), + 'title' => sprintf(_("Replies to %s"), $user->nickname), + 'link' => common_local_url('replies', + array('nickname' => + $user->nickname)), + 'description' => sprintf(_('Feed for replies to %s'), $user->nickname)); + return $c; + } - function get_image() { - $user = $this->user; - $profile = $user->getProfile(); - if (!$profile) { - return NULL; - } - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - return ($avatar) ? $avatar->url : NULL; - } + function get_image() { + $user = $this->user; + $profile = $user->getProfile(); + if (!$profile) { + return NULL; + } + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + return ($avatar) ? $avatar->url : NULL; + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/requesttoken.php b/_darcs/pristine/actions/requesttoken.php index 76019a929..4950d93c0 100644 --- a/_darcs/pristine/actions/requesttoken.php +++ b/_darcs/pristine/actions/requesttoken.php @@ -22,21 +22,21 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/omb.php'); class RequesttokenAction extends Action { - - function is_readonly() { - return false; - } - - function handle($args) { - parent::handle($args); - try { - common_remove_magic_from_request(); - $req = OAuthRequest::from_request(); - $server = omb_oauth_server(); - $token = $server->fetch_request_token($req); - print $token; - } catch (OAuthException $e) { - common_server_error($e->getMessage()); - } - } + + function is_readonly() { + return false; + } + + function handle($args) { + parent::handle($args); + try { + common_remove_magic_from_request(); + $req = OAuthRequest::from_request(); + $server = omb_oauth_server(); + $token = $server->fetch_request_token($req); + print $token; + } catch (OAuthException $e) { + common_server_error($e->getMessage()); + } + } } diff --git a/_darcs/pristine/actions/showfavorites.php b/_darcs/pristine/actions/showfavorites.php index 4de4b1271..2fd1e586d 100644 --- a/_darcs/pristine/actions/showfavorites.php +++ b/_darcs/pristine/actions/showfavorites.php @@ -23,75 +23,75 @@ require_once(INSTALLDIR.'/actions/showstream.php'); class ShowfavoritesAction extends StreamAction { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - $nickname = common_canonical_nickname($this->arg('nickname')); - $user = User::staticGet('nickname', $nickname); + $nickname = common_canonical_nickname($this->arg('nickname')); + $user = User::staticGet('nickname', $nickname); - if (!$user) { - $this->client_error(_('No such user.')); - return; - } + if (!$user) { + $this->client_error(_('No such user.')); + return; + } - $profile = $user->getProfile(); + $profile = $user->getProfile(); - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } - # Looks like we're good; show the header + # Looks like we're good; show the header - common_show_header(sprintf(_("%s favorite notices"), $profile->nickname), - array($this, 'show_header'), $user, - array($this, 'show_top')); + common_show_header(sprintf(_("%s favorite notices"), $profile->nickname), + array($this, 'show_header'), $user, + array($this, 'show_top')); - $this->show_notices($user); + $this->show_notices($user); - common_show_footer(); - } + common_show_footer(); + } - function show_header($user) { - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('favoritesrss', array('nickname' => - $user->nickname)), - 'type' => 'application/rss+xml', - 'title' => sprintf(_('Feed for favorites of %s'), $user->nickname))); - } + function show_header($user) { + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('favoritesrss', array('nickname' => + $user->nickname)), + 'type' => 'application/rss+xml', + 'title' => sprintf(_('Feed for favorites of %s'), $user->nickname))); + } - function show_top($user) { - $cur = common_current_user(); + function show_top($user) { + $cur = common_current_user(); - if ($cur && $cur->id == $user->id) { - common_notice_form('all'); - } + if ($cur && $cur->id == $user->id) { + common_notice_form('all'); + } - $this->show_feeds_list(array(0=>array('href'=>common_local_url('favoritesrss', array('nickname' => $user->nickname)), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'Favorites'))); - $this->views_menu(); - } + $this->show_feeds_list(array(0=>array('href'=>common_local_url('favoritesrss', array('nickname' => $user->nickname)), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'Favorites'))); + $this->views_menu(); + } - function show_notices($user) { + function show_notices($user) { - $page = $this->trimmed('page'); - if (!$page) { - $page = 1; - } + $page = $this->trimmed('page'); + if (!$page) { + $page = 1; + } - $notice = $user->favoriteNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); + $notice = $user->favoriteNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); - if (!$notice) { - $this->server_error(_('Could not retrieve favorite notices.')); - return; - } + if (!$notice) { + $this->server_error(_('Could not retrieve favorite notices.')); + return; + } $cnt = $this->show_notice_list($notice); - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'showfavorites', array('nickname' => $user->nickname)); - } + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'showfavorites', array('nickname' => $user->nickname)); + } } diff --git a/_darcs/pristine/actions/showmessage.php b/_darcs/pristine/actions/showmessage.php index c171ffe0b..f35f3eede 100644 --- a/_darcs/pristine/actions/showmessage.php +++ b/_darcs/pristine/actions/showmessage.php @@ -23,78 +23,78 @@ require_once(INSTALLDIR.'/lib/mailbox.php'); class ShowmessageAction extends MailboxAction { - function handle($args) { + function handle($args) { - Action::handle($args); + Action::handle($args); - $message = $this->get_message(); + $message = $this->get_message(); - if (!$message) { - $this->client_error(_('No such message.'), 404); - return; - } - - $cur = common_current_user(); - - if ($cur && ($cur->id == $message->from_profile || $cur->id == $message->to_profile)) { - $this->show_page($cur, 1); - } else { - $this->client_error(_('Only the sender and recipient may read this message.'), 403); - return; - } - } - - function get_message() { - $id = $this->trimmed('message'); - $message = Message::staticGet('id', $id); - return $message; - } - - function get_title($user, $page) { - $message = $this->get_message(); - if (!$message) { - return NULL; - } - - if ($user->id == $message->from_profile) { - $to = $message->getTo(); - $title = sprintf(_("Message to %1\$s on %2\$s"), - $to->nickname, - common_exact_date($message->created)); - } else if ($user->id == $message->to_profile) { - $from = $message->getFrom(); - $title = sprintf(_("Message from %1\$s on %2\$s"), - $from->nickname, - common_exact_date($message->created)); - } - return $title; - } + if (!$message) { + $this->client_error(_('No such message.'), 404); + return; + } + + $cur = common_current_user(); + + if ($cur && ($cur->id == $message->from_profile || $cur->id == $message->to_profile)) { + $this->show_page($cur, 1); + } else { + $this->client_error(_('Only the sender and recipient may read this message.'), 403); + return; + } + } + + function get_message() { + $id = $this->trimmed('message'); + $message = Message::staticGet('id', $id); + return $message; + } + + function get_title($user, $page) { + $message = $this->get_message(); + if (!$message) { + return NULL; + } + + if ($user->id == $message->from_profile) { + $to = $message->getTo(); + $title = sprintf(_("Message to %1\$s on %2\$s"), + $to->nickname, + common_exact_date($message->created)); + } else if ($user->id == $message->to_profile) { + $from = $message->getFrom(); + $title = sprintf(_("Message from %1\$s on %2\$s"), + $from->nickname, + common_exact_date($message->created)); + } + return $title; + } - function get_messages($user, $page) { - $message = new Message(); - $message->id = $this->trimmed('message'); - $message->find(); - return $message; - } - - function get_message_profile($message) { - $user = common_current_user(); - if ($user->id == $message->from_profile) { - return $message->getTo(); - } else if ($user->id == $message->to_profile) { - return $message->getFrom(); - } else { - # This shouldn't happen - return NULL; - } - } - - function get_instructions() { - return ''; - } - - function views_menu() { - return; - } + function get_messages($user, $page) { + $message = new Message(); + $message->id = $this->trimmed('message'); + $message->find(); + return $message; + } + + function get_message_profile($message) { + $user = common_current_user(); + if ($user->id == $message->from_profile) { + return $message->getTo(); + } else if ($user->id == $message->to_profile) { + return $message->getFrom(); + } else { + # This shouldn't happen + return NULL; + } + } + + function get_instructions() { + return ''; + } + + function views_menu() { + return; + } } - \ No newline at end of file + \ No newline at end of file diff --git a/_darcs/pristine/actions/shownotice.php b/_darcs/pristine/actions/shownotice.php index 6dea6d7bb..74d197ed1 100644 --- a/_darcs/pristine/actions/shownotice.php +++ b/_darcs/pristine/actions/shownotice.php @@ -23,94 +23,94 @@ require_once(INSTALLDIR.'/lib/stream.php'); class ShownoticeAction extends StreamAction { - var $notice = NULL; - var $profile = NULL; - var $avatar = NULL; + var $notice = NULL; + var $profile = NULL; + var $avatar = NULL; - function prepare($args) { + function prepare($args) { - parent::prepare($args); + parent::prepare($args); - $id = $this->arg('notice'); - $this->notice = Notice::staticGet($id); + $id = $this->arg('notice'); + $this->notice = Notice::staticGet($id); - if (!$this->notice) { - $this->client_error(_('No such notice.'), 404); - return false; - } + if (!$this->notice) { + $this->client_error(_('No such notice.'), 404); + return false; + } - $this->profile = $this->notice->getProfile(); + $this->profile = $this->notice->getProfile(); - if (!$this->profile) { - $this->server_error(_('Notice has no profile'), 500); - return false; - } + if (!$this->profile) { + $this->server_error(_('Notice has no profile'), 500); + return false; + } - $this->avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); + $this->avatar = $this->profile->getAvatar(AVATAR_STREAM_SIZE); - return true; - } + return true; + } - function last_modified() { - return max(strtotime($this->notice->created), - strtotime($this->profile->modified), - ($this->avatar) ? strtotime($this->avatar->modified) : 0); - } + function last_modified() { + return max(strtotime($this->notice->created), + strtotime($this->profile->modified), + ($this->avatar) ? strtotime($this->avatar->modified) : 0); + } - function etag() { - return 'W/"' . implode(':', array($this->arg('action'), - common_language(), - $this->notice->id, - strtotime($this->notice->created), - strtotime($this->profile->modified), - ($this->avatar) ? strtotime($this->avatar->modified) : 0)) . '"'; - } + function etag() { + return 'W/"' . implode(':', array($this->arg('action'), + common_language(), + $this->notice->id, + strtotime($this->notice->created), + strtotime($this->profile->modified), + ($this->avatar) ? strtotime($this->avatar->modified) : 0)) . '"'; + } - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); - common_show_header(sprintf(_('%1$s\'s status on %2$s'), - $this->profile->nickname, - common_exact_date($this->notice->created)), - array($this, 'show_header'), NULL, - array($this, 'show_top')); + common_show_header(sprintf(_('%1$s\'s status on %2$s'), + $this->profile->nickname, + common_exact_date($this->notice->created)), + array($this, 'show_header'), NULL, + array($this, 'show_top')); - common_element_start('ul', array('id' => 'notices')); + common_element_start('ul', array('id' => 'notices')); $nli = new NoticeListItem($this->notice); $nli->show(); - common_element_end('ul'); + common_element_end('ul'); - common_show_footer(); - } + common_show_footer(); + } - function show_header() { + function show_header() { - $user = User::staticGet($this->profile->id); + $user = User::staticGet($this->profile->id); - if (!$user) { - return; - } + if (!$user) { + return; + } - if ($user->emailmicroid && $user->email && $this->notice->uri) { - common_element('meta', array('name' => 'microid', - 'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($this->notice->uri)))); - } + if ($user->emailmicroid && $user->email && $this->notice->uri) { + common_element('meta', array('name' => 'microid', + 'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($this->notice->uri)))); + } - if ($user->jabbermicroid && $user->jabber && $this->notice->uri) { - common_element('meta', array('name' => 'microid', - 'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($this->notice->uri)))); - } - } + if ($user->jabbermicroid && $user->jabber && $this->notice->uri) { + common_element('meta', array('name' => 'microid', + 'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($this->notice->uri)))); + } + } - function show_top() { - $cur = common_current_user(); - if ($cur && $cur->id == $this->profile->id) { - common_notice_form(); - } - } + function show_top() { + $cur = common_current_user(); + if ($cur && $cur->id == $this->profile->id) { + common_notice_form(); + } + } - function no_such_notice() { - common_user_error(_('No such notice.')); - } + function no_such_notice() { + common_user_error(_('No such notice.')); + } } diff --git a/_darcs/pristine/actions/showstream.php b/_darcs/pristine/actions/showstream.php index 61fdec3fe..f8525348d 100644 --- a/_darcs/pristine/actions/showstream.php +++ b/_darcs/pristine/actions/showstream.php @@ -26,12 +26,12 @@ define('SUBSCRIPTIONS', 80); class ShowstreamAction extends StreamAction { - function handle($args) { + function handle($args) { - parent::handle($args); + parent::handle($args); $nickname_arg = $this->arg('nickname'); - $nickname = common_canonical_nickname($nickname_arg); + $nickname = common_canonical_nickname($nickname_arg); # Permanent redirect on non-canonical nickname @@ -44,163 +44,163 @@ class ShowstreamAction extends StreamAction { return; } - $user = User::staticGet('nickname', $nickname); - - if (!$user) { - $this->no_such_user(); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } - - # Looks like we're good; start output - - # For YADIS discovery, we also have a tag - - header('X-XRDS-Location: '. common_local_url('xrds', array('nickname' => - $user->nickname))); - - common_show_header($profile->nickname, - array($this, 'show_header'), $user, - array($this, 'show_top')); - - $this->show_profile($profile); - - $this->show_notices($user); - - common_show_footer(); - } - - function show_top($user) { - $cur = common_current_user(); - - if ($cur && $cur->id == $user->id) { - common_notice_form('showstream'); - } - - $this->views_menu(); - - $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('nickname' => $user->nickname)), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'notices'), - 1=>array('href'=>common_local_url('usertimeline', array('nickname' => $user->nickname)), - 'type' => 'atom', - 'version' => 'Atom 1.0', - 'item' => 'usertimeline'), - - 2=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), - 'type' => 'rdf', - 'version' => 'FOAF', - 'item' => 'foaf'))); - } - - function show_header($user) { - # Feeds - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('api', - array('apiaction' => 'statuses', - 'method' => 'user_timeline.rss', - 'argument' => $user->nickname)), - 'type' => 'application/rss+xml', - 'title' => sprintf(_('Notice feed for %s'), $user->nickname))); - common_element('link', array('rel' => 'alternate feed', - 'href' => common_local_url('api', - array('apiaction' => 'statuses', - 'method' => 'user_timeline.atom', - 'argument' => $user->nickname)), - 'type' => 'application/atom+xml', - 'title' => sprintf(_('Notice feed for %s'), $user->nickname))); - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('userrss', array('nickname' => - $user->nickname)), - 'type' => 'application/rdf+xml', - 'title' => sprintf(_('Notice feed for %s'), $user->nickname))); - # FOAF - common_element('link', array('rel' => 'meta', - 'href' => common_local_url('foaf', array('nickname' => - $user->nickname)), - 'type' => 'application/rdf+xml', - 'title' => 'FOAF')); - # for remote subscriptions etc. - common_element('meta', array('http-equiv' => 'X-XRDS-Location', - 'content' => common_local_url('xrds', array('nickname' => - $user->nickname)))); - $profile = $user->getProfile(); - if ($profile->bio) { - common_element('meta', array('name' => 'description', - 'content' => $profile->bio)); - } - - if ($user->emailmicroid && $user->email && $profile->profileurl) { - common_element('meta', array('name' => 'microid', - 'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($profile->profileurl)))); - } - if ($user->jabbermicroid && $user->jabber && $profile->profileurl) { - common_element('meta', array('name' => 'microid', - 'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($profile->profileurl)))); - } - - # See https://wiki.mozilla.org/Microsummaries - - common_element('link', array('rel' => 'microsummary', - 'href' => common_local_url('microsummary', - array('nickname' => $profile->nickname)))); - } - - function no_such_user() { - $this->client_error(_('No such user.'), 404); - } - - function show_profile($profile) { - - common_element_start('div', array('id' => 'profile', 'class' => 'vcard')); - - $this->show_personal($profile); - - $this->show_last_notice($profile); - - $cur = common_current_user(); - - $this->show_subscriptions($profile); - - common_element_end('div'); - } - - function show_personal($profile) { - - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - common_element_start('div', array('id' => 'profile_avatar')); - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE), - 'class' => 'avatar profile photo', - 'width' => AVATAR_PROFILE_SIZE, - 'height' => AVATAR_PROFILE_SIZE, - 'alt' => $profile->nickname)); + $user = User::staticGet('nickname', $nickname); + + if (!$user) { + $this->no_such_user(); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } + + # Looks like we're good; start output + + # For YADIS discovery, we also have a tag + + header('X-XRDS-Location: '. common_local_url('xrds', array('nickname' => + $user->nickname))); + + common_show_header($profile->nickname, + array($this, 'show_header'), $user, + array($this, 'show_top')); + + $this->show_profile($profile); + + $this->show_notices($user); + + common_show_footer(); + } + + function show_top($user) { + $cur = common_current_user(); + + if ($cur && $cur->id == $user->id) { + common_notice_form('showstream'); + } + + $this->views_menu(); + + $this->show_feeds_list(array(0=>array('href'=>common_local_url('userrss', array('nickname' => $user->nickname)), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'notices'), + 1=>array('href'=>common_local_url('usertimeline', array('nickname' => $user->nickname)), + 'type' => 'atom', + 'version' => 'Atom 1.0', + 'item' => 'usertimeline'), + + 2=>array('href'=>common_local_url('foaf',array('nickname' => $user->nickname)), + 'type' => 'rdf', + 'version' => 'FOAF', + 'item' => 'foaf'))); + } + + function show_header($user) { + # Feeds + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('api', + array('apiaction' => 'statuses', + 'method' => 'user_timeline.rss', + 'argument' => $user->nickname)), + 'type' => 'application/rss+xml', + 'title' => sprintf(_('Notice feed for %s'), $user->nickname))); + common_element('link', array('rel' => 'alternate feed', + 'href' => common_local_url('api', + array('apiaction' => 'statuses', + 'method' => 'user_timeline.atom', + 'argument' => $user->nickname)), + 'type' => 'application/atom+xml', + 'title' => sprintf(_('Notice feed for %s'), $user->nickname))); + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('userrss', array('nickname' => + $user->nickname)), + 'type' => 'application/rdf+xml', + 'title' => sprintf(_('Notice feed for %s'), $user->nickname))); + # FOAF + common_element('link', array('rel' => 'meta', + 'href' => common_local_url('foaf', array('nickname' => + $user->nickname)), + 'type' => 'application/rdf+xml', + 'title' => 'FOAF')); + # for remote subscriptions etc. + common_element('meta', array('http-equiv' => 'X-XRDS-Location', + 'content' => common_local_url('xrds', array('nickname' => + $user->nickname)))); + $profile = $user->getProfile(); + if ($profile->bio) { + common_element('meta', array('name' => 'description', + 'content' => $profile->bio)); + } + + if ($user->emailmicroid && $user->email && $profile->profileurl) { + common_element('meta', array('name' => 'microid', + 'content' => "mailto+http:sha1:" . sha1(sha1('mailto:' . $user->email) . sha1($profile->profileurl)))); + } + if ($user->jabbermicroid && $user->jabber && $profile->profileurl) { + common_element('meta', array('name' => 'microid', + 'content' => "xmpp+http:sha1:" . sha1(sha1('xmpp:' . $user->jabber) . sha1($profile->profileurl)))); + } + + # See https://wiki.mozilla.org/Microsummaries + + common_element('link', array('rel' => 'microsummary', + 'href' => common_local_url('microsummary', + array('nickname' => $profile->nickname)))); + } + + function no_such_user() { + $this->client_error(_('No such user.'), 404); + } + + function show_profile($profile) { + + common_element_start('div', array('id' => 'profile', 'class' => 'vcard')); + + $this->show_personal($profile); + + $this->show_last_notice($profile); + + $cur = common_current_user(); + + $this->show_subscriptions($profile); + + common_element_end('div'); + } + + function show_personal($profile) { + + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + common_element_start('div', array('id' => 'profile_avatar')); + common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE), + 'class' => 'avatar profile photo', + 'width' => AVATAR_PROFILE_SIZE, + 'height' => AVATAR_PROFILE_SIZE, + 'alt' => $profile->nickname)); common_element_start('ul', array('id' => 'profile_actions')); common_element_start('li', array('id' => 'profile_subscribe')); - $cur = common_current_user(); - if ($cur) { - if ($cur->id != $profile->id) { - if ($cur->isSubscribed($profile)) { - common_unsubscribe_form($profile); - } else { - common_subscribe_form($profile); - } - } - } else { - $this->show_remote_subscribe_link($profile); - } + $cur = common_current_user(); + if ($cur) { + if ($cur->id != $profile->id) { + if ($cur->isSubscribed($profile)) { + common_unsubscribe_form($profile); + } else { + common_subscribe_form($profile); + } + } + } else { + $this->show_remote_subscribe_link($profile); + } common_element_end('li'); - $user = User::staticGet('id', $profile->id); - common_profile_new_message_nudge($cur, $user, $profile); + $user = User::staticGet('id', $profile->id); + common_profile_new_message_nudge($cur, $user, $profile); if ($cur && $cur->id != $profile->id) { $blocked = $cur->hasBlocked($profile); @@ -215,224 +215,224 @@ class ShowstreamAction extends StreamAction { common_element_end('li'); } - common_element_end('ul'); - - common_element_end('div'); - - common_element_start('div', array('id' => 'profile_information')); - - if ($profile->fullname) { - common_element('h1', array('class' => 'fn'), $profile->fullname . ' (' . $profile->nickname . ')'); - } else { - common_element('h1', array('class' => 'fn nickname'), $profile->nickname); - } - - if ($profile->location) { - common_element('p', 'location', $profile->location); - } - if ($profile->bio) { - common_element('p', 'description note', $profile->bio); - } - if ($profile->homepage) { - common_element_start('p', 'website'); - common_element('a', array('href' => $profile->homepage, - 'rel' => 'me', 'class' => 'url'), - $profile->homepage); - common_element_end('p'); - } - - $this->show_statistics($profile); - - common_element_end('div'); - } - - function show_remote_subscribe_link($profile) { - $url = common_local_url('remotesubscribe', - array('nickname' => $profile->nickname)); - common_element('a', array('href' => $url, - 'id' => 'remotesubscribe'), - _('Subscribe')); - } - - function show_unsubscribe_form($profile) { - common_element_start('form', array('id' => 'unsubscribe', 'method' => 'post', - 'action' => common_local_url('unsubscribe'))); - common_hidden('token', common_session_token()); - common_element('input', array('id' => 'unsubscribeto', - 'name' => 'unsubscribeto', - 'type' => 'hidden', - 'value' => $profile->nickname)); - common_element('input', array('type' => 'submit', - 'class' => 'submit', - 'value' => _('Unsubscribe'))); - common_element_end('form'); - } - - function show_subscriptions($profile) { - global $config; - - $subs = DB_DataObject::factory('subscription'); - $subs->subscriber = $profile->id; - $subs->whereAdd('subscribed != ' . $profile->id); - - $subs->orderBy('created DESC'); - - # We ask for an extra one to know if we need to do another page - - $subs->limit(0, SUBSCRIPTIONS + 1); - - $subs_count = $subs->find(); - - common_element_start('div', array('id' => 'subscriptions')); - - common_element('h2', NULL, _('Subscriptions')); - - if ($subs_count > 0) { - - common_element_start('ul', array('id' => 'subscriptions_avatars')); - - for ($i = 0; $i < min($subs_count, SUBSCRIPTIONS); $i++) { - - if (!$subs->fetch()) { - common_debug('Weirdly, broke out of subscriptions loop early', __FILE__); - break; - } - - $other = Profile::staticGet($subs->subscribed); - - if (!$other) { - common_log_db_error($subs, 'SELECT', __FILE__); - continue; - } - - common_element_start('li', 'vcard'); - common_element_start('a', array('title' => ($other->fullname) ? - $other->fullname : - $other->nickname, - 'href' => $other->profileurl, - 'rel' => 'contact', - 'class' => 'subscription fn url')); - $avatar = $other->getAvatar(AVATAR_MINI_SIZE); - common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)), - 'width' => AVATAR_MINI_SIZE, - 'height' => AVATAR_MINI_SIZE, - 'class' => 'avatar mini photo', - 'alt' => ($other->fullname) ? - $other->fullname : - $other->nickname)); - common_element_end('a'); - common_element_end('li'); - } - - common_element_end('ul'); - } - - if ($subs_count > SUBSCRIPTIONS) { - common_element_start('p', array('id' => 'subscriptions_viewall')); - - common_element('a', array('href' => common_local_url('subscriptions', - array('nickname' => $profile->nickname)), - 'class' => 'moresubscriptions'), - _('All subscriptions')); - common_element_end('p'); - } - - common_element_end('div'); - } - - function show_statistics($profile) { - - // XXX: WORM cache this - $subs = DB_DataObject::factory('subscription'); - $subs->subscriber = $profile->id; - $subs_count = (int) $subs->count() - 1; - - $subbed = DB_DataObject::factory('subscription'); - $subbed->subscribed = $profile->id; - $subbed_count = (int) $subbed->count() - 1; - - $notices = DB_DataObject::factory('notice'); - $notices->profile_id = $profile->id; - $notice_count = (int) $notices->count(); - - common_element_start('div', 'statistics'); - common_element('h2', 'statistics', _('Statistics')); - - # Other stats...? - common_element_start('dl', 'statistics'); - common_element('dt', 'membersince', _('Member since')); - common_element('dd', 'membersince', date('j M Y', - strtotime($profile->created))); - - common_element_start('dt', 'subscriptions'); - common_element('a', array('href' => common_local_url('subscriptions', - array('nickname' => $profile->nickname))), - _('Subscriptions')); - common_element_end('dt'); - common_element('dd', 'subscriptions', (is_int($subs_count)) ? $subs_count : '0'); - common_element_start('dt', 'subscribers'); - common_element('a', array('href' => common_local_url('subscribers', - array('nickname' => $profile->nickname))), - _('Subscribers')); - common_element_end('dt'); - common_element('dd', 'subscribers', (is_int($subbed_count)) ? $subbed_count : '0'); - common_element('dt', 'notices', _('Notices')); - common_element('dd', 'notices', (is_int($notice_count)) ? $notice_count : '0'); - # XXX: link these to something - common_element('dt', 'tags', _('Tags')); - common_element_start('dd', 'tags'); - $tags = Profile_tag::getTags($profile->id, $profile->id); - - common_element_start('ul', 'tags xoxo'); - foreach ($tags as $tag) { - common_element_start('li'); - common_element('a', array('rel' => 'bookmark tag', - 'href' => common_local_url('peopletag', - array('tag' => $tag))), - $tag); - common_element_end('li'); - } - common_element_end('ul'); - common_element_end('dd'); - - common_element_end('dl'); - - common_element_end('div'); - } - - function show_notices($user) { - - $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - - $notice = $user->getNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); + common_element_end('ul'); + + common_element_end('div'); + + common_element_start('div', array('id' => 'profile_information')); + + if ($profile->fullname) { + common_element('h1', array('class' => 'fn'), $profile->fullname . ' (' . $profile->nickname . ')'); + } else { + common_element('h1', array('class' => 'fn nickname'), $profile->nickname); + } + + if ($profile->location) { + common_element('p', 'location', $profile->location); + } + if ($profile->bio) { + common_element('p', 'description note', $profile->bio); + } + if ($profile->homepage) { + common_element_start('p', 'website'); + common_element('a', array('href' => $profile->homepage, + 'rel' => 'me', 'class' => 'url'), + $profile->homepage); + common_element_end('p'); + } + + $this->show_statistics($profile); + + common_element_end('div'); + } + + function show_remote_subscribe_link($profile) { + $url = common_local_url('remotesubscribe', + array('nickname' => $profile->nickname)); + common_element('a', array('href' => $url, + 'id' => 'remotesubscribe'), + _('Subscribe')); + } + + function show_unsubscribe_form($profile) { + common_element_start('form', array('id' => 'unsubscribe', 'method' => 'post', + 'action' => common_local_url('unsubscribe'))); + common_hidden('token', common_session_token()); + common_element('input', array('id' => 'unsubscribeto', + 'name' => 'unsubscribeto', + 'type' => 'hidden', + 'value' => $profile->nickname)); + common_element('input', array('type' => 'submit', + 'class' => 'submit', + 'value' => _('Unsubscribe'))); + common_element_end('form'); + } + + function show_subscriptions($profile) { + global $config; + + $subs = DB_DataObject::factory('subscription'); + $subs->subscriber = $profile->id; + $subs->whereAdd('subscribed != ' . $profile->id); + + $subs->orderBy('created DESC'); + + # We ask for an extra one to know if we need to do another page + + $subs->limit(0, SUBSCRIPTIONS + 1); + + $subs_count = $subs->find(); + + common_element_start('div', array('id' => 'subscriptions')); + + common_element('h2', NULL, _('Subscriptions')); + + if ($subs_count > 0) { + + common_element_start('ul', array('id' => 'subscriptions_avatars')); + + for ($i = 0; $i < min($subs_count, SUBSCRIPTIONS); $i++) { + + if (!$subs->fetch()) { + common_debug('Weirdly, broke out of subscriptions loop early', __FILE__); + break; + } + + $other = Profile::staticGet($subs->subscribed); + + if (!$other) { + common_log_db_error($subs, 'SELECT', __FILE__); + continue; + } + + common_element_start('li', 'vcard'); + common_element_start('a', array('title' => ($other->fullname) ? + $other->fullname : + $other->nickname, + 'href' => $other->profileurl, + 'rel' => 'contact', + 'class' => 'subscription fn url')); + $avatar = $other->getAvatar(AVATAR_MINI_SIZE); + common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)), + 'width' => AVATAR_MINI_SIZE, + 'height' => AVATAR_MINI_SIZE, + 'class' => 'avatar mini photo', + 'alt' => ($other->fullname) ? + $other->fullname : + $other->nickname)); + common_element_end('a'); + common_element_end('li'); + } + + common_element_end('ul'); + } + + if ($subs_count > SUBSCRIPTIONS) { + common_element_start('p', array('id' => 'subscriptions_viewall')); + + common_element('a', array('href' => common_local_url('subscriptions', + array('nickname' => $profile->nickname)), + 'class' => 'moresubscriptions'), + _('All subscriptions')); + common_element_end('p'); + } + + common_element_end('div'); + } + + function show_statistics($profile) { + + // XXX: WORM cache this + $subs = DB_DataObject::factory('subscription'); + $subs->subscriber = $profile->id; + $subs_count = (int) $subs->count() - 1; + + $subbed = DB_DataObject::factory('subscription'); + $subbed->subscribed = $profile->id; + $subbed_count = (int) $subbed->count() - 1; + + $notices = DB_DataObject::factory('notice'); + $notices->profile_id = $profile->id; + $notice_count = (int) $notices->count(); + + common_element_start('div', 'statistics'); + common_element('h2', 'statistics', _('Statistics')); + + # Other stats...? + common_element_start('dl', 'statistics'); + common_element('dt', 'membersince', _('Member since')); + common_element('dd', 'membersince', date('j M Y', + strtotime($profile->created))); + + common_element_start('dt', 'subscriptions'); + common_element('a', array('href' => common_local_url('subscriptions', + array('nickname' => $profile->nickname))), + _('Subscriptions')); + common_element_end('dt'); + common_element('dd', 'subscriptions', (is_int($subs_count)) ? $subs_count : '0'); + common_element_start('dt', 'subscribers'); + common_element('a', array('href' => common_local_url('subscribers', + array('nickname' => $profile->nickname))), + _('Subscribers')); + common_element_end('dt'); + common_element('dd', 'subscribers', (is_int($subbed_count)) ? $subbed_count : '0'); + common_element('dt', 'notices', _('Notices')); + common_element('dd', 'notices', (is_int($notice_count)) ? $notice_count : '0'); + # XXX: link these to something + common_element('dt', 'tags', _('Tags')); + common_element_start('dd', 'tags'); + $tags = Profile_tag::getTags($profile->id, $profile->id); + + common_element_start('ul', 'tags xoxo'); + foreach ($tags as $tag) { + common_element_start('li'); + common_element('a', array('rel' => 'bookmark tag', + 'href' => common_local_url('peopletag', + array('tag' => $tag))), + $tag); + common_element_end('li'); + } + common_element_end('ul'); + common_element_end('dd'); + + common_element_end('dl'); + + common_element_end('div'); + } + + function show_notices($user) { + + $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + $notice = $user->getNotices(($page-1)*NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1); $pnl = new ProfileNoticeList($notice); $cnt = $pnl->show(); - common_pagination($page>1, $cnt>NOTICES_PER_PAGE, $page, - 'showstream', array('nickname' => $user->nickname)); - } - - function show_last_notice($profile) { - - common_element('h2', NULL, _('Currently')); - - $notice = $profile->getCurrentNotice(); - - if ($notice) { - # FIXME: URL, image, video, audio - common_element_start('p', array('class' => 'notice_current')); - if ($notice->rendered) { - common_raw($notice->rendered); - } else { - # XXX: may be some uncooked notices in the DB, - # we cook them right now. This can probably disappear in future - # versions (>> 0.4.x) - common_raw(common_render_content($notice->content, $notice)); - } - common_element_end('p'); - } - } + common_pagination($page>1, $cnt>NOTICES_PER_PAGE, $page, + 'showstream', array('nickname' => $user->nickname)); + } + + function show_last_notice($profile) { + + common_element('h2', NULL, _('Currently')); + + $notice = $profile->getCurrentNotice(); + + if ($notice) { + # FIXME: URL, image, video, audio + common_element_start('p', array('class' => 'notice_current')); + if ($notice->rendered) { + common_raw($notice->rendered); + } else { + # XXX: may be some uncooked notices in the DB, + # we cook them right now. This can probably disappear in future + # versions (>> 0.4.x) + common_raw(common_render_content($notice->content, $notice)); + } + common_element_end('p'); + } + } } # We don't show the author for a profile, since we already know who it is! diff --git a/_darcs/pristine/actions/smssettings.php b/_darcs/pristine/actions/smssettings.php index 5db26730a..506801e97 100644 --- a/_darcs/pristine/actions/smssettings.php +++ b/_darcs/pristine/actions/smssettings.php @@ -24,308 +24,308 @@ require_once(INSTALLDIR.'/actions/emailsettings.php'); class SmssettingsAction extends EmailsettingsAction { - function get_instructions() { - return _('You can receive SMS messages through email from %%site.name%%.'); - } - - function show_form($msg=NULL, $success=false) { - $user = common_current_user(); - $this->form_header(_('SMS Settings'), $msg, $success); - common_element_start('form', array('method' => 'post', - 'id' => 'smssettings', - 'action' => - common_local_url('smssettings'))); - common_hidden('token', common_session_token()); - common_element('h2', NULL, _('Address')); - - if ($user->sms) { - common_element_start('p'); - $carrier = $user->getCarrier(); - common_element('span', 'address confirmed', $user->sms . ' (' . $carrier->name . ')'); - common_element('span', 'input_instructions', - _('Current confirmed SMS-enabled phone number.')); - common_hidden('sms', $user->sms); - common_hidden('carrier', $user->carrier); - common_element_end('p'); - common_submit('remove', _('Remove')); - } else { - $confirm = $this->get_confirmation(); - if ($confirm) { - $carrier = Sms_carrier::staticGet($confirm->address_extra); - common_element_start('p'); - common_element('span', 'address unconfirmed', $confirm->address . ' (' . $carrier->name . ')'); - common_element('span', 'input_instructions', - _('Awaiting confirmation on this phone number.')); - common_hidden('sms', $confirm->address); - common_hidden('carrier', $confirm->address_extra); - common_element_end('p'); - common_submit('cancel', _('Cancel')); - common_input('code', _('Confirmation code'), NULL, - _('Enter the code you received on your phone.')); - common_submit('confirm', _('Confirm')); - } else { - common_input('sms', _('SMS Phone number'), - ($this->arg('sms')) ? $this->arg('sms') : NULL, - _('Phone number, no punctuation or spaces, with area code')); - $this->carrier_select(); - common_submit('add', _('Add')); - } - } - - if ($user->sms) { - common_element('h2', NULL, _('Incoming email')); - - if ($user->incomingemail) { - common_element_start('p'); - common_element('span', 'address', $user->incomingemail); - common_element('span', 'input_instructions', - _('Send email to this address to post new notices.')); - common_element_end('p'); - common_submit('removeincoming', _('Remove')); - } - - common_element_start('p'); - common_element('span', 'input_instructions', - _('Make a new email address for posting to; cancels the old one.')); - common_element_end('p'); - common_submit('newincoming', _('New')); - } - - common_element('h2', NULL, _('Preferences')); - - common_checkbox('smsnotify', - _('Send me notices through SMS; I understand I may incur exorbitant charges from my carrier.'), - $user->smsnotify); - - common_submit('save', _('Save')); - - common_element_end('form'); - common_show_footer(); - } - - function get_confirmation() { - $user = common_current_user(); - $confirm = new Confirm_address(); - $confirm->user_id = $user->id; - $confirm->address_type = 'sms'; - if ($confirm->find(TRUE)) { - return $confirm; - } else { - return NULL; - } - } - - function handle_post() { - - # CSRF protection - - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - if ($this->arg('save')) { - $this->save_preferences(); - } else if ($this->arg('add')) { - $this->add_address(); - } else if ($this->arg('cancel')) { - $this->cancel_confirmation(); - } else if ($this->arg('remove')) { - $this->remove_address(); - } else if ($this->arg('removeincoming')) { - $this->remove_incoming(); - } else if ($this->arg('newincoming')) { - $this->new_incoming(); - } else if ($this->arg('confirm')) { - $this->confirm_code(); - } else { - $this->show_form(_('Unexpected form submission.')); - } - } - - function save_preferences() { - - $smsnotify = $this->boolean('smsnotify'); - - $user = common_current_user(); - - assert(!is_null($user)); # should already be checked - - $user->query('BEGIN'); - - $original = clone($user); - - $user->smsnotify = $smsnotify; - - $result = $user->update($original); - - if ($result === FALSE) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } - - $user->query('COMMIT'); - - $this->show_form(_('Preferences saved.'), true); - } - - function add_address() { - - $user = common_current_user(); - - $sms = $this->trimmed('sms'); - $carrier_id = $this->trimmed('carrier'); - - # Some validation - - if (!$sms) { - $this->show_form(_('No phone number.')); - return; - } - - if (!$carrier_id) { - $this->show_form(_('No carrier selected.')); - return; - } - - $sms = common_canonical_sms($sms); - - if ($user->sms == $sms) { - $this->show_form(_('That is already your phone number.')); - return; - } else if ($this->sms_exists($sms)) { - $this->show_form(_('That phone number already belongs to another user.')); - return; - } - - $confirm = new Confirm_address(); - $confirm->address = $sms; - $confirm->address_extra = $carrier_id; - $confirm->address_type = 'sms'; - $confirm->user_id = $user->id; - $confirm->code = common_confirmation_code(40); - - $result = $confirm->insert(); - - if ($result === FALSE) { - common_log_db_error($confirm, 'INSERT', __FILE__); - common_server_error(_('Couldn\'t insert confirmation code.')); - return; - } - - $carrier = Sms_carrier::staticGet($carrier_id); - - mail_confirm_sms($confirm->code, - $user->nickname, - $carrier->toEmailAddress($sms)); - - $msg = _('A confirmation code was sent to the phone number you added. Check your inbox (and spam box!) for the code and instructions on how to use it.'); - - $this->show_form($msg, TRUE); - } - - function cancel_confirmation() { - - $sms = $this->trimmed('sms'); - $carrier = $this->trimmed('carrier'); - - $confirm = $this->get_confirmation(); - - if (!$confirm) { - $this->show_form(_('No pending confirmation to cancel.')); - return; - } - if ($confirm->address != $sms) { - $this->show_form(_('That is the wrong confirmation number.')); - return; - } + function get_instructions() { + return _('You can receive SMS messages through email from %%site.name%%.'); + } + + function show_form($msg=NULL, $success=false) { + $user = common_current_user(); + $this->form_header(_('SMS Settings'), $msg, $success); + common_element_start('form', array('method' => 'post', + 'id' => 'smssettings', + 'action' => + common_local_url('smssettings'))); + common_hidden('token', common_session_token()); + common_element('h2', NULL, _('Address')); + + if ($user->sms) { + common_element_start('p'); + $carrier = $user->getCarrier(); + common_element('span', 'address confirmed', $user->sms . ' (' . $carrier->name . ')'); + common_element('span', 'input_instructions', + _('Current confirmed SMS-enabled phone number.')); + common_hidden('sms', $user->sms); + common_hidden('carrier', $user->carrier); + common_element_end('p'); + common_submit('remove', _('Remove')); + } else { + $confirm = $this->get_confirmation(); + if ($confirm) { + $carrier = Sms_carrier::staticGet($confirm->address_extra); + common_element_start('p'); + common_element('span', 'address unconfirmed', $confirm->address . ' (' . $carrier->name . ')'); + common_element('span', 'input_instructions', + _('Awaiting confirmation on this phone number.')); + common_hidden('sms', $confirm->address); + common_hidden('carrier', $confirm->address_extra); + common_element_end('p'); + common_submit('cancel', _('Cancel')); + common_input('code', _('Confirmation code'), NULL, + _('Enter the code you received on your phone.')); + common_submit('confirm', _('Confirm')); + } else { + common_input('sms', _('SMS Phone number'), + ($this->arg('sms')) ? $this->arg('sms') : NULL, + _('Phone number, no punctuation or spaces, with area code')); + $this->carrier_select(); + common_submit('add', _('Add')); + } + } + + if ($user->sms) { + common_element('h2', NULL, _('Incoming email')); + + if ($user->incomingemail) { + common_element_start('p'); + common_element('span', 'address', $user->incomingemail); + common_element('span', 'input_instructions', + _('Send email to this address to post new notices.')); + common_element_end('p'); + common_submit('removeincoming', _('Remove')); + } + + common_element_start('p'); + common_element('span', 'input_instructions', + _('Make a new email address for posting to; cancels the old one.')); + common_element_end('p'); + common_submit('newincoming', _('New')); + } + + common_element('h2', NULL, _('Preferences')); + + common_checkbox('smsnotify', + _('Send me notices through SMS; I understand I may incur exorbitant charges from my carrier.'), + $user->smsnotify); + + common_submit('save', _('Save')); + + common_element_end('form'); + common_show_footer(); + } + + function get_confirmation() { + $user = common_current_user(); + $confirm = new Confirm_address(); + $confirm->user_id = $user->id; + $confirm->address_type = 'sms'; + if ($confirm->find(TRUE)) { + return $confirm; + } else { + return NULL; + } + } + + function handle_post() { + + # CSRF protection + + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + if ($this->arg('save')) { + $this->save_preferences(); + } else if ($this->arg('add')) { + $this->add_address(); + } else if ($this->arg('cancel')) { + $this->cancel_confirmation(); + } else if ($this->arg('remove')) { + $this->remove_address(); + } else if ($this->arg('removeincoming')) { + $this->remove_incoming(); + } else if ($this->arg('newincoming')) { + $this->new_incoming(); + } else if ($this->arg('confirm')) { + $this->confirm_code(); + } else { + $this->show_form(_('Unexpected form submission.')); + } + } + + function save_preferences() { + + $smsnotify = $this->boolean('smsnotify'); + + $user = common_current_user(); + + assert(!is_null($user)); # should already be checked + + $user->query('BEGIN'); + + $original = clone($user); + + $user->smsnotify = $smsnotify; + + $result = $user->update($original); + + if ($result === FALSE) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } + + $user->query('COMMIT'); + + $this->show_form(_('Preferences saved.'), true); + } + + function add_address() { + + $user = common_current_user(); + + $sms = $this->trimmed('sms'); + $carrier_id = $this->trimmed('carrier'); + + # Some validation + + if (!$sms) { + $this->show_form(_('No phone number.')); + return; + } + + if (!$carrier_id) { + $this->show_form(_('No carrier selected.')); + return; + } + + $sms = common_canonical_sms($sms); + + if ($user->sms == $sms) { + $this->show_form(_('That is already your phone number.')); + return; + } else if ($this->sms_exists($sms)) { + $this->show_form(_('That phone number already belongs to another user.')); + return; + } + + $confirm = new Confirm_address(); + $confirm->address = $sms; + $confirm->address_extra = $carrier_id; + $confirm->address_type = 'sms'; + $confirm->user_id = $user->id; + $confirm->code = common_confirmation_code(40); + + $result = $confirm->insert(); + + if ($result === FALSE) { + common_log_db_error($confirm, 'INSERT', __FILE__); + common_server_error(_('Couldn\'t insert confirmation code.')); + return; + } + + $carrier = Sms_carrier::staticGet($carrier_id); + + mail_confirm_sms($confirm->code, + $user->nickname, + $carrier->toEmailAddress($sms)); + + $msg = _('A confirmation code was sent to the phone number you added. Check your inbox (and spam box!) for the code and instructions on how to use it.'); + + $this->show_form($msg, TRUE); + } + + function cancel_confirmation() { + + $sms = $this->trimmed('sms'); + $carrier = $this->trimmed('carrier'); + + $confirm = $this->get_confirmation(); + + if (!$confirm) { + $this->show_form(_('No pending confirmation to cancel.')); + return; + } + if ($confirm->address != $sms) { + $this->show_form(_('That is the wrong confirmation number.')); + return; + } $result = $confirm->delete(); if (!$result) { - common_log_db_error($confirm, 'DELETE', __FILE__); + common_log_db_error($confirm, 'DELETE', __FILE__); $this->server_error(_('Couldn\'t delete email confirmation.')); return; } $this->show_form(_('Confirmation cancelled.'), TRUE); - } - - function remove_address() { - - $user = common_current_user(); - $sms = $this->arg('sms'); - $carrier = $this->arg('carrier'); - - # Maybe an old tab open...? - - if ($user->sms != $sms) { - $this->show_form(_('That is not your phone number.')); - return; - } - - $user->query('BEGIN'); - $original = clone($user); - $user->sms = NULL; - $user->carrier = NULL; - $user->smsemail = NULL; - $result = $user->updateKeys($original); - if (!$result) { - common_log_db_error($user, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t update user.')); - return; - } - $user->query('COMMIT'); - - $this->show_form(_('The address was removed.'), TRUE); - } - - function sms_exists($sms) { - $user = common_current_user(); - $other = User::staticGet('sms', $sms); - if (!$other) { - return false; - } else { - return $other->id != $user->id; - } - } - - function carrier_select() { - $carrier = new Sms_carrier(); - $cnt = $carrier->find(); - - common_element_start('p'); - common_element('label', array('for' => 'carrier')); - common_element_start('select', array('name' => 'carrier', - 'id' => 'carrier')); - common_element('option', array('value' => 0), - _('Select a carrier')); - while ($carrier->fetch()) { - common_element('option', array('value' => $carrier->id), - $carrier->name); - } - common_element_end('select'); - common_element_end('p'); - common_element('span', 'input_instructions', - sprintf(_('Mobile carrier for your phone. '. - 'If you know a carrier that accepts ' . - 'SMS over email but isn\'t listed here, ' . - 'send email to let us know at %s.'), - common_config('site', 'email'))); - } - - function confirm_code() { - - $code = $this->trimmed('code'); - - if (!$code) { - $this->show_form(_('No code entered')); - return; - } - - common_redirect(common_local_url('confirmaddress', - array('code' => $code))); - } + } + + function remove_address() { + + $user = common_current_user(); + $sms = $this->arg('sms'); + $carrier = $this->arg('carrier'); + + # Maybe an old tab open...? + + if ($user->sms != $sms) { + $this->show_form(_('That is not your phone number.')); + return; + } + + $user->query('BEGIN'); + $original = clone($user); + $user->sms = NULL; + $user->carrier = NULL; + $user->smsemail = NULL; + $result = $user->updateKeys($original); + if (!$result) { + common_log_db_error($user, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t update user.')); + return; + } + $user->query('COMMIT'); + + $this->show_form(_('The address was removed.'), TRUE); + } + + function sms_exists($sms) { + $user = common_current_user(); + $other = User::staticGet('sms', $sms); + if (!$other) { + return false; + } else { + return $other->id != $user->id; + } + } + + function carrier_select() { + $carrier = new Sms_carrier(); + $cnt = $carrier->find(); + + common_element_start('p'); + common_element('label', array('for' => 'carrier')); + common_element_start('select', array('name' => 'carrier', + 'id' => 'carrier')); + common_element('option', array('value' => 0), + _('Select a carrier')); + while ($carrier->fetch()) { + common_element('option', array('value' => $carrier->id), + $carrier->name); + } + common_element_end('select'); + common_element_end('p'); + common_element('span', 'input_instructions', + sprintf(_('Mobile carrier for your phone. '. + 'If you know a carrier that accepts ' . + 'SMS over email but isn\'t listed here, ' . + 'send email to let us know at %s.'), + common_config('site', 'email'))); + } + + function confirm_code() { + + $code = $this->trimmed('code'); + + if (!$code) { + $this->show_form(_('No code entered')); + return; + } + + common_redirect(common_local_url('confirmaddress', + array('code' => $code))); + } } diff --git a/_darcs/pristine/actions/subedit.php b/_darcs/pristine/actions/subedit.php index e7505e3fe..1d095ab9a 100644 --- a/_darcs/pristine/actions/subedit.php +++ b/_darcs/pristine/actions/subedit.php @@ -32,12 +32,12 @@ class SubeditAction extends Action { return false; } - $token = $this->trimmed('token'); + $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } $id = $this->trimmed('profile'); diff --git a/_darcs/pristine/actions/subscribe.php b/_darcs/pristine/actions/subscribe.php index 64abda004..c94c4d7eb 100644 --- a/_darcs/pristine/actions/subscribe.php +++ b/_darcs/pristine/actions/subscribe.php @@ -21,58 +21,58 @@ if (!defined('LACONICA')) { exit(1); } class SubscribeAction extends Action { - function handle($args) { - parent::handle($args); + function handle($args) { + parent::handle($args); - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - return; - } + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + return; + } - $user = common_current_user(); + $user = common_current_user(); - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname))); - return; - } + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname))); + return; + } - # CSRF protection + # CSRF protection - $token = $this->trimmed('token'); + $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } - $other_id = $this->arg('subscribeto'); + $other_id = $this->arg('subscribeto'); $other = User::staticGet('id', $other_id); if (!$other) { - $this->client_error(_('Not a local user.')); - return; + $this->client_error(_('Not a local user.')); + return; } - $result = subs_subscribe_to($user, $other); + $result = subs_subscribe_to($user, $other); - if($result != true) { - common_user_error($result); - return; - } + if($result != true) { + common_user_error($result); + return; + } - if ($this->boolean('ajax')) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Subscribed')); - common_element_end('head'); - common_element_start('body'); - common_unsubscribe_form($other->getProfile()); - common_element_end('body'); - common_element_end('html'); - } else { - common_redirect(common_local_url('subscriptions', array('nickname' => - $user->nickname))); + if ($this->boolean('ajax')) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Subscribed')); + common_element_end('head'); + common_element_start('body'); + common_unsubscribe_form($other->getProfile()); + common_element_end('body'); + common_element_end('html'); + } else { + common_redirect(common_local_url('subscriptions', array('nickname' => + $user->nickname))); } - } + } } diff --git a/_darcs/pristine/actions/subscribers.php b/_darcs/pristine/actions/subscribers.php index ae52526e1..b9ca92af3 100644 --- a/_darcs/pristine/actions/subscribers.php +++ b/_darcs/pristine/actions/subscribers.php @@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/gallery.php'); class SubscribersAction extends GalleryAction { - function gallery_type() { - return _('Subscribers'); - } - - function get_instructions(&$profile) { - $user =& common_current_user(); - if ($user && ($user->id == $profile->id)) { - return _('These are the people who listen to your notices.'); - } else { - return sprintf(_('These are the people who listen to %s\'s notices.'), $profile->nickname); - } - } - - function fields() { - return array('subscriber', 'subscribed'); - } - - function div_class() { - return 'subscribers'; - } - - function get_other(&$subs) { - return $subs->subscriber; - } + function gallery_type() { + return _('Subscribers'); + } + + function get_instructions(&$profile) { + $user =& common_current_user(); + if ($user && ($user->id == $profile->id)) { + return _('These are the people who listen to your notices.'); + } else { + return sprintf(_('These are the people who listen to %s\'s notices.'), $profile->nickname); + } + } + + function fields() { + return array('subscriber', 'subscribed'); + } + + function div_class() { + return 'subscribers'; + } + + function get_other(&$subs) { + return $subs->subscriber; + } function profile_list_class() { return 'SubscribersList'; diff --git a/_darcs/pristine/actions/subscriptions.php b/_darcs/pristine/actions/subscriptions.php index f518a1f92..c24f23a07 100644 --- a/_darcs/pristine/actions/subscriptions.php +++ b/_darcs/pristine/actions/subscriptions.php @@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/gallery.php'); class SubscriptionsAction extends GalleryAction { - function gallery_type() { - return _('Subscriptions'); - } + function gallery_type() { + return _('Subscriptions'); + } - function get_instructions(&$profile) { - $user =& common_current_user(); - if ($user && ($user->id == $profile->id)) { - return _('These are the people whose notices you listen to.'); - } else { - return sprintf(_('These are the people whose notices %s listens to.'), $profile->nickname); - } - } + function get_instructions(&$profile) { + $user =& common_current_user(); + if ($user && ($user->id == $profile->id)) { + return _('These are the people whose notices you listen to.'); + } else { + return sprintf(_('These are the people whose notices %s listens to.'), $profile->nickname); + } + } - function fields() { - return array('subscribed', 'subscriber'); - } + function fields() { + return array('subscribed', 'subscriber'); + } - function div_class() { - return 'subscriptions'; - } + function div_class() { + return 'subscriptions'; + } - function get_other(&$subs) { - return $subs->subscribed; - } + function get_other(&$subs) { + return $subs->subscribed; + } function profile_list_class() { return 'SubscriptionsList'; @@ -57,8 +57,8 @@ class SubscriptionsList extends ProfileList { function show_owner_controls($profile) { - $sub = Subscription::pkeyGet(array('subscriber' => $this->owner->id, - 'subscribed' => $profile->id)); + $sub = Subscription::pkeyGet(array('subscriber' => $this->owner->id, + 'subscribed' => $profile->id)); if (!$sub) { return; } diff --git a/_darcs/pristine/actions/sup.php b/_darcs/pristine/actions/sup.php index 887017b2a..3c9cbea2c 100644 --- a/_darcs/pristine/actions/sup.php +++ b/_darcs/pristine/actions/sup.php @@ -20,62 +20,62 @@ if (!defined('LACONICA')) { exit(1); } class SupAction extends Action { - - function handle($args) { - - parent::handle($args); - - $seconds = $this->trimmed('seconds'); - - if (!$seconds) { - $seconds = 15; - } + + function handle($args) { + + parent::handle($args); + + $seconds = $this->trimmed('seconds'); + + if (!$seconds) { + $seconds = 15; + } - $updates = $this->get_updates($seconds); - - header('Content-Type: application/json; charset=utf-8'); - - print json_encode(array('updated_time' => date('c'), - 'since_time' => date('c', time() - $seconds), - 'available_periods' => $this->available_periods(), - 'period' => $seconds, - 'updates' => $updates)); - } - - function available_periods() { - static $periods = array(86400, 43200, 21600, 7200, - 3600, 1800, 600, 300, 120, - 60, 30, 15); - $available = array(); - foreach ($periods as $period) { - $available[$period] = common_local_url('sup', - array('seconds' => $period)); - } - - return $available; - } - - function get_updates($seconds) { - $notice = new Notice(); + $updates = $this->get_updates($seconds); + + header('Content-Type: application/json; charset=utf-8'); + + print json_encode(array('updated_time' => date('c'), + 'since_time' => date('c', time() - $seconds), + 'available_periods' => $this->available_periods(), + 'period' => $seconds, + 'updates' => $updates)); + } + + function available_periods() { + static $periods = array(86400, 43200, 21600, 7200, + 3600, 1800, 600, 300, 120, + 60, 30, 15); + $available = array(); + foreach ($periods as $period) { + $available[$period] = common_local_url('sup', + array('seconds' => $period)); + } + + return $available; + } + + function get_updates($seconds) { + $notice = new Notice(); - # XXX: cache this. Depends on how big this protocol becomes; - # Re-doing this query every 15 seconds isn't the end of the world. + # XXX: cache this. Depends on how big this protocol becomes; + # Re-doing this query every 15 seconds isn't the end of the world. - $notice->query('SELECT profile_id, max(id) AS max_id ' . - 'FROM notice ' . - 'WHERE created > (now() - ' . $seconds . ') ' . - 'GROUP BY profile_id'); - - $updates = array(); - - while ($notice->fetch()) { - $updates[] = array($notice->profile_id, $notice->max_id); - } - - return $updates; - } - - function is_readonly() { - return true; - } + $notice->query('SELECT profile_id, max(id) AS max_id ' . + 'FROM notice ' . + 'WHERE created > (now() - ' . $seconds . ') ' . + 'GROUP BY profile_id'); + + $updates = array(); + + while ($notice->fetch()) { + $updates[] = array($notice->profile_id, $notice->max_id); + } + + return $updates; + } + + function is_readonly() { + return true; + } } diff --git a/_darcs/pristine/actions/tag.php b/_darcs/pristine/actions/tag.php index 25cc853c4..1325b85a5 100644 --- a/_darcs/pristine/actions/tag.php +++ b/_darcs/pristine/actions/tag.php @@ -24,142 +24,142 @@ define('TAGS_PER_PAGE', 100); class TagAction extends StreamAction { - function handle($args) { - - parent::handle($args); - - # Looks like we're good; show the header - - if (isset($args['tag']) && $args['tag']) { - $tag = $args['tag']; - common_show_header(sprintf(_("Notices tagged with %s"), $tag), - array($this, 'show_header'), $tag, - array($this, 'show_top')); - $this->show_notices($tag); - } else { - common_show_header(_("Tags"), - array($this, 'show_header'), '', - array($this, 'show_top')); - $this->show_tags(); - } - - common_show_footer(); - } - - function show_header($tag = false) { - if ($tag) { - common_element('link', array('rel' => 'alternate', - 'href' => common_local_url('tagrss', array('tag' => $tag)), - 'type' => 'application/rss+xml', - 'title' => sprintf(_('Feed for tag %s'), $tag))); - } - } - - function get_instructions() { - return _('Showing most popular tags from the last week'); - } - - function show_top($tag = false) { - if (!$tag) { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - $this->public_views_menu(); - } - else { - $this->show_feeds_list(array(0=>array('href'=>common_local_url('tagrss'), - 'type' => 'rss', - 'version' => 'RSS 1.0', - 'item' => 'tagrss'))); - } - } - - function show_tags() - { - # This should probably be cached rather than recalculated - $tags = DB_DataObject::factory('Notice_tag'); - - #Need to clear the selection and then only re-add the field - #we are grouping by, otherwise it's not a valid 'group by' - #even though MySQL seems to let it slide... - $tags->selectAdd(); - $tags->selectAdd('tag'); - - #Add the aggregated columns... - $tags->selectAdd('max(notice_id) as last_notice_id'); - if(common_config('db','type')=='pgsql') { - $calc='sum(exp(-extract(epoch from (now()-created))/%s)) as weight'; - } else { - $calc='sum(exp(-(now() - created)/%s)) as weight'; - } - $tags->selectAdd(sprintf($calc, common_config('tag', 'dropoff'))); - $tags->groupBy('tag'); - $tags->orderBy('weight DESC'); - - # $tags->whereAdd('created > "' . strftime('%Y-%m-%d %H:%M:%S', strtotime('-1 MONTH')) . '"'); - - $tags->limit(TAGS_PER_PAGE); - - $cnt = $tags->find(); - - if ($cnt > 0) { - common_element_start('p', 'tagcloud'); - - $tw = array(); - $sum = 0; - while ($tags->fetch()) { - $tw[$tags->tag] = $tags->weight; - $sum += $tags->weight; - } - - ksort($tw); - - foreach ($tw as $tag => $weight) { - $this->show_tag($tag, $weight, $weight/$sum); - } - - common_element_end('p'); - } - } - - function show_tag($tag, $weight, $relative) { - - # XXX: these should probably tune to the size of the site - if ($relative > 0.1) { - $cls = 'largest'; - } else if ($relative > 0.05) { - $cls = 'verylarge'; - } else if ($relative > 0.02) { - $cls = 'large'; - } else if ($relative > 0.01) { - $cls = 'medium'; - } else if ($relative > 0.005) { - $cls = 'small'; - } else if ($relative > 0.002) { - $cls = 'verysmall'; - } else { - $cls = 'smallest'; - } - - common_element('a', array('class' => "$cls weight-$weight relative-$relative", - 'href' => common_local_url('tag', array('tag' => $tag))), - $tag); - common_text(' '); - } - - function show_notices($tag) { - - $cnt = 0; - - $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; - - $notice = Notice_tag::getStream($tag, (($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1); + function handle($args) { + + parent::handle($args); + + # Looks like we're good; show the header + + if (isset($args['tag']) && $args['tag']) { + $tag = $args['tag']; + common_show_header(sprintf(_("Notices tagged with %s"), $tag), + array($this, 'show_header'), $tag, + array($this, 'show_top')); + $this->show_notices($tag); + } else { + common_show_header(_("Tags"), + array($this, 'show_header'), '', + array($this, 'show_top')); + $this->show_tags(); + } + + common_show_footer(); + } + + function show_header($tag = false) { + if ($tag) { + common_element('link', array('rel' => 'alternate', + 'href' => common_local_url('tagrss', array('tag' => $tag)), + 'type' => 'application/rss+xml', + 'title' => sprintf(_('Feed for tag %s'), $tag))); + } + } + + function get_instructions() { + return _('Showing most popular tags from the last week'); + } + + function show_top($tag = false) { + if (!$tag) { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + $this->public_views_menu(); + } + else { + $this->show_feeds_list(array(0=>array('href'=>common_local_url('tagrss'), + 'type' => 'rss', + 'version' => 'RSS 1.0', + 'item' => 'tagrss'))); + } + } + + function show_tags() + { + # This should probably be cached rather than recalculated + $tags = DB_DataObject::factory('Notice_tag'); + + #Need to clear the selection and then only re-add the field + #we are grouping by, otherwise it's not a valid 'group by' + #even though MySQL seems to let it slide... + $tags->selectAdd(); + $tags->selectAdd('tag'); + + #Add the aggregated columns... + $tags->selectAdd('max(notice_id) as last_notice_id'); + if(common_config('db','type')=='pgsql') { + $calc='sum(exp(-extract(epoch from (now()-created))/%s)) as weight'; + } else { + $calc='sum(exp(-(now() - created)/%s)) as weight'; + } + $tags->selectAdd(sprintf($calc, common_config('tag', 'dropoff'))); + $tags->groupBy('tag'); + $tags->orderBy('weight DESC'); + + # $tags->whereAdd('created > "' . strftime('%Y-%m-%d %H:%M:%S', strtotime('-1 MONTH')) . '"'); + + $tags->limit(TAGS_PER_PAGE); + + $cnt = $tags->find(); + + if ($cnt > 0) { + common_element_start('p', 'tagcloud'); + + $tw = array(); + $sum = 0; + while ($tags->fetch()) { + $tw[$tags->tag] = $tags->weight; + $sum += $tags->weight; + } + + ksort($tw); + + foreach ($tw as $tag => $weight) { + $this->show_tag($tag, $weight, $weight/$sum); + } + + common_element_end('p'); + } + } + + function show_tag($tag, $weight, $relative) { + + # XXX: these should probably tune to the size of the site + if ($relative > 0.1) { + $cls = 'largest'; + } else if ($relative > 0.05) { + $cls = 'verylarge'; + } else if ($relative > 0.02) { + $cls = 'large'; + } else if ($relative > 0.01) { + $cls = 'medium'; + } else if ($relative > 0.005) { + $cls = 'small'; + } else if ($relative > 0.002) { + $cls = 'verysmall'; + } else { + $cls = 'smallest'; + } + + common_element('a', array('class' => "$cls weight-$weight relative-$relative", + 'href' => common_local_url('tag', array('tag' => $tag))), + $tag); + common_text(' '); + } + + function show_notices($tag) { + + $cnt = 0; + + $page = ($this->arg('page')) ? ($this->arg('page')+0) : 1; + + $notice = Notice_tag::getStream($tag, (($page-1)*NOTICES_PER_PAGE), NOTICES_PER_PAGE + 1); $cnt = $this->show_notice_list($notice); - common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, - $page, 'tag', array('tag' => $tag)); - } + common_pagination($page > 1, $cnt > NOTICES_PER_PAGE, + $page, 'tag', array('tag' => $tag)); + } } diff --git a/_darcs/pristine/actions/tagother.php b/_darcs/pristine/actions/tagother.php index a4449dd69..832671ae7 100644 --- a/_darcs/pristine/actions/tagother.php +++ b/_darcs/pristine/actions/tagother.php @@ -23,171 +23,171 @@ require_once(INSTALLDIR.'/lib/settingsaction.php'); class TagotherAction extends Action { - function handle($args) { - - parent::handle($args); - - if (!common_logged_in()) { - $this->client_error(_('Not logged in'), 403); - return; - } - - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - $this->save_tags(); - } else { - $id = $this->trimmed('id'); - if (!$id) { - $this->client_error(_('No id argument.')); - return; - } - $profile = Profile::staticGet('id', $id); - if (!$profile) { - $this->client_error(_('No profile with that ID.')); - return; - } - $this->show_form($profile); - } - } - - function show_form($profile, $error=NULL) { - - $user = common_current_user(); - - common_show_header(_('Tag a person'), - NULL, array($profile, $error), array($this, 'show_top')); - - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - - common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE), - 'class' => 'avatar stream', - 'width' => AVATAR_PROFILE_SIZE, - 'height' => AVATAR_PROFILE_SIZE, - 'alt' => - ($profile->fullname) ? $profile->fullname : - $profile->nickname)); - - common_element('a', array('href' => $profile->profileurl, - 'class' => 'external profile nickname'), - $profile->nickname); - - if ($profile->fullname) { - common_element_start('div', 'fullname'); - if ($profile->homepage) { - common_element('a', array('href' => $profile->homepage), - $profile->fullname); - } else { - common_text($profile->fullname); - } - common_element_end('div'); - } - if ($profile->location) { - common_element('div', 'location', $profile->location); - } - if ($profile->bio) { - common_element('div', 'bio', $profile->bio); - } - - common_element_start('form', array('method' => 'post', - 'id' => 'tag_user', - 'name' => 'tagother', - 'action' => $this->self_url())); - common_hidden('token', common_session_token()); - common_hidden('id', $profile->id); - common_input('tags', _('Tags'), - ($this->arg('tags')) ? $this->arg('tags') : implode(' ', Profile_tag::getTags($user->id, $profile->id)), - _('Tags for this user (letters, numbers, -, ., and _), comma- or space- separated')); - - common_submit('save', _('Save')); - common_element_end('form'); - common_show_footer(); - - } - - function save_tags() { - - $id = $this->trimmed('id'); - $tagstring = $this->trimmed('tags'); - $token = $this->trimmed('token'); - - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - $profile = Profile::staticGet('id', $id); - - if (!$profile) { - $this->client_error(_('No such profile.')); - return; - } - - if (is_string($tagstring) && strlen($tagstring) > 0) { - - $tags = array_map('common_canonical_tag', - preg_split('/[\s,]+/', $tagstring)); - - foreach ($tags as $tag) { - if (!common_valid_profile_tag($tag)) { - $this->show_form($profile, sprintf(_('Invalid tag: "%s"'), $tag)); - return; - } - } - } else { - $tags = array(); - } - - $user = common_current_user(); - - if (!Subscription::pkeyGet(array('subscriber' => $user->id, - 'subscribed' => $profile->id)) && - !Subscription::pkeyGet(array('subscriber' => $profile->id, - 'subscribed' => $user->id))) - { - $this->client_error(_('You can only tag people you are subscribed to or who are subscribed to you.')); - return; - } - - $result = Profile_tag::setTags($user->id, $profile->id, $tags); - - if (!$result) { - $this->client_error(_('Could not save tags.')); - return; - } - - $action = $user->isSubscribed($profile) ? 'subscriptions' : 'subscribers'; - - if ($this->boolean('ajax')) { - common_start_html('text/xml'); - common_element_start('head'); - common_element('title', null, _('Tags')); - common_element_end('head'); - common_element_start('body'); - common_element_start('p', 'subtags'); - foreach ($tags as $tag) { - common_element('a', array('href' => common_local_url($action, - array('nickname' => $user->nickname, - 'tag' => $tag))), - $tag); - } - common_element_end('p'); - common_element_end('body'); - common_element_end('html'); - } else { - common_redirect(common_local_url($action, array('nickname' => - $user->nickname))); + function handle($args) { + + parent::handle($args); + + if (!common_logged_in()) { + $this->client_error(_('Not logged in'), 403); + return; + } + + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + $this->save_tags(); + } else { + $id = $this->trimmed('id'); + if (!$id) { + $this->client_error(_('No id argument.')); + return; + } + $profile = Profile::staticGet('id', $id); + if (!$profile) { + $this->client_error(_('No profile with that ID.')); + return; + } + $this->show_form($profile); + } + } + + function show_form($profile, $error=NULL) { + + $user = common_current_user(); + + common_show_header(_('Tag a person'), + NULL, array($profile, $error), array($this, 'show_top')); + + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + + common_element('img', array('src' => ($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_PROFILE_SIZE), + 'class' => 'avatar stream', + 'width' => AVATAR_PROFILE_SIZE, + 'height' => AVATAR_PROFILE_SIZE, + 'alt' => + ($profile->fullname) ? $profile->fullname : + $profile->nickname)); + + common_element('a', array('href' => $profile->profileurl, + 'class' => 'external profile nickname'), + $profile->nickname); + + if ($profile->fullname) { + common_element_start('div', 'fullname'); + if ($profile->homepage) { + common_element('a', array('href' => $profile->homepage), + $profile->fullname); + } else { + common_text($profile->fullname); + } + common_element_end('div'); + } + if ($profile->location) { + common_element('div', 'location', $profile->location); + } + if ($profile->bio) { + common_element('div', 'bio', $profile->bio); + } + + common_element_start('form', array('method' => 'post', + 'id' => 'tag_user', + 'name' => 'tagother', + 'action' => $this->self_url())); + common_hidden('token', common_session_token()); + common_hidden('id', $profile->id); + common_input('tags', _('Tags'), + ($this->arg('tags')) ? $this->arg('tags') : implode(' ', Profile_tag::getTags($user->id, $profile->id)), + _('Tags for this user (letters, numbers, -, ., and _), comma- or space- separated')); + + common_submit('save', _('Save')); + common_element_end('form'); + common_show_footer(); + + } + + function save_tags() { + + $id = $this->trimmed('id'); + $tagstring = $this->trimmed('tags'); + $token = $this->trimmed('token'); + + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + $profile = Profile::staticGet('id', $id); + + if (!$profile) { + $this->client_error(_('No such profile.')); + return; + } + + if (is_string($tagstring) && strlen($tagstring) > 0) { + + $tags = array_map('common_canonical_tag', + preg_split('/[\s,]+/', $tagstring)); + + foreach ($tags as $tag) { + if (!common_valid_profile_tag($tag)) { + $this->show_form($profile, sprintf(_('Invalid tag: "%s"'), $tag)); + return; + } + } + } else { + $tags = array(); + } + + $user = common_current_user(); + + if (!Subscription::pkeyGet(array('subscriber' => $user->id, + 'subscribed' => $profile->id)) && + !Subscription::pkeyGet(array('subscriber' => $profile->id, + 'subscribed' => $user->id))) + { + $this->client_error(_('You can only tag people you are subscribed to or who are subscribed to you.')); + return; + } + + $result = Profile_tag::setTags($user->id, $profile->id, $tags); + + if (!$result) { + $this->client_error(_('Could not save tags.')); + return; + } + + $action = $user->isSubscribed($profile) ? 'subscriptions' : 'subscribers'; + + if ($this->boolean('ajax')) { + common_start_html('text/xml'); + common_element_start('head'); + common_element('title', null, _('Tags')); + common_element_end('head'); + common_element_start('body'); + common_element_start('p', 'subtags'); + foreach ($tags as $tag) { + common_element('a', array('href' => common_local_url($action, + array('nickname' => $user->nickname, + 'tag' => $tag))), + $tag); + } + common_element_end('p'); + common_element_end('body'); + common_element_end('html'); + } else { + common_redirect(common_local_url($action, array('nickname' => + $user->nickname))); + } + } + + function show_top($arr = NULL) { + list($profile, $error) = $arr; + if ($error) { + common_element('p', 'error', $error); + } else { + common_element_start('div', 'instructions'); + common_element('p', NULL, + _('Use this form to add tags to your subscribers or subscriptions.')); + common_element_end('div'); } - } - - function show_top($arr = NULL) { - list($profile, $error) = $arr; - if ($error) { - common_element('p', 'error', $error); - } else { - common_element_start('div', 'instructions'); - common_element('p', NULL, - _('Use this form to add tags to your subscribers or subscriptions.')); - common_element_end('div'); - } - } + } } diff --git a/_darcs/pristine/actions/tagrss.php b/_darcs/pristine/actions/tagrss.php index 9187bdc87..45639fec4 100644 --- a/_darcs/pristine/actions/tagrss.php +++ b/_darcs/pristine/actions/tagrss.php @@ -25,41 +25,41 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class TagrssAction extends Rss10Action { - function init() { - $tag = $this->trimmed('tag'); - $this->tag = Notice_tag::staticGet('tag', $tag); + function init() { + $tag = $this->trimmed('tag'); + $this->tag = Notice_tag::staticGet('tag', $tag); - if (!$this->tag) { - common_user_error(_('No such tag.')); - return false; - } else { - return true; - } - } + if (!$this->tag) { + common_user_error(_('No such tag.')); + return false; + } else { + return true; + } + } - function get_notices($limit=0) { - $tag = $this->tag; + function get_notices($limit=0) { + $tag = $this->tag; - if (is_null($tag)) { - return NULL; - } + if (is_null($tag)) { + return NULL; + } - $notice = Notice_tag::getStream($tag->tag, 0, ($limit == 0) ? NOTICES_PER_PAGE : $limit); + $notice = Notice_tag::getStream($tag->tag, 0, ($limit == 0) ? NOTICES_PER_PAGE : $limit); - while ($notice->fetch()) { - $notices[] = clone($notice); - } + while ($notice->fetch()) { + $notices[] = clone($notice); + } - return $notices; - } + return $notices; + } - function get_channel() { - $tag = $this->tag->tag; + function get_channel() { + $tag = $this->tag->tag; - $c = array('url' => common_local_url('tagrss', array('tag' => $tagname)), - 'title' => $tagname, - 'link' => common_local_url('tagrss', array('tag' => $tagname)), - 'description' => sprintf(_('Microblog tagged with %s'), $tagname)); - return $c; - } + $c = array('url' => common_local_url('tagrss', array('tag' => $tagname)), + 'title' => $tagname, + 'link' => common_local_url('tagrss', array('tag' => $tagname)), + 'description' => sprintf(_('Microblog tagged with %s'), $tagname)); + return $c; + } } diff --git a/_darcs/pristine/actions/twitapiaccount.php b/_darcs/pristine/actions/twitapiaccount.php index f6e955828..b1caa3481 100644 --- a/_darcs/pristine/actions/twitapiaccount.php +++ b/_darcs/pristine/actions/twitapiaccount.php @@ -23,74 +23,74 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapiaccountAction extends TwitterapiAction { - function verify_credentials($args, $apidata) { - parent::handle($args); + function verify_credentials($args, $apidata) { + parent::handle($args); - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } - $this->show_extended_profile($apidata['user'], $apidata); - } + $this->show_extended_profile($apidata['user'], $apidata); + } - function end_session($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } + function end_session($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } - function update_location($args, $apidata) { - parent::handle($args); + function update_location($args, $apidata) { + parent::handle($args); - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); - return; - } + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); + return; + } - $location = trim($this->arg('location')); + $location = trim($this->arg('location')); - if (!is_null($location) && strlen($location) > 255) { + if (!is_null($location) && strlen($location) > 255) { - // XXX: But Twitter just truncates and runs with it. -- Zach - $this->client_error(_('That\'s too long. Max notice size is 255 chars.'), 406, $apidate['content-type']); - return; - } + // XXX: But Twitter just truncates and runs with it. -- Zach + $this->client_error(_('That\'s too long. Max notice size is 255 chars.'), 406, $apidate['content-type']); + return; + } - $user = $apidata['user']; - $profile = $user->getProfile(); + $user = $apidata['user']; + $profile = $user->getProfile(); - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } - $orig_profile = clone($profile); - $profile->location = $location; + $orig_profile = clone($profile); + $profile->location = $location; - $result = $profile->update($orig_profile); + $result = $profile->update($orig_profile); - if (!$result) { - common_log_db_error($profile, 'UPDATE', __FILE__); - common_server_error(_('Couldn\'t save profile.')); - return; - } + if (!$result) { + common_log_db_error($profile, 'UPDATE', __FILE__); + common_server_error(_('Couldn\'t save profile.')); + return; + } - common_broadcast_profile($profile); - $type = $apidata['content-type']; + common_broadcast_profile($profile); + $type = $apidata['content-type']; - $this->init_document($type); - $this->show_profile($profile, $type); - $this->end_document($type); - } + $this->init_document($type); + $this->show_profile($profile, $type); + $this->end_document($type); + } - function update_delivery_device($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } + function update_delivery_device($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } - function rate_limit_status($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } + function rate_limit_status($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/twitapiblocks.php b/_darcs/pristine/actions/twitapiblocks.php index 4852ff938..16b2e76bc 100644 --- a/_darcs/pristine/actions/twitapiblocks.php +++ b/_darcs/pristine/actions/twitapiblocks.php @@ -23,15 +23,15 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapiblocksAction extends TwitterapiAction { - function create($args, $apidata) { + function create($args, $apidata) { - parent::handle($args); + parent::handle($args); - $blockee = $this->get_user($apidata['api_arg'], $apidata); + $blockee = $this->get_user($apidata['api_arg'], $apidata); if (!$blockee) { - $this->client_error('Not Found', 404, $apidata['content-type']); - return; + $this->client_error('Not Found', 404, $apidata['content-type']); + return; } $user = $apidata['user']; @@ -42,17 +42,17 @@ class TwitapiblocksAction extends TwitterapiAction { $this->show_profile($blockee, $type); $this->end_document($type); } else { - common_server_error(_('Block user failed.')); + common_server_error(_('Block user failed.')); } - } + } - function destroy($args, $apidata) { - parent::handle($args); - $blockee = $this->get_user($apidata['api_arg'], $apidata); + function destroy($args, $apidata) { + parent::handle($args); + $blockee = $this->get_user($apidata['api_arg'], $apidata); if (!$blockee) { - $this->client_error('Not Found', 404, $apidata['content-type']); - return; + $this->client_error('Not Found', 404, $apidata['content-type']); + return; } $user = $apidata['user']; @@ -63,7 +63,7 @@ class TwitapiblocksAction extends TwitterapiAction { $this->show_profile($blockee, $type); $this->end_document($type); } else { - common_server_error(_('Unblock user failed.')); + common_server_error(_('Unblock user failed.')); } - } + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/twitapidirect_messages.php b/_darcs/pristine/actions/twitapidirect_messages.php index 535795ca4..2e3b50173 100644 --- a/_darcs/pristine/actions/twitapidirect_messages.php +++ b/_darcs/pristine/actions/twitapidirect_messages.php @@ -23,265 +23,265 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class Twitapidirect_messagesAction extends TwitterapiAction { - function direct_messages($args, $apidata) { - parent::handle($args); - return $this->show_messages($args, $apidata, 'received'); - } - - function sent($args, $apidata) { - parent::handle($args); - return $this->show_messages($args, $apidata, 'sent'); - } - - function show_messages($args, $apidata, $type) { - - $user = $apidata['user']; - - $count = $this->arg('count'); - $since = $this->arg('since'); - $since_id = $this->arg('since_id'); - $before_id = $this->arg('before_id'); - - $page = $this->arg('page'); - - if (!$page) { - $page = 1; - } - - if (!$count) { - $count = 20; - } - - $message = new Message(); - - $title = null; - $subtitle = null; - $link = null; - $server = common_root_url(); - - if ($type == 'received') { - $message->to_profile = $user->id; - $title = sprintf(_("Direct messages to %s"), $user->nickname); - $subtitle = sprintf(_("All the direct messages sent to %s"), $user->nickname); - $link = $server . $user->nickname . '/inbox'; - } else { - $message->from_profile = $user->id; - $title = _('Direct Messages You\'ve Sent'); - $subtitle = sprintf(_("All the direct messages sent from %s"), $user->nickname); - $link = $server . $user->nickname . '/outbox'; - } - - if ($before_id) { - $message->whereAdd("id < $before_id"); - } - - if ($since_id) { - $message->whereAdd("id > $since_id"); - } - - $since = strtotime($this->arg('since')); - - if ($since) { - $d = date('Y-m-d H:i:s', $since); - $message->whereAdd("created > '$d'"); - } - - $message->orderBy('created DESC, id DESC'); - $message->limit((($page-1)*20), $count); - $message->find(); - - switch($apidata['content-type']) { - case 'xml': - $this->show_xml_dmsgs($message); - break; - case 'rss': - $this->show_rss_dmsgs($message, $title, $link, $subtitle); - break; - case 'atom': - $this->show_atom_dmsgs($message, $title, $link, $subtitle); - break; - case 'json': - $this->show_json_dmsgs($message); - break; - default: - common_user_error(_('API method not found!'), $code = 404); - } - - } - - // had to change this from "new" to "create" to avoid PHP reserved word - function create($args, $apidata) { - parent::handle($args); - - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); - return; - } - - $user = $apidata['user']; - $source = $this->trimmed('source'); // Not supported by Twitter. + function direct_messages($args, $apidata) { + parent::handle($args); + return $this->show_messages($args, $apidata, 'received'); + } + + function sent($args, $apidata) { + parent::handle($args); + return $this->show_messages($args, $apidata, 'sent'); + } + + function show_messages($args, $apidata, $type) { + + $user = $apidata['user']; + + $count = $this->arg('count'); + $since = $this->arg('since'); + $since_id = $this->arg('since_id'); + $before_id = $this->arg('before_id'); + + $page = $this->arg('page'); + + if (!$page) { + $page = 1; + } + + if (!$count) { + $count = 20; + } + + $message = new Message(); + + $title = null; + $subtitle = null; + $link = null; + $server = common_root_url(); + + if ($type == 'received') { + $message->to_profile = $user->id; + $title = sprintf(_("Direct messages to %s"), $user->nickname); + $subtitle = sprintf(_("All the direct messages sent to %s"), $user->nickname); + $link = $server . $user->nickname . '/inbox'; + } else { + $message->from_profile = $user->id; + $title = _('Direct Messages You\'ve Sent'); + $subtitle = sprintf(_("All the direct messages sent from %s"), $user->nickname); + $link = $server . $user->nickname . '/outbox'; + } + + if ($before_id) { + $message->whereAdd("id < $before_id"); + } + + if ($since_id) { + $message->whereAdd("id > $since_id"); + } + + $since = strtotime($this->arg('since')); + + if ($since) { + $d = date('Y-m-d H:i:s', $since); + $message->whereAdd("created > '$d'"); + } + + $message->orderBy('created DESC, id DESC'); + $message->limit((($page-1)*20), $count); + $message->find(); + + switch($apidata['content-type']) { + case 'xml': + $this->show_xml_dmsgs($message); + break; + case 'rss': + $this->show_rss_dmsgs($message, $title, $link, $subtitle); + break; + case 'atom': + $this->show_atom_dmsgs($message, $title, $link, $subtitle); + break; + case 'json': + $this->show_json_dmsgs($message); + break; + default: + common_user_error(_('API method not found!'), $code = 404); + } + + } + + // had to change this from "new" to "create" to avoid PHP reserved word + function create($args, $apidata) { + parent::handle($args); + + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); + return; + } + + $user = $apidata['user']; + $source = $this->trimmed('source'); // Not supported by Twitter. $reserved_sources = array('web', 'omb', 'mail', 'xmpp', 'api'); - if (!$source || in_array($source, $reserved_sources)) { - $source = 'api'; - } - - $content = $this->trimmed('text'); - - if (!$content) { - $this->client_error(_('No message text!'), $code = 406, $apidata['content-type']); - } else { - $content_shortened = common_shorten_links($content); - if (mb_strlen($content_shortened) > 140) { - $this->client_error(_('That\'s too long. Max message size is 140 chars.'), - $code = 406, $apidata['content-type']); - return; - } - } - - $other = $this->get_user($this->trimmed('user')); - - if (!$other) { - $this->client_error(_('Recipient user not found.'), $code = 403, $apidata['content-type']); - return; - } else if (!$user->mutuallySubscribed($other)) { - $this->client_error(_('Can\'t send direct messages to users who aren\'t your friend.'), - $code = 403, $apidata['content-type']); - return; - } else if ($user->id == $other->id) { - // Sending msgs to yourself is allowed by Twitter - $this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), - $code = 403, $apidata['content-type']); - return; - } - - $message = Message::saveNew($user->id, $other->id, - html_entity_decode($content, ENT_NOQUOTES, 'UTF-8'), $source); - - if (is_string($message)) { - $this->server_error($message); - return; - } - - $this->notify($user, $other, $message); - - if ($apidata['content-type'] == 'xml') { - $this->show_single_xml_dmsg($message); - } elseif ($apidata['content-type'] == 'json') { - $this->show_single_json_dmsg($message); - } - - } - - function destroy($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } - - function show_xml_dmsgs($message) { - - $this->init_document('xml'); - common_element_start('direct-messages', array('type' => 'array')); - - if (is_array($messages)) { - foreach ($message as $m) { - $twitter_dm = $this->twitter_dmsg_array($m); - $this->show_twitter_xml_dmsg($twitter_dm); - } - } else { - while ($message->fetch()) { - $twitter_dm = $this->twitter_dmsg_array($message); - $this->show_twitter_xml_dmsg($twitter_dm); - } - } - - common_element_end('direct-messages'); - $this->end_document('xml'); - - } - - function show_json_dmsgs($message) { - - $this->init_document('json'); - - $dmsgs = array(); - - if (is_array($message)) { - foreach ($message as $m) { - $twitter_dm = $this->twitter_dmsg_array($m); - array_push($dmsgs, $twitter_dm); - } - } else { - while ($message->fetch()) { - $twitter_dm = $this->twitter_dmsg_array($message); - array_push($dmsgs, $twitter_dm); - } - } - - $this->show_json_objects($dmsgs); - $this->end_document('json'); - - } - - function show_rss_dmsgs($message, $title, $link, $subtitle) { - - $this->init_document('rss'); - - common_element_start('channel'); - common_element('title', NULL, $title); - - common_element('link', NULL, $link); - common_element('description', NULL, $subtitle); - common_element('language', NULL, 'en-us'); - common_element('ttl', NULL, '40'); - - if (is_array($message)) { - foreach ($message as $m) { - $entry = $this->twitter_rss_dmsg_array($m); - $this->show_twitter_rss_item($entry); - } - } else { - while ($message->fetch()) { - $entry = $this->twitter_rss_dmsg_array($message); - $this->show_twitter_rss_item($entry); - } - } - - common_element_end('channel'); - $this->end_twitter_rss(); - - } - - function show_atom_dmsgs($message, $title, $link, $subtitle) { - - $this->init_document('atom'); - - common_element('title', NULL, $title); - $siteserver = common_config('site', 'server'); - common_element('id', NULL, "tag:$siteserver,2008:DirectMessage"); - common_element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), NULL); - common_element('updated', NULL, common_date_iso8601(strftime('%c'))); - common_element('subtitle', NULL, $subtitle); - - if (is_array($message)) { - foreach ($message as $m) { - $entry = $this->twitter_rss_dmsg_array($m); - $this->show_twitter_atom_entry($entry); - } - } else { - while ($message->fetch()) { - $entry = $this->twitter_rss_dmsg_array($message); - $this->show_twitter_atom_entry($entry); - } - } - - $this->end_document('atom'); - } - - // swiped from MessageAction. Should it be place in util.php? - function notify($from, $to, $message) { - mail_notify_message($message, $from, $to); - # XXX: Jabber, SMS notifications... probably queued - } + if (!$source || in_array($source, $reserved_sources)) { + $source = 'api'; + } + + $content = $this->trimmed('text'); + + if (!$content) { + $this->client_error(_('No message text!'), $code = 406, $apidata['content-type']); + } else { + $content_shortened = common_shorten_links($content); + if (mb_strlen($content_shortened) > 140) { + $this->client_error(_('That\'s too long. Max message size is 140 chars.'), + $code = 406, $apidata['content-type']); + return; + } + } + + $other = $this->get_user($this->trimmed('user')); + + if (!$other) { + $this->client_error(_('Recipient user not found.'), $code = 403, $apidata['content-type']); + return; + } else if (!$user->mutuallySubscribed($other)) { + $this->client_error(_('Can\'t send direct messages to users who aren\'t your friend.'), + $code = 403, $apidata['content-type']); + return; + } else if ($user->id == $other->id) { + // Sending msgs to yourself is allowed by Twitter + $this->client_error(_('Don\'t send a message to yourself; just say it to yourself quietly instead.'), + $code = 403, $apidata['content-type']); + return; + } + + $message = Message::saveNew($user->id, $other->id, + html_entity_decode($content, ENT_NOQUOTES, 'UTF-8'), $source); + + if (is_string($message)) { + $this->server_error($message); + return; + } + + $this->notify($user, $other, $message); + + if ($apidata['content-type'] == 'xml') { + $this->show_single_xml_dmsg($message); + } elseif ($apidata['content-type'] == 'json') { + $this->show_single_json_dmsg($message); + } + + } + + function destroy($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } + + function show_xml_dmsgs($message) { + + $this->init_document('xml'); + common_element_start('direct-messages', array('type' => 'array')); + + if (is_array($messages)) { + foreach ($message as $m) { + $twitter_dm = $this->twitter_dmsg_array($m); + $this->show_twitter_xml_dmsg($twitter_dm); + } + } else { + while ($message->fetch()) { + $twitter_dm = $this->twitter_dmsg_array($message); + $this->show_twitter_xml_dmsg($twitter_dm); + } + } + + common_element_end('direct-messages'); + $this->end_document('xml'); + + } + + function show_json_dmsgs($message) { + + $this->init_document('json'); + + $dmsgs = array(); + + if (is_array($message)) { + foreach ($message as $m) { + $twitter_dm = $this->twitter_dmsg_array($m); + array_push($dmsgs, $twitter_dm); + } + } else { + while ($message->fetch()) { + $twitter_dm = $this->twitter_dmsg_array($message); + array_push($dmsgs, $twitter_dm); + } + } + + $this->show_json_objects($dmsgs); + $this->end_document('json'); + + } + + function show_rss_dmsgs($message, $title, $link, $subtitle) { + + $this->init_document('rss'); + + common_element_start('channel'); + common_element('title', NULL, $title); + + common_element('link', NULL, $link); + common_element('description', NULL, $subtitle); + common_element('language', NULL, 'en-us'); + common_element('ttl', NULL, '40'); + + if (is_array($message)) { + foreach ($message as $m) { + $entry = $this->twitter_rss_dmsg_array($m); + $this->show_twitter_rss_item($entry); + } + } else { + while ($message->fetch()) { + $entry = $this->twitter_rss_dmsg_array($message); + $this->show_twitter_rss_item($entry); + } + } + + common_element_end('channel'); + $this->end_twitter_rss(); + + } + + function show_atom_dmsgs($message, $title, $link, $subtitle) { + + $this->init_document('atom'); + + common_element('title', NULL, $title); + $siteserver = common_config('site', 'server'); + common_element('id', NULL, "tag:$siteserver,2008:DirectMessage"); + common_element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), NULL); + common_element('updated', NULL, common_date_iso8601(strftime('%c'))); + common_element('subtitle', NULL, $subtitle); + + if (is_array($message)) { + foreach ($message as $m) { + $entry = $this->twitter_rss_dmsg_array($m); + $this->show_twitter_atom_entry($entry); + } + } else { + while ($message->fetch()) { + $entry = $this->twitter_rss_dmsg_array($message); + $this->show_twitter_atom_entry($entry); + } + } + + $this->end_document('atom'); + } + + // swiped from MessageAction. Should it be place in util.php? + function notify($from, $to, $message) { + mail_notify_message($message, $from, $to); + # XXX: Jabber, SMS notifications... probably queued + } } diff --git a/_darcs/pristine/actions/twitapifavorites.php b/_darcs/pristine/actions/twitapifavorites.php index 3eaff327a..ad8c5f18b 100644 --- a/_darcs/pristine/actions/twitapifavorites.php +++ b/_darcs/pristine/actions/twitapifavorites.php @@ -23,153 +23,153 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapifavoritesAction extends TwitterapiAction { - function favorites($args, $apidata) { - parent::handle($args); - - $this->auth_user = $apidata['user']; - $user = $this->get_user($apidata['api_arg'], $apidata); - - if (!$user) { - $this->client_error('Not Found', 404, $apidata['content-type']); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } - - $page = $this->arg('page'); - - if (!$page) { - $page = 1; - } - - if (!$count) { - $count = 20; - } - - $notice = $user->favoriteNotices((($page-1)*20), $count); - - if (!$notice) { - common_server_error(_('Could not retrieve favorite notices.')); - return; - } - - $sitename = common_config('site', 'name'); - $siteserver = common_config('site', 'server'); - - $title = sprintf(_('%s / Favorites from %s'), $sitename, $user->nickname); - $id = "tag:$siteserver:favorites:".$user->id; - $link = common_local_url('favorites', array('nickname' => $user->nickname)); - $subtitle = sprintf(_('%s updates favorited by %s / %s.'), $sitename, $profile->getBestName(), $user->nickname); - - switch($apidata['content-type']) { - case 'xml': - $this->show_xml_timeline($notice); - break; - case 'rss': - $this->show_rss_timeline($notice, $title, $link, $subtitle); - break; - case 'atom': - $this->show_atom_timeline($notice, $title, $id, $link, $subtitle); - break; - case 'json': - $this->show_json_timeline($notice); - break; - default: - common_user_error(_('API method not found!'), $code = 404); - } - - } - - function create($args, $apidata) { - parent::handle($args); - - // Check for RESTfulness - if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { - // XXX: Twitter just prints the err msg, no XML / JSON. - $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); - return; - } - - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } - - $this->auth_user = $apidata['user']; - $user = $this->auth_user; - $notice_id = $apidata['api_arg']; - $notice = Notice::staticGet($notice_id); - - if (!$notice) { - $this->client_error(_('No status found with that ID.'), 404, $apidata['content-type']); - return; - } - - // XXX: Twitter lets you fave things repeatedly via api. - if ($user->hasFave($notice)) { - $this->client_error(_('This notice is already a favorite!'), 403, $apidata['content-type']); - return; - } - - $fave = Fave::addNew($user, $notice); - - if (!$fave) { - common_server_error(_('Could not create favorite.')); - return; - } - - $this->notify($fave, $notice, $user); - $user->blowFavesCache(); - - if ($apidata['content-type'] == 'xml') { - $this->show_single_xml_status($notice); - } elseif ($apidata['content-type'] == 'json') { - $this->show_single_json_status($notice); - } - - } - - function destroy($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } - - // XXX: these two funcs swiped from faves. Maybe put in util.php, or some common base class? - - function notify($fave, $notice, $user) { - $other = User::staticGet('id', $notice->profile_id); - if ($other && $other->id != $user->id) { - if ($other->email && $other->emailnotifyfav) { - $this->notify_mail($other, $user, $notice); - } - # XXX: notify by IM - # XXX: notify by SMS - } - } - - function notify_mail($other, $user, $notice) { - $profile = $user->getProfile(); - $bestname = $profile->getBestName(); - $subject = sprintf(_('%s added your notice as a favorite'), $bestname); - $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . - "In case you forgot, you can see the text of your notice here:\n\n" . - "%3\$s\n\n" . - "You can see the list of %1\$s's favorites here:\n\n" . - "%4\$s\n\n" . - "Faithfully yours,\n" . - "%5\$s\n"), - $bestname, - common_exact_date($notice->created), - common_local_url('shownotice', array('notice' => $notice->id)), - common_local_url('showfavorites', array('nickname' => $user->nickname)), - common_config('site', 'name')); - - mail_to_user($other, $subject, $body); - } + function favorites($args, $apidata) { + parent::handle($args); + + $this->auth_user = $apidata['user']; + $user = $this->get_user($apidata['api_arg'], $apidata); + + if (!$user) { + $this->client_error('Not Found', 404, $apidata['content-type']); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } + + $page = $this->arg('page'); + + if (!$page) { + $page = 1; + } + + if (!$count) { + $count = 20; + } + + $notice = $user->favoriteNotices((($page-1)*20), $count); + + if (!$notice) { + common_server_error(_('Could not retrieve favorite notices.')); + return; + } + + $sitename = common_config('site', 'name'); + $siteserver = common_config('site', 'server'); + + $title = sprintf(_('%s / Favorites from %s'), $sitename, $user->nickname); + $id = "tag:$siteserver:favorites:".$user->id; + $link = common_local_url('favorites', array('nickname' => $user->nickname)); + $subtitle = sprintf(_('%s updates favorited by %s / %s.'), $sitename, $profile->getBestName(), $user->nickname); + + switch($apidata['content-type']) { + case 'xml': + $this->show_xml_timeline($notice); + break; + case 'rss': + $this->show_rss_timeline($notice, $title, $link, $subtitle); + break; + case 'atom': + $this->show_atom_timeline($notice, $title, $id, $link, $subtitle); + break; + case 'json': + $this->show_json_timeline($notice); + break; + default: + common_user_error(_('API method not found!'), $code = 404); + } + + } + + function create($args, $apidata) { + parent::handle($args); + + // Check for RESTfulness + if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { + // XXX: Twitter just prints the err msg, no XML / JSON. + $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); + return; + } + + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } + + $this->auth_user = $apidata['user']; + $user = $this->auth_user; + $notice_id = $apidata['api_arg']; + $notice = Notice::staticGet($notice_id); + + if (!$notice) { + $this->client_error(_('No status found with that ID.'), 404, $apidata['content-type']); + return; + } + + // XXX: Twitter lets you fave things repeatedly via api. + if ($user->hasFave($notice)) { + $this->client_error(_('This notice is already a favorite!'), 403, $apidata['content-type']); + return; + } + + $fave = Fave::addNew($user, $notice); + + if (!$fave) { + common_server_error(_('Could not create favorite.')); + return; + } + + $this->notify($fave, $notice, $user); + $user->blowFavesCache(); + + if ($apidata['content-type'] == 'xml') { + $this->show_single_xml_status($notice); + } elseif ($apidata['content-type'] == 'json') { + $this->show_single_json_status($notice); + } + + } + + function destroy($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } + + // XXX: these two funcs swiped from faves. Maybe put in util.php, or some common base class? + + function notify($fave, $notice, $user) { + $other = User::staticGet('id', $notice->profile_id); + if ($other && $other->id != $user->id) { + if ($other->email && $other->emailnotifyfav) { + $this->notify_mail($other, $user, $notice); + } + # XXX: notify by IM + # XXX: notify by SMS + } + } + + function notify_mail($other, $user, $notice) { + $profile = $user->getProfile(); + $bestname = $profile->getBestName(); + $subject = sprintf(_('%s added your notice as a favorite'), $bestname); + $body = sprintf(_("%1\$s just added your notice from %2\$s as one of their favorites.\n\n" . + "In case you forgot, you can see the text of your notice here:\n\n" . + "%3\$s\n\n" . + "You can see the list of %1\$s's favorites here:\n\n" . + "%4\$s\n\n" . + "Faithfully yours,\n" . + "%5\$s\n"), + $bestname, + common_exact_date($notice->created), + common_local_url('shownotice', array('notice' => $notice->id)), + common_local_url('showfavorites', array('nickname' => $user->nickname)), + common_config('site', 'name')); + + mail_to_user($other, $subject, $body); + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/twitapifriendships.php b/_darcs/pristine/actions/twitapifriendships.php index e4b49cbe4..d352b933b 100644 --- a/_darcs/pristine/actions/twitapifriendships.php +++ b/_darcs/pristine/actions/twitapifriendships.php @@ -23,133 +23,133 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapifriendshipsAction extends TwitterapiAction { - function create($args, $apidata) { - parent::handle($args); + function create($args, $apidata) { + parent::handle($args); - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); - return; - } + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); + return; + } - $id = $apidata['api_arg']; + $id = $apidata['api_arg']; - $other = $this->get_user($id); + $other = $this->get_user($id); - if (!$other) { - $this->client_error(_('Could not follow user: User not found.'), 403, $apidata['content-type']); - return; - } + if (!$other) { + $this->client_error(_('Could not follow user: User not found.'), 403, $apidata['content-type']); + return; + } - $user = $apidata['user']; + $user = $apidata['user']; - if ($user->isSubscribed($other)) { - $errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname); - $this->client_error($errmsg, 403, $apidata['content-type']); - return; - } + if ($user->isSubscribed($other)) { + $errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname); + $this->client_error($errmsg, 403, $apidata['content-type']); + return; + } - $sub = new Subscription(); + $sub = new Subscription(); - $sub->query('BEGIN'); + $sub->query('BEGIN'); - $sub->subscriber = $user->id; - $sub->subscribed = $other->id; - $sub->created = DB_DataObject_Cast::dateTime(); # current time + $sub->subscriber = $user->id; + $sub->subscribed = $other->id; + $sub->created = DB_DataObject_Cast::dateTime(); # current time - $result = $sub->insert(); + $result = $sub->insert(); - if (!$result) { - $errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname); - $this->client_error($errmsg, 400, $apidata['content-type']); - return; - } + if (!$result) { + $errmsg = sprintf(_('Could not follow user: %s is already on your list.'), $other->nickname); + $this->client_error($errmsg, 400, $apidata['content-type']); + return; + } - $sub->query('COMMIT'); + $sub->query('COMMIT'); - mail_subscribe_notify($other, $user); + mail_subscribe_notify($other, $user); - $type = $apidata['content-type']; - $this->init_document($type); - $this->show_profile($other, $type); - $this->end_document($type); + $type = $apidata['content-type']; + $this->init_document($type); + $this->show_profile($other, $type); + $this->end_document($type); - } + } - function destroy($args, $apidata) { - parent::handle($args); + function destroy($args, $apidata) { + parent::handle($args); - if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { - $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); - return; - } + if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { + $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); + return; + } - $id = $apidata['api_arg']; + $id = $apidata['api_arg']; - # We can't subscribe to a remote person, but we can unsub + # We can't subscribe to a remote person, but we can unsub - $other = $this->get_profile($id); - $user = $apidata['user']; + $other = $this->get_profile($id); + $user = $apidata['user']; - $sub = new Subscription(); - $sub->subscriber = $user->id; - $sub->subscribed = $other->id; + $sub = new Subscription(); + $sub->subscriber = $user->id; + $sub->subscribed = $other->id; - if ($sub->find(TRUE)) { - $sub->query('BEGIN'); - $sub->delete(); - $sub->query('COMMIT'); - } else { - $this->client_error(_('You are not friends with the specified user.'), 403, $apidata['content-type']); - return; - } + if ($sub->find(TRUE)) { + $sub->query('BEGIN'); + $sub->delete(); + $sub->query('COMMIT'); + } else { + $this->client_error(_('You are not friends with the specified user.'), 403, $apidata['content-type']); + return; + } - $type = $apidata['content-type']; - $this->init_document($type); - $this->show_profile($other, $type); - $this->end_document($type); + $type = $apidata['content-type']; + $this->init_document($type); + $this->show_profile($other, $type); + $this->end_document($type); - } + } - function exists($args, $apidata) { - parent::handle($args); + function exists($args, $apidata) { + parent::handle($args); - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } - $user_a_id = $this->trimmed('user_a'); - $user_b_id = $this->trimmed('user_b'); + $user_a_id = $this->trimmed('user_a'); + $user_b_id = $this->trimmed('user_b'); - $user_a = $this->get_user($user_a_id); - $user_b = $this->get_user($user_b_id); + $user_a = $this->get_user($user_a_id); + $user_b = $this->get_user($user_b_id); - if (!$user_a || !$user_b) { - $this->client_error(_('Two user ids or screen_names must be supplied.'), 400, $apidata['content-type']); - return; - } + if (!$user_a || !$user_b) { + $this->client_error(_('Two user ids or screen_names must be supplied.'), 400, $apidata['content-type']); + return; + } - if ($user_a->isSubscribed($user_b)) { - $result = 'true'; - } else { - $result = 'false'; - } + if ($user_a->isSubscribed($user_b)) { + $result = 'true'; + } else { + $result = 'false'; + } - switch ($apidata['content-type']) { - case 'xml': - $this->init_document('xml'); - common_element('friends', NULL, $result); - $this->end_document('xml'); - break; - case 'json': - $this->init_document('json'); - print json_encode($result); - $this->end_document('json'); - break; - default: - break; - } + switch ($apidata['content-type']) { + case 'xml': + $this->init_document('xml'); + common_element('friends', NULL, $result); + $this->end_document('xml'); + break; + case 'json': + $this->init_document('json'); + print json_encode($result); + $this->end_document('json'); + break; + default: + break; + } - } + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/twitapihelp.php b/_darcs/pristine/actions/twitapihelp.php index c5d503e11..d268b7c82 100644 --- a/_darcs/pristine/actions/twitapihelp.php +++ b/_darcs/pristine/actions/twitapihelp.php @@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapihelpAction extends TwitterapiAction { - /* Returns the string "ok" in the requested format with a 200 OK HTTP status code. - * URL:http://identi.ca/api/help/test.format - * Formats: xml, json - */ - function test($args, $apidata) { - parent::handle($args); - - if ($apidata['content-type'] == 'xml') { - $this->init_document('xml'); - common_element('ok', NULL, 'true'); - $this->end_document('xml'); - } elseif ($apidata['content-type'] == 'json') { - $this->init_document('json'); - print '"ok"'; - $this->end_document('json'); - } else { - common_user_error(_('API method not found!'), $code=404); - } - - } - - function downtime_schedule($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } + /* Returns the string "ok" in the requested format with a 200 OK HTTP status code. + * URL:http://identi.ca/api/help/test.format + * Formats: xml, json + */ + function test($args, $apidata) { + parent::handle($args); + + if ($apidata['content-type'] == 'xml') { + $this->init_document('xml'); + common_element('ok', NULL, 'true'); + $this->end_document('xml'); + } elseif ($apidata['content-type'] == 'json') { + $this->init_document('json'); + print '"ok"'; + $this->end_document('json'); + } else { + common_user_error(_('API method not found!'), $code=404); + } + + } + + function downtime_schedule($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/twitapinotifications.php b/_darcs/pristine/actions/twitapinotifications.php index 8d93309a2..26f66d7e5 100644 --- a/_darcs/pristine/actions/twitapinotifications.php +++ b/_darcs/pristine/actions/twitapinotifications.php @@ -24,14 +24,14 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); # This naming convention looks real sick class TwitapinotificationsAction extends TwitterapiAction { - function follow($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } + function follow($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } - function leave($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } + function leave($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/twitapistatuses.php b/_darcs/pristine/actions/twitapistatuses.php index 7b6598b10..c33643a3c 100644 --- a/_darcs/pristine/actions/twitapistatuses.php +++ b/_darcs/pristine/actions/twitapistatuses.php @@ -23,541 +23,541 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapistatusesAction extends TwitterapiAction { - function public_timeline($args, $apidata) { - parent::handle($args); - - $sitename = common_config('site', 'name'); - $siteserver = common_config('site', 'server'); - $title = sprintf(_("%s public timeline"), $sitename); - $id = "tag:$siteserver:Statuses"; - $link = common_root_url(); - $subtitle = sprintf(_("%s updates from everyone!"), $sitename); - - // Number of public statuses to return by default -- Twitter sends 20 - $MAX_PUBSTATUSES = 20; - - // FIXME: To really live up to the spec we need to build a list - // of notices by users who have custom avatars, so fix this SQL -- Zach - - $page = $this->arg('page'); - $since_id = $this->arg('since_id'); - $before_id = $this->arg('before_id'); - - // NOTE: page, since_id, and before_id are extensions to Twitter API -- TB - if (!$page) { - $page = 1; - } - if (!$since_id) { - $since_id = 0; - } - if (!$before_id) { - $before_id = 0; - } - - $since = strtotime($this->arg('since')); - - $notice = Notice::publicStream((($page-1)*$MAX_PUBSTATUSES), $MAX_PUBSTATUSES, $since_id, $before_id, $since); - - if ($notice) { - - switch($apidata['content-type']) { - case 'xml': - $this->show_xml_timeline($notice); - break; - case 'rss': - $this->show_rss_timeline($notice, $title, $link, $subtitle); - break; - case 'atom': - $this->show_atom_timeline($notice, $title, $id, $link, $subtitle); - break; - case 'json': - $this->show_json_timeline($notice); - break; - default: - common_user_error(_('API method not found!'), $code = 404); - break; - } - - } else { - common_server_error(_('Couldn\'t find any statuses.'), $code = 503); - } - - } - - function friends_timeline($args, $apidata) { - parent::handle($args); - - $since = $this->arg('since'); - $since_id = $this->arg('since_id'); - $count = $this->arg('count'); - $page = $this->arg('page'); - $before_id = $this->arg('before_id'); - - if (!$page) { - $page = 1; - } - - if (!$count) { - $count = 20; - } - - if (!$since_id) { - $since_id = 0; - } - - // NOTE: before_id is an extension to Twitter API -- TB - if (!$before_id) { - $before_id = 0; - } - - $since = strtotime($this->arg('since')); - - $user = $this->get_user(NULL, $apidata); - $this->auth_user = $user; - - $profile = $user->getProfile(); - - $sitename = common_config('site', 'name'); - $siteserver = common_config('site', 'server'); - - $title = sprintf(_("%s and friends"), $user->nickname); - $id = "tag:$siteserver:friends:" . $user->id; - $link = common_local_url('all', array('nickname' => $user->nickname)); - $subtitle = sprintf(_('Updates from %1$s and friends on %2$s!'), $user->nickname, $sitename); - - $notice = $user->noticesWithFriends(($page-1)*20, $count, $since_id, $before_id, $since); - - switch($apidata['content-type']) { - case 'xml': - $this->show_xml_timeline($notice); - break; - case 'rss': - $this->show_rss_timeline($notice, $title, $link, $subtitle); - break; - case 'atom': - $this->show_atom_timeline($notice, $title, $id, $link, $subtitle); - break; - case 'json': - $this->show_json_timeline($notice); - break; - default: - common_user_error(_('API method not found!'), $code = 404); - } - - } - - function user_timeline($args, $apidata) { - parent::handle($args); - - $this->auth_user = $apidata['user']; - $user = $this->get_user($apidata['api_arg'], $apidata); - - if (!$user) { - $this->client_error('Not Found', 404, $apidata['content-type']); - return; - } - - $profile = $user->getProfile(); - - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } - - $count = $this->arg('count'); - $since = $this->arg('since'); - $since_id = $this->arg('since_id'); - $page = $this->arg('page'); - $before_id = $this->arg('before_id'); - - if (!$page) { - $page = 1; - } - - if (!$count) { - $count = 20; - } - - if (!$since_id) { - $since_id = 0; - } - - // NOTE: before_id is an extensions to Twitter API -- TB - if (!$before_id) { - $before_id = 0; - } - - $since = strtotime($this->arg('since')); - - $sitename = common_config('site', 'name'); - $siteserver = common_config('site', 'server'); - - $title = sprintf(_("%s timeline"), $user->nickname); - $id = "tag:$siteserver:user:".$user->id; - $link = common_local_url('showstream', array('nickname' => $user->nickname)); - $subtitle = sprintf(_('Updates from %1$s on %2$s!'), $user->nickname, $sitename); - - # FriendFeed's SUP protocol - # Also added RSS and Atom feeds - - $suplink = common_local_url('sup', NULL, $user->id); - header('X-SUP-ID: '.$suplink); - - # XXX: since - - $notice = $user->getNotices((($page-1)*20), $count, $since_id, $before_id, $since); - - switch($apidata['content-type']) { - case 'xml': - $this->show_xml_timeline($notice); - break; - case 'rss': - $this->show_rss_timeline($notice, $title, $link, $subtitle, $suplink); - break; - case 'atom': - $this->show_atom_timeline($notice, $title, $id, $link, $subtitle, $suplink); - break; - case 'json': - $this->show_json_timeline($notice); - break; - default: - common_user_error(_('API method not found!'), $code = 404); - } - - } - - function update($args, $apidata) { - - parent::handle($args); - - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } - - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); - return; - } - - $this->auth_user = $apidata['user']; - $user = $this->auth_user; - $status = $this->trimmed('status'); - $source = $this->trimmed('source'); - $in_reply_to_status_id = intval($this->trimmed('in_reply_to_status_id')); + function public_timeline($args, $apidata) { + parent::handle($args); + + $sitename = common_config('site', 'name'); + $siteserver = common_config('site', 'server'); + $title = sprintf(_("%s public timeline"), $sitename); + $id = "tag:$siteserver:Statuses"; + $link = common_root_url(); + $subtitle = sprintf(_("%s updates from everyone!"), $sitename); + + // Number of public statuses to return by default -- Twitter sends 20 + $MAX_PUBSTATUSES = 20; + + // FIXME: To really live up to the spec we need to build a list + // of notices by users who have custom avatars, so fix this SQL -- Zach + + $page = $this->arg('page'); + $since_id = $this->arg('since_id'); + $before_id = $this->arg('before_id'); + + // NOTE: page, since_id, and before_id are extensions to Twitter API -- TB + if (!$page) { + $page = 1; + } + if (!$since_id) { + $since_id = 0; + } + if (!$before_id) { + $before_id = 0; + } + + $since = strtotime($this->arg('since')); + + $notice = Notice::publicStream((($page-1)*$MAX_PUBSTATUSES), $MAX_PUBSTATUSES, $since_id, $before_id, $since); + + if ($notice) { + + switch($apidata['content-type']) { + case 'xml': + $this->show_xml_timeline($notice); + break; + case 'rss': + $this->show_rss_timeline($notice, $title, $link, $subtitle); + break; + case 'atom': + $this->show_atom_timeline($notice, $title, $id, $link, $subtitle); + break; + case 'json': + $this->show_json_timeline($notice); + break; + default: + common_user_error(_('API method not found!'), $code = 404); + break; + } + + } else { + common_server_error(_('Couldn\'t find any statuses.'), $code = 503); + } + + } + + function friends_timeline($args, $apidata) { + parent::handle($args); + + $since = $this->arg('since'); + $since_id = $this->arg('since_id'); + $count = $this->arg('count'); + $page = $this->arg('page'); + $before_id = $this->arg('before_id'); + + if (!$page) { + $page = 1; + } + + if (!$count) { + $count = 20; + } + + if (!$since_id) { + $since_id = 0; + } + + // NOTE: before_id is an extension to Twitter API -- TB + if (!$before_id) { + $before_id = 0; + } + + $since = strtotime($this->arg('since')); + + $user = $this->get_user(NULL, $apidata); + $this->auth_user = $user; + + $profile = $user->getProfile(); + + $sitename = common_config('site', 'name'); + $siteserver = common_config('site', 'server'); + + $title = sprintf(_("%s and friends"), $user->nickname); + $id = "tag:$siteserver:friends:" . $user->id; + $link = common_local_url('all', array('nickname' => $user->nickname)); + $subtitle = sprintf(_('Updates from %1$s and friends on %2$s!'), $user->nickname, $sitename); + + $notice = $user->noticesWithFriends(($page-1)*20, $count, $since_id, $before_id, $since); + + switch($apidata['content-type']) { + case 'xml': + $this->show_xml_timeline($notice); + break; + case 'rss': + $this->show_rss_timeline($notice, $title, $link, $subtitle); + break; + case 'atom': + $this->show_atom_timeline($notice, $title, $id, $link, $subtitle); + break; + case 'json': + $this->show_json_timeline($notice); + break; + default: + common_user_error(_('API method not found!'), $code = 404); + } + + } + + function user_timeline($args, $apidata) { + parent::handle($args); + + $this->auth_user = $apidata['user']; + $user = $this->get_user($apidata['api_arg'], $apidata); + + if (!$user) { + $this->client_error('Not Found', 404, $apidata['content-type']); + return; + } + + $profile = $user->getProfile(); + + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } + + $count = $this->arg('count'); + $since = $this->arg('since'); + $since_id = $this->arg('since_id'); + $page = $this->arg('page'); + $before_id = $this->arg('before_id'); + + if (!$page) { + $page = 1; + } + + if (!$count) { + $count = 20; + } + + if (!$since_id) { + $since_id = 0; + } + + // NOTE: before_id is an extensions to Twitter API -- TB + if (!$before_id) { + $before_id = 0; + } + + $since = strtotime($this->arg('since')); + + $sitename = common_config('site', 'name'); + $siteserver = common_config('site', 'server'); + + $title = sprintf(_("%s timeline"), $user->nickname); + $id = "tag:$siteserver:user:".$user->id; + $link = common_local_url('showstream', array('nickname' => $user->nickname)); + $subtitle = sprintf(_('Updates from %1$s on %2$s!'), $user->nickname, $sitename); + + # FriendFeed's SUP protocol + # Also added RSS and Atom feeds + + $suplink = common_local_url('sup', NULL, $user->id); + header('X-SUP-ID: '.$suplink); + + # XXX: since + + $notice = $user->getNotices((($page-1)*20), $count, $since_id, $before_id, $since); + + switch($apidata['content-type']) { + case 'xml': + $this->show_xml_timeline($notice); + break; + case 'rss': + $this->show_rss_timeline($notice, $title, $link, $subtitle, $suplink); + break; + case 'atom': + $this->show_atom_timeline($notice, $title, $id, $link, $subtitle, $suplink); + break; + case 'json': + $this->show_json_timeline($notice); + break; + default: + common_user_error(_('API method not found!'), $code = 404); + } + + } + + function update($args, $apidata) { + + parent::handle($args); + + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } + + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + $this->client_error(_('This method requires a POST.'), 400, $apidata['content-type']); + return; + } + + $this->auth_user = $apidata['user']; + $user = $this->auth_user; + $status = $this->trimmed('status'); + $source = $this->trimmed('source'); + $in_reply_to_status_id = intval($this->trimmed('in_reply_to_status_id')); $reserved_sources = array('web', 'omb', 'mail', 'xmpp', 'api'); - if (!$source || in_array($source, $reserved_sources)) { - $source = 'api'; - } + if (!$source || in_array($source, $reserved_sources)) { + $source = 'api'; + } - if (!$status) { + if (!$status) { - // XXX: Note: In this case, Twitter simply returns '200 OK' - // No error is given, but the status is not posted to the - // user's timeline. Seems bad. Shouldn't we throw an - // errror? -- Zach - return; + // XXX: Note: In this case, Twitter simply returns '200 OK' + // No error is given, but the status is not posted to the + // user's timeline. Seems bad. Shouldn't we throw an + // errror? -- Zach + return; - } else { + } else { - $status_shortened = common_shorten_links($status); + $status_shortened = common_shorten_links($status); - if (mb_strlen($status_shortened) > 140) { + if (mb_strlen($status_shortened) > 140) { - // XXX: Twitter truncates anything over 140, flags the status - // as "truncated." Sending this error may screw up some clients - // that assume Twitter will truncate for them. Should we just - // truncate too? -- Zach - $this->client_error(_('That\'s too long. Max notice size is 140 chars.'), $code = 406, $apidata['content-type']); - return; + // XXX: Twitter truncates anything over 140, flags the status + // as "truncated." Sending this error may screw up some clients + // that assume Twitter will truncate for them. Should we just + // truncate too? -- Zach + $this->client_error(_('That\'s too long. Max notice size is 140 chars.'), $code = 406, $apidata['content-type']); + return; - } - } + } + } - // Check for commands - $inter = new CommandInterpreter(); - $cmd = $inter->handle_command($user, $status_shortened); + // Check for commands + $inter = new CommandInterpreter(); + $cmd = $inter->handle_command($user, $status_shortened); - if ($cmd) { + if ($cmd) { - if ($this->supported($cmd)) { - $cmd->execute(new Channel()); - } - - // cmd not supported? Twitter just returns your latest status. - // And, it returns your last status whether the cmd was successful - // or not! - $n = $user->getCurrentNotice(); - $apidata['api_arg'] = $n->id; - } else { + if ($this->supported($cmd)) { + $cmd->execute(new Channel()); + } + + // cmd not supported? Twitter just returns your latest status. + // And, it returns your last status whether the cmd was successful + // or not! + $n = $user->getCurrentNotice(); + $apidata['api_arg'] = $n->id; + } else { - $reply_to = NULL; + $reply_to = NULL; - if ($in_reply_to_status_id) { - - // check whether notice actually exists - $reply = Notice::staticGet($in_reply_to_status_id); - - if ($reply) { - $reply_to = $in_reply_to_status_id; - } else { - $this->client_error(_('Not found'), $code = 404, $apidata['content-type']); - return; - } - } - - $notice = Notice::saveNew($user->id, html_entity_decode($status, ENT_NOQUOTES, 'UTF-8'), - $source, 1, $reply_to); - - if (is_string($notice)) { - $this->server_error($notice); - return; - } - - common_broadcast_notice($notice); - $apidata['api_arg'] = $notice->id; - } - - $this->show($args, $apidata); - } - - function replies($args, $apidata) { - - parent::handle($args); - - $since = $this->arg('since'); - $count = $this->arg('count'); - $page = $this->arg('page'); - $since_id = $this->arg('since_id'); - $before_id = $this->arg('before_id'); - - $this->auth_user = $apidata['user']; - $user = $this->auth_user; - $profile = $user->getProfile(); - - $sitename = common_config('site', 'name'); - $siteserver = common_config('site', 'server'); - - $title = sprintf(_('%1$s / Updates replying to %2$s'), $sitename, $user->nickname); - $id = "tag:$siteserver:replies:".$user->id; - $link = common_local_url('replies', array('nickname' => $user->nickname)); - $subtitle = sprintf(_('%1$s updates that reply to updates from %2$s / %3$s.'), $sitename, $user->nickname, $profile->getBestName()); - - if (!$page) { - $page = 1; - } - - if (!$count) { - $count = 20; - } - - if (!$since_id) { - $since_id = 0; - } - - // NOTE: before_id is an extension to Twitter API -- TB - if (!$before_id) { - $before_id = 0; - } - - $since = strtotime($this->arg('since')); - - $notice = $user->getReplies((($page-1)*20), $count, $since_id, $before_id, $since); - $notices = array(); - - while ($notice->fetch()) { - $notices[] = clone($notice); - } - - switch($apidata['content-type']) { - case 'xml': - $this->show_xml_timeline($notices); - break; - case 'rss': - $this->show_rss_timeline($notices, $title, $link, $subtitle); - break; - case 'atom': - $this->show_atom_timeline($notices, $title, $id, $link, $subtitle); - break; - case 'json': - $this->show_json_timeline($notices); - break; - default: - common_user_error(_('API method not found!'), $code = 404); - } - - } - - function show($args, $apidata) { - parent::handle($args); - - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } - - $this->auth_user = $apidata['user']; - $notice_id = $apidata['api_arg']; - $notice = Notice::staticGet($notice_id); - - if ($notice) { - if ($apidata['content-type'] == 'xml') { - $this->show_single_xml_status($notice); - } elseif ($apidata['content-type'] == 'json') { - $this->show_single_json_status($notice); - } - } else { - // XXX: Twitter just sets a 404 header and doens't bother to return an err msg - $this->client_error(_('No status with that ID found.'), 404, $apidata['content-type']); - } - - } - - function destroy($args, $apidata) { - - parent::handle($args); - - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } - - // Check for RESTfulness - if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { - // XXX: Twitter just prints the err msg, no XML / JSON. - $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); - return; - } - - $this->auth_user = $apidata['user']; - $user = $this->auth_user; - $notice_id = $apidata['api_arg']; - $notice = Notice::staticGet($notice_id); - - if (!$notice) { - $this->client_error(_('No status found with that ID.'), 404, $apidata['content-type']); - return; - } - - if ($user->id == $notice->profile_id) { - $replies = new Reply; - $replies->get('notice_id', $notice_id); - common_dequeue_notice($notice); - $replies->delete(); - $notice->delete(); - - if ($apidata['content-type'] == 'xml') { - $this->show_single_xml_status($notice); - } elseif ($apidata['content-type'] == 'json') { - $this->show_single_json_status($notice); - } - } else { - $this->client_error(_('You may not delete another user\'s status.'), 403, $apidata['content-type']); - } - - } - - function friends($args, $apidata) { - parent::handle($args); - return $this->subscriptions($apidata, 'subscribed', 'subscriber'); - } - - function followers($args, $apidata) { - parent::handle($args); - - return $this->subscriptions($apidata, 'subscriber', 'subscribed'); - } - - function subscriptions($apidata, $other_attr, $user_attr) { - - # XXX: lite - - $this->auth_user = $apidate['user']; - $user = $this->get_user($apidata['api_arg'], $apidata); - - if (!$user) { - $this->client_error('Not Found', 404, $apidata['content-type']); - return; - } - - $page = $this->trimmed('page'); - - if (!$page || !is_numeric($page)) { - $page = 1; - } - - $profile = $user->getProfile(); - - if (!$profile) { - common_server_error(_('User has no profile.')); - return; - } - - $sub = new Subscription(); - $sub->$user_attr = $profile->id; - - $since = strtotime($this->trimmed('since')); - - if ($since) { - $d = date('Y-m-d H:i:s', $since); - $sub->whereAdd("created > '$d'"); - } - - $sub->orderBy('created DESC'); - $sub->limit(($page-1)*100, 100); - - $others = array(); - - if ($sub->find()) { - while ($sub->fetch()) { - $others[] = Profile::staticGet($sub->$other_attr); - } - } else { - // user has no followers - } - - $type = $apidata['content-type']; - - $this->init_document($type); - $this->show_profiles($others, $type); - $this->end_document($type); - } - - function show_profiles($profiles, $type) { - switch ($type) { - case 'xml': - common_element_start('users', array('type' => 'array')); - foreach ($profiles as $profile) { - $this->show_profile($profile); - } - common_element_end('users'); - break; - case 'json': - $arrays = array(); - foreach ($profiles as $profile) { - $arrays[] = $this->twitter_user_array($profile, true); - } - print json_encode($arrays); - break; - default: - $this->client_error(_('unsupported file type')); - } - } - - function featured($args, $apidata) { - parent::handle($args); - common_server_error(_('API method under construction.'), $code=501); - } - - function supported($cmd) { - - $cmdlist = array('MessageCommand', 'SubCommand', 'UnsubCommand', 'FavCommand', 'OnCommand', 'OffCommand'); + if ($in_reply_to_status_id) { + + // check whether notice actually exists + $reply = Notice::staticGet($in_reply_to_status_id); + + if ($reply) { + $reply_to = $in_reply_to_status_id; + } else { + $this->client_error(_('Not found'), $code = 404, $apidata['content-type']); + return; + } + } + + $notice = Notice::saveNew($user->id, html_entity_decode($status, ENT_NOQUOTES, 'UTF-8'), + $source, 1, $reply_to); + + if (is_string($notice)) { + $this->server_error($notice); + return; + } + + common_broadcast_notice($notice); + $apidata['api_arg'] = $notice->id; + } + + $this->show($args, $apidata); + } + + function replies($args, $apidata) { + + parent::handle($args); + + $since = $this->arg('since'); + $count = $this->arg('count'); + $page = $this->arg('page'); + $since_id = $this->arg('since_id'); + $before_id = $this->arg('before_id'); + + $this->auth_user = $apidata['user']; + $user = $this->auth_user; + $profile = $user->getProfile(); + + $sitename = common_config('site', 'name'); + $siteserver = common_config('site', 'server'); + + $title = sprintf(_('%1$s / Updates replying to %2$s'), $sitename, $user->nickname); + $id = "tag:$siteserver:replies:".$user->id; + $link = common_local_url('replies', array('nickname' => $user->nickname)); + $subtitle = sprintf(_('%1$s updates that reply to updates from %2$s / %3$s.'), $sitename, $user->nickname, $profile->getBestName()); + + if (!$page) { + $page = 1; + } + + if (!$count) { + $count = 20; + } + + if (!$since_id) { + $since_id = 0; + } + + // NOTE: before_id is an extension to Twitter API -- TB + if (!$before_id) { + $before_id = 0; + } + + $since = strtotime($this->arg('since')); + + $notice = $user->getReplies((($page-1)*20), $count, $since_id, $before_id, $since); + $notices = array(); + + while ($notice->fetch()) { + $notices[] = clone($notice); + } + + switch($apidata['content-type']) { + case 'xml': + $this->show_xml_timeline($notices); + break; + case 'rss': + $this->show_rss_timeline($notices, $title, $link, $subtitle); + break; + case 'atom': + $this->show_atom_timeline($notices, $title, $id, $link, $subtitle); + break; + case 'json': + $this->show_json_timeline($notices); + break; + default: + common_user_error(_('API method not found!'), $code = 404); + } + + } + + function show($args, $apidata) { + parent::handle($args); + + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } + + $this->auth_user = $apidata['user']; + $notice_id = $apidata['api_arg']; + $notice = Notice::staticGet($notice_id); + + if ($notice) { + if ($apidata['content-type'] == 'xml') { + $this->show_single_xml_status($notice); + } elseif ($apidata['content-type'] == 'json') { + $this->show_single_json_status($notice); + } + } else { + // XXX: Twitter just sets a 404 header and doens't bother to return an err msg + $this->client_error(_('No status with that ID found.'), 404, $apidata['content-type']); + } + + } + + function destroy($args, $apidata) { + + parent::handle($args); + + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } + + // Check for RESTfulness + if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) { + // XXX: Twitter just prints the err msg, no XML / JSON. + $this->client_error(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']); + return; + } + + $this->auth_user = $apidata['user']; + $user = $this->auth_user; + $notice_id = $apidata['api_arg']; + $notice = Notice::staticGet($notice_id); + + if (!$notice) { + $this->client_error(_('No status found with that ID.'), 404, $apidata['content-type']); + return; + } + + if ($user->id == $notice->profile_id) { + $replies = new Reply; + $replies->get('notice_id', $notice_id); + common_dequeue_notice($notice); + $replies->delete(); + $notice->delete(); + + if ($apidata['content-type'] == 'xml') { + $this->show_single_xml_status($notice); + } elseif ($apidata['content-type'] == 'json') { + $this->show_single_json_status($notice); + } + } else { + $this->client_error(_('You may not delete another user\'s status.'), 403, $apidata['content-type']); + } + + } + + function friends($args, $apidata) { + parent::handle($args); + return $this->subscriptions($apidata, 'subscribed', 'subscriber'); + } + + function followers($args, $apidata) { + parent::handle($args); + + return $this->subscriptions($apidata, 'subscriber', 'subscribed'); + } + + function subscriptions($apidata, $other_attr, $user_attr) { + + # XXX: lite + + $this->auth_user = $apidate['user']; + $user = $this->get_user($apidata['api_arg'], $apidata); + + if (!$user) { + $this->client_error('Not Found', 404, $apidata['content-type']); + return; + } + + $page = $this->trimmed('page'); + + if (!$page || !is_numeric($page)) { + $page = 1; + } + + $profile = $user->getProfile(); + + if (!$profile) { + common_server_error(_('User has no profile.')); + return; + } + + $sub = new Subscription(); + $sub->$user_attr = $profile->id; + + $since = strtotime($this->trimmed('since')); + + if ($since) { + $d = date('Y-m-d H:i:s', $since); + $sub->whereAdd("created > '$d'"); + } + + $sub->orderBy('created DESC'); + $sub->limit(($page-1)*100, 100); + + $others = array(); + + if ($sub->find()) { + while ($sub->fetch()) { + $others[] = Profile::staticGet($sub->$other_attr); + } + } else { + // user has no followers + } + + $type = $apidata['content-type']; + + $this->init_document($type); + $this->show_profiles($others, $type); + $this->end_document($type); + } + + function show_profiles($profiles, $type) { + switch ($type) { + case 'xml': + common_element_start('users', array('type' => 'array')); + foreach ($profiles as $profile) { + $this->show_profile($profile); + } + common_element_end('users'); + break; + case 'json': + $arrays = array(); + foreach ($profiles as $profile) { + $arrays[] = $this->twitter_user_array($profile, true); + } + print json_encode($arrays); + break; + default: + $this->client_error(_('unsupported file type')); + } + } + + function featured($args, $apidata) { + parent::handle($args); + common_server_error(_('API method under construction.'), $code=501); + } + + function supported($cmd) { + + $cmdlist = array('MessageCommand', 'SubCommand', 'UnsubCommand', 'FavCommand', 'OnCommand', 'OffCommand'); - if (in_array(get_class($cmd), $cmdlist)) { - return true; - } + if (in_array(get_class($cmd), $cmdlist)) { + return true; + } - return false; - } + return false; + } } diff --git a/_darcs/pristine/actions/twitapiusers.php b/_darcs/pristine/actions/twitapiusers.php index 9e06efa64..43f6969f4 100644 --- a/_darcs/pristine/actions/twitapiusers.php +++ b/_darcs/pristine/actions/twitapiusers.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,30 +23,30 @@ require_once(INSTALLDIR.'/lib/twitterapi.php'); class TwitapiusersAction extends TwitterapiAction { - function show($args, $apidata) { - parent::handle($args); + function show($args, $apidata) { + parent::handle($args); - if (!in_array($apidata['content-type'], array('xml', 'json'))) { - common_user_error(_('API method not found!'), $code = 404); - return; - } + if (!in_array($apidata['content-type'], array('xml', 'json'))) { + common_user_error(_('API method not found!'), $code = 404); + return; + } - $user = null; - $email = $this->arg('email'); + $user = null; + $email = $this->arg('email'); - if ($email) { - $user = User::staticGet('email', $email); - } elseif (isset($apidata['api_arg'])) { - $user = $this->get_user($apidata['api_arg']); - } + if ($email) { + $user = User::staticGet('email', $email); + } elseif (isset($apidata['api_arg'])) { + $user = $this->get_user($apidata['api_arg']); + } - if (!$user) { - // XXX: Twitter returns a random(?) user instead of throwing and err! -- Zach - $this->client_error(_('Not found.'), 404, $apidata['content-type']); - return; - } + if (!$user) { + // XXX: Twitter returns a random(?) user instead of throwing and err! -- Zach + $this->client_error(_('Not found.'), 404, $apidata['content-type']); + return; + } - $this->show_extended_profile($user, $apidata); - } + $this->show_extended_profile($user, $apidata); + } } diff --git a/_darcs/pristine/actions/twittersettings.php b/_darcs/pristine/actions/twittersettings.php index ae3aff877..e300e699a 100644 --- a/_darcs/pristine/actions/twittersettings.php +++ b/_darcs/pristine/actions/twittersettings.php @@ -25,354 +25,354 @@ define('SUBSCRIPTIONS', 80); class TwittersettingsAction extends SettingsAction { - function get_instructions() { - return _('Add your Twitter account to automatically send your notices to Twitter, ' . - 'and subscribe to Twitter friends already here.'); - } + function get_instructions() { + return _('Add your Twitter account to automatically send your notices to Twitter, ' . + 'and subscribe to Twitter friends already here.'); + } - function show_form($msg=NULL, $success=false) { - $user = common_current_user(); - $profile = $user->getProfile(); - $fuser = NULL; - $flink = Foreign_link::getByUserID($user->id, 1); // 1 == Twitter + function show_form($msg=NULL, $success=false) { + $user = common_current_user(); + $profile = $user->getProfile(); + $fuser = NULL; + $flink = Foreign_link::getByUserID($user->id, 1); // 1 == Twitter - if ($flink) { - $fuser = $flink->getForeignUser(); - } + if ($flink) { + $fuser = $flink->getForeignUser(); + } - $this->form_header(_('Twitter settings'), $msg, $success); - common_element_start('form', array('method' => 'post', - 'id' => 'twittersettings', - 'action' => - common_local_url('twittersettings'))); - common_hidden('token', common_session_token()); + $this->form_header(_('Twitter settings'), $msg, $success); + common_element_start('form', array('method' => 'post', + 'id' => 'twittersettings', + 'action' => + common_local_url('twittersettings'))); + common_hidden('token', common_session_token()); - common_element('h2', NULL, _('Twitter Account')); + common_element('h2', NULL, _('Twitter Account')); - if ($fuser) { - common_element_start('p'); + if ($fuser) { + common_element_start('p'); - common_element('span', 'twitter_user', $fuser->nickname); - common_element('a', array('href' => $fuser->uri), $fuser->uri); - common_element('span', 'input_instructions', - _('Current verified Twitter account.')); - common_hidden('flink_foreign_id', $flink->foreign_id); - common_element_end('p'); - common_submit('remove', _('Remove')); - } else { - common_input('twitter_username', _('Twitter user name'), - ($this->arg('twitter_username')) ? $this->arg('twitter_username') : $profile->nickname, - _('No spaces, please.')); // hey, it's what Twitter says + common_element('span', 'twitter_user', $fuser->nickname); + common_element('a', array('href' => $fuser->uri), $fuser->uri); + common_element('span', 'input_instructions', + _('Current verified Twitter account.')); + common_hidden('flink_foreign_id', $flink->foreign_id); + common_element_end('p'); + common_submit('remove', _('Remove')); + } else { + common_input('twitter_username', _('Twitter user name'), + ($this->arg('twitter_username')) ? $this->arg('twitter_username') : $profile->nickname, + _('No spaces, please.')); // hey, it's what Twitter says - common_password('twitter_password', _('Twitter password')); - } + common_password('twitter_password', _('Twitter password')); + } - common_element('h2', NULL, _('Preferences')); + common_element('h2', NULL, _('Preferences')); - common_checkbox('noticesync', _('Automatically send my notices to Twitter.'), - ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND) : true); + common_checkbox('noticesync', _('Automatically send my notices to Twitter.'), + ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND) : true); - common_checkbox('replysync', _('Send local "@" replies to Twitter.'), - ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : true); + common_checkbox('replysync', _('Send local "@" replies to Twitter.'), + ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : true); - common_checkbox('friendsync', _('Subscribe to my Twitter friends here.'), - ($flink) ? ($flink->friendsync & FOREIGN_FRIEND_RECV) : false); + common_checkbox('friendsync', _('Subscribe to my Twitter friends here.'), + ($flink) ? ($flink->friendsync & FOREIGN_FRIEND_RECV) : false); - if ($flink) { - common_submit('save', _('Save')); - } else { - common_submit('add', _('Add')); - } + if ($flink) { + common_submit('save', _('Save')); + } else { + common_submit('add', _('Add')); + } - $this->show_twitter_subscriptions(); + $this->show_twitter_subscriptions(); - common_element_end('form'); + common_element_end('form'); - common_show_footer(); - } + common_show_footer(); + } - function subscribed_twitter_users() { + function subscribed_twitter_users() { - $current_user = common_current_user(); + $current_user = common_current_user(); - $qry = 'SELECT user.* ' . - 'FROM subscription ' . - 'JOIN user ON subscription.subscribed = user.id ' . - 'JOIN foreign_link ON foreign_link.user_id = user.id ' . - 'WHERE subscriber = %d ' . - 'ORDER BY user.nickname'; + $qry = 'SELECT user.* ' . + 'FROM subscription ' . + 'JOIN user ON subscription.subscribed = user.id ' . + 'JOIN foreign_link ON foreign_link.user_id = user.id ' . + 'WHERE subscriber = %d ' . + 'ORDER BY user.nickname'; - $user = new User(); + $user = new User(); - $user->query(sprintf($qry, $current_user->id)); - - $users = array(); + $user->query(sprintf($qry, $current_user->id)); + + $users = array(); - while ($user->fetch()) { - - // Don't include the user's own self-subscription - if ($user->id != $current_user->id) { - $users[] = clone($user); - } - } - - return $users; - } - - function show_twitter_subscriptions() { - - $friends = $this->subscribed_twitter_users(); - $friends_count = count($friends); - - if ($friends_count > 0) { - - common_element('h3', NULL, _('Twitter Friends')); - common_element_start('div', array('id' => 'subscriptions')); - common_element_start('ul', array('id' => 'subscriptions_avatars')); - - for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) { - - $other = Profile::staticGet($friends[$i]->id); - - if (!$other) { - common_log_db_error($subs, 'SELECT', __FILE__); - continue; - } - - common_element_start('li'); - common_element_start('a', array('title' => ($other->fullname) ? - $other->fullname : - $other->nickname, - 'href' => $other->profileurl, - 'rel' => 'contact', - 'class' => 'subscription')); - $avatar = $other->getAvatar(AVATAR_MINI_SIZE); - common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)), - 'width' => AVATAR_MINI_SIZE, - 'height' => AVATAR_MINI_SIZE, - 'class' => 'avatar mini', - 'alt' => ($other->fullname) ? - $other->fullname : - $other->nickname)); - common_element_end('a'); - common_element_end('li'); - - } + while ($user->fetch()) { + + // Don't include the user's own self-subscription + if ($user->id != $current_user->id) { + $users[] = clone($user); + } + } + + return $users; + } + + function show_twitter_subscriptions() { + + $friends = $this->subscribed_twitter_users(); + $friends_count = count($friends); + + if ($friends_count > 0) { + + common_element('h3', NULL, _('Twitter Friends')); + common_element_start('div', array('id' => 'subscriptions')); + common_element_start('ul', array('id' => 'subscriptions_avatars')); + + for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) { + + $other = Profile::staticGet($friends[$i]->id); + + if (!$other) { + common_log_db_error($subs, 'SELECT', __FILE__); + continue; + } + + common_element_start('li'); + common_element_start('a', array('title' => ($other->fullname) ? + $other->fullname : + $other->nickname, + 'href' => $other->profileurl, + 'rel' => 'contact', + 'class' => 'subscription')); + $avatar = $other->getAvatar(AVATAR_MINI_SIZE); + common_element('img', array('src' => (($avatar) ? common_avatar_display_url($avatar) : common_default_avatar(AVATAR_MINI_SIZE)), + 'width' => AVATAR_MINI_SIZE, + 'height' => AVATAR_MINI_SIZE, + 'class' => 'avatar mini', + 'alt' => ($other->fullname) ? + $other->fullname : + $other->nickname)); + common_element_end('a'); + common_element_end('li'); + + } - common_element_end('ul'); - common_element_end('div'); + common_element_end('ul'); + common_element_end('div'); - } + } - // XXX Figure out a way to show all Twitter friends... ? + // XXX Figure out a way to show all Twitter friends... ? - /* - if ($subs_count > SUBSCRIPTIONS) { - common_element_start('p', array('id' => 'subscriptions_viewall')); + /* + if ($subs_count > SUBSCRIPTIONS) { + common_element_start('p', array('id' => 'subscriptions_viewall')); - common_element('a', array('href' => common_local_url('subscriptions', - array('nickname' => $profile->nickname)), - 'class' => 'moresubscriptions'), - _('All subscriptions')); - common_element_end('p'); - } - */ + common_element('a', array('href' => common_local_url('subscriptions', + array('nickname' => $profile->nickname)), + 'class' => 'moresubscriptions'), + _('All subscriptions')); + common_element_end('p'); + } + */ - } - - function handle_post() { + } + + function handle_post() { - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->show_form(_('There was a problem with your session token. Try again, please.')); - return; - } - - if ($this->arg('save')) { - $this->save_preferences(); - } else if ($this->arg('add')) { - $this->add_twitter_acct(); - } else if ($this->arg('remove')) { - $this->remove_twitter_acct(); - } else { - $this->show_form(_('Unexpected form submission.')); - } - } + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $this->show_form(_('There was a problem with your session token. Try again, please.')); + return; + } + + if ($this->arg('save')) { + $this->save_preferences(); + } else if ($this->arg('add')) { + $this->add_twitter_acct(); + } else if ($this->arg('remove')) { + $this->remove_twitter_acct(); + } else { + $this->show_form(_('Unexpected form submission.')); + } + } - function add_twitter_acct() { + function add_twitter_acct() { - $screen_name = $this->trimmed('twitter_username'); - $password = $this->trimmed('twitter_password'); - $noticesync = $this->boolean('noticesync'); - $replysync = $this->boolean('replysync'); - $friendsync = $this->boolean('friendsync'); - - if (!Validate::string($screen_name, - array( 'min_length' => 1, - 'max_length' => 15, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA . '_'))) { - $this->show_form( - _('Username must have only numbers, upper- and lowercase letters, and underscore (_). 15 chars max.')); - return; - } - - if (!$this->verify_credentials($screen_name, $password)) { - $this->show_form(_('Could not verify your Twitter credentials!')); - return; - } - - $twit_user = twitter_user_info($screen_name, $password); - - if (!$twit_user) { - $this->show_form(sprintf(_('Unable to retrieve account information for "%s" from Twitter.'), - $screen_name)); - return; - } - - if (!save_twitter_user($twit_user->id, $screen_name)) { - $this->show_form(_('Unable to save your Twitter settings!')); - return; - } - - $user = common_current_user(); - - $flink = DB_DataObject::factory('foreign_link'); - $flink->user_id = $user->id; - $flink->foreign_id = $twit_user->id; - $flink->service = 1; // Twitter - $flink->credentials = $password; - $flink->created = common_sql_now(); - - $this->set_flags($flink, $noticesync, $replysync, $friendsync); - - $flink_id = $flink->insert(); - - if (!$flink_id) { - common_log_db_error($flink, 'INSERT', __FILE__); - $this->show_form(_('Unable to save your Twitter settings!')); - return; - } + $screen_name = $this->trimmed('twitter_username'); + $password = $this->trimmed('twitter_password'); + $noticesync = $this->boolean('noticesync'); + $replysync = $this->boolean('replysync'); + $friendsync = $this->boolean('friendsync'); + + if (!Validate::string($screen_name, + array( 'min_length' => 1, + 'max_length' => 15, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA . '_'))) { + $this->show_form( + _('Username must have only numbers, upper- and lowercase letters, and underscore (_). 15 chars max.')); + return; + } + + if (!$this->verify_credentials($screen_name, $password)) { + $this->show_form(_('Could not verify your Twitter credentials!')); + return; + } + + $twit_user = twitter_user_info($screen_name, $password); + + if (!$twit_user) { + $this->show_form(sprintf(_('Unable to retrieve account information for "%s" from Twitter.'), + $screen_name)); + return; + } + + if (!save_twitter_user($twit_user->id, $screen_name)) { + $this->show_form(_('Unable to save your Twitter settings!')); + return; + } + + $user = common_current_user(); + + $flink = DB_DataObject::factory('foreign_link'); + $flink->user_id = $user->id; + $flink->foreign_id = $twit_user->id; + $flink->service = 1; // Twitter + $flink->credentials = $password; + $flink->created = common_sql_now(); + + $this->set_flags($flink, $noticesync, $replysync, $friendsync); + + $flink_id = $flink->insert(); + + if (!$flink_id) { + common_log_db_error($flink, 'INSERT', __FILE__); + $this->show_form(_('Unable to save your Twitter settings!')); + return; + } - if ($friendsync) { - save_twitter_friends($user, $twit_user->id, $screen_name, $password); - } + if ($friendsync) { + save_twitter_friends($user, $twit_user->id, $screen_name, $password); + } - $this->show_form(_('Twitter settings saved.'), true); - } + $this->show_form(_('Twitter settings saved.'), true); + } - function remove_twitter_acct() { - - $user = common_current_user(); - $flink = Foreign_link::getByUserID($user->id, 1); - $flink_foreign_id = $this->arg('flink_foreign_id'); - - # Maybe an old tab open...? - if ($flink->foreign_id != $flink_foreign_id) { - $this->show_form(_('That is not your Twitter account.')); - return; - } - - $result = $flink->delete(); - - if (!$result) { - common_log_db_error($flink, 'DELETE', __FILE__); - common_server_error(_('Couldn\'t remove Twitter user.')); - return; - } - - $this->show_form(_('Twitter account removed.'), TRUE); - } - - function save_preferences() { - - $noticesync = $this->boolean('noticesync'); - $friendsync = $this->boolean('friendsync'); - $replysync = $this->boolean('replysync'); - - $user = common_current_user(); - - $flink = Foreign_link::getByUserID($user->id, 1); - - if (!$flink) { - common_log_db_error($flink, 'SELECT', __FILE__); - $this->show_form(_('Couldn\'t save Twitter preferences.')); - return; - } + function remove_twitter_acct() { + + $user = common_current_user(); + $flink = Foreign_link::getByUserID($user->id, 1); + $flink_foreign_id = $this->arg('flink_foreign_id'); + + # Maybe an old tab open...? + if ($flink->foreign_id != $flink_foreign_id) { + $this->show_form(_('That is not your Twitter account.')); + return; + } + + $result = $flink->delete(); + + if (!$result) { + common_log_db_error($flink, 'DELETE', __FILE__); + common_server_error(_('Couldn\'t remove Twitter user.')); + return; + } + + $this->show_form(_('Twitter account removed.'), TRUE); + } + + function save_preferences() { + + $noticesync = $this->boolean('noticesync'); + $friendsync = $this->boolean('friendsync'); + $replysync = $this->boolean('replysync'); + + $user = common_current_user(); + + $flink = Foreign_link::getByUserID($user->id, 1); + + if (!$flink) { + common_log_db_error($flink, 'SELECT', __FILE__); + $this->show_form(_('Couldn\'t save Twitter preferences.')); + return; + } - $twitter_id = $flink->foreign_id; - $password = $flink->credentials; - - $fuser = $flink->getForeignUser(); + $twitter_id = $flink->foreign_id; + $password = $flink->credentials; + + $fuser = $flink->getForeignUser(); - if (!$fuser) { - common_log_db_error($fuser, 'SELECT', __FILE__); - $this->show_form(_('Couldn\'t save Twitter preferences.')); - return; - } + if (!$fuser) { + common_log_db_error($fuser, 'SELECT', __FILE__); + $this->show_form(_('Couldn\'t save Twitter preferences.')); + return; + } - $screen_name = $fuser->nickname; + $screen_name = $fuser->nickname; - $original = clone($flink); - $this->set_flags($flink, $noticesync, $replysync, $friendsync); - $result = $flink->update($original); + $original = clone($flink); + $this->set_flags($flink, $noticesync, $replysync, $friendsync); + $result = $flink->update($original); - if ($result === FALSE) { - common_log_db_error($flink, 'UPDATE', __FILE__); - $this->show_form(_('Couldn\'t save Twitter preferences.')); - return; - } + if ($result === FALSE) { + common_log_db_error($flink, 'UPDATE', __FILE__); + $this->show_form(_('Couldn\'t save Twitter preferences.')); + return; + } - if ($friendsync) { - save_twitter_friends($user, $flink->foreign_id, $screen_name, $password); - } + if ($friendsync) { + save_twitter_friends($user, $flink->foreign_id, $screen_name, $password); + } - $this->show_form(_('Twitter preferences saved.')); - } + $this->show_form(_('Twitter preferences saved.')); + } - function verify_credentials($screen_name, $password) { - $uri = 'http://twitter.com/account/verify_credentials.json'; - $data = get_twitter_data($uri, $screen_name, $password); + function verify_credentials($screen_name, $password) { + $uri = 'http://twitter.com/account/verify_credentials.json'; + $data = get_twitter_data($uri, $screen_name, $password); - if (!$data) { - return false; - } + if (!$data) { + return false; + } - $user = json_decode($data); + $user = json_decode($data); - if (!$user) { - return false; - } + if (!$user) { + return false; + } - $twitter_id = $user->status->id; + $twitter_id = $user->status->id; - if ($twitter_id) { - return $twitter_id; - } + if ($twitter_id) { + return $twitter_id; + } - return false; - } + return false; + } - function set_flags(&$flink, $noticesync, $replysync, $friendsync) { - if ($noticesync) { - $flink->noticesync |= FOREIGN_NOTICE_SEND; - } else { - $flink->noticesync &= ~FOREIGN_NOTICE_SEND; - } + function set_flags(&$flink, $noticesync, $replysync, $friendsync) { + if ($noticesync) { + $flink->noticesync |= FOREIGN_NOTICE_SEND; + } else { + $flink->noticesync &= ~FOREIGN_NOTICE_SEND; + } - if ($replysync) { - $flink->noticesync |= FOREIGN_NOTICE_SEND_REPLY; - } else { - $flink->noticesync &= ~FOREIGN_NOTICE_SEND_REPLY; - } + if ($replysync) { + $flink->noticesync |= FOREIGN_NOTICE_SEND_REPLY; + } else { + $flink->noticesync &= ~FOREIGN_NOTICE_SEND_REPLY; + } - if ($friendsync) { - $flink->friendsync |= FOREIGN_FRIEND_RECV; - } else { - $flink->friendsync &= ~FOREIGN_FRIEND_RECV; - } + if ($friendsync) { + $flink->friendsync |= FOREIGN_FRIEND_RECV; + } else { + $flink->friendsync &= ~FOREIGN_FRIEND_RECV; + } - $flink->profilesync = 0; - } + $flink->profilesync = 0; + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/unblock.php b/_darcs/pristine/actions/unblock.php index d60cc7088..6a86c2bf0 100644 --- a/_darcs/pristine/actions/unblock.php +++ b/_darcs/pristine/actions/unblock.php @@ -32,12 +32,12 @@ class UnblockAction extends Action { return false; } - $token = $this->trimmed('token'); + $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } $id = $this->trimmed('unblockto'); diff --git a/_darcs/pristine/actions/unsubscribe.php b/_darcs/pristine/actions/unsubscribe.php index 98291e897..38fcc21de 100644 --- a/_darcs/pristine/actions/unsubscribe.php +++ b/_darcs/pristine/actions/unsubscribe.php @@ -19,30 +19,30 @@ class UnsubscribeAction extends Action { - function handle($args) { - parent::handle($args); - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - return; - } + function handle($args) { + parent::handle($args); + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + return; + } - $user = common_current_user(); + $user = common_current_user(); - if ($_SERVER['REQUEST_METHOD'] != 'POST') { - common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname))); - return; - } + if ($_SERVER['REQUEST_METHOD'] != 'POST') { + common_redirect(common_local_url('subscriptions', array('nickname' => $user->nickname))); + return; + } - # CSRF protection + # CSRF protection - $token = $this->trimmed('token'); + $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $this->client_error(_('There was a problem with your session token. Try again, please.')); - return; - } + if (!$token || $token != common_session_token()) { + $this->client_error(_('There was a problem with your session token. Try again, please.')); + return; + } - $other_id = $this->arg('unsubscribeto'); + $other_id = $this->arg('unsubscribeto'); if (!$other_id) { $this->client_error(_('No profile id in request.')); @@ -56,25 +56,25 @@ class UnsubscribeAction extends Action { return; } - $result = subs_unsubscribe_to($user, $other); + $result = subs_unsubscribe_to($user, $other); - if ($result != true) { - common_user_error($result); - return; - } + if ($result != true) { + common_user_error($result); + return; + } - if ($this->boolean('ajax')) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Unsubscribed')); - common_element_end('head'); - common_element_start('body'); - common_subscribe_form($other); - common_element_end('body'); - common_element_end('html'); - } else { - common_redirect(common_local_url('subscriptions', array('nickname' => - $user->nickname))); + if ($this->boolean('ajax')) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Unsubscribed')); + common_element_end('head'); + common_element_start('body'); + common_subscribe_form($other); + common_element_end('body'); + common_element_end('html'); + } else { + common_redirect(common_local_url('subscriptions', array('nickname' => + $user->nickname))); } - } + } } diff --git a/_darcs/pristine/actions/updateprofile.php b/_darcs/pristine/actions/updateprofile.php index 921e88e63..4b4bb53a1 100644 --- a/_darcs/pristine/actions/updateprofile.php +++ b/_darcs/pristine/actions/updateprofile.php @@ -22,153 +22,153 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/lib/omb.php'); class UpdateprofileAction extends Action { - - function handle($args) { - parent::handle($args); - try { - common_remove_magic_from_request(); - $req = OAuthRequest::from_request(); - # Note: server-to-server function! - $server = omb_oauth_server(); - list($consumer, $token) = $server->verify_request($req); - if ($this->update_profile($req, $consumer, $token)) { - print "omb_version=".OMB_VERSION_01; - } - } catch (OAuthException $e) { - $this->server_error($e->getMessage()); - return; - } - } + + function handle($args) { + parent::handle($args); + try { + common_remove_magic_from_request(); + $req = OAuthRequest::from_request(); + # Note: server-to-server function! + $server = omb_oauth_server(); + list($consumer, $token) = $server->verify_request($req); + if ($this->update_profile($req, $consumer, $token)) { + print "omb_version=".OMB_VERSION_01; + } + } catch (OAuthException $e) { + $this->server_error($e->getMessage()); + return; + } + } - function update_profile($req, $consumer, $token) { - $version = $req->get_parameter('omb_version'); - if ($version != OMB_VERSION_01) { - $this->client_error(_('Unsupported OMB version'), 400); - return false; - } - # First, check to see if listenee exists - $listenee = $req->get_parameter('omb_listenee'); - $remote = Remote_profile::staticGet('uri', $listenee); - if (!$remote) { - $this->client_error(_('Profile unknown'), 404); - return false; - } - # Second, check to see if they should be able to post updates! - # We see if there are any subscriptions to that remote user with - # the given token. + function update_profile($req, $consumer, $token) { + $version = $req->get_parameter('omb_version'); + if ($version != OMB_VERSION_01) { + $this->client_error(_('Unsupported OMB version'), 400); + return false; + } + # First, check to see if listenee exists + $listenee = $req->get_parameter('omb_listenee'); + $remote = Remote_profile::staticGet('uri', $listenee); + if (!$remote) { + $this->client_error(_('Profile unknown'), 404); + return false; + } + # Second, check to see if they should be able to post updates! + # We see if there are any subscriptions to that remote user with + # the given token. - $sub = new Subscription(); - $sub->subscribed = $remote->id; - $sub->token = $token->key; - if (!$sub->find(true)) { - $this->client_error(_('You did not send us that profile'), 403); - return false; - } + $sub = new Subscription(); + $sub->subscribed = $remote->id; + $sub->token = $token->key; + if (!$sub->find(true)) { + $this->client_error(_('You did not send us that profile'), 403); + return false; + } - $profile = Profile::staticGet('id', $remote->id); - if (!$profile) { - # This one is our fault - $this->server_error(_('Remote profile with no matching profile'), 500); - return false; - } - $nickname = $req->get_parameter('omb_listenee_nickname'); - if ($nickname && !Validate::string($nickname, array('min_length' => 1, - 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { - $this->client_error(_('Nickname must have only lowercase letters and numbers and no spaces.')); - return false; - } - $license = $req->get_parameter('omb_listenee_license'); - if ($license && !common_valid_http_url($license)) { - $this->client_error(sprintf(_("Invalid license URL '%s'"), $license)); - return false; - } - $profile_url = $req->get_parameter('omb_listenee_profile'); - if ($profile_url && !common_valid_http_url($profile_url)) { - $this->client_error(sprintf(_("Invalid profile URL '%s'."), $profile_url)); - return false; - } - # optional stuff - $fullname = $req->get_parameter('omb_listenee_fullname'); - if ($fullname && strlen($fullname) > 255) { - $this->client_error(_("Full name is too long (max 255 chars).")); - return false; - } - $homepage = $req->get_parameter('omb_listenee_homepage'); - if ($homepage && (!common_valid_http_url($homepage) || strlen($homepage) > 255)) { - $this->client_error(sprintf(_("Invalid homepage '%s'"), $homepage)); - return false; - } - $bio = $req->get_parameter('omb_listenee_bio'); - if ($bio && strlen($bio) > 140) { - $this->client_error(_("Bio is too long (max 140 chars).")); - return false; - } - $location = $req->get_parameter('omb_listenee_location'); - if ($location && strlen($location) > 255) { - $this->client_error(_("Location is too long (max 255 chars).")); - return false; - } - $avatar = $req->get_parameter('omb_listenee_avatar'); - if ($avatar) { - if (!common_valid_http_url($avatar) || strlen($avatar) > 255) { - $this->client_error(sprintf(_("Invalid avatar URL '%s'"), $avatar)); - return false; - } - $size = @getimagesize($avatar); - if (!$size) { - $this->client_error(sprintf(_("Can't read avatar URL '%s'"), $avatar)); - return false; - } - if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) { - $this->client_error(sprintf(_("Wrong size image at '%s'"), $avatar)); - return false; - } - if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, - IMAGETYPE_PNG))) { - $this->client_error(sprintf(_("Wrong image type for '%s'"), $avatar)); - return false; - } - } + $profile = Profile::staticGet('id', $remote->id); + if (!$profile) { + # This one is our fault + $this->server_error(_('Remote profile with no matching profile'), 500); + return false; + } + $nickname = $req->get_parameter('omb_listenee_nickname'); + if ($nickname && !Validate::string($nickname, array('min_length' => 1, + 'max_length' => 64, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + $this->client_error(_('Nickname must have only lowercase letters and numbers and no spaces.')); + return false; + } + $license = $req->get_parameter('omb_listenee_license'); + if ($license && !common_valid_http_url($license)) { + $this->client_error(sprintf(_("Invalid license URL '%s'"), $license)); + return false; + } + $profile_url = $req->get_parameter('omb_listenee_profile'); + if ($profile_url && !common_valid_http_url($profile_url)) { + $this->client_error(sprintf(_("Invalid profile URL '%s'."), $profile_url)); + return false; + } + # optional stuff + $fullname = $req->get_parameter('omb_listenee_fullname'); + if ($fullname && strlen($fullname) > 255) { + $this->client_error(_("Full name is too long (max 255 chars).")); + return false; + } + $homepage = $req->get_parameter('omb_listenee_homepage'); + if ($homepage && (!common_valid_http_url($homepage) || strlen($homepage) > 255)) { + $this->client_error(sprintf(_("Invalid homepage '%s'"), $homepage)); + return false; + } + $bio = $req->get_parameter('omb_listenee_bio'); + if ($bio && strlen($bio) > 140) { + $this->client_error(_("Bio is too long (max 140 chars).")); + return false; + } + $location = $req->get_parameter('omb_listenee_location'); + if ($location && strlen($location) > 255) { + $this->client_error(_("Location is too long (max 255 chars).")); + return false; + } + $avatar = $req->get_parameter('omb_listenee_avatar'); + if ($avatar) { + if (!common_valid_http_url($avatar) || strlen($avatar) > 255) { + $this->client_error(sprintf(_("Invalid avatar URL '%s'"), $avatar)); + return false; + } + $size = @getimagesize($avatar); + if (!$size) { + $this->client_error(sprintf(_("Can't read avatar URL '%s'"), $avatar)); + return false; + } + if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) { + $this->client_error(sprintf(_("Wrong size image at '%s'"), $avatar)); + return false; + } + if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, + IMAGETYPE_PNG))) { + $this->client_error(sprintf(_("Wrong image type for '%s'"), $avatar)); + return false; + } + } - $orig_profile = clone($profile); + $orig_profile = clone($profile); - if ($nickname) { - $profile->nickname = $nickname; - } - if ($profile_url) { - $profile->profileurl = $profile_url; - } - if ($fullname) { - $profile->fullname = $fullname; - } - if ($homepage) { - $profile->homepage = $homepage; - } - if ($bio) { - $profile->bio = $bio; - } - if ($location) { - $profile->location = $location; - } + if ($nickname) { + $profile->nickname = $nickname; + } + if ($profile_url) { + $profile->profileurl = $profile_url; + } + if ($fullname) { + $profile->fullname = $fullname; + } + if ($homepage) { + $profile->homepage = $homepage; + } + if ($bio) { + $profile->bio = $bio; + } + if ($location) { + $profile->location = $location; + } - if (!$profile->update($orig_profile)) { - $this->server_error(_('Could not save new profile info'), 500); - return false; - } else { - if ($avatar) { - $temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar'); - copy($avatar, $temp_filename); - if (!$profile->setOriginal($temp_filename)) { - $this->server_error(_('Could not save avatar info'), 500); - return false; - } - } - header('HTTP/1.1 200 OK'); - header('Content-type: text/plain'); - print 'Updated profile'; - print "\n"; - return true; - } - } + if (!$profile->update($orig_profile)) { + $this->server_error(_('Could not save new profile info'), 500); + return false; + } else { + if ($avatar) { + $temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar'); + copy($avatar, $temp_filename); + if (!$profile->setOriginal($temp_filename)) { + $this->server_error(_('Could not save avatar info'), 500); + return false; + } + } + header('HTTP/1.1 200 OK'); + header('Content-type: text/plain'); + print 'Updated profile'; + print "\n"; + return true; + } + } } diff --git a/_darcs/pristine/actions/userauthorization.php b/_darcs/pristine/actions/userauthorization.php index ac0a0728c..97809f197 100644 --- a/_darcs/pristine/actions/userauthorization.php +++ b/_darcs/pristine/actions/userauthorization.php @@ -24,556 +24,556 @@ define('TIMESTAMP_THRESHOLD', 300); class UserauthorizationAction extends Action { - function handle($args) { - parent::handle($args); - - if ($_SERVER['REQUEST_METHOD'] == 'POST') { - # CSRF protection - $token = $this->trimmed('token'); - if (!$token || $token != common_session_token()) { - $req = $this->get_stored_request(); - $this->show_form(_('There was a problem with your session token. Try again, please.'), $req); - return; - } - # We've shown the form, now post user's choice - $this->send_authorization(); - } else { - if (!common_logged_in()) { - # Go log in, and then come back - common_debug('saving URL for returnto', __FILE__); - common_set_returnto($_SERVER['REQUEST_URI']); - - common_debug('redirecting to login', __FILE__); - common_redirect(common_local_url('login')); - return; - } - try { - # this must be a new request - common_debug('getting new request', __FILE__); - $req = $this->get_new_request(); - if (!$req) { - $this->client_error(_('No request found!')); - } - common_debug('validating request', __FILE__); - # XXX: only validate new requests, since nonce is one-time use - $this->validate_request($req); - common_debug('showing form', __FILE__); - $this->store_request($req); - $this->show_form($req); - } catch (OAuthException $e) { - $this->clear_request(); - $this->client_error($e->getMessage()); - return; - } - - } - } - - function show_form($req) { - - $nickname = $req->get_parameter('omb_listenee_nickname'); - $profile = $req->get_parameter('omb_listenee_profile'); - $license = $req->get_parameter('omb_listenee_license'); - $fullname = $req->get_parameter('omb_listenee_fullname'); - $homepage = $req->get_parameter('omb_listenee_homepage'); - $bio = $req->get_parameter('omb_listenee_bio'); - $location = $req->get_parameter('omb_listenee_location'); - $avatar = $req->get_parameter('omb_listenee_avatar'); - - common_show_header(_('Authorize subscription')); - common_element('p', NULL, _('Please check these details to make sure '. - 'that you want to subscribe to this user\'s notices. '. - 'If you didn\'t just ask to subscribe to someone\'s notices, '. - 'click "Cancel".')); - common_element_start('div', 'profile'); - if ($avatar) { - common_element('img', array('src' => $avatar, - 'class' => 'avatar profile', - 'width' => AVATAR_PROFILE_SIZE, - 'height' => AVATAR_PROFILE_SIZE, - 'alt' => $nickname)); - } - common_element('a', array('href' => $profile, - 'class' => 'external profile nickname'), - $nickname); - if ($fullname) { - common_element_start('div', 'fullname'); - if ($homepage) { - common_element('a', array('href' => $homepage), - $fullname); - } else { - common_text($fullname); - } - common_element_end('div'); - } - if ($location) { - common_element('div', 'location', $location); - } - if ($bio) { - common_element('div', 'bio', $bio); - } - common_element_start('div', 'license'); - common_element('a', array('href' => $license, - 'class' => 'license'), - $license); - common_element_end('div'); - common_element_end('div'); - common_element_start('form', array('method' => 'post', - 'id' => 'userauthorization', - 'name' => 'userauthorization', - 'action' => common_local_url('userauthorization'))); - common_hidden('token', common_session_token()); - common_submit('accept', _('Accept')); - common_submit('reject', _('Reject')); - common_element_end('form'); - common_show_footer(); - } - - function send_authorization() { - $req = $this->get_stored_request(); - - if (!$req) { - common_user_error(_('No authorization request!')); - return; - } - - $callback = $req->get_parameter('oauth_callback'); - - if ($this->arg('accept')) { - if (!$this->authorize_token($req)) { - $this->client_error(_('Error authorizing token')); - } - if (!$this->save_remote_profile($req)) { - $this->client_error(_('Error saving remote profile')); - } - if (!$callback) { - $this->show_accept_message($req->get_parameter('oauth_token')); - } else { - $params = array(); - $params['oauth_token'] = $req->get_parameter('oauth_token'); - $params['omb_version'] = OMB_VERSION_01; - $user = User::staticGet('uri', $req->get_parameter('omb_listener')); - $profile = $user->getProfile(); - if (!$profile) { - common_log_db_error($user, 'SELECT', __FILE__); - $this->server_error(_('User without matching profile')); - return; - } - $params['omb_listener_nickname'] = $user->nickname; - $params['omb_listener_profile'] = common_local_url('showstream', - array('nickname' => $user->nickname)); - if ($profile->fullname) { - $params['omb_listener_fullname'] = $profile->fullname; - } - if ($profile->homepage) { - $params['omb_listener_homepage'] = $profile->homepage; - } - if ($profile->bio) { - $params['omb_listener_bio'] = $profile->bio; - } - if ($profile->location) { - $params['omb_listener_location'] = $profile->location; - } - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - if ($avatar) { - $params['omb_listener_avatar'] = $avatar->url; - } - $parts = array(); - foreach ($params as $k => $v) { - $parts[] = $k . '=' . OAuthUtil::urlencodeRFC3986($v); - } - $query_string = implode('&', $parts); - $parsed = parse_url($callback); - $url = $callback . (($parsed['query']) ? '&' : '?') . $query_string; - common_redirect($url, 303); - } - } else { - if (!$callback) { - $this->show_reject_message(); - } else { - # XXX: not 100% sure how to signal failure... just redirect without token? - common_redirect($callback, 303); - } - } - } - - function authorize_token(&$req) { - $consumer_key = $req->get_parameter('oauth_consumer_key'); - $token_field = $req->get_parameter('oauth_token'); - common_debug('consumer key = "'.$consumer_key.'"', __FILE__); - common_debug('token field = "'.$token_field.'"', __FILE__); - $rt = new Token(); - $rt->consumer_key = $consumer_key; - $rt->tok = $token_field; - $rt->type = 0; - $rt->state = 0; - common_debug('request token to look up: "'.print_r($rt,TRUE).'"'); - if ($rt->find(true)) { - common_debug('found request token to authorize', __FILE__); - $orig_rt = clone($rt); - $rt->state = 1; # Authorized but not used - if ($rt->update($orig_rt)) { - common_debug('updated request token so it is authorized', __FILE__); - return true; - } - } - return FALSE; - } - - # XXX: refactor with similar code in finishremotesubscribe.php - - function save_remote_profile(&$req) { - # FIXME: we should really do this when the consumer comes - # back for an access token. If they never do, we've got stuff in a - # weird state. - - $nickname = $req->get_parameter('omb_listenee_nickname'); - $fullname = $req->get_parameter('omb_listenee_fullname'); - $profile_url = $req->get_parameter('omb_listenee_profile'); - $homepage = $req->get_parameter('omb_listenee_homepage'); - $bio = $req->get_parameter('omb_listenee_bio'); - $location = $req->get_parameter('omb_listenee_location'); - $avatar_url = $req->get_parameter('omb_listenee_avatar'); - - $listenee = $req->get_parameter('omb_listenee'); - $remote = Remote_profile::staticGet('uri', $listenee); - - if ($remote) { - $exists = true; - $profile = Profile::staticGet($remote->id); - $orig_remote = clone($remote); - $orig_profile = clone($profile); - } else { - $exists = false; - $remote = new Remote_profile(); - $remote->uri = $listenee; - $profile = new Profile(); - } - - $profile->nickname = $nickname; - $profile->profileurl = $profile_url; - - if ($fullname) { - $profile->fullname = $fullname; - } - if ($homepage) { - $profile->homepage = $homepage; - } - if ($bio) { - $profile->bio = $bio; - } - if ($location) { - $profile->location = $location; - } - - if ($exists) { - $profile->update($orig_profile); - } else { - $profile->created = DB_DataObject_Cast::dateTime(); # current time - $id = $profile->insert(); - if (!$id) { - return FALSE; - } - $remote->id = $id; - } - - if ($exists) { - if (!$remote->update($orig_remote)) { - return FALSE; - } - } else { - $remote->created = DB_DataObject_Cast::dateTime(); # current time - if (!$remote->insert()) { - return FALSE; - } - } - - if ($avatar_url) { - if (!$this->add_avatar($profile, $avatar_url)) { - return FALSE; - } - } - - $user = common_current_user(); - $datastore = omb_oauth_datastore(); - $consumer = $this->get_consumer($datastore, $req); - $token = $this->get_token($datastore, $req, $consumer); - - $sub = new Subscription(); - $sub->subscriber = $user->id; - $sub->subscribed = $remote->id; - $sub->token = $token->key; # NOTE: request token, not valid for use! - $sub->created = DB_DataObject_Cast::dateTime(); # current time - - if (!$sub->insert()) { - return FALSE; - } - - return TRUE; - } - - function add_avatar($profile, $url) { - $temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar'); - copy($url, $temp_filename); - return $profile->setOriginal($temp_filename); - } - - function show_accept_message($tok) { - common_show_header(_('Subscription authorized')); - common_element('p', NULL, - _('The subscription has been authorized, but no '. - 'callback URL was passed. Check with the site\'s instructions for '. - 'details on how to authorize the subscription. Your subscription token is:')); - common_element('blockquote', 'token', $tok); - common_show_footer(); - } - - function show_reject_message($tok) { - common_show_header(_('Subscription rejected')); - common_element('p', NULL, - _('The subscription has been rejected, but no '. - 'callback URL was passed. Check with the site\'s instructions for '. - 'details on how to fully reject the subscription.')); - common_show_footer(); - } - - function store_request($req) { - common_ensure_session(); - $_SESSION['userauthorizationrequest'] = $req; - } - - function clear_request() { - common_ensure_session(); - unset($_SESSION['userauthorizationrequest']); - } - - function get_stored_request() { - common_ensure_session(); - $req = $_SESSION['userauthorizationrequest']; - return $req; - } - - function get_new_request() { - common_remove_magic_from_request(); - $req = OAuthRequest::from_request(); - return $req; - } - - # Throws an OAuthException if anything goes wrong - - function validate_request(&$req) { - # OAuth stuff -- have to copy from OAuth.php since they're - # all private methods, and there's no user-authentication method - common_debug('checking version', __FILE__); - $this->check_version($req); - common_debug('getting datastore', __FILE__); - $datastore = omb_oauth_datastore(); - common_debug('getting consumer', __FILE__); - $consumer = $this->get_consumer($datastore, $req); - common_debug('getting token', __FILE__); - $token = $this->get_token($datastore, $req, $consumer); - common_debug('checking timestamp', __FILE__); - $this->check_timestamp($req); - common_debug('checking nonce', __FILE__); - $this->check_nonce($datastore, $req, $consumer, $token); - common_debug('checking signature', __FILE__); - $this->check_signature($req, $consumer, $token); - common_debug('validating omb stuff', __FILE__); - $this->validate_omb($req); - common_debug('done validating', __FILE__); - return true; - } - - function validate_omb(&$req) { - foreach (array('omb_version', 'omb_listener', 'omb_listenee', - 'omb_listenee_profile', 'omb_listenee_nickname', - 'omb_listenee_license') as $param) - { - if (!$req->get_parameter($param)) { - throw new OAuthException("Required parameter '$param' not found"); - } - } - # Now, OMB stuff - $version = $req->get_parameter('omb_version'); - if ($version != OMB_VERSION_01) { - throw new OAuthException("OpenMicroBlogging version '$version' not supported"); - } - $listener = $req->get_parameter('omb_listener'); - $user = User::staticGet('uri', $listener); - if (!$user) { - throw new OAuthException("Listener URI '$listener' not found here"); - } - $cur = common_current_user(); - if ($cur->id != $user->id) { - throw new OAuthException("Can't add for another user!"); - } - $listenee = $req->get_parameter('omb_listenee'); - if (!Validate::uri($listenee) && - !common_valid_tag($listenee)) { - throw new OAuthException("Listenee URI '$listenee' not a recognizable URI"); - } - if (strlen($listenee) > 255) { - throw new OAuthException("Listenee URI '$listenee' too long"); - } - - $other = User::staticGet('uri', $listenee); - if ($other) { - throw new OAuthException("Listenee URI '$listenee' is local user"); - } - - $remote = Remote_profile::staticGet('uri', $listenee); - if ($remote) { - $sub = new Subscription(); - $sub->subscriber = $user->id; - $sub->subscribed = $remote->id; - if ($sub->find(TRUE)) { - throw new OAuthException("Already subscribed to user!"); - } - } - $nickname = $req->get_parameter('omb_listenee_nickname'); - if (!Validate::string($nickname, array('min_length' => 1, - 'max_length' => 64, - 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { - throw new OAuthException('Nickname must have only letters and numbers and no spaces.'); - } - $profile = $req->get_parameter('omb_listenee_profile'); - if (!common_valid_http_url($profile)) { - throw new OAuthException("Invalid profile URL '$profile'."); - } - - if ($profile == common_local_url('showstream', array('nickname' => $nickname))) { - throw new OAuthException("Profile URL '$profile' is for a local user."); - } - - $license = $req->get_parameter('omb_listenee_license'); - if (!common_valid_http_url($license)) { - throw new OAuthException("Invalid license URL '$license'."); - } - $site_license = common_config('license', 'url'); - if (!common_compatible_license($license, $site_license)) { - throw new OAuthException("Listenee stream license '$license' not compatible with site license '$site_license'."); - } - # optional stuff - $fullname = $req->get_parameter('omb_listenee_fullname'); - if ($fullname && strlen($fullname) > 255) { - throw new OAuthException("Full name '$fullname' too long."); - } - $homepage = $req->get_parameter('omb_listenee_homepage'); - if ($homepage && (!common_valid_http_url($homepage) || strlen($homepage) > 255)) { - throw new OAuthException("Invalid homepage '$homepage'"); - } - $bio = $req->get_parameter('omb_listenee_bio'); - if ($bio && strlen($bio) > 140) { - throw new OAuthException("Bio too long '$bio'"); - } - $location = $req->get_parameter('omb_listenee_location'); - if ($location && strlen($location) > 255) { - throw new OAuthException("Location too long '$location'"); - } - $avatar = $req->get_parameter('omb_listenee_avatar'); - if ($avatar) { - if (!common_valid_http_url($avatar) || strlen($avatar) > 255) { - throw new OAuthException("Invalid avatar URL '$avatar'"); - } - $size = @getimagesize($avatar); - if (!$size) { - throw new OAuthException("Can't read avatar URL '$avatar'"); - } - if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) { - throw new OAuthException("Wrong size image at '$avatar'"); - } - if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, - IMAGETYPE_PNG))) { - throw new OAuthException("Wrong image type for '$avatar'"); - } - } - $callback = $req->get_parameter('oauth_callback'); - if ($callback && !common_valid_http_url($callback)) { - throw new OAuthException("Invalid callback URL '$callback'"); - } - if ($callback && $callback == common_local_url('finishremotesubscribe')) { - throw new OAuthException("Callback URL '$callback' is for local site."); - } - } - - # Snagged from OAuthServer - - function check_version(&$req) { - $version = $req->get_parameter("oauth_version"); - if (!$version) { - $version = 1.0; - } - if ($version != 1.0) { - throw new OAuthException("OAuth version '$version' not supported"); - } - return $version; - } - - # Snagged from OAuthServer - - function get_consumer($datastore, $req) { - $consumer_key = @$req->get_parameter("oauth_consumer_key"); - if (!$consumer_key) { - throw new OAuthException("Invalid consumer key"); - } - - $consumer = $datastore->lookup_consumer($consumer_key); - if (!$consumer) { - throw new OAuthException("Invalid consumer"); - } - return $consumer; - } - - # Mostly cadged from OAuthServer - - function get_token($datastore, &$req, $consumer) {/*{{{*/ - $token_field = @$req->get_parameter('oauth_token'); - $token = $datastore->lookup_token($consumer, 'request', $token_field); - if (!$token) { - throw new OAuthException("Invalid $token_type token: $token_field"); - } - return $token; - } - - function check_timestamp(&$req) { - $timestamp = @$req->get_parameter('oauth_timestamp'); - $now = time(); - if ($now - $timestamp > TIMESTAMP_THRESHOLD) { - throw new OAuthException("Expired timestamp, yours $timestamp, ours $now"); - } - } - - # NOTE: don't call twice on the same request; will fail! - function check_nonce(&$datastore, &$req, $consumer, $token) { - $timestamp = @$req->get_parameter('oauth_timestamp'); - $nonce = @$req->get_parameter('oauth_nonce'); - $found = $datastore->lookup_nonce($consumer, $token, $nonce, $timestamp); - if ($found) { - throw new OAuthException("Nonce already used"); - } - return true; - } - - function check_signature(&$req, $consumer, $token) { - $signature_method = $this->get_signature_method($req); - $signature = $req->get_parameter('oauth_signature'); - $valid_sig = $signature_method->check_signature($req, - $consumer, - $token, - $signature); - if (!$valid_sig) { - throw new OAuthException("Invalid signature"); - } - } - - function get_signature_method(&$req) { - $signature_method = @$req->get_parameter("oauth_signature_method"); - if (!$signature_method) { - $signature_method = "PLAINTEXT"; - } - if ($signature_method != 'HMAC-SHA1') { - throw new OAuthException("Signature method '$signature_method' not supported."); - } - return omb_hmac_sha1(); - } + function handle($args) { + parent::handle($args); + + if ($_SERVER['REQUEST_METHOD'] == 'POST') { + # CSRF protection + $token = $this->trimmed('token'); + if (!$token || $token != common_session_token()) { + $req = $this->get_stored_request(); + $this->show_form(_('There was a problem with your session token. Try again, please.'), $req); + return; + } + # We've shown the form, now post user's choice + $this->send_authorization(); + } else { + if (!common_logged_in()) { + # Go log in, and then come back + common_debug('saving URL for returnto', __FILE__); + common_set_returnto($_SERVER['REQUEST_URI']); + + common_debug('redirecting to login', __FILE__); + common_redirect(common_local_url('login')); + return; + } + try { + # this must be a new request + common_debug('getting new request', __FILE__); + $req = $this->get_new_request(); + if (!$req) { + $this->client_error(_('No request found!')); + } + common_debug('validating request', __FILE__); + # XXX: only validate new requests, since nonce is one-time use + $this->validate_request($req); + common_debug('showing form', __FILE__); + $this->store_request($req); + $this->show_form($req); + } catch (OAuthException $e) { + $this->clear_request(); + $this->client_error($e->getMessage()); + return; + } + + } + } + + function show_form($req) { + + $nickname = $req->get_parameter('omb_listenee_nickname'); + $profile = $req->get_parameter('omb_listenee_profile'); + $license = $req->get_parameter('omb_listenee_license'); + $fullname = $req->get_parameter('omb_listenee_fullname'); + $homepage = $req->get_parameter('omb_listenee_homepage'); + $bio = $req->get_parameter('omb_listenee_bio'); + $location = $req->get_parameter('omb_listenee_location'); + $avatar = $req->get_parameter('omb_listenee_avatar'); + + common_show_header(_('Authorize subscription')); + common_element('p', NULL, _('Please check these details to make sure '. + 'that you want to subscribe to this user\'s notices. '. + 'If you didn\'t just ask to subscribe to someone\'s notices, '. + 'click "Cancel".')); + common_element_start('div', 'profile'); + if ($avatar) { + common_element('img', array('src' => $avatar, + 'class' => 'avatar profile', + 'width' => AVATAR_PROFILE_SIZE, + 'height' => AVATAR_PROFILE_SIZE, + 'alt' => $nickname)); + } + common_element('a', array('href' => $profile, + 'class' => 'external profile nickname'), + $nickname); + if ($fullname) { + common_element_start('div', 'fullname'); + if ($homepage) { + common_element('a', array('href' => $homepage), + $fullname); + } else { + common_text($fullname); + } + common_element_end('div'); + } + if ($location) { + common_element('div', 'location', $location); + } + if ($bio) { + common_element('div', 'bio', $bio); + } + common_element_start('div', 'license'); + common_element('a', array('href' => $license, + 'class' => 'license'), + $license); + common_element_end('div'); + common_element_end('div'); + common_element_start('form', array('method' => 'post', + 'id' => 'userauthorization', + 'name' => 'userauthorization', + 'action' => common_local_url('userauthorization'))); + common_hidden('token', common_session_token()); + common_submit('accept', _('Accept')); + common_submit('reject', _('Reject')); + common_element_end('form'); + common_show_footer(); + } + + function send_authorization() { + $req = $this->get_stored_request(); + + if (!$req) { + common_user_error(_('No authorization request!')); + return; + } + + $callback = $req->get_parameter('oauth_callback'); + + if ($this->arg('accept')) { + if (!$this->authorize_token($req)) { + $this->client_error(_('Error authorizing token')); + } + if (!$this->save_remote_profile($req)) { + $this->client_error(_('Error saving remote profile')); + } + if (!$callback) { + $this->show_accept_message($req->get_parameter('oauth_token')); + } else { + $params = array(); + $params['oauth_token'] = $req->get_parameter('oauth_token'); + $params['omb_version'] = OMB_VERSION_01; + $user = User::staticGet('uri', $req->get_parameter('omb_listener')); + $profile = $user->getProfile(); + if (!$profile) { + common_log_db_error($user, 'SELECT', __FILE__); + $this->server_error(_('User without matching profile')); + return; + } + $params['omb_listener_nickname'] = $user->nickname; + $params['omb_listener_profile'] = common_local_url('showstream', + array('nickname' => $user->nickname)); + if ($profile->fullname) { + $params['omb_listener_fullname'] = $profile->fullname; + } + if ($profile->homepage) { + $params['omb_listener_homepage'] = $profile->homepage; + } + if ($profile->bio) { + $params['omb_listener_bio'] = $profile->bio; + } + if ($profile->location) { + $params['omb_listener_location'] = $profile->location; + } + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + if ($avatar) { + $params['omb_listener_avatar'] = $avatar->url; + } + $parts = array(); + foreach ($params as $k => $v) { + $parts[] = $k . '=' . OAuthUtil::urlencodeRFC3986($v); + } + $query_string = implode('&', $parts); + $parsed = parse_url($callback); + $url = $callback . (($parsed['query']) ? '&' : '?') . $query_string; + common_redirect($url, 303); + } + } else { + if (!$callback) { + $this->show_reject_message(); + } else { + # XXX: not 100% sure how to signal failure... just redirect without token? + common_redirect($callback, 303); + } + } + } + + function authorize_token(&$req) { + $consumer_key = $req->get_parameter('oauth_consumer_key'); + $token_field = $req->get_parameter('oauth_token'); + common_debug('consumer key = "'.$consumer_key.'"', __FILE__); + common_debug('token field = "'.$token_field.'"', __FILE__); + $rt = new Token(); + $rt->consumer_key = $consumer_key; + $rt->tok = $token_field; + $rt->type = 0; + $rt->state = 0; + common_debug('request token to look up: "'.print_r($rt,TRUE).'"'); + if ($rt->find(true)) { + common_debug('found request token to authorize', __FILE__); + $orig_rt = clone($rt); + $rt->state = 1; # Authorized but not used + if ($rt->update($orig_rt)) { + common_debug('updated request token so it is authorized', __FILE__); + return true; + } + } + return FALSE; + } + + # XXX: refactor with similar code in finishremotesubscribe.php + + function save_remote_profile(&$req) { + # FIXME: we should really do this when the consumer comes + # back for an access token. If they never do, we've got stuff in a + # weird state. + + $nickname = $req->get_parameter('omb_listenee_nickname'); + $fullname = $req->get_parameter('omb_listenee_fullname'); + $profile_url = $req->get_parameter('omb_listenee_profile'); + $homepage = $req->get_parameter('omb_listenee_homepage'); + $bio = $req->get_parameter('omb_listenee_bio'); + $location = $req->get_parameter('omb_listenee_location'); + $avatar_url = $req->get_parameter('omb_listenee_avatar'); + + $listenee = $req->get_parameter('omb_listenee'); + $remote = Remote_profile::staticGet('uri', $listenee); + + if ($remote) { + $exists = true; + $profile = Profile::staticGet($remote->id); + $orig_remote = clone($remote); + $orig_profile = clone($profile); + } else { + $exists = false; + $remote = new Remote_profile(); + $remote->uri = $listenee; + $profile = new Profile(); + } + + $profile->nickname = $nickname; + $profile->profileurl = $profile_url; + + if ($fullname) { + $profile->fullname = $fullname; + } + if ($homepage) { + $profile->homepage = $homepage; + } + if ($bio) { + $profile->bio = $bio; + } + if ($location) { + $profile->location = $location; + } + + if ($exists) { + $profile->update($orig_profile); + } else { + $profile->created = DB_DataObject_Cast::dateTime(); # current time + $id = $profile->insert(); + if (!$id) { + return FALSE; + } + $remote->id = $id; + } + + if ($exists) { + if (!$remote->update($orig_remote)) { + return FALSE; + } + } else { + $remote->created = DB_DataObject_Cast::dateTime(); # current time + if (!$remote->insert()) { + return FALSE; + } + } + + if ($avatar_url) { + if (!$this->add_avatar($profile, $avatar_url)) { + return FALSE; + } + } + + $user = common_current_user(); + $datastore = omb_oauth_datastore(); + $consumer = $this->get_consumer($datastore, $req); + $token = $this->get_token($datastore, $req, $consumer); + + $sub = new Subscription(); + $sub->subscriber = $user->id; + $sub->subscribed = $remote->id; + $sub->token = $token->key; # NOTE: request token, not valid for use! + $sub->created = DB_DataObject_Cast::dateTime(); # current time + + if (!$sub->insert()) { + return FALSE; + } + + return TRUE; + } + + function add_avatar($profile, $url) { + $temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar'); + copy($url, $temp_filename); + return $profile->setOriginal($temp_filename); + } + + function show_accept_message($tok) { + common_show_header(_('Subscription authorized')); + common_element('p', NULL, + _('The subscription has been authorized, but no '. + 'callback URL was passed. Check with the site\'s instructions for '. + 'details on how to authorize the subscription. Your subscription token is:')); + common_element('blockquote', 'token', $tok); + common_show_footer(); + } + + function show_reject_message($tok) { + common_show_header(_('Subscription rejected')); + common_element('p', NULL, + _('The subscription has been rejected, but no '. + 'callback URL was passed. Check with the site\'s instructions for '. + 'details on how to fully reject the subscription.')); + common_show_footer(); + } + + function store_request($req) { + common_ensure_session(); + $_SESSION['userauthorizationrequest'] = $req; + } + + function clear_request() { + common_ensure_session(); + unset($_SESSION['userauthorizationrequest']); + } + + function get_stored_request() { + common_ensure_session(); + $req = $_SESSION['userauthorizationrequest']; + return $req; + } + + function get_new_request() { + common_remove_magic_from_request(); + $req = OAuthRequest::from_request(); + return $req; + } + + # Throws an OAuthException if anything goes wrong + + function validate_request(&$req) { + # OAuth stuff -- have to copy from OAuth.php since they're + # all private methods, and there's no user-authentication method + common_debug('checking version', __FILE__); + $this->check_version($req); + common_debug('getting datastore', __FILE__); + $datastore = omb_oauth_datastore(); + common_debug('getting consumer', __FILE__); + $consumer = $this->get_consumer($datastore, $req); + common_debug('getting token', __FILE__); + $token = $this->get_token($datastore, $req, $consumer); + common_debug('checking timestamp', __FILE__); + $this->check_timestamp($req); + common_debug('checking nonce', __FILE__); + $this->check_nonce($datastore, $req, $consumer, $token); + common_debug('checking signature', __FILE__); + $this->check_signature($req, $consumer, $token); + common_debug('validating omb stuff', __FILE__); + $this->validate_omb($req); + common_debug('done validating', __FILE__); + return true; + } + + function validate_omb(&$req) { + foreach (array('omb_version', 'omb_listener', 'omb_listenee', + 'omb_listenee_profile', 'omb_listenee_nickname', + 'omb_listenee_license') as $param) + { + if (!$req->get_parameter($param)) { + throw new OAuthException("Required parameter '$param' not found"); + } + } + # Now, OMB stuff + $version = $req->get_parameter('omb_version'); + if ($version != OMB_VERSION_01) { + throw new OAuthException("OpenMicroBlogging version '$version' not supported"); + } + $listener = $req->get_parameter('omb_listener'); + $user = User::staticGet('uri', $listener); + if (!$user) { + throw new OAuthException("Listener URI '$listener' not found here"); + } + $cur = common_current_user(); + if ($cur->id != $user->id) { + throw new OAuthException("Can't add for another user!"); + } + $listenee = $req->get_parameter('omb_listenee'); + if (!Validate::uri($listenee) && + !common_valid_tag($listenee)) { + throw new OAuthException("Listenee URI '$listenee' not a recognizable URI"); + } + if (strlen($listenee) > 255) { + throw new OAuthException("Listenee URI '$listenee' too long"); + } + + $other = User::staticGet('uri', $listenee); + if ($other) { + throw new OAuthException("Listenee URI '$listenee' is local user"); + } + + $remote = Remote_profile::staticGet('uri', $listenee); + if ($remote) { + $sub = new Subscription(); + $sub->subscriber = $user->id; + $sub->subscribed = $remote->id; + if ($sub->find(TRUE)) { + throw new OAuthException("Already subscribed to user!"); + } + } + $nickname = $req->get_parameter('omb_listenee_nickname'); + if (!Validate::string($nickname, array('min_length' => 1, + 'max_length' => 64, + 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) { + throw new OAuthException('Nickname must have only letters and numbers and no spaces.'); + } + $profile = $req->get_parameter('omb_listenee_profile'); + if (!common_valid_http_url($profile)) { + throw new OAuthException("Invalid profile URL '$profile'."); + } + + if ($profile == common_local_url('showstream', array('nickname' => $nickname))) { + throw new OAuthException("Profile URL '$profile' is for a local user."); + } + + $license = $req->get_parameter('omb_listenee_license'); + if (!common_valid_http_url($license)) { + throw new OAuthException("Invalid license URL '$license'."); + } + $site_license = common_config('license', 'url'); + if (!common_compatible_license($license, $site_license)) { + throw new OAuthException("Listenee stream license '$license' not compatible with site license '$site_license'."); + } + # optional stuff + $fullname = $req->get_parameter('omb_listenee_fullname'); + if ($fullname && strlen($fullname) > 255) { + throw new OAuthException("Full name '$fullname' too long."); + } + $homepage = $req->get_parameter('omb_listenee_homepage'); + if ($homepage && (!common_valid_http_url($homepage) || strlen($homepage) > 255)) { + throw new OAuthException("Invalid homepage '$homepage'"); + } + $bio = $req->get_parameter('omb_listenee_bio'); + if ($bio && strlen($bio) > 140) { + throw new OAuthException("Bio too long '$bio'"); + } + $location = $req->get_parameter('omb_listenee_location'); + if ($location && strlen($location) > 255) { + throw new OAuthException("Location too long '$location'"); + } + $avatar = $req->get_parameter('omb_listenee_avatar'); + if ($avatar) { + if (!common_valid_http_url($avatar) || strlen($avatar) > 255) { + throw new OAuthException("Invalid avatar URL '$avatar'"); + } + $size = @getimagesize($avatar); + if (!$size) { + throw new OAuthException("Can't read avatar URL '$avatar'"); + } + if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) { + throw new OAuthException("Wrong size image at '$avatar'"); + } + if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, + IMAGETYPE_PNG))) { + throw new OAuthException("Wrong image type for '$avatar'"); + } + } + $callback = $req->get_parameter('oauth_callback'); + if ($callback && !common_valid_http_url($callback)) { + throw new OAuthException("Invalid callback URL '$callback'"); + } + if ($callback && $callback == common_local_url('finishremotesubscribe')) { + throw new OAuthException("Callback URL '$callback' is for local site."); + } + } + + # Snagged from OAuthServer + + function check_version(&$req) { + $version = $req->get_parameter("oauth_version"); + if (!$version) { + $version = 1.0; + } + if ($version != 1.0) { + throw new OAuthException("OAuth version '$version' not supported"); + } + return $version; + } + + # Snagged from OAuthServer + + function get_consumer($datastore, $req) { + $consumer_key = @$req->get_parameter("oauth_consumer_key"); + if (!$consumer_key) { + throw new OAuthException("Invalid consumer key"); + } + + $consumer = $datastore->lookup_consumer($consumer_key); + if (!$consumer) { + throw new OAuthException("Invalid consumer"); + } + return $consumer; + } + + # Mostly cadged from OAuthServer + + function get_token($datastore, &$req, $consumer) {/*{{{*/ + $token_field = @$req->get_parameter('oauth_token'); + $token = $datastore->lookup_token($consumer, 'request', $token_field); + if (!$token) { + throw new OAuthException("Invalid $token_type token: $token_field"); + } + return $token; + } + + function check_timestamp(&$req) { + $timestamp = @$req->get_parameter('oauth_timestamp'); + $now = time(); + if ($now - $timestamp > TIMESTAMP_THRESHOLD) { + throw new OAuthException("Expired timestamp, yours $timestamp, ours $now"); + } + } + + # NOTE: don't call twice on the same request; will fail! + function check_nonce(&$datastore, &$req, $consumer, $token) { + $timestamp = @$req->get_parameter('oauth_timestamp'); + $nonce = @$req->get_parameter('oauth_nonce'); + $found = $datastore->lookup_nonce($consumer, $token, $nonce, $timestamp); + if ($found) { + throw new OAuthException("Nonce already used"); + } + return true; + } + + function check_signature(&$req, $consumer, $token) { + $signature_method = $this->get_signature_method($req); + $signature = $req->get_parameter('oauth_signature'); + $valid_sig = $signature_method->check_signature($req, + $consumer, + $token, + $signature); + if (!$valid_sig) { + throw new OAuthException("Invalid signature"); + } + } + + function get_signature_method(&$req) { + $signature_method = @$req->get_parameter("oauth_signature_method"); + if (!$signature_method) { + $signature_method = "PLAINTEXT"; + } + if ($signature_method != 'HMAC-SHA1') { + throw new OAuthException("Signature method '$signature_method' not supported."); + } + return omb_hmac_sha1(); + } } diff --git a/_darcs/pristine/actions/userbyid.php b/_darcs/pristine/actions/userbyid.php index 38bff2ede..4eab8758c 100644 --- a/_darcs/pristine/actions/userbyid.php +++ b/_darcs/pristine/actions/userbyid.php @@ -20,30 +20,30 @@ if (!defined('LACONICA')) { exit(1); } class UserbyidAction extends Action { - - function is_readonly() { - return true; - } - + + function is_readonly() { + return true; + } + function handle($args) { parent::handle($args); $id = $this->trimmed('id'); if (!$id) { - $this->client_error(_('No id.')); - } - $user =& User::staticGet($id); - if (!$user) { - $this->client_error(_('No such user.')); + $this->client_error(_('No id.')); + } + $user =& User::staticGet($id); + if (!$user) { + $this->client_error(_('No such user.')); } // support redirecting to FOAF rdf/xml if the agent prefers it $page_prefs = 'application/rdf+xml,text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2'; $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL; - $type = common_negotiate_type(common_accept_to_prefs($httpaccept), + $type = common_negotiate_type(common_accept_to_prefs($httpaccept), common_accept_to_prefs($page_prefs)); - $page = $type == 'application/rdf+xml' ? 'foaf' : 'showstream'; + $page = $type == 'application/rdf+xml' ? 'foaf' : 'showstream'; - $url = common_local_url($page, array('nickname' => $user->nickname)); - common_redirect($url, 303); - } + $url = common_local_url($page, array('nickname' => $user->nickname)); + common_redirect($url, 303); + } } diff --git a/_darcs/pristine/actions/userrss.php b/_darcs/pristine/actions/userrss.php index e57f86105..b5cb5a40a 100644 --- a/_darcs/pristine/actions/userrss.php +++ b/_darcs/pristine/actions/userrss.php @@ -25,66 +25,66 @@ require_once(INSTALLDIR.'/lib/rssaction.php'); class UserrssAction extends Rss10Action { - var $user = NULL; + var $user = NULL; - function init() { - $nickname = $this->trimmed('nickname'); - $this->user = User::staticGet('nickname', $nickname); + function init() { + $nickname = $this->trimmed('nickname'); + $this->user = User::staticGet('nickname', $nickname); - if (!$this->user) { - common_user_error(_('No such user.')); - return false; - } else { - return true; - } - } + if (!$this->user) { + common_user_error(_('No such user.')); + return false; + } else { + return true; + } + } - function get_notices($limit=0) { + function get_notices($limit=0) { - $user = $this->user; - - if (is_null($user)) { - return NULL; - } - - $notice = $user->getNotices(0, ($limit == 0) ? NOTICES_PER_PAGE : $limit); - - while ($notice->fetch()) { - $notices[] = clone($notice); - } + $user = $this->user; + + if (is_null($user)) { + return NULL; + } + + $notice = $user->getNotices(0, ($limit == 0) ? NOTICES_PER_PAGE : $limit); + + while ($notice->fetch()) { + $notices[] = clone($notice); + } - return $notices; - } + return $notices; + } - function get_channel() { - $user = $this->user; - $profile = $user->getProfile(); - $c = array('url' => common_local_url('userrss', - array('nickname' => - $user->nickname)), - 'title' => $user->nickname, - 'link' => $profile->profileurl, - 'description' => sprintf(_('Microblog by %s'), $user->nickname)); - return $c; - } + function get_channel() { + $user = $this->user; + $profile = $user->getProfile(); + $c = array('url' => common_local_url('userrss', + array('nickname' => + $user->nickname)), + 'title' => $user->nickname, + 'link' => $profile->profileurl, + 'description' => sprintf(_('Microblog by %s'), $user->nickname)); + return $c; + } - function get_image() { - $user = $this->user; - $profile = $user->getProfile(); - if (!$profile) { - common_log_db_error($user, 'SELECT', __FILE__); - $this->server_error(_('User without matching profile')); - return NULL; - } - $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); - return ($avatar) ? $avatar->url : NULL; - } + function get_image() { + $user = $this->user; + $profile = $user->getProfile(); + if (!$profile) { + common_log_db_error($user, 'SELECT', __FILE__); + $this->server_error(_('User without matching profile')); + return NULL; + } + $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE); + return ($avatar) ? $avatar->url : NULL; + } - # override parent to add X-SUP-ID URL - - function init_rss($limit=0) { - $url = common_local_url('sup', NULL, $this->user->id); - header('X-SUP-ID: '.$url); - parent::init_rss($limit); - } + # override parent to add X-SUP-ID URL + + function init_rss($limit=0) { + $url = common_local_url('sup', NULL, $this->user->id); + header('X-SUP-ID: '.$url); + parent::init_rss($limit); + } } \ No newline at end of file diff --git a/_darcs/pristine/actions/xrds.php b/_darcs/pristine/actions/xrds.php index 1d516aab7..9788c87aa 100644 --- a/_darcs/pristine/actions/xrds.php +++ b/_darcs/pristine/actions/xrds.php @@ -23,110 +23,110 @@ require_once(INSTALLDIR.'/lib/omb.php'); class XrdsAction extends Action { - function is_readonly() { - return true; - } - - function handle($args) { - parent::handle($args); - $nickname = $this->trimmed('nickname'); - $user = User::staticGet('nickname', $nickname); - if (!$user) { - common_user_error(_('No such user.')); - return; - } - $this->show_xrds($user); - } - - function show_xrds($user) { - - header('Content-Type: application/xrds+xml'); - - common_start_xml(); - common_element_start('XRDS', array('xmlns' => 'xri://$xrds')); - - common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', - 'xml:id' => 'oauth', - 'xmlns:simple' => 'http://xrds-simple.net/core/1.0', - 'version' => '2.0')); - - common_element('Type', NULL, 'xri://$xrds*simple'); - - $this->show_service(OAUTH_ENDPOINT_REQUEST, - common_local_url('requesttoken'), - array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), - array(OAUTH_HMAC_SHA1), - $user->uri); - - $this->show_service(OAUTH_ENDPOINT_AUTHORIZE, - common_local_url('userauthorization'), - array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), - array(OAUTH_HMAC_SHA1)); - - $this->show_service(OAUTH_ENDPOINT_ACCESS, - common_local_url('accesstoken'), - array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), - array(OAUTH_HMAC_SHA1)); - - $this->show_service(OAUTH_ENDPOINT_RESOURCE, - NULL, - array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), - array(OAUTH_HMAC_SHA1)); - - common_element_end('XRD'); - - # XXX: decide whether to include user's ID/nickname in postNotice URL - - common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', - 'xml:id' => 'omb', - 'xmlns:simple' => 'http://xrds-simple.net/core/1.0', - 'version' => '2.0')); - - common_element('Type', NULL, 'xri://$xrds*simple'); - - $this->show_service(OMB_ENDPOINT_POSTNOTICE, - common_local_url('postnotice')); - - $this->show_service(OMB_ENDPOINT_UPDATEPROFILE, - common_local_url('updateprofile')); - - common_element_end('XRD'); - - common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', - 'version' => '2.0')); - - common_element('Type', NULL, 'xri://$xrds*simple'); - - $this->show_service(OAUTH_DISCOVERY, - '#oauth'); - $this->show_service(OMB_NAMESPACE, - '#omb'); - - common_element_end('XRD'); - - common_element_end('XRDS'); - common_end_xml(); - } - - function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) { - common_element_start('Service'); - if ($uri) { - common_element('URI', NULL, $uri); - } - common_element('Type', NULL, $type); - if ($params) { - foreach ($params as $param) { - common_element('Type', NULL, $param); - } - } - if ($sigs) { - foreach ($sigs as $sig) { - common_element('Type', NULL, $sig); - } - } - if ($localId) { - common_element('LocalID', NULL, $localId); - } - common_element_end('Service'); - } + function is_readonly() { + return true; + } + + function handle($args) { + parent::handle($args); + $nickname = $this->trimmed('nickname'); + $user = User::staticGet('nickname', $nickname); + if (!$user) { + common_user_error(_('No such user.')); + return; + } + $this->show_xrds($user); + } + + function show_xrds($user) { + + header('Content-Type: application/xrds+xml'); + + common_start_xml(); + common_element_start('XRDS', array('xmlns' => 'xri://$xrds')); + + common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', + 'xml:id' => 'oauth', + 'xmlns:simple' => 'http://xrds-simple.net/core/1.0', + 'version' => '2.0')); + + common_element('Type', NULL, 'xri://$xrds*simple'); + + $this->show_service(OAUTH_ENDPOINT_REQUEST, + common_local_url('requesttoken'), + array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), + array(OAUTH_HMAC_SHA1), + $user->uri); + + $this->show_service(OAUTH_ENDPOINT_AUTHORIZE, + common_local_url('userauthorization'), + array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), + array(OAUTH_HMAC_SHA1)); + + $this->show_service(OAUTH_ENDPOINT_ACCESS, + common_local_url('accesstoken'), + array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), + array(OAUTH_HMAC_SHA1)); + + $this->show_service(OAUTH_ENDPOINT_RESOURCE, + NULL, + array(OAUTH_AUTH_HEADER, OAUTH_POST_BODY), + array(OAUTH_HMAC_SHA1)); + + common_element_end('XRD'); + + # XXX: decide whether to include user's ID/nickname in postNotice URL + + common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', + 'xml:id' => 'omb', + 'xmlns:simple' => 'http://xrds-simple.net/core/1.0', + 'version' => '2.0')); + + common_element('Type', NULL, 'xri://$xrds*simple'); + + $this->show_service(OMB_ENDPOINT_POSTNOTICE, + common_local_url('postnotice')); + + $this->show_service(OMB_ENDPOINT_UPDATEPROFILE, + common_local_url('updateprofile')); + + common_element_end('XRD'); + + common_element_start('XRD', array('xmlns' => 'xri://$xrd*($v*2.0)', + 'version' => '2.0')); + + common_element('Type', NULL, 'xri://$xrds*simple'); + + $this->show_service(OAUTH_DISCOVERY, + '#oauth'); + $this->show_service(OMB_NAMESPACE, + '#omb'); + + common_element_end('XRD'); + + common_element_end('XRDS'); + common_end_xml(); + } + + function show_service($type, $uri, $params=NULL, $sigs=NULL, $localId=NULL) { + common_element_start('Service'); + if ($uri) { + common_element('URI', NULL, $uri); + } + common_element('Type', NULL, $type); + if ($params) { + foreach ($params as $param) { + common_element('Type', NULL, $param); + } + } + if ($sigs) { + foreach ($sigs as $sig) { + common_element('Type', NULL, $sig); + } + } + if ($localId) { + common_element('LocalID', NULL, $localId); + } + common_element_end('Service'); + } } \ No newline at end of file diff --git a/_darcs/pristine/classes/Avatar.php b/_darcs/pristine/classes/Avatar.php index 901c47c51..e63668a33 100644 --- a/_darcs/pristine/classes/Avatar.php +++ b/_darcs/pristine/classes/Avatar.php @@ -26,70 +26,70 @@ class Avatar extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - # We clean up the file, too + # We clean up the file, too - function delete() { - $filename = $this->filename; - if (parent::delete()) { - @unlink(common_avatar_path($filename)); - } - } + function delete() { + $filename = $this->filename; + if (parent::delete()) { + @unlink(common_avatar_path($filename)); + } + } - # Create and save scaled version of this avatar - # XXX: maybe break into different methods + # Create and save scaled version of this avatar + # XXX: maybe break into different methods - function scale($size) { + function scale($size) { - $image_s = imagecreatetruecolor($size, $size); - $image_a = $this->to_image(); - $square = min($this->width, $this->height); + $image_s = imagecreatetruecolor($size, $size); + $image_a = $this->to_image(); + $square = min($this->width, $this->height); imagecolortransparent($image_s, imagecolorallocate($image_s, 0, 0, 0)); imagealphablending($image_s, false); imagesavealpha($image_s, true); - imagecopyresampled($image_s, $image_a, 0, 0, 0, 0, - $size, $size, $square, $square); + imagecopyresampled($image_s, $image_a, 0, 0, 0, 0, + $size, $size, $square, $square); - $ext = ($this->mediattype == 'image/jpeg') ? ".jpeg" : ".png"; + $ext = ($this->mediattype == 'image/jpeg') ? ".jpeg" : ".png"; - $filename = common_avatar_filename($this->profile_id, $ext, $size, common_timestamp()); + $filename = common_avatar_filename($this->profile_id, $ext, $size, common_timestamp()); - if ($this->mediatype == 'image/jpeg') { - imagejpeg($image_s, common_avatar_path($filename)); - } else { - imagepng($image_s, common_avatar_path($filename)); - } + if ($this->mediatype == 'image/jpeg') { + imagejpeg($image_s, common_avatar_path($filename)); + } else { + imagepng($image_s, common_avatar_path($filename)); + } - $scaled = DB_DataObject::factory('avatar'); - $scaled->profile_id = $this->profile_id; - $scaled->width = $size; - $scaled->height = $size; - $scaled->original = false; - $scaled->mediatype = ($this->mediattype == 'image/jpeg') ? 'image/jpeg' : 'image/png'; - $scaled->filename = $filename; - $scaled->url = common_avatar_url($filename); - $scaled->created = DB_DataObject_Cast::dateTime(); # current time + $scaled = DB_DataObject::factory('avatar'); + $scaled->profile_id = $this->profile_id; + $scaled->width = $size; + $scaled->height = $size; + $scaled->original = false; + $scaled->mediatype = ($this->mediattype == 'image/jpeg') ? 'image/jpeg' : 'image/png'; + $scaled->filename = $filename; + $scaled->url = common_avatar_url($filename); + $scaled->created = DB_DataObject_Cast::dateTime(); # current time - if ($scaled->insert()) { - return $scaled; - } else { - return NULL; - } - } + if ($scaled->insert()) { + return $scaled; + } else { + return NULL; + } + } - function to_image() { - $filepath = common_avatar_path($this->filename); - if ($this->mediatype == 'image/gif') { - return imagecreatefromgif($filepath); - } else if ($this->mediatype == 'image/jpeg') { - return imagecreatefromjpeg($filepath); - } else if ($this->mediatype == 'image/png') { - return imagecreatefrompng($filepath); - } else { - return NULL; - } - } - - function &pkeyGet($kv) { - return Memcached_DataObject::pkeyGet('Avatar', $kv); - } + function to_image() { + $filepath = common_avatar_path($this->filename); + if ($this->mediatype == 'image/gif') { + return imagecreatefromgif($filepath); + } else if ($this->mediatype == 'image/jpeg') { + return imagecreatefromjpeg($filepath); + } else if ($this->mediatype == 'image/png') { + return imagecreatefrompng($filepath); + } else { + return NULL; + } + } + + function &pkeyGet($kv) { + return Memcached_DataObject::pkeyGet('Avatar', $kv); + } } diff --git a/_darcs/pristine/classes/Channel.php b/_darcs/pristine/classes/Channel.php index bcc0c36b5..384fe8bb1 100644 --- a/_darcs/pristine/classes/Channel.php +++ b/_darcs/pristine/classes/Channel.php @@ -20,181 +20,181 @@ 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; - } + + 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; - } - } + 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 { - 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 - common_show_header(_('Command results')); - common_element('p', NULL, $text); - common_show_footer(); - } - - function error($user, $text) { - common_user_error($text); - } + 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 + common_show_header(_('Command results')); + common_element('p', NULL, $text); + common_show_footer(); + } + + function error($user, $text) { + common_user_error($text); + } } class AjaxWebChannel extends WebChannel { - function output($user, $text) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Command results')); - common_element_end('head'); - common_element_start('body'); - common_element('p', array('id' => 'command_result'), $text); - common_element_end('body'); - common_element_end('html'); - } - - function error($user, $text) { - common_start_html('text/xml;charset=utf-8', true); - common_element_start('head'); - common_element('title', null, _('Ajax Error')); - common_element_end('head'); - common_element_start('body'); - common_element('p', array('id' => 'error'), $text); - common_element_end('body'); - common_element_end('html'); - } + function output($user, $text) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Command results')); + common_element_end('head'); + common_element_start('body'); + common_element('p', array('id' => 'command_result'), $text); + common_element_end('body'); + common_element_end('html'); + } + + function error($user, $text) { + common_start_html('text/xml;charset=utf-8', true); + common_element_start('head'); + common_element('title', null, _('Ajax Error')); + common_element_end('head'); + common_element_start('body'); + common_element('p', array('id' => 'error'), $text); + common_element_end('body'); + common_element_end('html'); + } } 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; - } + 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/_darcs/pristine/classes/Command.php b/_darcs/pristine/classes/Command.php index c2409d140..ff44b9d1e 100644 --- a/_darcs/pristine/classes/Command.php +++ b/_darcs/pristine/classes/Command.php @@ -22,22 +22,22 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/classes/Channel.php'); class Command { - - var $user = NULL; - - function __construct($user=NULL) { - $this->user = $user; - } - - function execute($channel) { - return false; - } + + 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.")); - } + function execute($channel) { + $channel->error($this->user, _("Sorry, this command is not yet implemented.")); + } } class TrackingCommand extends UnimplementedCommand { @@ -47,330 +47,330 @@ class TrackOffCommand extends UnimplementedCommand { } class TrackCommand extends UnimplementedCommand { - var $word = NULL; - function __construct($user, $word) { - parent::__construct($user); - $this->word = $word; - } + 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; - } + 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; - } + 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; - } + var $other = NULL; + function __construct($user, $other) { + parent::__construct($user); + $this->other = $other; + } } class StatsCommand extends Command { - function execute($channel) { + function execute($channel) { - $subs = new Subscription(); - $subs->subscriber = $this->user->id; - $subs_count = (int) $subs->count() - 1; + $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; + $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)); - } + $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); + + 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; - } + 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.')); - } + $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); - } + 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.')); - } - } + 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); + + 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); - } + 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); - } - } + + 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; - } + 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); - } - } + 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.')); - } - } - } + 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.')); - } - } - } + 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 - subscribe to user\n". - "leave - unsubscribe from user\n". - "d - direct message to user\n". - "get - get last notice from user\n". - "whois - get profile info on user\n". - "fav - 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 - same as 'follow'\n". - "unsub - same as 'leave'\n". - "last - same as 'get'\n". - "on - not yet implemented.\n". - "off - not yet implemented.\n". - "nudge - not yet implemented.\n". - "invite - not yet implemented.\n". - "track - not yet implemented.\n". - "untrack - 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")); - } + 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 - subscribe to user\n". + "leave - unsubscribe from user\n". + "d - direct message to user\n". + "get - get last notice from user\n". + "whois - get profile info on user\n". + "fav - 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 - same as 'follow'\n". + "unsub - same as 'leave'\n". + "last - same as 'get'\n". + "on - not yet implemented.\n". + "off - not yet implemented.\n". + "nudge - not yet implemented.\n". + "invite - not yet implemented.\n". + "track - not yet implemented.\n". + "untrack - 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/_darcs/pristine/classes/CommandInterpreter.php b/_darcs/pristine/classes/CommandInterpreter.php index 4e27f8f79..8192fb1a9 100644 --- a/_darcs/pristine/classes/CommandInterpreter.php +++ b/_darcs/pristine/classes/CommandInterpreter.php @@ -22,174 +22,174 @@ if (!defined('LACONICA')) { exit(1); } require_once(INSTALLDIR.'/classes/Command.php'); class CommandInterpreter { - - function handle_command($user, $text) { - # XXX: localise + + function handle_command($user, $text) { + # XXX: localise - $text = preg_replace('/\s+/', ' ', trim($text)); - list($cmd, $arg) = explode(' ', $text, 2); + $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': - 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; - } - } + # 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': + 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/_darcs/pristine/classes/Fave.php b/_darcs/pristine/classes/Fave.php index 7cc3f585e..b70a8a897 100644 --- a/_darcs/pristine/classes/Fave.php +++ b/_darcs/pristine/classes/Fave.php @@ -20,18 +20,18 @@ class Fave extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - static function addNew($user, $notice) { - $fave = new Fave(); - $fave->user_id = $user->id; - $fave->notice_id = $notice->id; - if (!$fave->insert()) { - common_log_db_error($fave, 'INSERT', __FILE__); - return false; - } - return $fave; - } - - function &pkeyGet($kv) { - return Memcached_DataObject::pkeyGet('Fave', $kv); - } + static function addNew($user, $notice) { + $fave = new Fave(); + $fave->user_id = $user->id; + $fave->notice_id = $notice->id; + if (!$fave->insert()) { + common_log_db_error($fave, 'INSERT', __FILE__); + return false; + } + return $fave; + } + + function &pkeyGet($kv) { + return Memcached_DataObject::pkeyGet('Fave', $kv); + } } diff --git a/_darcs/pristine/classes/Foreign_link.php b/_darcs/pristine/classes/Foreign_link.php index 7a625a209..7ce0df833 100644 --- a/_darcs/pristine/classes/Foreign_link.php +++ b/_darcs/pristine/classes/Foreign_link.php @@ -26,51 +26,51 @@ class Foreign_link extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - // XXX: This only returns a 1->1 single obj mapping. Change? Or make - // a getForeignUsers() that returns more than one? --Zach - static function getByUserID($user_id, $service) { - $flink = new Foreign_link(); - $flink->service = $service; - $flink->user_id = $user_id; - $flink->limit(1); + // XXX: This only returns a 1->1 single obj mapping. Change? Or make + // a getForeignUsers() that returns more than one? --Zach + static function getByUserID($user_id, $service) { + $flink = new Foreign_link(); + $flink->service = $service; + $flink->user_id = $user_id; + $flink->limit(1); - if ($flink->find(TRUE)) { - return $flink; - } + if ($flink->find(TRUE)) { + return $flink; + } - return NULL; - } - - static function getByForeignID($foreign_id, $service) { - $flink = new Foreign_link(); - $flink->service = $service; - $flink->foreign_id = $foreign_id; - $flink->limit(1); + return NULL; + } + + static function getByForeignID($foreign_id, $service) { + $flink = new Foreign_link(); + $flink->service = $service; + $flink->foreign_id = $foreign_id; + $flink->limit(1); - if ($flink->find(TRUE)) { - return $flink; - } + if ($flink->find(TRUE)) { + return $flink; + } - return NULL; - } - - # Convenience methods - function getForeignUser() { - $fuser = new Foreign_user(); - $fuser->service = $this->service; - $fuser->id = $this->foreign_id; - - $fuser->limit(1); - - if ($fuser->find(TRUE)) { - return $fuser; - } - - return NULL; - } - - function getUser() { - return User::staticGet($this->user_id); - } - + return NULL; + } + + # Convenience methods + function getForeignUser() { + $fuser = new Foreign_user(); + $fuser->service = $this->service; + $fuser->id = $this->foreign_id; + + $fuser->limit(1); + + if ($fuser->find(TRUE)) { + return $fuser; + } + + return NULL; + } + + function getUser() { + return User::staticGet($this->user_id); + } + } diff --git a/_darcs/pristine/classes/Foreign_user.php b/_darcs/pristine/classes/Foreign_user.php index 027fae69d..396680128 100644 --- a/_darcs/pristine/classes/Foreign_user.php +++ b/_darcs/pristine/classes/Foreign_user.php @@ -22,49 +22,49 @@ class Foreign_user extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - - // XXX: This only returns a 1->1 single obj mapping. Change? Or make - // a getForeignUsers() that returns more than one? --Zach - static function getForeignUser($id, $service) { - $fuser = new Foreign_user(); - $fuser->whereAdd("service = $service"); - $fuser->whereAdd("id = $id"); - $fuser->limit(1); - - if ($fuser->find()) { - $fuser->fetch(); - return $fuser; - } - - return NULL; - } - - function updateKeys(&$orig) { - $parts = array(); - foreach (array('id', 'service', 'uri', 'nickname') as $k) { - if (strcmp($this->$k, $orig->$k) != 0) { - $parts[] = $k . ' = ' . $this->_quote($this->$k); - } - } - if (count($parts) == 0) { - # No changes - return true; - } - $toupdate = implode(', ', $parts); + + // XXX: This only returns a 1->1 single obj mapping. Change? Or make + // a getForeignUsers() that returns more than one? --Zach + static function getForeignUser($id, $service) { + $fuser = new Foreign_user(); + $fuser->whereAdd("service = $service"); + $fuser->whereAdd("id = $id"); + $fuser->limit(1); + + if ($fuser->find()) { + $fuser->fetch(); + return $fuser; + } + + return NULL; + } + + function updateKeys(&$orig) { + $parts = array(); + foreach (array('id', 'service', 'uri', 'nickname') as $k) { + if (strcmp($this->$k, $orig->$k) != 0) { + $parts[] = $k . ' = ' . $this->_quote($this->$k); + } + } + if (count($parts) == 0) { + # No changes + return true; + } + $toupdate = implode(', ', $parts); - $table = $this->tableName(); - if(common_config('db','quote_identifiers')) { - $table = '"' . $table . '"'; - } - $qry = 'UPDATE ' . $table . ' SET ' . $toupdate . - ' WHERE id = ' . $this->id; - $orig->decache(); - $result = $this->query($qry); - if ($result) { - $this->encache(); - } - return $result; - } + $table = $this->tableName(); + if(common_config('db','quote_identifiers')) { + $table = '"' . $table . '"'; + } + $qry = 'UPDATE ' . $table . ' SET ' . $toupdate . + ' WHERE id = ' . $this->id; + $orig->decache(); + $result = $this->query($qry); + if ($result) { + $this->encache(); + } + return $result; + } - + } diff --git a/_darcs/pristine/classes/Memcached_DataObject.php b/_darcs/pristine/classes/Memcached_DataObject.php index 7a33e158d..7699e1b38 100644 --- a/_darcs/pristine/classes/Memcached_DataObject.php +++ b/_darcs/pristine/classes/Memcached_DataObject.php @@ -24,151 +24,151 @@ require_once INSTALLDIR.'/classes/Memcached_DataObject.php'; class Memcached_DataObject extends DB_DataObject { function &staticGet($cls, $k, $v=NULL) { - if (is_null($v)) { - $v = $k; - # XXX: HACK! - $i = new $cls; - $keys = $i->keys(); - $k = $keys[0]; - unset($i); - } - $i = Memcached_DataObject::getcached($cls, $k, $v); - if ($i) { - return $i; - } else { - $i = DB_DataObject::staticGet($cls, $k, $v); - if ($i) { - $i->encache(); - } - return $i; - } - } + if (is_null($v)) { + $v = $k; + # XXX: HACK! + $i = new $cls; + $keys = $i->keys(); + $k = $keys[0]; + unset($i); + } + $i = Memcached_DataObject::getcached($cls, $k, $v); + if ($i) { + return $i; + } else { + $i = DB_DataObject::staticGet($cls, $k, $v); + if ($i) { + $i->encache(); + } + return $i; + } + } - function &pkeyGet($cls, $kv) { - $i = Memcached_DataObject::multicache($cls, $kv); - if ($i) { - return $i; - } else { - $i = new $cls(); - foreach ($kv as $k => $v) { - $i->$k = $v; - } - if ($i->find(true)) { - $i->encache(); - } else { - $i = NULL; - } + function &pkeyGet($cls, $kv) { + $i = Memcached_DataObject::multicache($cls, $kv); + if ($i) { + return $i; + } else { + $i = new $cls(); + foreach ($kv as $k => $v) { + $i->$k = $v; + } + if ($i->find(true)) { + $i->encache(); + } else { + $i = NULL; + } return $i; - } - } + } + } - function insert() { - $result = parent::insert(); - return $result; - } - - function update($orig=NULL) { - if (is_object($orig) && $orig instanceof Memcached_DataObject) { - $orig->decache(); # might be different keys - } - $result = parent::update($orig); - if ($result) { - $this->encache(); - } - return $result; - } - - function delete() { - $this->decache(); # while we still have the values! - return parent::delete(); - } - - static function memcache() { - return common_memcache(); - } - - static function cacheKey($cls, $k, $v) { - return common_cache_key(strtolower($cls).':'.$k.':'.$v); - } - - static function getcached($cls, $k, $v) { - $c = Memcached_DataObject::memcache(); - if (!$c) { - return false; - } else { - return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v)); - } - } + function insert() { + $result = parent::insert(); + return $result; + } + + function update($orig=NULL) { + if (is_object($orig) && $orig instanceof Memcached_DataObject) { + $orig->decache(); # might be different keys + } + $result = parent::update($orig); + if ($result) { + $this->encache(); + } + return $result; + } + + function delete() { + $this->decache(); # while we still have the values! + return parent::delete(); + } + + static function memcache() { + return common_memcache(); + } + + static function cacheKey($cls, $k, $v) { + return common_cache_key(strtolower($cls).':'.$k.':'.$v); + } + + static function getcached($cls, $k, $v) { + $c = Memcached_DataObject::memcache(); + if (!$c) { + return false; + } else { + return $c->get(Memcached_DataObject::cacheKey($cls, $k, $v)); + } + } - function keyTypes() { - global $_DB_DATAOBJECT; + function keyTypes() { + global $_DB_DATAOBJECT; if (!isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) { - $this->databaseStructure(); + $this->databaseStructure(); } - return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]; - } - - function encache() { - $c = $this->memcache(); - if (!$c) { - return false; - } else { - $pkey = array(); - $pval = array(); - $types = $this->keyTypes(); - ksort($types); - foreach ($types as $key => $type) { - if ($type == 'K') { - $pkey[] = $key; - $pval[] = $this->$key; - } else { - $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this); - } - } - # XXX: should work for both compound and scalar pkeys - $pvals = implode(',', $pval); - $pkeys = implode(',', $pkey); - $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this); - } - } - - function decache() { - $c = $this->memcache(); - if (!$c) { - return false; - } else { - $pkey = array(); - $pval = array(); - $types = $this->keyTypes(); - ksort($types); - foreach ($types as $key => $type) { - if ($type == 'K') { - $pkey[] = $key; - $pval[] = $this->$key; - } else { - $c->delete($this->cacheKey($this->tableName(), $key, $this->$key)); - } - } - # should work for both compound and scalar pkeys - # XXX: comma works for now but may not be safe separator for future keys - $pvals = implode(',', $pval); - $pkeys = implode(',', $pkey); - $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals)); - } - } + return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]; + } + + function encache() { + $c = $this->memcache(); + if (!$c) { + return false; + } else { + $pkey = array(); + $pval = array(); + $types = $this->keyTypes(); + ksort($types); + foreach ($types as $key => $type) { + if ($type == 'K') { + $pkey[] = $key; + $pval[] = $this->$key; + } else { + $c->set($this->cacheKey($this->tableName(), $key, $this->$key), $this); + } + } + # XXX: should work for both compound and scalar pkeys + $pvals = implode(',', $pval); + $pkeys = implode(',', $pkey); + $c->set($this->cacheKey($this->tableName(), $pkeys, $pvals), $this); + } + } + + function decache() { + $c = $this->memcache(); + if (!$c) { + return false; + } else { + $pkey = array(); + $pval = array(); + $types = $this->keyTypes(); + ksort($types); + foreach ($types as $key => $type) { + if ($type == 'K') { + $pkey[] = $key; + $pval[] = $this->$key; + } else { + $c->delete($this->cacheKey($this->tableName(), $key, $this->$key)); + } + } + # should work for both compound and scalar pkeys + # XXX: comma works for now but may not be safe separator for future keys + $pvals = implode(',', $pval); + $pkeys = implode(',', $pkey); + $c->delete($this->cacheKey($this->tableName(), $pkeys, $pvals)); + } + } - function multicache($cls, $kv) { - ksort($kv); - $c = Memcached_DataObject::memcache(); - if (!$c) { - return false; - } else { - $pkeys = implode(',', array_keys($kv)); - $pvals = implode(',', array_values($kv)); - return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals)); - } - } + function multicache($cls, $kv) { + ksort($kv); + $c = Memcached_DataObject::memcache(); + if (!$c) { + return false; + } else { + $pkeys = implode(',', array_keys($kv)); + $pvals = implode(',', array_values($kv)); + return $c->get(Memcached_DataObject::cacheKey($cls, $pkeys, $pvals)); + } + } function getSearchEngine($table) { require_once INSTALLDIR.'/lib/search_engines.php'; diff --git a/_darcs/pristine/classes/Message.php b/_darcs/pristine/classes/Message.php index ef4bd0316..dc527fcb1 100644 --- a/_darcs/pristine/classes/Message.php +++ b/_darcs/pristine/classes/Message.php @@ -26,43 +26,43 @@ class Message extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - - function getFrom() { - return Profile::staticGet('id', $this->from_profile); - } - - function getTo() { - return Profile::staticGet('id', $this->to_profile); - } - - static function saveNew($from, $to, $content, $source) { - - $msg = new Message(); - - $msg->from_profile = $from; - $msg->to_profile = $to; - $msg->content = common_shorten_links($content); - $msg->rendered = common_render_text($content); - $msg->created = common_sql_now(); - $msg->source = $source; - - $result = $msg->insert(); - - if (!$result) { - common_log_db_error($msg, 'INSERT', __FILE__); - return _('Could not insert message.'); - } - - $orig = clone($msg); - $msg->uri = common_local_url('showmessage', array('message' => $msg->id)); - - $result = $msg->update($orig); - - if (!$result) { - common_log_db_error($msg, 'UPDATE', __FILE__); - return _('Could not update message with new URI.'); - } - - return $msg; - } + + function getFrom() { + return Profile::staticGet('id', $this->from_profile); + } + + function getTo() { + return Profile::staticGet('id', $this->to_profile); + } + + static function saveNew($from, $to, $content, $source) { + + $msg = new Message(); + + $msg->from_profile = $from; + $msg->to_profile = $to; + $msg->content = common_shorten_links($content); + $msg->rendered = common_render_text($content); + $msg->created = common_sql_now(); + $msg->source = $source; + + $result = $msg->insert(); + + if (!$result) { + common_log_db_error($msg, 'INSERT', __FILE__); + return _('Could not insert message.'); + } + + $orig = clone($msg); + $msg->uri = common_local_url('showmessage', array('message' => $msg->id)); + + $result = $msg->update($orig); + + if (!$result) { + common_log_db_error($msg, 'UPDATE', __FILE__); + return _('Could not update message with new URI.'); + } + + return $msg; + } } diff --git a/_darcs/pristine/classes/Notice.php b/_darcs/pristine/classes/Notice.php index ca8283bce..35e03e342 100644 --- a/_darcs/pristine/classes/Notice.php +++ b/_darcs/pristine/classes/Notice.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -31,69 +31,69 @@ define('NOTICE_CACHE_WINDOW', 61); class Notice extends Memcached_DataObject { - ###START_AUTOCODE - /* the code below is auto generated do not remove the above tag */ - - public $__table = 'notice'; // table name - public $id; // int(4) primary_key not_null - public $profile_id; // int(4) not_null - public $uri; // varchar(255) unique_key - public $content; // varchar(140) - public $rendered; // text() - public $url; // varchar(255) - public $created; // datetime() not_null - public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP - public $reply_to; // int(4) - public $is_local; // tinyint(1) - public $source; // varchar(32) - - /* Static get */ - function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Notice',$k,$v); } - - /* the code above is auto generated do not remove the tag below */ - ###END_AUTOCODE - - function getProfile() { - return Profile::staticGet('id', $this->profile_id); - } - - function delete() { - $this->blowCaches(true); - $this->blowFavesCache(true); - $this->blowInboxes(); - return parent::delete(); - } - - function saveTags() { - /* extract all #hastags */ - $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match); - if (!$count) { - return true; - } - - /* elide characters we don't want in the tag */ - $match[1] = str_replace(array('-', '_', '.'), '', $match[1]); - - /* Add them to the database */ - foreach(array_unique($match[1]) as $hashtag) { - $tag = DB_DataObject::factory('Notice_tag'); - $tag->notice_id = $this->id; - $tag->tag = $hashtag; - $tag->created = $this->created; - $id = $tag->insert(); - if (!$id) { - $last_error = PEAR::getStaticProperty('DB_DataObject','lastError'); - common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message); - common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message)); - return; - } - } - return true; - } - - static function saveNew($profile_id, $content, $source=NULL, $is_local=1, $reply_to=NULL, $uri=NULL) { - - $profile = Profile::staticGet($profile_id); + ###START_AUTOCODE + /* the code below is auto generated do not remove the above tag */ + + public $__table = 'notice'; // table name + public $id; // int(4) primary_key not_null + public $profile_id; // int(4) not_null + public $uri; // varchar(255) unique_key + public $content; // varchar(140) + public $rendered; // text() + public $url; // varchar(255) + public $created; // datetime() not_null + public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP + public $reply_to; // int(4) + public $is_local; // tinyint(1) + public $source; // varchar(32) + + /* Static get */ + function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Notice',$k,$v); } + + /* the code above is auto generated do not remove the tag below */ + ###END_AUTOCODE + + function getProfile() { + return Profile::staticGet('id', $this->profile_id); + } + + function delete() { + $this->blowCaches(true); + $this->blowFavesCache(true); + $this->blowInboxes(); + return parent::delete(); + } + + function saveTags() { + /* extract all #hastags */ + $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match); + if (!$count) { + return true; + } + + /* elide characters we don't want in the tag */ + $match[1] = str_replace(array('-', '_', '.'), '', $match[1]); + + /* Add them to the database */ + foreach(array_unique($match[1]) as $hashtag) { + $tag = DB_DataObject::factory('Notice_tag'); + $tag->notice_id = $this->id; + $tag->tag = $hashtag; + $tag->created = $this->created; + $id = $tag->insert(); + if (!$id) { + $last_error = PEAR::getStaticProperty('DB_DataObject','lastError'); + common_log(LOG_ERR, 'DB error inserting hashtag: ' . $last_error->message); + common_server_error(sprintf(_('DB error inserting hashtag: %s'), $last_error->message)); + return; + } + } + return true; + } + + static function saveNew($profile_id, $content, $source=NULL, $is_local=1, $reply_to=NULL, $uri=NULL) { + + $profile = Profile::staticGet($profile_id); if (!$profile) { common_log(LOG_ERR, 'Problem saving notice. Unknown user.'); @@ -102,69 +102,69 @@ class Notice extends Memcached_DataObject if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) { common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.'); - return _('Too many notices too fast; take a breather and post again in a few minutes.'); + return _('Too many notices too fast; take a breather and post again in a few minutes.'); } - $banned = common_config('profile', 'banned'); + $banned = common_config('profile', 'banned'); - if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) { - common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id)."); + if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) { + common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id)."); return _('You are banned from posting notices on this site.'); - } + } - $notice = new Notice(); - $notice->profile_id = $profile_id; + $notice = new Notice(); + $notice->profile_id = $profile_id; - $blacklist = common_config('public', 'blacklist'); + $blacklist = common_config('public', 'blacklist'); - # Blacklisted are non-false, but not 1, either + # Blacklisted are non-false, but not 1, either - if ($blacklist && in_array($profile_id, $blacklist)) { - $notice->is_local = -1; - } else { - $notice->is_local = $is_local; - } + if ($blacklist && in_array($profile_id, $blacklist)) { + $notice->is_local = -1; + } else { + $notice->is_local = $is_local; + } - $notice->reply_to = $reply_to; - $notice->created = common_sql_now(); - $notice->content = common_shorten_links($content); - $notice->rendered = common_render_content($notice->content, $notice); - $notice->source = $source; - $notice->uri = $uri; + $notice->reply_to = $reply_to; + $notice->created = common_sql_now(); + $notice->content = common_shorten_links($content); + $notice->rendered = common_render_content($notice->content, $notice); + $notice->source = $source; + $notice->uri = $uri; - $id = $notice->insert(); + $id = $notice->insert(); - if (!$id) { - common_log_db_error($notice, 'INSERT', __FILE__); - return _('Problem saving notice.'); - } + if (!$id) { + common_log_db_error($notice, 'INSERT', __FILE__); + return _('Problem saving notice.'); + } - # Update the URI after the notice is in the database - if (!$uri) { - $orig = clone($notice); - $notice->uri = common_notice_uri($notice); + # Update the URI after the notice is in the database + if (!$uri) { + $orig = clone($notice); + $notice->uri = common_notice_uri($notice); - if (!$notice->update($orig)) { - common_log_db_error($notice, 'UPDATE', __FILE__); - return _('Problem saving notice.'); - } - } + if (!$notice->update($orig)) { + common_log_db_error($notice, 'UPDATE', __FILE__); + return _('Problem saving notice.'); + } + } - # XXX: do we need to change this for remote users? + # XXX: do we need to change this for remote users? - common_save_replies($notice); - $notice->saveTags(); + common_save_replies($notice); + $notice->saveTags(); - # Clear the cache for subscribed users, so they'll update at next request - # XXX: someone clever could prepend instead of clearing the cache + # Clear the cache for subscribed users, so they'll update at next request + # XXX: someone clever could prepend instead of clearing the cache - if (common_config('memcached', 'enabled')) { - $notice->blowCaches(); - } + if (common_config('memcached', 'enabled')) { + $notice->blowCaches(); + } - $notice->addToInboxes(); - return $notice; - } + $notice->addToInboxes(); + return $notice; + } static function checkEditThrottle($profile_id) { $profile = Profile::staticGet($profile_id); @@ -184,356 +184,356 @@ class Notice extends Memcached_DataObject return true; } - function blowCaches($blowLast=false) { - $this->blowSubsCache($blowLast); - $this->blowNoticeCache($blowLast); - $this->blowRepliesCache($blowLast); - $this->blowPublicCache($blowLast); - $this->blowTagCache($blowLast); - } - - function blowTagCache($blowLast=false) { - $cache = common_memcache(); - if ($cache) { - $tag = new Notice_tag(); - $tag->notice_id = $this->id; - if ($tag->find()) { - while ($tag->fetch()) { - $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag)); - if ($blowLast) { - $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last')); - } - } - } - $tag->free(); - unset($tag); - } - } - - function blowSubsCache($blowLast=false) { - $cache = common_memcache(); - if ($cache) { - $user = new User(); - - $user->query('SELECT id ' . - 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . - 'WHERE subscription.subscribed = ' . $this->profile_id); - - while ($user->fetch()) { - $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id)); - if ($blowLast) { - $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last')); - } - } - $user->free(); - unset($user); - } - } - - function blowNoticeCache($blowLast=false) { - if ($this->is_local) { - $cache = common_memcache(); - if ($cache) { - $cache->delete(common_cache_key('profile:notices:'.$this->profile_id)); - if ($blowLast) { - $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last')); - } - } - } - } - - function blowRepliesCache($blowLast=false) { - $cache = common_memcache(); - if ($cache) { - $reply = new Reply(); - $reply->notice_id = $this->id; - if ($reply->find()) { - while ($reply->fetch()) { - $cache->delete(common_cache_key('user:replies:'.$reply->profile_id)); - if ($blowLast) { - $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last')); - } - } - } - $reply->free(); - unset($reply); - } - } - - function blowPublicCache($blowLast=false) { - if ($this->is_local == 1) { - $cache = common_memcache(); - if ($cache) { - $cache->delete(common_cache_key('public')); - if ($blowLast) { - $cache->delete(common_cache_key('public').';last'); - } - } - } - } - - function blowFavesCache($blowLast=false) { - $cache = common_memcache(); - if ($cache) { - $fave = new Fave(); - $fave->notice_id = $this->id; - if ($fave->find()) { - while ($fave->fetch()) { - $cache->delete(common_cache_key('user:faves:'.$fave->user_id)); - if ($blowLast) { - $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last')); - } - } - } - $fave->free(); - unset($fave); - } - } - - # XXX: too many args; we need to move to named params or even a separate - # class for notice streams - - static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL, $since=NULL) { - - if (common_config('memcached', 'enabled')) { - - # Skip the cache if this is a since, since_id or before_id qry - if ($since_id > 0 || $before_id > 0 || $since) { - return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since); - } else { - return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order); - } - } - - return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since); - } - - static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) { - - $needAnd = FALSE; - $needWhere = TRUE; - - if (preg_match('/\bWHERE\b/i', $qry)) { - $needWhere = FALSE; - $needAnd = TRUE; - } - - if ($since_id > 0) { - - if ($needWhere) { - $qry .= ' WHERE '; - $needWhere = FALSE; - } else { - $qry .= ' AND '; - } - - $qry .= ' notice.id > ' . $since_id; - } - - if ($before_id > 0) { - - if ($needWhere) { - $qry .= ' WHERE '; - $needWhere = FALSE; - } else { - $qry .= ' AND '; - } - - $qry .= ' notice.id < ' . $before_id; - } + function blowCaches($blowLast=false) { + $this->blowSubsCache($blowLast); + $this->blowNoticeCache($blowLast); + $this->blowRepliesCache($blowLast); + $this->blowPublicCache($blowLast); + $this->blowTagCache($blowLast); + } + + function blowTagCache($blowLast=false) { + $cache = common_memcache(); + if ($cache) { + $tag = new Notice_tag(); + $tag->notice_id = $this->id; + if ($tag->find()) { + while ($tag->fetch()) { + $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag)); + if ($blowLast) { + $cache->delete(common_cache_key('notice_tag:notice_stream:' . $tag->tag . ';last')); + } + } + } + $tag->free(); + unset($tag); + } + } + + function blowSubsCache($blowLast=false) { + $cache = common_memcache(); + if ($cache) { + $user = new User(); + + $user->query('SELECT id ' . + 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . + 'WHERE subscription.subscribed = ' . $this->profile_id); + + while ($user->fetch()) { + $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id)); + if ($blowLast) { + $cache->delete(common_cache_key('user:notices_with_friends:' . $user->id . ';last')); + } + } + $user->free(); + unset($user); + } + } + + function blowNoticeCache($blowLast=false) { + if ($this->is_local) { + $cache = common_memcache(); + if ($cache) { + $cache->delete(common_cache_key('profile:notices:'.$this->profile_id)); + if ($blowLast) { + $cache->delete(common_cache_key('profile:notices:'.$this->profile_id.';last')); + } + } + } + } + + function blowRepliesCache($blowLast=false) { + $cache = common_memcache(); + if ($cache) { + $reply = new Reply(); + $reply->notice_id = $this->id; + if ($reply->find()) { + while ($reply->fetch()) { + $cache->delete(common_cache_key('user:replies:'.$reply->profile_id)); + if ($blowLast) { + $cache->delete(common_cache_key('user:replies:'.$reply->profile_id.';last')); + } + } + } + $reply->free(); + unset($reply); + } + } + + function blowPublicCache($blowLast=false) { + if ($this->is_local == 1) { + $cache = common_memcache(); + if ($cache) { + $cache->delete(common_cache_key('public')); + if ($blowLast) { + $cache->delete(common_cache_key('public').';last'); + } + } + } + } + + function blowFavesCache($blowLast=false) { + $cache = common_memcache(); + if ($cache) { + $fave = new Fave(); + $fave->notice_id = $this->id; + if ($fave->find()) { + while ($fave->fetch()) { + $cache->delete(common_cache_key('user:faves:'.$fave->user_id)); + if ($blowLast) { + $cache->delete(common_cache_key('user:faves:'.$fave->user_id.';last')); + } + } + } + $fave->free(); + unset($fave); + } + } + + # XXX: too many args; we need to move to named params or even a separate + # class for notice streams - if ($since) { - - if ($needWhere) { - $qry .= ' WHERE '; - $needWhere = FALSE; - } else { - $qry .= ' AND '; - } + static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $before_id=0, $order=NULL, $since=NULL) { - $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\''; - } + if (common_config('memcached', 'enabled')) { - # Allow ORDER override + # Skip the cache if this is a since, since_id or before_id qry + if ($since_id > 0 || $before_id > 0 || $since) { + return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since); + } else { + return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order); + } + } - if ($order) { - $qry .= $order; - } else { - $qry .= ' ORDER BY notice.created DESC, notice.id DESC '; - } + return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since); + } - if (common_config('db','type') == 'pgsql') { - $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } else { - $qry .= ' LIMIT ' . $offset . ', ' . $limit; - } + static function getStreamDirect($qry, $offset, $limit, $since_id, $before_id, $order, $since) { - $notice = new Notice(); + $needAnd = FALSE; + $needWhere = TRUE; - $notice->query($qry); + if (preg_match('/\bWHERE\b/i', $qry)) { + $needWhere = FALSE; + $needAnd = TRUE; + } - return $notice; - } + if ($since_id > 0) { - # XXX: this is pretty long and should probably be broken up into - # some helper functions + if ($needWhere) { + $qry .= ' WHERE '; + $needWhere = FALSE; + } else { + $qry .= ' AND '; + } - static function getCachedStream($qry, $cachekey, $offset, $limit, $order) { + $qry .= ' notice.id > ' . $since_id; + } - # If outside our cache window, just go to the DB + if ($before_id > 0) { - if ($offset + $limit > NOTICE_CACHE_WINDOW) { - return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL); - } + if ($needWhere) { + $qry .= ' WHERE '; + $needWhere = FALSE; + } else { + $qry .= ' AND '; + } - # Get the cache; if we can't, just go to the DB + $qry .= ' notice.id < ' . $before_id; + } - $cache = common_memcache(); + if ($since) { - if (!$cache) { - return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL); - } + if ($needWhere) { + $qry .= ' WHERE '; + $needWhere = FALSE; + } else { + $qry .= ' AND '; + } - # Get the notices out of the cache + $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\''; + } - $notices = $cache->get(common_cache_key($cachekey)); + # Allow ORDER override - # On a cache hit, return a DB-object-like wrapper + if ($order) { + $qry .= $order; + } else { + $qry .= ' ORDER BY notice.created DESC, notice.id DESC '; + } - if ($notices !== FALSE) { - $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit)); - return $wrapper; - } + if (common_config('db','type') == 'pgsql') { + $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; + } else { + $qry .= ' LIMIT ' . $offset . ', ' . $limit; + } - # If the cache was invalidated because of new data being - # added, we can try and just get the new stuff. We keep an additional - # copy of the data at the key + ';last' + $notice = new Notice(); - # No cache hit. Try to get the *last* cached version + $notice->query($qry); - $last_notices = $cache->get(common_cache_key($cachekey) . ';last'); + return $notice; + } - if ($last_notices) { + # XXX: this is pretty long and should probably be broken up into + # some helper functions - # Reverse-chron order, so last ID is last. + static function getCachedStream($qry, $cachekey, $offset, $limit, $order) { - $last_id = $last_notices[0]->id; + # If outside our cache window, just go to the DB - # XXX: this assumes monotonically increasing IDs; a fair - # bet with our DB. + if ($offset + $limit > NOTICE_CACHE_WINDOW) { + return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL); + } - $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, - $last_id, NULL, $order, NULL); + # Get the cache; if we can't, just go to the DB - if ($new_notice) { - $new_notices = array(); - while ($new_notice->fetch()) { - $new_notices[] = clone($new_notice); - } - $new_notice->free(); - $notices = array_slice(array_merge($new_notices, $last_notices), - 0, NOTICE_CACHE_WINDOW); + $cache = common_memcache(); - # Store the array in the cache for next time + if (!$cache) { + return Notice::getStreamDirect($qry, $offset, $limit, NULL, NULL, $order, NULL); + } - $result = $cache->set(common_cache_key($cachekey), $notices); - $result = $cache->set(common_cache_key($cachekey) . ';last', $notices); + # Get the notices out of the cache - # return a wrapper of the array for use now + $notices = $cache->get(common_cache_key($cachekey)); - return new NoticeWrapper(array_slice($notices, $offset, $limit)); - } - } + # On a cache hit, return a DB-object-like wrapper - # Otherwise, get the full cache window out of the DB + if ($notices !== FALSE) { + $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit)); + return $wrapper; + } - $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order, NULL); + # If the cache was invalidated because of new data being + # added, we can try and just get the new stuff. We keep an additional + # copy of the data at the key + ';last' - # If there are no hits, just return the value + # No cache hit. Try to get the *last* cached version - if (!$notice) { - return $notice; - } + $last_notices = $cache->get(common_cache_key($cachekey) . ';last'); - # Pack results into an array + if ($last_notices) { - $notices = array(); + # Reverse-chron order, so last ID is last. - while ($notice->fetch()) { - $notices[] = clone($notice); - } + $last_id = $last_notices[0]->id; - $notice->free(); + # XXX: this assumes monotonically increasing IDs; a fair + # bet with our DB. - # Store the array in the cache for next time + $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, + $last_id, NULL, $order, NULL); - $result = $cache->set(common_cache_key($cachekey), $notices); - $result = $cache->set(common_cache_key($cachekey) . ';last', $notices); + if ($new_notice) { + $new_notices = array(); + while ($new_notice->fetch()) { + $new_notices[] = clone($new_notice); + } + $new_notice->free(); + $notices = array_slice(array_merge($new_notices, $last_notices), + 0, NOTICE_CACHE_WINDOW); - # return a wrapper of the array for use now + # Store the array in the cache for next time - $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit)); + $result = $cache->set(common_cache_key($cachekey), $notices); + $result = $cache->set(common_cache_key($cachekey) . ';last', $notices); - return $wrapper; - } + # return a wrapper of the array for use now - function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=NULL) { + return new NoticeWrapper(array_slice($notices, $offset, $limit)); + } + } - $parts = array(); + # Otherwise, get the full cache window out of the DB - $qry = 'SELECT * FROM notice '; + $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, NULL, NULL, $order, NULL); - if (common_config('public', 'localonly')) { - $parts[] = 'is_local = 1'; - } else { - # -1 == blacklisted - $parts[] = 'is_local != -1'; - } + # If there are no hits, just return the value - if ($parts) { - $qry .= ' WHERE ' . implode(' AND ', $parts); - } + if (!$notice) { + return $notice; + } - return Notice::getStream($qry, - 'public', - $offset, $limit, $since_id, $before_id, NULL, $since); - } + # Pack results into an array - function addToInboxes() { - $enabled = common_config('inboxes', 'enabled'); + $notices = array(); - if ($enabled === true || $enabled === 'transitional') { - $inbox = new Notice_inbox(); - $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' . - 'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' . - 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . - 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' . - 'AND NOT EXISTS (SELECT user_id, notice_id ' . - 'FROM notice_inbox ' . - 'WHERE user_id = user.id ' . - 'AND notice_id = ' . $this->id . ' )'; - if ($enabled === 'transitional') { - $qry .= ' AND user.inboxed = 1'; - } - $inbox->query($qry); - } - return; - } + while ($notice->fetch()) { + $notices[] = clone($notice); + } - # Delete from inboxes if we're deleted. + $notice->free(); - function blowInboxes() { + # Store the array in the cache for next time - $enabled = common_config('inboxes', 'enabled'); + $result = $cache->set(common_cache_key($cachekey), $notices); + $result = $cache->set(common_cache_key($cachekey) . ';last', $notices); - if ($enabled === true || $enabled === 'transitional') { - $inbox = new Notice_inbox(); - $inbox->notice_id = $this->id; - $inbox->delete(); - } + # return a wrapper of the array for use now - return; - } + $wrapper = new NoticeWrapper(array_slice($notices, $offset, $limit)); + + return $wrapper; + } + + function publicStream($offset=0, $limit=20, $since_id=0, $before_id=0, $since=NULL) { + + $parts = array(); + + $qry = 'SELECT * FROM notice '; + + if (common_config('public', 'localonly')) { + $parts[] = 'is_local = 1'; + } else { + # -1 == blacklisted + $parts[] = 'is_local != -1'; + } + + if ($parts) { + $qry .= ' WHERE ' . implode(' AND ', $parts); + } + + return Notice::getStream($qry, + 'public', + $offset, $limit, $since_id, $before_id, NULL, $since); + } + + function addToInboxes() { + $enabled = common_config('inboxes', 'enabled'); + + if ($enabled === true || $enabled === 'transitional') { + $inbox = new Notice_inbox(); + $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' . + 'SELECT user.id, ' . $this->id . ', "' . $this->created . '" ' . + 'FROM user JOIN subscription ON user.id = subscription.subscriber ' . + 'WHERE subscription.subscribed = ' . $this->profile_id . ' ' . + 'AND NOT EXISTS (SELECT user_id, notice_id ' . + 'FROM notice_inbox ' . + 'WHERE user_id = user.id ' . + 'AND notice_id = ' . $this->id . ' )'; + if ($enabled === 'transitional') { + $qry .= ' AND user.inboxed = 1'; + } + $inbox->query($qry); + } + return; + } + + # Delete from inboxes if we're deleted. + + function blowInboxes() { + + $enabled = common_config('inboxes', 'enabled'); + + if ($enabled === true || $enabled === 'transitional') { + $inbox = new Notice_inbox(); + $inbox->notice_id = $this->id; + $inbox->delete(); + } + + return; + } } diff --git a/_darcs/pristine/classes/NoticeWrapper.php b/_darcs/pristine/classes/NoticeWrapper.php index f8c0aa381..edecb3092 100644 --- a/_darcs/pristine/classes/NoticeWrapper.php +++ b/_darcs/pristine/classes/NoticeWrapper.php @@ -35,25 +35,25 @@ class NoticeWrapper extends Notice { public $is_local; // tinyint(1) public $source; // varchar(32) - var $notices = NULL; - var $i = -1; - - function __construct($arr) { - $this->notices = $arr; - } - - function fetch() { - static $fields = array('id', 'profile_id', 'uri', 'content', 'rendered', - 'url', 'created', 'modified', 'reply_to', 'is_local', 'source'); - $this->i++; - if ($this->i >= count($this->notices)) { - return false; - } else { - $n = $this->notices[$this->i]; - foreach ($fields as $f) { - $this->$f = $n->$f; - } - return true; - } - } + var $notices = NULL; + var $i = -1; + + function __construct($arr) { + $this->notices = $arr; + } + + function fetch() { + static $fields = array('id', 'profile_id', 'uri', 'content', 'rendered', + 'url', 'created', 'modified', 'reply_to', 'is_local', 'source'); + $this->i++; + if ($this->i >= count($this->notices)) { + return false; + } else { + $n = $this->notices[$this->i]; + foreach ($fields as $f) { + $this->$f = $n->$f; + } + return true; + } + } } \ No newline at end of file diff --git a/_darcs/pristine/classes/Notice_tag.php b/_darcs/pristine/classes/Notice_tag.php index 5b75ff13f..84c4a1020 100644 --- a/_darcs/pristine/classes/Notice_tag.php +++ b/_darcs/pristine/classes/Notice_tag.php @@ -34,22 +34,22 @@ class Notice_tag extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - - static function getStream($tag, $offset=0, $limit=20) { - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN notice_tag ON notice.id = notice_tag.notice_id ' . - 'WHERE notice_tag.tag = "%s" '; + + static function getStream($tag, $offset=0, $limit=20) { + $qry = + 'SELECT notice.* ' . + 'FROM notice JOIN notice_tag ON notice.id = notice_tag.notice_id ' . + 'WHERE notice_tag.tag = "%s" '; - return Notice::getStream(sprintf($qry, $tag), - 'notice_tag:notice_stream:' . common_keyize($tag), - $offset, $limit); - } - - function blowCache() { - $cache = common_memcache(); - if ($cache) { - $cache->delete(common_cache_key('notice_tag:notice_stream:' . $this->tag)); - } - } + return Notice::getStream(sprintf($qry, $tag), + 'notice_tag:notice_stream:' . common_keyize($tag), + $offset, $limit); + } + + function blowCache() { + $cache = common_memcache(); + if ($cache) { + $cache->delete(common_cache_key('notice_tag:notice_stream:' . $this->tag)); + } + } } diff --git a/_darcs/pristine/classes/Profile.php b/_darcs/pristine/classes/Profile.php index b57d7e38d..1f4508bf1 100644 --- a/_darcs/pristine/classes/Profile.php +++ b/_darcs/pristine/classes/Profile.php @@ -46,114 +46,114 @@ class Profile extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - function getAvatar($width, $height=NULL) { - if (is_null($height)) { - $height = $width; - } - return Avatar::pkeyGet(array('profile_id' => $this->id, - 'width' => $width, - 'height' => $height)); - } - - function getOriginalAvatar() { - $avatar = DB_DataObject::factory('avatar'); - $avatar->profile_id = $this->id; - $avatar->original = true; - if ($avatar->find(true)) { - return $avatar; - } else { - return NULL; - } - } - - function setOriginal($source) { - - $info = @getimagesize($source); - - if (!$info) { - return NULL; - } - - $filename = common_avatar_filename($this->id, - image_type_to_extension($info[2]), - NULL, common_timestamp()); - $filepath = common_avatar_path($filename); - - copy($source, $filepath); - - $avatar = new Avatar(); - - $avatar->profile_id = $this->id; - $avatar->width = $info[0]; - $avatar->height = $info[1]; - $avatar->mediatype = image_type_to_mime_type($info[2]); - $avatar->filename = $filename; - $avatar->original = true; - $avatar->url = common_avatar_url($filename); - $avatar->created = DB_DataObject_Cast::dateTime(); # current time - - # XXX: start a transaction here - - if (!$this->delete_avatars()) { - @unlink($filepath); - return NULL; - } - - if (!$avatar->insert()) { - @unlink($filepath); - return NULL; - } - - foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) { - # We don't do a scaled one if original is our scaled size - if (!($avatar->width == $size && $avatar->height == $size)) { - $s = $avatar->scale($size); - if (!$s) { - return NULL; - } - } - } - - return $avatar; - } - - function delete_avatars() { - $avatar = new Avatar(); - $avatar->profile_id = $this->id; - $avatar->find(); - while ($avatar->fetch()) { - $avatar->delete(); - } - return true; - } - - function getBestName() { - return ($this->fullname) ? $this->fullname : $this->nickname; - } + function getAvatar($width, $height=NULL) { + if (is_null($height)) { + $height = $width; + } + return Avatar::pkeyGet(array('profile_id' => $this->id, + 'width' => $width, + 'height' => $height)); + } + + function getOriginalAvatar() { + $avatar = DB_DataObject::factory('avatar'); + $avatar->profile_id = $this->id; + $avatar->original = true; + if ($avatar->find(true)) { + return $avatar; + } else { + return NULL; + } + } + + function setOriginal($source) { + + $info = @getimagesize($source); + + if (!$info) { + return NULL; + } + + $filename = common_avatar_filename($this->id, + image_type_to_extension($info[2]), + NULL, common_timestamp()); + $filepath = common_avatar_path($filename); + + copy($source, $filepath); + + $avatar = new Avatar(); + + $avatar->profile_id = $this->id; + $avatar->width = $info[0]; + $avatar->height = $info[1]; + $avatar->mediatype = image_type_to_mime_type($info[2]); + $avatar->filename = $filename; + $avatar->original = true; + $avatar->url = common_avatar_url($filename); + $avatar->created = DB_DataObject_Cast::dateTime(); # current time + + # XXX: start a transaction here + + if (!$this->delete_avatars()) { + @unlink($filepath); + return NULL; + } + + if (!$avatar->insert()) { + @unlink($filepath); + return NULL; + } + + foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) { + # We don't do a scaled one if original is our scaled size + if (!($avatar->width == $size && $avatar->height == $size)) { + $s = $avatar->scale($size); + if (!$s) { + return NULL; + } + } + } + + return $avatar; + } + + function delete_avatars() { + $avatar = new Avatar(); + $avatar->profile_id = $this->id; + $avatar->find(); + while ($avatar->fetch()) { + $avatar->delete(); + } + return true; + } + + function getBestName() { + return ($this->fullname) ? $this->fullname : $this->nickname; + } # Get latest notice on or before date; default now - function getCurrentNotice($dt=NULL) { - $notice = new Notice(); - $notice->profile_id = $this->id; - if ($dt) { - $notice->whereAdd('created < "' . $dt . '"'); - } - $notice->orderBy('created DESC, notice.id DESC'); - $notice->limit(1); - if ($notice->find(true)) { - return $notice; - } - return NULL; - } - - function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) { - $qry = - 'SELECT * ' . - 'FROM notice ' . - 'WHERE profile_id = %d '; - - return Notice::getStream(sprintf($qry, $this->id), - 'profile:notices:'.$this->id, - $offset, $limit, $since_id, $before_id); - } + function getCurrentNotice($dt=NULL) { + $notice = new Notice(); + $notice->profile_id = $this->id; + if ($dt) { + $notice->whereAdd('created < "' . $dt . '"'); + } + $notice->orderBy('created DESC, notice.id DESC'); + $notice->limit(1); + if ($notice->find(true)) { + return $notice; + } + return NULL; + } + + function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) { + $qry = + 'SELECT * ' . + 'FROM notice ' . + 'WHERE profile_id = %d '; + + return Notice::getStream(sprintf($qry, $this->id), + 'profile:notices:'.$this->id, + $offset, $limit, $since_id, $before_id); + } } diff --git a/_darcs/pristine/classes/Profile_tag.php b/_darcs/pristine/classes/Profile_tag.php index dde19aea2..2daabf867 100644 --- a/_darcs/pristine/classes/Profile_tag.php +++ b/_darcs/pristine/classes/Profile_tag.php @@ -21,81 +21,81 @@ class Profile_tag extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - static function getTags($tagger, $tagged) { - - $tags = array(); + static function getTags($tagger, $tagged) { + + $tags = array(); - # XXX: store this in memcached - - $profile_tag = new Profile_tag(); - $profile_tag->tagger = $tagger; - $profile_tag->tagged = $tagged; - - $profile_tag->find(); - - while ($profile_tag->fetch()) { - $tags[] = $profile_tag->tag; - } - - $profile_tag->free(); - - return $tags; - } - - static function setTags($tagger, $tagged, $newtags) { - - $oldtags = Profile_tag::getTags($tagger, $tagged); - - # Delete stuff that's old that not in new - - $to_delete = array_diff($oldtags, $newtags); - - # Insert stuff that's in new and not in old - - $to_insert = array_diff($newtags, $oldtags); - - $profile_tag = new Profile_tag(); - - $profile_tag->tagger = $tagger; - $profile_tag->tagged = $tagged; - - $profile_tag->query('BEGIN'); - - foreach ($to_delete as $deltag) { - $profile_tag->tag = $deltag; - $result = $profile_tag->delete(); - if (!$result) { - common_log_db_error($profile_tag, 'DELETE', __FILE__); - return false; - } - } - - foreach ($to_insert as $instag) { - $profile_tag->tag = $instag; - $result = $profile_tag->insert(); - if (!$result) { - common_log_db_error($profile_tag, 'INSERT', __FILE__); - return false; - } - } - - $profile_tag->query('COMMIT'); - - return true; - } - - # Return profiles with a given tag - static function getTagged($tagger, $tag) { - $profile = new Profile(); - $profile->query('SELECT profile.* ' . - 'FROM profile JOIN profile_tag ' . - 'ON profile.id = profile_tag.tagged ' . - 'WHERE profile_tag.tagger = ' . $tagger . ' ' . - 'AND profile_tag.tag = "' . $tag . '" '); - $tagged = array(); - while ($profile->fetch()) { - $tagged[] = clone($profile); - } - return $tagged; - } + # XXX: store this in memcached + + $profile_tag = new Profile_tag(); + $profile_tag->tagger = $tagger; + $profile_tag->tagged = $tagged; + + $profile_tag->find(); + + while ($profile_tag->fetch()) { + $tags[] = $profile_tag->tag; + } + + $profile_tag->free(); + + return $tags; + } + + static function setTags($tagger, $tagged, $newtags) { + + $oldtags = Profile_tag::getTags($tagger, $tagged); + + # Delete stuff that's old that not in new + + $to_delete = array_diff($oldtags, $newtags); + + # Insert stuff that's in new and not in old + + $to_insert = array_diff($newtags, $oldtags); + + $profile_tag = new Profile_tag(); + + $profile_tag->tagger = $tagger; + $profile_tag->tagged = $tagged; + + $profile_tag->query('BEGIN'); + + foreach ($to_delete as $deltag) { + $profile_tag->tag = $deltag; + $result = $profile_tag->delete(); + if (!$result) { + common_log_db_error($profile_tag, 'DELETE', __FILE__); + return false; + } + } + + foreach ($to_insert as $instag) { + $profile_tag->tag = $instag; + $result = $profile_tag->insert(); + if (!$result) { + common_log_db_error($profile_tag, 'INSERT', __FILE__); + return false; + } + } + + $profile_tag->query('COMMIT'); + + return true; + } + + # Return profiles with a given tag + static function getTagged($tagger, $tag) { + $profile = new Profile(); + $profile->query('SELECT profile.* ' . + 'FROM profile JOIN profile_tag ' . + 'ON profile.id = profile_tag.tagged ' . + 'WHERE profile_tag.tagger = ' . $tagger . ' ' . + 'AND profile_tag.tag = "' . $tag . '" '); + $tagged = array(); + while ($profile->fetch()) { + $tagged[] = clone($profile); + } + return $tagged; + } } diff --git a/_darcs/pristine/classes/Queue_item.php b/_darcs/pristine/classes/Queue_item.php index 8ba3281de..e54b4976b 100644 --- a/_darcs/pristine/classes/Queue_item.php +++ b/_darcs/pristine/classes/Queue_item.php @@ -22,34 +22,34 @@ class Queue_item extends Memcached_DataObject ###END_AUTOCODE function sequenceKey() { return array(false, false); } - - static function top($transport) { - - $qi = new Queue_item(); - $qi->transport = $transport; - $qi->orderBy('created'); - $qi->whereAdd('claimed is NULL'); - - $qi->limit(1); - - $cnt = $qi->find(TRUE); - - if ($cnt) { - # XXX: potential race condition - # can we force it to only update if claimed is still NULL - # (or old)? - common_log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id . ' for transport ' . $transport); - $orig = clone($qi); - $qi->claimed = common_sql_now(); - $result = $qi->update($orig); - if ($result) { - common_log(LOG_INFO, 'claim succeeded.'); - return $qi; - } else { - common_log(LOG_INFO, 'claim failed.'); - } - } - $qi = NULL; - return NULL; - } + + static function top($transport) { + + $qi = new Queue_item(); + $qi->transport = $transport; + $qi->orderBy('created'); + $qi->whereAdd('claimed is NULL'); + + $qi->limit(1); + + $cnt = $qi->find(TRUE); + + if ($cnt) { + # XXX: potential race condition + # can we force it to only update if claimed is still NULL + # (or old)? + common_log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id . ' for transport ' . $transport); + $orig = clone($qi); + $qi->claimed = common_sql_now(); + $result = $qi->update($orig); + if ($result) { + common_log(LOG_INFO, 'claim succeeded.'); + return $qi; + } else { + common_log(LOG_INFO, 'claim failed.'); + } + } + $qi = NULL; + return NULL; + } } diff --git a/_darcs/pristine/classes/Sms_carrier.php b/_darcs/pristine/classes/Sms_carrier.php index 6ecb51346..f6e0791f9 100644 --- a/_darcs/pristine/classes/Sms_carrier.php +++ b/_darcs/pristine/classes/Sms_carrier.php @@ -21,8 +21,8 @@ class Sms_carrier extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - - function toEmailAddress($sms) { - return sprintf($this->email_pattern, $sms); - } + + function toEmailAddress($sms) { + return sprintf($this->email_pattern, $sms); + } } diff --git a/_darcs/pristine/classes/Subscription.php b/_darcs/pristine/classes/Subscription.php index cc174fcce..a3b5e4b90 100644 --- a/_darcs/pristine/classes/Subscription.php +++ b/_darcs/pristine/classes/Subscription.php @@ -44,8 +44,8 @@ class Subscription extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - - function &pkeyGet($kv) { - return Memcached_DataObject::pkeyGet('Subscription', $kv); - } + + function &pkeyGet($kv) { + return Memcached_DataObject::pkeyGet('Subscription', $kv); + } } diff --git a/_darcs/pristine/classes/User.php b/_darcs/pristine/classes/User.php index 32d5bedde..c2c6ad57f 100644 --- a/_darcs/pristine/classes/User.php +++ b/_darcs/pristine/classes/User.php @@ -67,82 +67,82 @@ class User extends Memcached_DataObject /* the code above is auto generated do not remove the tag below */ ###END_AUTOCODE - function getProfile() { - return Profile::staticGet('id', $this->id); - } - - function isSubscribed($other) { - assert(!is_null($other)); - # XXX: cache results of this query - $sub = Subscription::pkeyGet(array('subscriber' => $this->id, - 'subscribed' => $other->id)); - return (is_null($sub)) ? false : true; - } - - # 'update' won't write key columns, so we have to do it ourselves. - - function updateKeys(&$orig) { - $parts = array(); - foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) { - if (strcmp($this->$k, $orig->$k) != 0) { - $parts[] = $k . ' = ' . $this->_quote($this->$k); - } - } - if (count($parts) == 0) { - # No changes - return true; - } - $toupdate = implode(', ', $parts); - - $table = $this->tableName(); - if(common_config('db','quote_identifiers')) { - $table = '"' . $table . '"'; - } - $qry = 'UPDATE ' . $table . ' SET ' . $toupdate . - ' WHERE id = ' . $this->id; - $orig->decache(); - $result = $this->query($qry); - if ($result) { - $this->encache(); - } - return $result; - } - - function allowed_nickname($nickname) { - # XXX: should already be validated for size, content, etc. - static $blacklist = array('rss', 'xrds', 'doc', 'main', - 'settings', 'notice', 'user', - 'search', 'avatar', 'tag', 'tags', - 'api', 'message'); - $merged = array_merge($blacklist, common_config('nickname', 'blacklist')); - return !in_array($nickname, $merged); - } - - function getCurrentNotice($dt=NULL) { - $profile = $this->getProfile(); - if (!$profile) { - return NULL; - } - return $profile->getCurrentNotice($dt); - } - - function getCarrier() { - return Sms_carrier::staticGet('id', $this->carrier); - } - - function subscribeTo($other) { - $sub = new Subscription(); - $sub->subscriber = $this->id; - $sub->subscribed = $other->id; - - $sub->created = common_sql_now(); # current time - - if (!$sub->insert()) { - return false; - } - - return true; - } + function getProfile() { + return Profile::staticGet('id', $this->id); + } + + function isSubscribed($other) { + assert(!is_null($other)); + # XXX: cache results of this query + $sub = Subscription::pkeyGet(array('subscriber' => $this->id, + 'subscribed' => $other->id)); + return (is_null($sub)) ? false : true; + } + + # 'update' won't write key columns, so we have to do it ourselves. + + function updateKeys(&$orig) { + $parts = array(); + foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) { + if (strcmp($this->$k, $orig->$k) != 0) { + $parts[] = $k . ' = ' . $this->_quote($this->$k); + } + } + if (count($parts) == 0) { + # No changes + return true; + } + $toupdate = implode(', ', $parts); + + $table = $this->tableName(); + if(common_config('db','quote_identifiers')) { + $table = '"' . $table . '"'; + } + $qry = 'UPDATE ' . $table . ' SET ' . $toupdate . + ' WHERE id = ' . $this->id; + $orig->decache(); + $result = $this->query($qry); + if ($result) { + $this->encache(); + } + return $result; + } + + function allowed_nickname($nickname) { + # XXX: should already be validated for size, content, etc. + static $blacklist = array('rss', 'xrds', 'doc', 'main', + 'settings', 'notice', 'user', + 'search', 'avatar', 'tag', 'tags', + 'api', 'message'); + $merged = array_merge($blacklist, common_config('nickname', 'blacklist')); + return !in_array($nickname, $merged); + } + + function getCurrentNotice($dt=NULL) { + $profile = $this->getProfile(); + if (!$profile) { + return NULL; + } + return $profile->getCurrentNotice($dt); + } + + function getCarrier() { + return Sms_carrier::staticGet('id', $this->carrier); + } + + function subscribeTo($other) { + $sub = new Subscription(); + $sub->subscriber = $this->id; + $sub->subscribed = $other->id; + + $sub->created = common_sql_now(); # current time + + if (!$sub->insert()) { + return false; + } + + return true; + } function hasBlocked($other) { @@ -158,193 +158,193 @@ class User extends Memcached_DataObject return $result; } - static function register($fields) { + static function register($fields) { + + # MAGICALLY put fields into current scope + + extract($fields); + + $profile = new Profile(); + + $profile->query('BEGIN'); + + $profile->nickname = $nickname; + $profile->profileurl = common_profile_url($nickname); + + if ($fullname) { + $profile->fullname = $fullname; + } + if ($homepage) { + $profile->homepage = $homepage; + } + if ($bio) { + $profile->bio = $bio; + } + if ($location) { + $profile->location = $location; + } + + $profile->created = common_sql_now(); + + $id = $profile->insert(); + + if (!$id) { + common_log_db_error($profile, 'INSERT', __FILE__); + return FALSE; + } + + $user = new User(); - # MAGICALLY put fields into current scope + $user->id = $id; + $user->nickname = $nickname; - extract($fields); + if ($password) { # may not have a password for OpenID users + $user->password = common_munge_password($password, $id); + } + + # Users who respond to invite email have proven their ownership of that address + + if ($code) { + $invite = Invitation::staticGet($code); + if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) { + $user->email = $invite->address; + } + } + + $inboxes = common_config('inboxes', 'enabled'); - $profile = new Profile(); + if ($inboxes === true || $inboxes == 'transitional') { + $user->inboxed = 1; + } + + $user->created = common_sql_now(); + $user->uri = common_user_uri($user); + + $result = $user->insert(); + + if (!$result) { + common_log_db_error($user, 'INSERT', __FILE__); + return FALSE; + } - $profile->query('BEGIN'); + # Everyone is subscribed to themself - $profile->nickname = $nickname; - $profile->profileurl = common_profile_url($nickname); + $subscription = new Subscription(); + $subscription->subscriber = $user->id; + $subscription->subscribed = $user->id; + $subscription->created = $user->created; - if ($fullname) { - $profile->fullname = $fullname; - } - if ($homepage) { - $profile->homepage = $homepage; - } - if ($bio) { - $profile->bio = $bio; - } - if ($location) { - $profile->location = $location; - } + $result = $subscription->insert(); + + if (!$result) { + common_log_db_error($subscription, 'INSERT', __FILE__); + return FALSE; + } + + if ($email && !$user->email) { + + $confirm = new Confirm_address(); + $confirm->code = common_confirmation_code(128); + $confirm->user_id = $user->id; + $confirm->address = $email; + $confirm->address_type = 'email'; + + $result = $confirm->insert(); + if (!$result) { + common_log_db_error($confirm, 'INSERT', __FILE__); + return FALSE; + } + } + + if ($code && $user->email) { + $user->emailChanged(); + } - $profile->created = common_sql_now(); + $profile->query('COMMIT'); - $id = $profile->insert(); + if ($email && !$user->email) { + mail_confirm_address($user, $confirm->code, $profile->nickname, $email); + } - if (!$id) { - common_log_db_error($profile, 'INSERT', __FILE__); - return FALSE; - } + return $user; + } - $user = new User(); + # Things we do when the email changes - $user->id = $id; - $user->nickname = $nickname; + function emailChanged() { - if ($password) { # may not have a password for OpenID users - $user->password = common_munge_password($password, $id); - } + $invites = new Invitation(); + $invites->address = $this->email; + $invites->address_type = 'email'; - # Users who respond to invite email have proven their ownership of that address + if ($invites->find()) { + while ($invites->fetch()) { + $other = User::staticGet($invites->user_id); + subs_subscribe_to($other, $this); + } + } + } - if ($code) { - $invite = Invitation::staticGet($code); - if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) { - $user->email = $invite->address; - } - } - - $inboxes = common_config('inboxes', 'enabled'); - - if ($inboxes === true || $inboxes == 'transitional') { - $user->inboxed = 1; - } - - $user->created = common_sql_now(); - $user->uri = common_user_uri($user); - - $result = $user->insert(); - - if (!$result) { - common_log_db_error($user, 'INSERT', __FILE__); - return FALSE; - } - - # Everyone is subscribed to themself - - $subscription = new Subscription(); - $subscription->subscriber = $user->id; - $subscription->subscribed = $user->id; - $subscription->created = $user->created; - - $result = $subscription->insert(); - - if (!$result) { - common_log_db_error($subscription, 'INSERT', __FILE__); - return FALSE; - } - - if ($email && !$user->email) { - - $confirm = new Confirm_address(); - $confirm->code = common_confirmation_code(128); - $confirm->user_id = $user->id; - $confirm->address = $email; - $confirm->address_type = 'email'; - - $result = $confirm->insert(); - if (!$result) { - common_log_db_error($confirm, 'INSERT', __FILE__); - return FALSE; - } - } - - if ($code && $user->email) { - $user->emailChanged(); - } - - $profile->query('COMMIT'); - - if ($email && !$user->email) { - mail_confirm_address($user, $confirm->code, $profile->nickname, $email); - } - - return $user; - } - - # Things we do when the email changes - - function emailChanged() { - - $invites = new Invitation(); - $invites->address = $this->email; - $invites->address_type = 'email'; - - if ($invites->find()) { - while ($invites->fetch()) { - $other = User::staticGet($invites->user_id); - subs_subscribe_to($other, $this); - } - } - } - - function hasFave($notice) { - $cache = common_memcache(); - - # XXX: Kind of a hack. - if ($cache) { - # This is the stream of favorite notices, in rev chron - # order. This forces it into cache. - $faves = $this->favoriteNotices(0, NOTICE_CACHE_WINDOW); - $cnt = 0; - while ($faves->fetch()) { - if ($faves->id < $notice->id) { - # If we passed it, it's not a fave - return false; - } else if ($faves->id == $notice->id) { - # If it matches a cached notice, then it's a fave - return true; - } - $cnt++; - } - # If we're not past the end of the cache window, - # then the cache has all available faves, so this one - # is not a fave. - if ($cnt < NOTICE_CACHE_WINDOW) { - return false; - } - # Otherwise, cache doesn't have all faves; - # fall through to the default - } - $fave = Fave::pkeyGet(array('user_id' => $this->id, - 'notice_id' => $notice->id)); - return ((is_null($fave)) ? false : true); - } - function mutuallySubscribed($other) { - return $this->isSubscribed($other) && - $other->isSubscribed($this); - } + function hasFave($notice) { + $cache = common_memcache(); + + # XXX: Kind of a hack. + if ($cache) { + # This is the stream of favorite notices, in rev chron + # order. This forces it into cache. + $faves = $this->favoriteNotices(0, NOTICE_CACHE_WINDOW); + $cnt = 0; + while ($faves->fetch()) { + if ($faves->id < $notice->id) { + # If we passed it, it's not a fave + return false; + } else if ($faves->id == $notice->id) { + # If it matches a cached notice, then it's a fave + return true; + } + $cnt++; + } + # If we're not past the end of the cache window, + # then the cache has all available faves, so this one + # is not a fave. + if ($cnt < NOTICE_CACHE_WINDOW) { + return false; + } + # Otherwise, cache doesn't have all faves; + # fall through to the default + } + $fave = Fave::pkeyGet(array('user_id' => $this->id, + 'notice_id' => $notice->id)); + return ((is_null($fave)) ? false : true); + } + function mutuallySubscribed($other) { + return $this->isSubscribed($other) && + $other->isSubscribed($this); + } function mutuallySubscribedUsers() { - # 3-way join; probably should get cached - $qry = 'SELECT user.* ' . - 'FROM subscription sub1 JOIN user ON sub1.subscribed = user.id ' . - 'JOIN subscription sub2 ON user.id = sub2.subscriber ' . - 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' . - 'ORDER BY user.nickname'; - $user = new User(); - $user->query(sprintf($qry, $this->id, $this->id)); - - return $user; - } - - function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=NULL) { - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN reply ON notice.id = reply.notice_id ' . - 'WHERE reply.profile_id = %d '; - return Notice::getStream(sprintf($qry, $this->id), - 'user:replies:'.$this->id, - $offset, $limit, $since_id, $before_id, NULL, $since); - } + # 3-way join; probably should get cached + $qry = 'SELECT user.* ' . + 'FROM subscription sub1 JOIN user ON sub1.subscribed = user.id ' . + 'JOIN subscription sub2 ON user.id = sub2.subscriber ' . + 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' . + 'ORDER BY user.nickname'; + $user = new User(); + $user->query(sprintf($qry, $this->id, $this->id)); + + return $user; + } + + function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=NULL) { + $qry = + 'SELECT notice.* ' . + 'FROM notice JOIN reply ON notice.id = reply.notice_id ' . + 'WHERE reply.profile_id = %d '; + return Notice::getStream(sprintf($qry, $this->id), + 'user:replies:'.$this->id, + $offset, $limit, $since_id, $before_id, NULL, $since); + } function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=NULL) { $profile = $this->getProfile(); @@ -353,64 +353,64 @@ class User extends Memcached_DataObject } else { return $profile->getNotices($offset, $limit, $since_id, $before_id); } - } + } function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE) { - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN fave ON notice.id = fave.notice_id ' . - 'WHERE fave.user_id = %d '; - return Notice::getStream(sprintf($qry, $this->id), - 'user:faves:'.$this->id, - $offset, $limit); - } + $qry = + 'SELECT notice.* ' . + 'FROM notice JOIN fave ON notice.id = fave.notice_id ' . + 'WHERE fave.user_id = %d '; + return Notice::getStream(sprintf($qry, $this->id), + 'user:faves:'.$this->id, + $offset, $limit); + } function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=NULL) { - $enabled = common_config('inboxes', 'enabled'); - - # Complicated code, depending on whether we support inboxes yet - # XXX: make this go away when inboxes become mandatory - - if ($enabled === false || - ($enabled == 'transitional' && $this->inboxed == 0)) { - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' . - 'WHERE subscription.subscriber = %d '; - $order = NULL; - } else if ($enabled === true || - ($enabled == 'transitional' && $this->inboxed == 1)) { - - $qry = - 'SELECT notice.* ' . - 'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' . - 'WHERE notice_inbox.user_id = %d '; - # NOTE: we override ORDER - $order = 'ORDER BY notice_inbox.created DESC, notice_inbox.notice_id DESC '; - } - return Notice::getStream(sprintf($qry, $this->id), - 'user:notices_with_friends:' . $this->id, - $offset, $limit, $since_id, $before_id, - $order, $since); - } + $enabled = common_config('inboxes', 'enabled'); + + # Complicated code, depending on whether we support inboxes yet + # XXX: make this go away when inboxes become mandatory + + if ($enabled === false || + ($enabled == 'transitional' && $this->inboxed == 0)) { + $qry = + 'SELECT notice.* ' . + 'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' . + 'WHERE subscription.subscriber = %d '; + $order = NULL; + } else if ($enabled === true || + ($enabled == 'transitional' && $this->inboxed == 1)) { + + $qry = + 'SELECT notice.* ' . + 'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' . + 'WHERE notice_inbox.user_id = %d '; + # NOTE: we override ORDER + $order = 'ORDER BY notice_inbox.created DESC, notice_inbox.notice_id DESC '; + } + return Notice::getStream(sprintf($qry, $this->id), + 'user:notices_with_friends:' . $this->id, + $offset, $limit, $since_id, $before_id, + $order, $since); + } function blowFavesCache() { - $cache = common_memcache(); - if ($cache) { - # Faves don't happen chronologically, so we need to blow - # ;last cache, too - $cache->delete(common_cache_key('user:faves:'.$this->id)); - $cache->delete(common_cache_key('user:faves:'.$this->id).';last'); - } - } + $cache = common_memcache(); + if ($cache) { + # Faves don't happen chronologically, so we need to blow + # ;last cache, too + $cache->delete(common_cache_key('user:faves:'.$this->id)); + $cache->delete(common_cache_key('user:faves:'.$this->id).';last'); + } + } function getSelfTags() { - return Profile_tag::getTags($this->id, $this->id); - } + return Profile_tag::getTags($this->id, $this->id); + } function setSelfTags($newtags) { - return Profile_tag::setTags($this->id, $this->id, $newtags); - } + return Profile_tag::setTags($this->id, $this->id, $newtags); + } function block($other) { @@ -434,8 +434,8 @@ class User extends Memcached_DataObject # Cancel their subscription, if it exists - $sub = Subscription::pkeyGet(array('subscriber' => $other->id, - 'subscribed' => $this->id)); + $sub = Subscription::pkeyGet(array('subscriber' => $other->id, + 'subscribed' => $this->id)); if ($sub) { $result = $sub->delete(); diff --git a/_darcs/pristine/lib/common.php b/_darcs/pristine/lib/common.php index 5a28c3091..95ba64d0f 100644 --- a/_darcs/pristine/lib/common.php +++ b/_darcs/pristine/lib/common.php @@ -54,100 +54,100 @@ require_once(INSTALLDIR.'/lib/language.php'); $config = array('site' => - array('name' => 'Just another Laconica microblog', - 'server' => 'localhost', - 'theme' => 'default', - 'path' => '/', - 'logfile' => NULL, - 'fancy' => false, - 'locale_path' => INSTALLDIR.'/locale', - 'language' => 'en_US', - 'languages' => get_all_languages(), - 'email' => - array_key_exists('SERVER_ADMIN', $_SERVER) ? $_SERVER['SERVER_ADMIN'] : NULL, - 'broughtby' => NULL, - 'timezone' => 'UTC', - 'broughtbyurl' => NULL, - 'closed' => false, - 'inviteonly' => false, + array('name' => 'Just another Laconica microblog', + 'server' => 'localhost', + 'theme' => 'default', + 'path' => '/', + 'logfile' => NULL, + 'fancy' => false, + 'locale_path' => INSTALLDIR.'/locale', + 'language' => 'en_US', + 'languages' => get_all_languages(), + 'email' => + array_key_exists('SERVER_ADMIN', $_SERVER) ? $_SERVER['SERVER_ADMIN'] : NULL, + 'broughtby' => NULL, + 'timezone' => 'UTC', + 'broughtbyurl' => NULL, + 'closed' => false, + 'inviteonly' => false, 'private' => false), - 'syslog' => - array('appname' => 'laconica', # for syslog - 'priority' => 'debug'), # XXX: currently ignored - 'queue' => - array('enabled' => false), - 'license' => - array('url' => 'http://creativecommons.org/licenses/by/3.0/', - 'title' => 'Creative Commons Attribution 3.0', - 'image' => 'http://i.creativecommons.org/l/by/3.0/88x31.png'), - 'mail' => - array('backend' => 'mail', - 'params' => NULL), - 'nickname' => - array('blacklist' => array(), - 'featured' => array()), - 'profile' => - array('banned' => array()), - 'avatar' => - array('server' => NULL), - 'public' => - array('localonly' => true, - 'blacklist' => array()), - 'theme' => - array('server' => NULL), - 'throttle' => + 'syslog' => + array('appname' => 'laconica', # for syslog + 'priority' => 'debug'), # XXX: currently ignored + 'queue' => + array('enabled' => false), + 'license' => + array('url' => 'http://creativecommons.org/licenses/by/3.0/', + 'title' => 'Creative Commons Attribution 3.0', + 'image' => 'http://i.creativecommons.org/l/by/3.0/88x31.png'), + 'mail' => + array('backend' => 'mail', + 'params' => NULL), + 'nickname' => + array('blacklist' => array(), + 'featured' => array()), + 'profile' => + array('banned' => array()), + 'avatar' => + array('server' => NULL), + 'public' => + array('localonly' => true, + 'blacklist' => array()), + 'theme' => + array('server' => NULL), + 'throttle' => array('enabled' => false, // whether to throttle edits; false by default 'count' => 20, // number of allowed messages in timespan 'timespan' => 600), // timespan for throttling - 'xmpp' => - array('enabled' => false, - 'server' => 'INVALID SERVER', - 'port' => 5222, - 'user' => 'update', - 'encryption' => true, - 'resource' => 'uniquename', - 'password' => 'blahblahblah', - 'host' => NULL, # only set if != server - 'debug' => false, # print extra debug info - 'public' => array()), # JIDs of users who want to receive the public stream + 'xmpp' => + array('enabled' => false, + 'server' => 'INVALID SERVER', + 'port' => 5222, + 'user' => 'update', + 'encryption' => true, + 'resource' => 'uniquename', + 'password' => 'blahblahblah', + 'host' => NULL, # only set if != server + 'debug' => false, # print extra debug info + 'public' => array()), # JIDs of users who want to receive the public stream 'sphinx' => array('enabled' => false, 'server' => 'localhost', 'port' => 3312), - 'tag' => - array('dropoff' => 864000.0), - 'popular' => - array('dropoff' => 864000.0), - 'daemon' => - array('piddir' => '/var/run', - 'user' => false, - 'group' => false), - 'integration' => - array('source' => 'Laconica'), # source attribute for Twitter - 'memcached' => - array('enabled' => false, - 'server' => 'localhost', - 'port' => 11211), - 'inboxes' => - array('enabled' => true), # on by default for new sites - ); + 'tag' => + array('dropoff' => 864000.0), + 'popular' => + array('dropoff' => 864000.0), + 'daemon' => + array('piddir' => '/var/run', + 'user' => false, + 'group' => false), + 'integration' => + array('source' => 'Laconica'), # source attribute for Twitter + 'memcached' => + array('enabled' => false, + 'server' => 'localhost', + 'port' => 11211), + 'inboxes' => + array('enabled' => true), # on by default for new sites + ); $config['db'] = &PEAR::getStaticProperty('DB_DataObject','options'); $config['db'] = array('database' => 'YOU HAVE TO SET THIS IN config.php', - 'schema_location' => INSTALLDIR . '/classes', - 'class_location' => INSTALLDIR . '/classes', - 'require_prefix' => 'classes/', - 'class_prefix' => '', - 'mirror' => NULL, + 'schema_location' => INSTALLDIR . '/classes', + 'class_location' => INSTALLDIR . '/classes', + 'require_prefix' => 'classes/', + 'class_prefix' => '', + 'mirror' => NULL, 'db_driver' => 'DB', # XXX: JanRain libs only work with DB - 'quote_identifiers' => false, - 'type' => 'mysql' ); + 'quote_identifiers' => false, + 'type' => 'mysql' ); if (function_exists('date_default_timezone_set')) { - /* Work internally in UTC */ - date_default_timezone_set('UTC'); + /* Work internally in UTC */ + date_default_timezone_set('UTC'); } require_once(INSTALLDIR.'/config.php'); @@ -164,9 +164,9 @@ require_once(INSTALLDIR.'/lib/Shorturl_api.php'); require_once(INSTALLDIR.'/lib/twitter.php'); function __autoload($class) { - if ($class == 'OAuthRequest') { - require_once('OAuth.php'); - } else if (file_exists(INSTALLDIR.'/classes/' . $class . '.php')) { + if ($class == 'OAuthRequest') { + require_once('OAuth.php'); + } else if (file_exists(INSTALLDIR.'/classes/' . $class . '.php')) { require_once(INSTALLDIR.'/classes/' . $class . '.php'); } } diff --git a/_darcs/pristine/lib/deleteaction.php b/_darcs/pristine/lib/deleteaction.php index 5ba0e7e44..335070cc4 100644 --- a/_darcs/pristine/lib/deleteaction.php +++ b/_darcs/pristine/lib/deleteaction.php @@ -21,41 +21,41 @@ if (!defined('LACONICA')) { exit(1); } class DeleteAction extends Action { - function handle($args) { - parent::handle($args); - $user = common_current_user(); - $notice_id = $this->trimmed('notice'); - $notice = Notice::staticGet($notice_id); - if (!$notice) { - common_user_error(_('No such notice.')); - exit; - } - - $profile = $notice->getProfile(); - $user_profile = $user->getProfile(); - - if (!common_logged_in()) { - common_user_error(_('Not logged in.')); - exit; - } else if ($notice->profile_id != $user_profile->id) { - common_user_error(_('Can\'t delete this notice.')); - exit; - } - } - - function show_top($arr=NULL) { - $instr = $this->get_instructions(); - $output = common_markup_to_html($instr); - common_element_start('div', 'instructions'); - common_raw($output); - common_element_end('div'); - } - - function get_title() { - return NULL; - } - - function show_header() { - return; - } + function handle($args) { + parent::handle($args); + $user = common_current_user(); + $notice_id = $this->trimmed('notice'); + $notice = Notice::staticGet($notice_id); + if (!$notice) { + common_user_error(_('No such notice.')); + exit; + } + + $profile = $notice->getProfile(); + $user_profile = $user->getProfile(); + + if (!common_logged_in()) { + common_user_error(_('Not logged in.')); + exit; + } else if ($notice->profile_id != $user_profile->id) { + common_user_error(_('Can\'t delete this notice.')); + exit; + } + } + + function show_top($arr=NULL) { + $instr = $this->get_instructions(); + $output = common_markup_to_html($instr); + common_element_start('div', 'instructions'); + common_raw($output); + common_element_end('div'); + } + + function get_title() { + return NULL; + } + + function show_header() { + return; + } } diff --git a/_darcs/pristine/lib/facebookaction.php b/_darcs/pristine/lib/facebookaction.php index 87a82ba01..67595861f 100644 --- a/_darcs/pristine/lib/facebookaction.php +++ b/_darcs/pristine/lib/facebookaction.php @@ -10,11 +10,11 @@ * * 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 + * 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 . + * along with this program. If not, see . */ if (!defined('LACONICA')) { exit(1); } @@ -23,261 +23,261 @@ require_once(INSTALLDIR.'/extlib/facebook/facebook.php'); class FacebookAction extends Action { - function handle($args) { - parent::handle($args); - } - - function get_facebook() { - $apikey = common_config('facebook', 'apikey'); - $secret = common_config('facebook', 'secret'); - return new Facebook($apikey, $secret); - } - - function update_profile_box($facebook, $fbuid, $user) { - - $notice = $user->getCurrentNotice(); - - # Need to include inline CSS for styling the Profile box - - $style = ''; - - $html = $this->render_notice($notice); - - $fbml = "$content $html"; - $fbml .= "$content $html"; - - $fbml_main = "$content $html"; - - $facebook->api_client->profile_setFBML(NULL, $fbuid, $fbml, NULL, NULL, $fbml_main); - } - - # Display methods - - function show_header($selected ='Home') { - - # Add a timestamp to the CSS file so Facebook cache wont ignore our changes - $ts = filemtime(theme_file('facebookapp.css')); - $cssurl = theme_path('facebookapp.css') . "?ts=$ts"; - - $header = ''; - # $header .=''; - $header .= ''; - - $header .= - '' - .'' - .'' - .'' - .''; - $header .= '
          '; - - echo $header; - - } - - function show_footer() { - $footer = '
          '; - echo $footer; - } - - function show_login_form() { - - $loginform = - '

          To add the Identi.ca application, you need to log into your Identi.ca account.

          ' - .'' - .' ' - .'' - .'

          Login

          ' - .'
          ' - .'

          Login with your username and password. Don\'t have a username yet?' - .' Register a new account.' - .'

          ' - .'
          ' - .'
          ' - .'
          ' - .'

          ' - .' ' - .' ' - .'

          ' - .'

          ' - .' ' - .' ' - .'

          ' - .'

          ' - .' ' - .'

          ' - .'
          ' - .'

          ' - .' Lost or forgotten password?' - .'

          ' - .'getProfile(); - $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE); - - $noticeurl = common_local_url('shownotice', array('notice' => $notice->id)); - - # XXX: we need to figure this out better. Is this right? - if (strcmp($notice->uri, $noticeurl) != 0 && preg_match('/^http/', $notice->uri)) { - $noticeurl = $notice->uri; - } - - $html = - '
        • ' - .'' - .'';
-
-		if ($profile->fullname) {
-			$html .= $profile->fullname;
-		} else {
-			$html .= $profile->nickname;
-		}
-
-		$html .=
-		'' - .'' . $profile->nickname . '' - .'

          ' . $notice->rendered . '

          ' - .'

          ' - .''; - - if ($notice->source) { - $html .= _(' from '); - $html .= $this->source_link($notice->source); - } - - if ($notice->reply_to) { - $replyurl = common_local_url('shownotice', array('notice' => $notice->reply_to)); - $html .= - ' (' . _('in reply to...') . ')'; - } - - $html .= '

        • '; - - return $html; - } - - function source_link($source) { - $source_name = _($source); - - $html = ''; - - switch ($source) { - case 'web': - case 'xmpp': - case 'mail': - case 'omb': - case 'api': - $html .= $source_name; - break; - default: - $ns = Notice_source::staticGet($source); - if ($ns) { - $html .= '' . $ns->name . ''; - } else { - $html .= $source_name; - } - break; - } - - $html .= ''; - - return $html; - } - - function pagination($have_before, $have_after, $page, $fbaction, $args=NULL) { - - $html = ''; - - if ($have_before || $have_after) { - $html = '