3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
24 function common_server_error($msg, $code=500) {
25 static $status = array(500 => 'Internal Server Error',
26 501 => 'Not Implemented',
28 503 => 'Service Unavailable',
29 504 => 'Gateway Timeout',
30 505 => 'HTTP Version Not Supported');
32 if (!array_key_exists($code, $status)) {
36 $status_string = $status[$code];
38 header('HTTP/1.1 '.$code.' '.$status_string);
39 header('Content-type: text/plain');
47 function common_user_error($msg, $code=400) {
48 static $status = array(400 => 'Bad Request',
49 401 => 'Unauthorized',
50 402 => 'Payment Required',
53 405 => 'Method Not Allowed',
54 406 => 'Not Acceptable',
55 407 => 'Proxy Authentication Required',
56 408 => 'Request Timeout',
59 411 => 'Length Required',
60 412 => 'Precondition Failed',
61 413 => 'Request Entity Too Large',
62 414 => 'Request-URI Too Long',
63 415 => 'Unsupported Media Type',
64 416 => 'Requested Range Not Satisfiable',
65 417 => 'Expectation Failed');
67 if (!array_key_exists($code, $status)) {
71 $status_string = $status[$code];
73 header('HTTP/1.1 '.$code.' '.$status_string);
75 common_show_header('Error');
76 common_element('div', array('class' => 'error'), $msg);
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
85 $xw->startElement($tag);
86 if (is_array($attrs)) {
87 foreach ($attrs as $name => $value) {
88 $xw->writeAttribute($name, $value);
90 } else if (is_string($attrs)) {
91 $xw->writeAttribute('class', $attrs);
95 function common_element_end($tag) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 # XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109 common_element_start($tag, $attrs);
111 if (!is_null($content)) {
114 common_element_end($tag);
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 function common_init_language() {
135 mb_internal_encoding('UTF-8');
136 $language = common_language();
137 # So we don't have to make people install the gettext locales
138 putenv('LANGUAGE='.$language);
139 putenv('LANG='.$language);
140 $locale_set = setlocale(LC_ALL, $language . ".utf8",
142 $language . ".utf-8",
143 $language . ".UTF-8",
145 bindtextdomain("laconica", common_config('site','locale_path'));
146 bind_textdomain_codeset("laconica", "UTF-8");
147 textdomain("laconica");
148 setlocale(LC_CTYPE, 'C');
151 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
153 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
159 common_element_start('head');
160 common_element('title', NULL,
161 $pagetitle . " - " . $config['site']['name']);
162 common_element('link', array('rel' => 'stylesheet',
163 'type' => 'text/css',
164 'href' => theme_path('display.css'),
165 'media' => 'screen, projection, tv'));
166 foreach (array(6,7) as $ver) {
167 if (file_exists(theme_file('ie'.$ver.'.css'))) {
168 # Yes, IE people should be put in jail.
169 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
170 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
174 common_element('script', array('type' => 'text/javascript',
175 'src' => common_path('js/jquery.min.js')),
177 common_element('script', array('type' => 'text/javascript',
178 'src' => common_path('js/jquery.form.js')),
180 common_element('script', array('type' => 'text/javascript',
181 'src' => common_path('js/util.js')),
183 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
184 'href' => common_local_url('opensearch', array('type' => 'people')),
185 'title' => common_config('site', 'name').' People Search'));
187 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
188 'href' => common_local_url('opensearch', array('type' => 'notice')),
189 'title' => common_config('site', 'name').' Notice Search'));
193 call_user_func($callable, $data);
195 call_user_func($callable);
198 common_element_end('head');
199 common_element_start('body');
200 common_element_start('div', array('id' => 'wrap'));
201 common_element_start('div', array('id' => 'header'));
203 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
204 || file_exists(theme_file('logo.png')))
206 common_element_start('a', array('href' => common_local_url('public')));
207 common_element('img', array('src' => isset($config['site']['logo']) ?
208 ($config['site']['logo']) : theme_path('logo.png'),
209 'alt' => $config['site']['name'],
211 common_element_end('a');
213 common_element_start('p', array('id' => 'branding'));
214 common_element('a', array('href' => common_local_url('public')),
215 $config['site']['name']);
216 common_element_end('p');
219 common_element('h1', 'pagetitle', $pagetitle);
223 call_user_func($headercall, $data);
225 call_user_func($headercall);
228 common_element_end('div');
229 common_element_start('div', array('id' => 'content'));
232 function common_start_html($type=NULL) {
235 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
237 # XXX: allow content negotiation for RDF, RSS, or XRDS
239 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
240 common_accept_to_prefs(PAGE_TYPE_PREFS));
243 common_user_error(_('This page is not available in a media type you accept'), 406);
248 header('Content-Type: '.$type);
250 common_start_xml('html',
251 '-//W3C//DTD XHTML 1.0 Strict//EN',
252 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
254 # FIXME: correct language for interface
256 $language = common_language();
258 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
259 'xml:lang' => $language,
260 'lang' => $language));
263 function common_show_footer() {
265 common_element_end('div'); # content div
267 common_element_start('div', array('id' => 'footer'));
268 common_element_start('div', 'laconica');
269 if (common_config('site', 'broughtby')) {
270 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
272 $instr = _('**%%site.name%%** is a microblogging service. ');
274 $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);
275 $output = common_markup_to_html($instr);
277 common_element_end('div');
278 common_element('img', array('id' => 'cc',
279 'src' => $config['license']['image'],
280 'alt' => $config['license']['title']));
281 common_element_start('p');
282 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
283 common_element('a', array('class' => 'license',
285 'href' => $config['license']['url']),
286 $config['license']['title']);
287 common_text(_('. Contributors should be attributed by full name or nickname.'));
288 common_element_end('p');
289 common_element_end('div');
290 common_element_end('div');
291 common_element_end('body');
292 common_element_end('html');
296 function common_text($txt) {
301 function common_raw($xml) {
306 function common_nav_menu() {
307 $user = common_current_user();
308 common_element_start('ul', array('id' => 'nav'));
310 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
313 common_menu_item(common_local_url('peoplesearch'), _('Search'));
314 common_menu_item(common_local_url('tags'), _('Tags'));
316 common_menu_item(common_local_url('profilesettings'),
318 common_menu_item(common_local_url('invite'),
320 common_menu_item(common_local_url('logout'),
323 common_menu_item(common_local_url('login'), _('Login'));
324 if (!common_config('site', 'closed')) {
325 common_menu_item(common_local_url('register'), _('Register'));
327 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
329 common_element_end('ul');
332 function common_foot_menu() {
333 common_element_start('ul', array('id' => 'nav_sub'));
334 common_menu_item(common_local_url('doc', array('title' => 'help')),
336 common_menu_item(common_local_url('doc', array('title' => 'about')),
338 common_menu_item(common_local_url('doc', array('title' => 'faq')),
340 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
342 common_menu_item(common_local_url('doc', array('title' => 'source')),
344 common_menu_item(common_local_url('doc', array('title' => 'contact')),
346 common_element_end('ul');
349 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
352 $lattrs['class'] = 'current';
354 common_element_start('li', $lattrs);
355 $attrs['href'] = $url;
357 $attrs['title'] = $title;
359 common_element('a', $attrs, $text);
360 common_element_end('li');
363 function common_input($id, $label, $value=NULL,$instructions=NULL) {
364 common_element_start('p');
365 common_element('label', array('for' => $id), $label);
366 $attrs = array('name' => $id,
368 'class' => 'input_text',
371 $attrs['value'] = htmlspecialchars($value);
373 common_element('input', $attrs);
375 common_element('span', 'input_instructions', $instructions);
377 common_element_end('p');
380 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
382 common_element_start('p');
383 $attrs = array('name' => $id,
384 'type' => 'checkbox',
385 'class' => 'checkbox',
388 $attrs['value'] = htmlspecialchars($value);
391 $attrs['checked'] = 'checked';
393 common_element('input', $attrs);
396 common_element('span', 'checkbox_label', $label);
399 common_element('span', 'input_instructions', $instructions);
401 common_element_end('p');
404 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
405 common_element_start('p');
406 common_element('label', array('for' => $id), $label);
407 common_element_start('select', array('id' => $id, 'name' => $id));
409 common_element('option', array('value' => ''));
411 foreach ($content as $value => $option) {
412 if ($value == $selected) {
413 common_element('option', array('value' => $value, 'selected' => $value), $option);
415 common_element('option', array('value' => $value), $option);
418 common_element_end('select');
420 common_element('span', 'input_instructions', $instructions);
422 common_element_end('p');
424 function common_hidden($id, $value) {
425 common_element('input', array('name' => $id,
431 function common_password($id, $label, $instructions=NULL) {
432 common_element_start('p');
433 common_element('label', array('for' => $id), $label);
434 $attrs = array('name' => $id,
435 'type' => 'password',
436 'class' => 'password',
438 common_element('input', $attrs);
440 common_element('span', 'input_instructions', $instructions);
442 common_element_end('p');
445 function common_submit($id, $label, $cls='submit') {
447 common_element_start('p');
448 common_element('input', array('type' => 'submit',
453 common_element_end('p');
456 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
457 common_element_start('p');
458 common_element('label', array('for' => $id), $label);
459 common_element('textarea', array('rows' => 3,
463 ($content) ? $content : '');
465 common_element('span', 'input_instructions', $instructions);
467 common_element_end('p');
470 function common_timezone() {
471 if (common_logged_in()) {
472 $user = common_current_user();
473 if ($user->timezone) {
474 return $user->timezone;
479 return $config['site']['timezone'];
482 function common_language() {
483 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
485 $user_language = FALSE;
487 if (common_logged_in()) {
488 $user = common_current_user();
489 $user_language = $user->language;
492 if ($user_language) {
493 return $user_language;
494 } else if (!empty($httplang)) {
495 $language = client_prefered_language($httplang);
500 return $config['site']['language'];
503 # salted, hashed passwords are stored in the DB
505 function common_munge_password($password, $id) {
506 return md5($password . $id);
509 # check if a username exists and has matching password
510 function common_check_user($nickname, $password) {
511 # NEVER allow blank passwords, even if they match the DB
512 if (mb_strlen($password) == 0) {
515 $user = User::staticGet('nickname', $nickname);
516 if (is_null($user)) {
519 if (0 == strcmp(common_munge_password($password, $user->id),
528 # is the current user logged in?
529 function common_logged_in() {
530 return (!is_null(common_current_user()));
533 function common_have_session() {
534 return (0 != strcmp(session_id(), ''));
537 function common_ensure_session() {
538 if (!common_have_session()) {
543 # Three kinds of arguments:
548 function common_set_user($user) {
549 if (is_null($user) && common_have_session()) {
550 unset($_SESSION['userid']);
552 } else if (is_string($user)) {
554 $user = User::staticGet('nickname', $nickname);
555 } else if (!($user instanceof User)) {
560 common_ensure_session();
561 $_SESSION['userid'] = $user->id;
567 function common_set_cookie($key, $value, $expiration=0) {
568 $path = common_config('site', 'path');
569 $server = common_config('site', 'server');
571 if ($path && ($path != '/')) {
572 $cookiepath = '/' . $path . '/';
576 return setcookie($key,
583 define('REMEMBERME', 'rememberme');
584 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
586 function common_rememberme($user=NULL) {
588 $user = common_current_user();
590 common_debug('No current user to remember', __FILE__);
594 $rm = new Remember_me();
595 $rm->code = common_good_rand(16);
596 $rm->user_id = $user->id;
597 $result = $rm->insert();
599 common_log_db_error($rm, 'INSERT', __FILE__);
600 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
603 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
604 common_set_cookie(REMEMBERME,
605 implode(':', array($rm->user_id, $rm->code)),
606 time() + REMEMBERME_EXPIRY);
610 function common_remembered_user() {
613 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
615 list($id, $code) = explode(':', $packed);
617 $rm = Remember_me::staticGet($code);
618 if ($rm && ($rm->user_id == $id)) {
619 $user = User::staticGet($rm->user_id);
622 $result = $rm->delete();
624 common_log_db_error($rm, 'DELETE', __FILE__);
627 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
628 common_set_user($user->nickname);
629 common_real_login(false);
630 # We issue a new cookie, so they can log in
631 # automatically again after this session
632 common_rememberme($user);
641 # must be called with a valid user!
643 function common_forgetme() {
644 common_set_cookie(REMEMBERME, '', 0);
647 # who is the current user?
648 function common_current_user() {
649 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
650 common_ensure_session();
651 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
653 # note: this should cache
654 $user = User::staticGet($id);
658 # that didn't work; try to remember
659 $user = common_remembered_user();
661 common_debug("Got User " . $user->nickname);
662 common_debug("Faking session on remembered user");
663 $_SESSION['userid'] = $user->id;
668 # Logins that are 'remembered' aren't 'real' -- they're subject to
669 # cookie-stealing. So, we don't let them do certain things. New reg,
670 # OpenID, and password logins _are_ real.
672 function common_real_login($real=true) {
673 common_ensure_session();
674 $_SESSION['real_login'] = $real;
677 function common_is_real_login() {
678 return common_logged_in() && $_SESSION['real_login'];
681 # get canonical version of nickname for comparison
682 function common_canonical_nickname($nickname) {
683 # XXX: UTF-8 canonicalization (like combining chars)
684 return strtolower($nickname);
687 # get canonical version of email for comparison
688 function common_canonical_email($email) {
689 # XXX: canonicalize UTF-8
690 # XXX: lcase the domain part
694 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$_+!*();/?:~-]))');
696 function common_render_content($text, $notice) {
697 $r = common_render_text($text);
698 $id = $notice->profile_id;
699 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
700 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
704 function common_render_text($text) {
705 $r = htmlspecialchars($text);
707 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
708 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
709 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
714 function common_tag_link($tag) {
715 $canonical = common_canonical_tag($tag);
716 $url = common_local_url('tag', array('tag' => $canonical));
717 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
720 function common_canonical_tag($tag) {
721 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
724 function common_at_link($sender_id, $nickname) {
725 $sender = Profile::staticGet($sender_id);
726 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
728 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
734 function common_relative_profile($sender, $nickname, $dt=NULL) {
735 # Try to find profiles this profile is subscribed to that have this nickname
736 $recipient = new Profile();
737 # XXX: use a join instead of a subquery
738 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
739 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
740 if ($recipient->find(TRUE)) {
741 # XXX: should probably differentiate between profiles with
742 # the same name by date of most recent update
745 # Try to find profiles that listen to this profile and that have this nickname
746 $recipient = new Profile();
747 # XXX: use a join instead of a subquery
748 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
749 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
750 if ($recipient->find(TRUE)) {
751 # XXX: should probably differentiate between profiles with
752 # the same name by date of most recent update
755 # If this is a local user, try to find a local user with that nickname.
756 $sender = User::staticGet($sender->id);
758 $recipient_user = User::staticGet('nickname', $nickname);
759 if ($recipient_user) {
760 return $recipient_user->getProfile();
763 # Otherwise, no links. @messages from local users to remote users,
764 # or from remote users to other remote users, are just
765 # outside our ability to make intelligent guesses about
769 // where should the avatar go for this user?
771 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
775 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
777 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
781 function common_avatar_path($filename) {
783 return INSTALLDIR . '/avatar/' . $filename;
786 function common_avatar_url($filename) {
787 return common_path('avatar/'.$filename);
790 function common_avatar_display_url($avatar) {
791 $server = common_config('avatar', 'server');
793 return 'http://'.$server.'/'.$avatar->filename;
799 function common_default_avatar($size) {
800 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
801 AVATAR_STREAM_SIZE => 'stream',
802 AVATAR_MINI_SIZE => 'mini');
803 return theme_path('default-avatar-'.$sizenames[$size].'.png');
806 function common_local_url($action, $args=NULL) {
808 if ($config['site']['fancy']) {
809 return common_fancy_url($action, $args);
811 return common_simple_url($action, $args);
815 function common_fancy_url($action, $args=NULL) {
816 switch (strtolower($action)) {
818 if ($args && isset($args['page'])) {
819 return common_path('?page=' . $args['page']);
821 return common_path('');
824 return common_path('rss');
826 return common_path('xrds');
828 if ($args && $args['type']) {
829 return common_path('opensearch/'.$args['type']);
831 return common_path('opensearch/people');
834 return common_path('doc/'.$args['title']);
840 return common_path('main/'.$action);
842 if ($args && $args['code']) {
843 return common_path('main/register/'.$args['code']);
845 return common_path('main/register');
847 case 'remotesubscribe':
848 if ($args && $args['nickname']) {
849 return common_path('main/remote?nickname=' . $args['nickname']);
851 return common_path('main/remote');
854 return common_path('main/openid');
855 case 'profilesettings':
856 return common_path('settings/profile');
857 case 'emailsettings':
858 return common_path('settings/email');
859 case 'openidsettings':
860 return common_path('settings/openid');
862 return common_path('settings/sms');
863 case 'twittersettings':
864 return common_path('settings/twitter');
866 if ($args && $args['replyto']) {
867 return common_path('notice/new?replyto='.$args['replyto']);
869 return common_path('notice/new');
872 return common_path('notice/'.$args['notice']);
874 if ($args && $args['notice']) {
875 return common_path('notice/delete/'.$args['notice']);
877 return common_path('notice/delete');
881 return common_path($args['nickname'].'/'.$action);
882 case 'subscriptions':
888 if ($args && isset($args['page'])) {
889 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
891 return common_path($args['nickname'].'/'.$action);
894 return common_path($args['nickname'].'/all/rss');
896 return common_path($args['nickname'].'/replies/rss');
898 return common_path($args['nickname'].'/rss');
900 if ($args && isset($args['page'])) {
901 return common_path($args['nickname'].'?page=' . $args['page']);
903 return common_path($args['nickname']);
905 case 'confirmaddress':
906 return common_path('main/confirmaddress/'.$args['code']);
908 return common_path('user/'.$args['id']);
909 case 'recoverpassword':
910 $path = 'main/recoverpassword';
912 $path .= '/' . $args['code'];
914 return common_path($path);
916 return common_path('settings/im');
918 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
920 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
921 case 'noticesearchrss':
922 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
923 case 'avatarbynickname':
924 return common_path($args['nickname'].'/avatar/'.$args['size']);
926 if (isset($args['tag']) && $args['tag']) {
927 $path = 'tag/' . $args['tag'];
932 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
934 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
936 return common_path('main/favor');
938 return common_path('main/disfavor');
939 case 'showfavorites':
940 if ($args && isset($args['page'])) {
941 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
943 return common_path($args['nickname'].'/favorites');
946 return common_path('message/' . $args['message']);
948 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
950 return common_simple_url($action, $args);
954 function common_simple_url($action, $args=NULL) {
956 /* XXX: pretty URLs */
959 foreach ($args as $key => $value) {
960 $extra .= "&${key}=${value}";
963 return common_path("index.php?action=${action}${extra}");
966 function common_path($relative) {
968 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
969 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
972 function common_date_string($dt) {
973 // XXX: do some sexy date formatting
974 // return date(DATE_RFC822, $dt);
979 if ($now < $t) { # that shouldn't happen!
980 return common_exact_date($dt);
981 } else if ($diff < 60) {
982 return _('a few seconds ago');
983 } else if ($diff < 92) {
984 return _('about a minute ago');
985 } else if ($diff < 3300) {
986 return sprintf(_('about %d minutes ago'), round($diff/60));
987 } else if ($diff < 5400) {
988 return _('about an hour ago');
989 } else if ($diff < 22 * 3600) {
990 return sprintf(_('about %d hours ago'), round($diff/3600));
991 } else if ($diff < 37 * 3600) {
992 return _('about a day ago');
993 } else if ($diff < 24 * 24 * 3600) {
994 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
995 } else if ($diff < 46 * 24 * 3600) {
996 return _('about a month ago');
997 } else if ($diff < 330 * 24 * 3600) {
998 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
999 } else if ($diff < 480 * 24 * 3600) {
1000 return _('about a year ago');
1002 return common_exact_date($dt);
1006 function common_exact_date($dt) {
1011 $_utc = new DateTimeZone('UTC');
1012 $_siteTz = new DateTimeZone(common_timezone());
1015 $dateStr = date('d F Y H:i:s', strtotime($dt));
1016 $d = new DateTime($dateStr, $_utc);
1017 $d->setTimezone($_siteTz);
1018 return $d->format(DATE_RFC850);
1021 function common_date_w3dtf($dt) {
1022 $dateStr = date('d F Y H:i:s', strtotime($dt));
1023 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1024 $d->setTimezone(new DateTimeZone(common_timezone()));
1025 return $d->format(DATE_W3C);
1028 function common_date_rfc2822($dt) {
1029 $dateStr = date('d F Y H:i:s', strtotime($dt));
1030 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1031 $d->setTimezone(new DateTimeZone(common_timezone()));
1032 return $d->format('r');
1035 function common_date_iso8601($dt) {
1036 $dateStr = date('d F Y H:i:s', strtotime($dt));
1037 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1038 $d->setTimezone(new DateTimeZone(common_timezone()));
1039 return $d->format('c');
1042 function common_sql_now() {
1043 return strftime('%Y-%m-%d %H:%M:%S', time());
1046 function common_redirect($url, $code=307) {
1047 static $status = array(301 => "Moved Permanently",
1050 307 => "Temporary Redirect");
1051 header("Status: ${code} $status[$code]");
1052 header("Location: $url");
1054 common_start_xml('a',
1055 '-//W3C//DTD XHTML 1.0 Strict//EN',
1056 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1057 common_element('a', array('href' => $url), $url);
1062 function common_save_replies($notice) {
1063 # Alternative reply format
1065 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1068 # extract all @messages
1069 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1070 if (!$cnt && !$tname) {
1073 # XXX: is there another way to make an array copy?
1074 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1075 $sender = Profile::staticGet($notice->profile_id);
1076 # store replied only for first @ (what user/notice what the reply directed,
1077 # we assume first @ is it)
1078 for ($i=0; $i<count($names); $i++) {
1079 $nickname = $names[$i];
1080 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1084 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1085 $reply_for = $recipient;
1086 $recipient_notice = $reply_for->getCurrentNotice();
1087 if ($recipient_notice) {
1088 $orig = clone($notice);
1089 $notice->reply_to = $recipient_notice->id;
1090 $notice->update($orig);
1093 $reply = new Reply();
1094 $reply->notice_id = $notice->id;
1095 $reply->profile_id = $recipient->id;
1096 $id = $reply->insert();
1098 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1099 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1100 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1106 function common_broadcast_notice($notice, $remote=false) {
1108 // Check to see if notice should go to Twitter
1109 $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1112 if (!common_twitter_broadcast($notice, $flink)) {
1113 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1117 if (common_config('queue', 'enabled')) {
1119 return common_enqueue_notice($notice);
1121 return common_real_broadcast($notice, $remote);
1125 function common_twitter_broadcast($notice, $flink) {
1128 $fuser = $flink->getForeignUser();
1129 $twitter_user = $fuser->nickname;
1130 $twitter_password = $flink->credentials;
1131 $uri = 'http://www.twitter.com/statuses/update.json';
1132 $statustxt = $notice->content;
1135 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1136 CURLOPT_POST => true,
1137 CURLOPT_POSTFIELDS => array(
1138 'status' => $statustxt,
1139 'source' => $config['integration']['source']
1141 CURLOPT_RETURNTRANSFER => true,
1142 CURLOPT_FAILONERROR => true,
1143 CURLOPT_HEADER => false,
1144 CURLOPT_FOLLOWLOCATION => true,
1145 CURLOPT_USERAGENT => "Laconica",
1146 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1147 CURLOPT_TIMEOUT => 120
1150 $ch = curl_init($uri);
1151 curl_setopt_array($ch, $options);
1152 $data = curl_exec($ch);
1153 $errmsg = curl_error($ch);
1156 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1164 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1169 // Twitter should return a status
1170 $status = json_decode($data);
1173 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1181 # Stick the notice on the queue
1183 function common_enqueue_notice($notice) {
1184 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1185 $qi = new Queue_item();
1186 $qi->notice_id = $notice->id;
1187 $qi->transport = $transport;
1188 $qi->created = $notice->created;
1189 $result = $qi->insert();
1191 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1192 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1195 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1200 function common_dequeue_notice($notice) {
1201 $qi = Queue_item::staticGet($notice->id);
1203 $result = $qi->delete();
1205 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1206 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1209 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1216 function common_real_broadcast($notice, $remote=false) {
1219 # Make sure we have the OMB stuff
1220 require_once(INSTALLDIR.'/lib/omb.php');
1221 $success = omb_broadcast_remote_subscribers($notice);
1223 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1227 require_once(INSTALLDIR.'/lib/jabber.php');
1228 $success = jabber_broadcast_notice($notice);
1230 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1234 require_once(INSTALLDIR.'/lib/mail.php');
1235 $success = mail_broadcast_notice_sms($notice);
1237 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1241 $success = jabber_public_notice($notice);
1243 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1246 // XXX: broadcast notices to other IM
1250 function common_broadcast_profile($profile) {
1251 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1252 require_once(INSTALLDIR.'/lib/omb.php');
1253 omb_broadcast_profile($profile);
1254 // XXX: Other broadcasts...?
1258 function common_profile_url($nickname) {
1259 return common_local_url('showstream', array('nickname' => $nickname));
1262 # Don't call if nobody's logged in
1264 function common_notice_form($action=NULL, $content=NULL) {
1265 $user = common_current_user();
1266 assert(!is_null($user));
1267 common_element_start('form', array('id' => 'status_form',
1269 'action' => common_local_url('newnotice')));
1270 common_element_start('p');
1271 common_element('label', array('for' => 'status_textarea',
1272 'id' => 'status_label'),
1273 sprintf(_('What\'s up, %s?'), $user->nickname));
1274 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1275 common_element('textarea', array('id' => 'status_textarea',
1278 'name' => 'status_textarea'),
1279 ($content) ? $content : '');
1281 common_hidden('returnto', $action);
1283 common_element('input', array('id' => 'status_submit',
1284 'name' => 'status_submit',
1286 'value' => _('Send')));
1287 common_element_end('p');
1288 common_element_end('form');
1291 # Should make up a reasonable root URL
1293 function common_root_url() {
1294 return common_path('');
1297 # returns $bytes bytes of random data as a hexadecimal string
1298 # "good" here is a goal and not a guarantee
1300 function common_good_rand($bytes) {
1301 # XXX: use random.org...?
1302 if (file_exists('/dev/urandom')) {
1303 return common_urandom($bytes);
1304 } else { # FIXME: this is probably not good enough
1305 return common_mtrand($bytes);
1309 function common_urandom($bytes) {
1310 $h = fopen('/dev/urandom', 'rb');
1312 $src = fread($h, $bytes);
1315 for ($i = 0; $i < $bytes; $i++) {
1316 $enc .= sprintf("%02x", (ord($src[$i])));
1321 function common_mtrand($bytes) {
1323 for ($i = 0; $i < $bytes; $i++) {
1324 $enc .= sprintf("%02x", mt_rand(0, 255));
1329 function common_set_returnto($url) {
1330 common_ensure_session();
1331 $_SESSION['returnto'] = $url;
1334 function common_get_returnto() {
1335 common_ensure_session();
1336 return $_SESSION['returnto'];
1339 function common_timestamp() {
1340 return date('YmdHis');
1343 function common_ensure_syslog() {
1344 static $initialized = false;
1345 if (!$initialized) {
1347 openlog($config['syslog']['appname'], 0, LOG_USER);
1348 $initialized = true;
1352 function common_log($priority, $msg, $filename=NULL) {
1353 $logfile = common_config('site', 'logfile');
1355 $log = fopen($logfile, "a");
1357 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1358 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1359 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1360 fwrite($log, $output);
1364 common_ensure_syslog();
1365 syslog($priority, $msg);
1369 function common_debug($msg, $filename=NULL) {
1371 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1373 common_log(LOG_DEBUG, $msg);
1377 function common_log_db_error(&$object, $verb, $filename=NULL) {
1378 $objstr = common_log_objstring($object);
1379 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1380 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1383 function common_log_objstring(&$object) {
1384 if (is_null($object)) {
1387 $arr = $object->toArray();
1389 foreach ($arr as $k => $v) {
1390 $fields[] = "$k='$v'";
1392 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1396 function common_valid_http_url($url) {
1397 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1400 function common_valid_tag($tag) {
1401 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1402 return (Validate::email($matches[1]) ||
1403 preg_match('/^([\w-\.]+)$/', $matches[1]));
1408 # Does a little before-after block for next/prev page
1410 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1412 if ($have_before || $have_after) {
1413 common_element_start('div', array('id' => 'pagination'));
1414 common_element_start('ul', array('id' => 'nav_pagination'));
1418 $pargs = array('page' => $page-1);
1419 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1421 common_element_start('li', 'before');
1422 common_element('a', array('href' => common_local_url($action, $newargs)),
1424 common_element_end('li');
1428 $pargs = array('page' => $page+1);
1429 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1430 common_element_start('li', 'after');
1431 common_element('a', array('href' => common_local_url($action, $newargs)),
1433 common_element_end('li');
1436 if ($have_before || $have_after) {
1437 common_element_end('ul');
1438 common_element_end('div');
1442 /* Following functions are copied from MediaWiki GlobalFunctions.php
1443 * and written by Evan Prodromou. */
1445 function common_accept_to_prefs($accept, $def = '*/*') {
1446 # No arg means accept anything (per HTTP spec)
1448 return array($def => 1);
1453 $parts = explode(',', $accept);
1455 foreach($parts as $part) {
1456 # FIXME: doesn't deal with params like 'text/html; level=1'
1457 @list($value, $qpart) = explode(';', $part);
1459 if(!isset($qpart)) {
1461 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1462 $prefs[$value] = $match[1];
1469 function common_mime_type_match($type, $avail) {
1470 if(array_key_exists($type, $avail)) {
1473 $parts = explode('/', $type);
1474 if(array_key_exists($parts[0] . '/*', $avail)) {
1475 return $parts[0] . '/*';
1476 } elseif(array_key_exists('*/*', $avail)) {
1484 function common_negotiate_type($cprefs, $sprefs) {
1487 foreach(array_keys($sprefs) as $type) {
1488 $parts = explode('/', $type);
1489 if($parts[1] != '*') {
1490 $ckey = common_mime_type_match($type, $cprefs);
1492 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1497 foreach(array_keys($cprefs) as $type) {
1498 $parts = explode('/', $type);
1499 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1500 $skey = common_mime_type_match($type, $sprefs);
1502 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1508 $besttype = "text/html";
1510 foreach(array_keys($combine) as $type) {
1511 if($combine[$type] > $bestq) {
1513 $bestq = $combine[$type];
1520 function common_config($main, $sub) {
1522 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1525 function common_copy_args($from) {
1527 $strip = get_magic_quotes_gpc();
1528 foreach ($from as $k => $v) {
1529 $to[$k] = ($strip) ? stripslashes($v) : $v;
1534 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1535 // This is used before handing a request off to OAuthRequest::from_request.
1536 function common_remove_magic_from_request() {
1537 if(get_magic_quotes_gpc()) {
1538 $_POST=array_map('stripslashes',$_POST);
1539 $_GET=array_map('stripslashes',$_GET);
1543 function common_user_uri(&$user) {
1544 return common_local_url('userbyid', array('id' => $user->id));
1547 function common_notice_uri(&$notice) {
1548 return common_local_url('shownotice',
1549 array('notice' => $notice->id));
1552 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1554 function common_confirmation_code($bits) {
1555 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1556 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1557 $chars = ceil($bits/5);
1559 for ($i = 0; $i < $chars; $i++) {
1560 # XXX: convert to string and back
1561 $num = hexdec(common_good_rand(1));
1562 # XXX: randomness is too precious to throw away almost
1563 # 40% of the bits we get!
1564 $code .= $codechars[$num%32];
1569 # convert markup to HTML
1571 function common_markup_to_html($c) {
1572 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1573 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1574 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1575 return Markdown($c);
1578 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1579 $avatar = $profile->getAvatar($size);
1581 return common_avatar_display_url($avatar);
1583 return common_default_avatar($size);
1587 function common_profile_uri($profile) {
1591 $user = User::staticGet($profile->id);
1596 $remote = Remote_profile::staticGet($profile->id);
1598 return $remote->uri;
1600 # XXX: this is a very bad profile!
1604 function common_canonical_sms($sms) {
1606 preg_replace('/\D/', '', $sms);
1610 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1613 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1617 case E_USER_WARNING:
1618 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1622 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1626 # FIXME: show error page if we're on the Web
1627 /* Don't execute PHP internal error handler */
1631 function common_session_token() {
1632 common_ensure_session();
1633 if (!array_key_exists('token', $_SESSION)) {
1634 $_SESSION['token'] = common_good_rand(64);
1636 return $_SESSION['token'];
1639 function common_disfavor_form($notice) {
1640 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1642 'class' => 'disfavor',
1643 'action' => common_local_url('disfavor')));
1644 common_hidden('token', common_session_token());
1645 common_hidden('notice', $notice->id);
1646 common_element('input', array('type' => 'submit',
1647 'id' => 'disfavor-submit-' . $notice->id,
1648 'name' => 'disfavor-submit-' . $notice->id,
1649 'class' => 'disfavor',
1651 common_element_end('form');
1654 function common_favor_form($notice) {
1655 common_element_start('form', array('id' => 'favor-' . $notice->id,
1658 'action' => common_local_url('favor')));
1659 common_hidden('token', common_session_token());
1660 common_hidden('notice', $notice->id);
1661 common_element('input', array('type' => 'submit',
1662 'id' => 'favor-submit-' . $notice->id,
1663 'name' => 'favor-submit-' . $notice->id,
1666 common_element_end('form');
1669 function common_cache_key($extra) {
1670 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1673 function common_keyize($str) {
1674 $str = strtolower($str);
1675 $str = preg_replace('/\s/', '_', $str);