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') . '?version=' . LACONICA_VERSION,
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').'?version='.LACONICA_VERSION.'" /><![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', $disabled=false)
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';
394 $attrs['disabled'] = 'true';
396 common_element('input', $attrs);
399 common_element('span', 'checkbox_label', $label);
402 common_element('span', 'input_instructions', $instructions);
404 common_element_end('p');
407 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
408 common_element_start('p');
409 common_element('label', array('for' => $id), $label);
410 common_element_start('select', array('id' => $id, 'name' => $id));
412 common_element('option', array('value' => ''));
414 foreach ($content as $value => $option) {
415 if ($value == $selected) {
416 common_element('option', array('value' => $value, 'selected' => $value), $option);
418 common_element('option', array('value' => $value), $option);
421 common_element_end('select');
423 common_element('span', 'input_instructions', $instructions);
425 common_element_end('p');
427 function common_hidden($id, $value) {
428 common_element('input', array('name' => $id,
434 function common_password($id, $label, $instructions=NULL) {
435 common_element_start('p');
436 common_element('label', array('for' => $id), $label);
437 $attrs = array('name' => $id,
438 'type' => 'password',
439 'class' => 'password',
441 common_element('input', $attrs);
443 common_element('span', 'input_instructions', $instructions);
445 common_element_end('p');
448 function common_submit($id, $label, $cls='submit') {
450 common_element_start('p');
451 common_element('input', array('type' => 'submit',
456 common_element_end('p');
459 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
460 common_element_start('p');
461 common_element('label', array('for' => $id), $label);
462 common_element('textarea', array('rows' => 3,
466 ($content) ? $content : '');
468 common_element('span', 'input_instructions', $instructions);
470 common_element_end('p');
473 function common_timezone() {
474 if (common_logged_in()) {
475 $user = common_current_user();
476 if ($user->timezone) {
477 return $user->timezone;
482 return $config['site']['timezone'];
485 function common_language() {
486 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
488 $user_language = FALSE;
490 if (common_logged_in()) {
491 $user = common_current_user();
492 $user_language = $user->language;
495 if ($user_language) {
496 return $user_language;
497 } else if (!empty($httplang)) {
498 $language = client_prefered_language($httplang);
503 return common_config('site', 'language');
506 # salted, hashed passwords are stored in the DB
508 function common_munge_password($password, $id) {
509 return md5($password . $id);
512 # check if a username exists and has matching password
513 function common_check_user($nickname, $password) {
514 # NEVER allow blank passwords, even if they match the DB
515 if (mb_strlen($password) == 0) {
518 $user = User::staticGet('nickname', $nickname);
519 if (is_null($user)) {
522 if (0 == strcmp(common_munge_password($password, $user->id),
531 # is the current user logged in?
532 function common_logged_in() {
533 return (!is_null(common_current_user()));
536 function common_have_session() {
537 return (0 != strcmp(session_id(), ''));
540 function common_ensure_session() {
541 if (!common_have_session()) {
546 # Three kinds of arguments:
551 function common_set_user($user) {
552 if (is_null($user) && common_have_session()) {
553 unset($_SESSION['userid']);
555 } else if (is_string($user)) {
557 $user = User::staticGet('nickname', $nickname);
558 } else if (!($user instanceof User)) {
563 common_ensure_session();
564 $_SESSION['userid'] = $user->id;
570 function common_set_cookie($key, $value, $expiration=0) {
571 $path = common_config('site', 'path');
572 $server = common_config('site', 'server');
574 if ($path && ($path != '/')) {
575 $cookiepath = '/' . $path . '/';
579 return setcookie($key,
586 define('REMEMBERME', 'rememberme');
587 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
589 function common_rememberme($user=NULL) {
591 $user = common_current_user();
593 common_debug('No current user to remember', __FILE__);
597 $rm = new Remember_me();
598 $rm->code = common_good_rand(16);
599 $rm->user_id = $user->id;
600 $result = $rm->insert();
602 common_log_db_error($rm, 'INSERT', __FILE__);
603 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
606 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
607 common_set_cookie(REMEMBERME,
608 implode(':', array($rm->user_id, $rm->code)),
609 time() + REMEMBERME_EXPIRY);
613 function common_remembered_user() {
616 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
618 list($id, $code) = explode(':', $packed);
620 $rm = Remember_me::staticGet($code);
621 if ($rm && ($rm->user_id == $id)) {
622 $user = User::staticGet($rm->user_id);
625 $result = $rm->delete();
627 common_log_db_error($rm, 'DELETE', __FILE__);
630 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
631 common_set_user($user->nickname);
632 common_real_login(false);
633 # We issue a new cookie, so they can log in
634 # automatically again after this session
635 common_rememberme($user);
644 # must be called with a valid user!
646 function common_forgetme() {
647 common_set_cookie(REMEMBERME, '', 0);
650 # who is the current user?
651 function common_current_user() {
652 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
653 common_ensure_session();
654 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
656 # note: this should cache
657 $user = User::staticGet($id);
661 # that didn't work; try to remember
662 $user = common_remembered_user();
664 common_debug("Got User " . $user->nickname);
665 common_debug("Faking session on remembered user");
666 $_SESSION['userid'] = $user->id;
671 # Logins that are 'remembered' aren't 'real' -- they're subject to
672 # cookie-stealing. So, we don't let them do certain things. New reg,
673 # OpenID, and password logins _are_ real.
675 function common_real_login($real=true) {
676 common_ensure_session();
677 $_SESSION['real_login'] = $real;
680 function common_is_real_login() {
681 return common_logged_in() && $_SESSION['real_login'];
684 # get canonical version of nickname for comparison
685 function common_canonical_nickname($nickname) {
686 # XXX: UTF-8 canonicalization (like combining chars)
687 return strtolower($nickname);
690 # get canonical version of email for comparison
691 function common_canonical_email($email) {
692 # XXX: canonicalize UTF-8
693 # XXX: lcase the domain part
697 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$_+!*();/?:~-]))');
699 function common_render_content($text, $notice) {
700 $r = common_render_text($text);
701 $id = $notice->profile_id;
702 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
703 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
707 function common_render_text($text) {
708 $r = htmlspecialchars($text);
710 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
711 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
712 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
717 function common_tag_link($tag) {
718 $canonical = common_canonical_tag($tag);
719 $url = common_local_url('tag', array('tag' => $canonical));
720 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
723 function common_canonical_tag($tag) {
724 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
727 function common_at_link($sender_id, $nickname) {
728 $sender = Profile::staticGet($sender_id);
729 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
731 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
737 function common_relative_profile($sender, $nickname, $dt=NULL) {
738 # Try to find profiles this profile is subscribed to that have this nickname
739 $recipient = new Profile();
740 # XXX: use a join instead of a subquery
741 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
742 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
743 if ($recipient->find(TRUE)) {
744 # XXX: should probably differentiate between profiles with
745 # the same name by date of most recent update
748 # Try to find profiles that listen to this profile and that have this nickname
749 $recipient = new Profile();
750 # XXX: use a join instead of a subquery
751 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
752 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
753 if ($recipient->find(TRUE)) {
754 # XXX: should probably differentiate between profiles with
755 # the same name by date of most recent update
758 # If this is a local user, try to find a local user with that nickname.
759 $sender = User::staticGet($sender->id);
761 $recipient_user = User::staticGet('nickname', $nickname);
762 if ($recipient_user) {
763 return $recipient_user->getProfile();
766 # Otherwise, no links. @messages from local users to remote users,
767 # or from remote users to other remote users, are just
768 # outside our ability to make intelligent guesses about
772 // where should the avatar go for this user?
774 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
778 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
780 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
784 function common_avatar_path($filename) {
786 return INSTALLDIR . '/avatar/' . $filename;
789 function common_avatar_url($filename) {
790 return common_path('avatar/'.$filename);
793 function common_avatar_display_url($avatar) {
794 $server = common_config('avatar', 'server');
796 return 'http://'.$server.'/'.$avatar->filename;
802 function common_default_avatar($size) {
803 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
804 AVATAR_STREAM_SIZE => 'stream',
805 AVATAR_MINI_SIZE => 'mini');
806 return theme_path('default-avatar-'.$sizenames[$size].'.png');
809 function common_local_url($action, $args=NULL) {
811 if ($config['site']['fancy']) {
812 return common_fancy_url($action, $args);
814 return common_simple_url($action, $args);
818 function common_fancy_url($action, $args=NULL) {
819 switch (strtolower($action)) {
821 if ($args && isset($args['page'])) {
822 return common_path('?page=' . $args['page']);
824 return common_path('');
827 return common_path('rss');
829 return common_path('xrds');
831 if ($args && $args['type']) {
832 return common_path('opensearch/'.$args['type']);
834 return common_path('opensearch/people');
837 return common_path('doc/'.$args['title']);
843 return common_path('main/'.$action);
845 if ($args && $args['code']) {
846 return common_path('main/register/'.$args['code']);
848 return common_path('main/register');
850 case 'remotesubscribe':
851 if ($args && $args['nickname']) {
852 return common_path('main/remote?nickname=' . $args['nickname']);
854 return common_path('main/remote');
857 return common_path('main/openid');
858 case 'profilesettings':
859 return common_path('settings/profile');
860 case 'emailsettings':
861 return common_path('settings/email');
862 case 'openidsettings':
863 return common_path('settings/openid');
865 return common_path('settings/sms');
866 case 'twittersettings':
867 return common_path('settings/twitter');
869 if ($args && $args['replyto']) {
870 return common_path('notice/new?replyto='.$args['replyto']);
872 return common_path('notice/new');
875 return common_path('notice/'.$args['notice']);
877 if ($args && $args['notice']) {
878 return common_path('notice/delete/'.$args['notice']);
880 return common_path('notice/delete');
884 return common_path($args['nickname'].'/'.$action);
885 case 'subscriptions':
891 if ($args && isset($args['page'])) {
892 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
894 return common_path($args['nickname'].'/'.$action);
897 return common_path($args['nickname'].'/all/rss');
899 return common_path($args['nickname'].'/replies/rss');
901 return common_path($args['nickname'].'/rss');
903 if ($args && isset($args['page'])) {
904 return common_path($args['nickname'].'?page=' . $args['page']);
906 return common_path($args['nickname']);
908 case 'confirmaddress':
909 return common_path('main/confirmaddress/'.$args['code']);
911 return common_path('user/'.$args['id']);
912 case 'recoverpassword':
913 $path = 'main/recoverpassword';
915 $path .= '/' . $args['code'];
917 return common_path($path);
919 return common_path('settings/im');
921 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
923 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
924 case 'noticesearchrss':
925 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
926 case 'avatarbynickname':
927 return common_path($args['nickname'].'/avatar/'.$args['size']);
929 if (isset($args['tag']) && $args['tag']) {
930 $path = 'tag/' . $args['tag'];
935 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
937 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
939 return common_path('main/favor');
941 return common_path('main/disfavor');
942 case 'showfavorites':
943 if ($args && isset($args['page'])) {
944 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
946 return common_path($args['nickname'].'/favorites');
949 return common_path('message/' . $args['message']);
951 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
953 return common_simple_url($action, $args);
957 function common_simple_url($action, $args=NULL) {
959 /* XXX: pretty URLs */
962 foreach ($args as $key => $value) {
963 $extra .= "&${key}=${value}";
966 return common_path("index.php?action=${action}${extra}");
969 function common_path($relative) {
971 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
972 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
975 function common_date_string($dt) {
976 // XXX: do some sexy date formatting
977 // return date(DATE_RFC822, $dt);
982 if ($now < $t) { # that shouldn't happen!
983 return common_exact_date($dt);
984 } else if ($diff < 60) {
985 return _('a few seconds ago');
986 } else if ($diff < 92) {
987 return _('about a minute ago');
988 } else if ($diff < 3300) {
989 return sprintf(_('about %d minutes ago'), round($diff/60));
990 } else if ($diff < 5400) {
991 return _('about an hour ago');
992 } else if ($diff < 22 * 3600) {
993 return sprintf(_('about %d hours ago'), round($diff/3600));
994 } else if ($diff < 37 * 3600) {
995 return _('about a day ago');
996 } else if ($diff < 24 * 24 * 3600) {
997 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
998 } else if ($diff < 46 * 24 * 3600) {
999 return _('about a month ago');
1000 } else if ($diff < 330 * 24 * 3600) {
1001 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1002 } else if ($diff < 480 * 24 * 3600) {
1003 return _('about a year ago');
1005 return common_exact_date($dt);
1009 function common_exact_date($dt) {
1014 $_utc = new DateTimeZone('UTC');
1015 $_siteTz = new DateTimeZone(common_timezone());
1018 $dateStr = date('d F Y H:i:s', strtotime($dt));
1019 $d = new DateTime($dateStr, $_utc);
1020 $d->setTimezone($_siteTz);
1021 return $d->format(DATE_RFC850);
1024 function common_date_w3dtf($dt) {
1025 $dateStr = date('d F Y H:i:s', strtotime($dt));
1026 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1027 $d->setTimezone(new DateTimeZone(common_timezone()));
1028 return $d->format(DATE_W3C);
1031 function common_date_rfc2822($dt) {
1032 $dateStr = date('d F Y H:i:s', strtotime($dt));
1033 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1034 $d->setTimezone(new DateTimeZone(common_timezone()));
1035 return $d->format('r');
1038 function common_date_iso8601($dt) {
1039 $dateStr = date('d F Y H:i:s', strtotime($dt));
1040 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1041 $d->setTimezone(new DateTimeZone(common_timezone()));
1042 return $d->format('c');
1045 function common_sql_now() {
1046 return strftime('%Y-%m-%d %H:%M:%S', time());
1049 function common_redirect($url, $code=307) {
1050 static $status = array(301 => "Moved Permanently",
1053 307 => "Temporary Redirect");
1054 header("Status: ${code} $status[$code]");
1055 header("Location: $url");
1057 common_start_xml('a',
1058 '-//W3C//DTD XHTML 1.0 Strict//EN',
1059 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1060 common_element('a', array('href' => $url), $url);
1065 function common_save_replies($notice) {
1066 # Alternative reply format
1068 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1071 # extract all @messages
1072 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1073 if (!$cnt && !$tname) {
1076 # XXX: is there another way to make an array copy?
1077 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1078 $sender = Profile::staticGet($notice->profile_id);
1079 # store replied only for first @ (what user/notice what the reply directed,
1080 # we assume first @ is it)
1081 for ($i=0; $i<count($names); $i++) {
1082 $nickname = $names[$i];
1083 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1087 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1088 $reply_for = $recipient;
1089 $recipient_notice = $reply_for->getCurrentNotice();
1090 if ($recipient_notice) {
1091 $orig = clone($notice);
1092 $notice->reply_to = $recipient_notice->id;
1093 $notice->update($orig);
1096 $reply = new Reply();
1097 $reply->notice_id = $notice->id;
1098 $reply->profile_id = $recipient->id;
1099 $id = $reply->insert();
1101 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1102 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1103 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1109 function common_broadcast_notice($notice, $remote=false) {
1111 // Check to see if notice should go to Twitter
1112 $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1113 if ($flink->noticesync & FOREIGN_NOTICE_SEND) {
1115 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1117 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/', $notice->content) ||
1118 ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
1120 $result = common_twitter_broadcast($notice, $flink);
1123 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1128 if (common_config('queue', 'enabled')) {
1130 return common_enqueue_notice($notice);
1132 return common_real_broadcast($notice, $remote);
1136 function common_twitter_broadcast($notice, $flink) {
1139 $fuser = $flink->getForeignUser();
1140 $twitter_user = $fuser->nickname;
1141 $twitter_password = $flink->credentials;
1142 $uri = 'http://www.twitter.com/statuses/update.json';
1144 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1145 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1148 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1149 CURLOPT_POST => true,
1150 CURLOPT_POSTFIELDS => array(
1151 'status' => $statustxt,
1152 'source' => $config['integration']['source']
1154 CURLOPT_RETURNTRANSFER => true,
1155 CURLOPT_FAILONERROR => true,
1156 CURLOPT_HEADER => false,
1157 CURLOPT_FOLLOWLOCATION => true,
1158 CURLOPT_USERAGENT => "Laconica",
1159 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1160 CURLOPT_TIMEOUT => 120
1163 $ch = curl_init($uri);
1164 curl_setopt_array($ch, $options);
1165 $data = curl_exec($ch);
1166 $errmsg = curl_error($ch);
1169 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1177 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1182 // Twitter should return a status
1183 $status = json_decode($data);
1186 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1194 # Stick the notice on the queue
1196 function common_enqueue_notice($notice) {
1197 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1198 $qi = new Queue_item();
1199 $qi->notice_id = $notice->id;
1200 $qi->transport = $transport;
1201 $qi->created = $notice->created;
1202 $result = $qi->insert();
1204 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1205 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1208 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1213 function common_dequeue_notice($notice) {
1214 $qi = Queue_item::staticGet($notice->id);
1216 $result = $qi->delete();
1218 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1219 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1222 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1229 function common_real_broadcast($notice, $remote=false) {
1232 # Make sure we have the OMB stuff
1233 require_once(INSTALLDIR.'/lib/omb.php');
1234 $success = omb_broadcast_remote_subscribers($notice);
1236 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1240 require_once(INSTALLDIR.'/lib/jabber.php');
1241 $success = jabber_broadcast_notice($notice);
1243 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1247 require_once(INSTALLDIR.'/lib/mail.php');
1248 $success = mail_broadcast_notice_sms($notice);
1250 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1254 $success = jabber_public_notice($notice);
1256 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1259 // XXX: broadcast notices to other IM
1263 function common_broadcast_profile($profile) {
1264 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1265 require_once(INSTALLDIR.'/lib/omb.php');
1266 omb_broadcast_profile($profile);
1267 // XXX: Other broadcasts...?
1271 function common_profile_url($nickname) {
1272 return common_local_url('showstream', array('nickname' => $nickname));
1275 # Don't call if nobody's logged in
1277 function common_notice_form($action=NULL, $content=NULL) {
1278 $user = common_current_user();
1279 assert(!is_null($user));
1280 common_element_start('form', array('id' => 'status_form',
1282 'action' => common_local_url('newnotice')));
1283 common_element_start('p');
1284 common_element('label', array('for' => 'status_textarea',
1285 'id' => 'status_label'),
1286 sprintf(_('What\'s up, %s?'), $user->nickname));
1287 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1288 common_element('textarea', array('id' => 'status_textarea',
1291 'name' => 'status_textarea'),
1292 ($content) ? $content : '');
1294 common_hidden('returnto', $action);
1296 common_element('input', array('id' => 'status_submit',
1297 'name' => 'status_submit',
1299 'value' => _('Send')));
1300 common_element_end('p');
1301 common_element_end('form');
1304 # Should make up a reasonable root URL
1306 function common_root_url() {
1307 return common_path('');
1310 # returns $bytes bytes of random data as a hexadecimal string
1311 # "good" here is a goal and not a guarantee
1313 function common_good_rand($bytes) {
1314 # XXX: use random.org...?
1315 if (file_exists('/dev/urandom')) {
1316 return common_urandom($bytes);
1317 } else { # FIXME: this is probably not good enough
1318 return common_mtrand($bytes);
1322 function common_urandom($bytes) {
1323 $h = fopen('/dev/urandom', 'rb');
1325 $src = fread($h, $bytes);
1328 for ($i = 0; $i < $bytes; $i++) {
1329 $enc .= sprintf("%02x", (ord($src[$i])));
1334 function common_mtrand($bytes) {
1336 for ($i = 0; $i < $bytes; $i++) {
1337 $enc .= sprintf("%02x", mt_rand(0, 255));
1342 function common_set_returnto($url) {
1343 common_ensure_session();
1344 $_SESSION['returnto'] = $url;
1347 function common_get_returnto() {
1348 common_ensure_session();
1349 return $_SESSION['returnto'];
1352 function common_timestamp() {
1353 return date('YmdHis');
1356 function common_ensure_syslog() {
1357 static $initialized = false;
1358 if (!$initialized) {
1360 openlog($config['syslog']['appname'], 0, LOG_USER);
1361 $initialized = true;
1365 function common_log($priority, $msg, $filename=NULL) {
1366 $logfile = common_config('site', 'logfile');
1368 $log = fopen($logfile, "a");
1370 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1371 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1372 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1373 fwrite($log, $output);
1377 common_ensure_syslog();
1378 syslog($priority, $msg);
1382 function common_debug($msg, $filename=NULL) {
1384 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1386 common_log(LOG_DEBUG, $msg);
1390 function common_log_db_error(&$object, $verb, $filename=NULL) {
1391 $objstr = common_log_objstring($object);
1392 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1393 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1396 function common_log_objstring(&$object) {
1397 if (is_null($object)) {
1400 $arr = $object->toArray();
1402 foreach ($arr as $k => $v) {
1403 $fields[] = "$k='$v'";
1405 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1409 function common_valid_http_url($url) {
1410 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1413 function common_valid_tag($tag) {
1414 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1415 return (Validate::email($matches[1]) ||
1416 preg_match('/^([\w-\.]+)$/', $matches[1]));
1421 # Does a little before-after block for next/prev page
1423 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1425 if ($have_before || $have_after) {
1426 common_element_start('div', array('id' => 'pagination'));
1427 common_element_start('ul', array('id' => 'nav_pagination'));
1431 $pargs = array('page' => $page-1);
1432 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1434 common_element_start('li', 'before');
1435 common_element('a', array('href' => common_local_url($action, $newargs)),
1437 common_element_end('li');
1441 $pargs = array('page' => $page+1);
1442 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1443 common_element_start('li', 'after');
1444 common_element('a', array('href' => common_local_url($action, $newargs)),
1446 common_element_end('li');
1449 if ($have_before || $have_after) {
1450 common_element_end('ul');
1451 common_element_end('div');
1455 /* Following functions are copied from MediaWiki GlobalFunctions.php
1456 * and written by Evan Prodromou. */
1458 function common_accept_to_prefs($accept, $def = '*/*') {
1459 # No arg means accept anything (per HTTP spec)
1461 return array($def => 1);
1466 $parts = explode(',', $accept);
1468 foreach($parts as $part) {
1469 # FIXME: doesn't deal with params like 'text/html; level=1'
1470 @list($value, $qpart) = explode(';', $part);
1472 if(!isset($qpart)) {
1474 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1475 $prefs[$value] = $match[1];
1482 function common_mime_type_match($type, $avail) {
1483 if(array_key_exists($type, $avail)) {
1486 $parts = explode('/', $type);
1487 if(array_key_exists($parts[0] . '/*', $avail)) {
1488 return $parts[0] . '/*';
1489 } elseif(array_key_exists('*/*', $avail)) {
1497 function common_negotiate_type($cprefs, $sprefs) {
1500 foreach(array_keys($sprefs) as $type) {
1501 $parts = explode('/', $type);
1502 if($parts[1] != '*') {
1503 $ckey = common_mime_type_match($type, $cprefs);
1505 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1510 foreach(array_keys($cprefs) as $type) {
1511 $parts = explode('/', $type);
1512 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1513 $skey = common_mime_type_match($type, $sprefs);
1515 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1521 $besttype = "text/html";
1523 foreach(array_keys($combine) as $type) {
1524 if($combine[$type] > $bestq) {
1526 $bestq = $combine[$type];
1533 function common_config($main, $sub) {
1535 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1538 function common_copy_args($from) {
1540 $strip = get_magic_quotes_gpc();
1541 foreach ($from as $k => $v) {
1542 $to[$k] = ($strip) ? stripslashes($v) : $v;
1547 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1548 // This is used before handing a request off to OAuthRequest::from_request.
1549 function common_remove_magic_from_request() {
1550 if(get_magic_quotes_gpc()) {
1551 $_POST=array_map('stripslashes',$_POST);
1552 $_GET=array_map('stripslashes',$_GET);
1556 function common_user_uri(&$user) {
1557 return common_local_url('userbyid', array('id' => $user->id));
1560 function common_notice_uri(&$notice) {
1561 return common_local_url('shownotice',
1562 array('notice' => $notice->id));
1565 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1567 function common_confirmation_code($bits) {
1568 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1569 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1570 $chars = ceil($bits/5);
1572 for ($i = 0; $i < $chars; $i++) {
1573 # XXX: convert to string and back
1574 $num = hexdec(common_good_rand(1));
1575 # XXX: randomness is too precious to throw away almost
1576 # 40% of the bits we get!
1577 $code .= $codechars[$num%32];
1582 # convert markup to HTML
1584 function common_markup_to_html($c) {
1585 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1586 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1587 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1588 return Markdown($c);
1591 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1592 $avatar = $profile->getAvatar($size);
1594 return common_avatar_display_url($avatar);
1596 return common_default_avatar($size);
1600 function common_profile_uri($profile) {
1604 $user = User::staticGet($profile->id);
1609 $remote = Remote_profile::staticGet($profile->id);
1611 return $remote->uri;
1613 # XXX: this is a very bad profile!
1617 function common_canonical_sms($sms) {
1619 preg_replace('/\D/', '', $sms);
1623 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1626 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1630 case E_USER_WARNING:
1631 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1635 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1639 # FIXME: show error page if we're on the Web
1640 /* Don't execute PHP internal error handler */
1644 function common_session_token() {
1645 common_ensure_session();
1646 if (!array_key_exists('token', $_SESSION)) {
1647 $_SESSION['token'] = common_good_rand(64);
1649 return $_SESSION['token'];
1652 function common_disfavor_form($notice) {
1653 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1655 'class' => 'disfavor',
1656 'action' => common_local_url('disfavor')));
1657 common_hidden('token', common_session_token());
1658 common_hidden('notice', $notice->id);
1659 common_element('input', array('type' => 'submit',
1660 'id' => 'disfavor-submit-' . $notice->id,
1661 'name' => 'disfavor-submit-' . $notice->id,
1662 'class' => 'disfavor',
1664 common_element_end('form');
1667 function common_favor_form($notice) {
1668 common_element_start('form', array('id' => 'favor-' . $notice->id,
1671 'action' => common_local_url('favor')));
1672 common_hidden('token', common_session_token());
1673 common_hidden('notice', $notice->id);
1674 common_element('input', array('type' => 'submit',
1675 'id' => 'favor-submit-' . $notice->id,
1676 'name' => 'favor-submit-' . $notice->id,
1679 common_element_end('form');
1682 function common_cache_key($extra) {
1683 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1686 function common_keyize($str) {
1687 $str = strtolower($str);
1688 $str = preg_replace('/\s/', '_', $str);
1692 function common_message_form($content, $user, $to) {
1694 common_element_start('form', array('id' => 'message_form',
1696 'action' => common_local_url('newmessage')));
1698 $mutual_users = $user->mutuallySubscribedUsers();
1702 while ($mutual_users->fetch()) {
1703 if ($mutual_users->id != $user->id) {
1704 $mutual[$mutual_users->id] = $mutual_users->nickname;
1708 $mutual_users->free();
1709 unset($mutual_users);
1711 common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
1713 common_element_start('p');
1715 common_element('textarea', array('id' => 'message_content',
1718 'name' => 'content'),
1719 ($content) ? $content : '');
1721 common_element('input', array('id' => 'message_send',
1722 'name' => 'message_send',
1724 'value' => _('Send')));
1726 common_hidden('token', common_session_token());
1728 common_element_end('p');
1729 common_element_end('form');