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) {
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101 common_element_start($tag, $attrs);
106 common_element_end($tag);
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
111 $xw = new XMLWriter();
112 $xw->openURI('php://output');
113 $xw->setIndent(true);
114 $xw->startDocument('1.0', 'UTF-8');
116 $xw->writeDTD($doc, $public, $system);
120 function common_end_xml() {
126 define('PAGE_TYPE_PREFS', 'application/xhtml+xml,text/html;q=0.7,application/xml;q=0.3,text/xml;q=0.2');
128 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
131 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
133 # XXX: allow content negotiation for RDF, RSS, or XRDS
135 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
136 common_accept_to_prefs(PAGE_TYPE_PREFS));
139 common_client_error(_t('This page is not available in a media type you accept'), 406);
143 header('Content-Type: '.$type);
145 common_start_xml('html',
146 '-//W3C//DTD XHTML 1.0 Strict//EN',
147 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
149 # FIXME: correct language for interface
151 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
155 common_element_start('head');
156 common_element('title', NULL,
157 $pagetitle . " - " . $config['site']['name']);
158 common_element('link', array('rel' => 'stylesheet',
159 'type' => 'text/css',
160 'href' => theme_path('display.css'),
161 'media' => 'screen, projection, tv'));
162 foreach (array(6,7) as $ver) {
163 if (file_exists(theme_file('ie'.$ver.'.css'))) {
164 # Yes, IE people should be put in jail.
165 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
166 'href="'.theme_path('ie'.$ver.'.css').' /><![endif]');
170 common_element('script', array('type' => 'text/javascript',
171 'src' => common_path('js/jquery.min.js')),
176 call_user_func($callable, $data);
178 call_user_func($callable);
181 common_element_end('head');
182 common_element_start('body');
183 common_element_start('div', array('id' => 'wrap'));
184 common_element_start('div', array('id' => 'header'));
186 if ($config['site']['logo'] || file_exists(theme_file('logo.png'))) {
187 common_element_start('a', array('href' => common_local_url('public')));
188 common_element('img', array('src' => ($config['site']['logo']) ?
189 ($config['site']['logo']) : theme_path('logo.png'),
190 'alt' => $config['site']['name'],
192 common_element_end('a');
194 common_element('h1', 'pagetitle', $pagetitle);
195 common_element('h2', 'sitename', $config['site']['name']);
199 call_user_func($headercall, $data);
201 call_user_func($headercall);
204 common_element_end('div');
205 common_element_start('div', array('id' => 'content'));
208 function common_show_footer() {
210 common_element_end('div'); # content div
212 common_element_start('div', array('id' => 'footer'));
213 common_element_start('p', 'laconica');
214 common_text(_t('This site is running the '));
215 common_element('a', array('class' => 'software',
216 href => 'http://laconi.ca/'),
218 common_text(_t('microblogging tool, version ' . LACONICA_VERSION . ', available under the '));
219 common_element('a', array(href => 'http://www.fsf.org/licensing/licenses/agpl-3.0.html'),
220 'GNU Affero General Public License');
221 common_text(_t('.'));
222 common_element_end('p');
223 common_element('img', array('id' => 'cc',
224 'src' => $config['license']['image'],
225 'alt' => $config['license']['title']));
226 common_element_start('p');
227 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
228 common_element('a', array('class' => 'license',
230 href => $config['license']['url']),
231 $config['license']['title']);
232 common_text(_t('. Contributors should be attributed by full name or nickname.'));
233 common_element_end('p');
234 common_element_end('div');
235 common_element_end('div');
236 common_element_end('body');
237 common_element_end('html');
241 function common_text($txt) {
246 function common_raw($xml) {
251 function common_nav_menu() {
252 $user = common_current_user();
253 common_element_start('ul', array('id' => 'nav'));
255 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
258 common_menu_item(common_local_url('public'), _t('Public'));
259 common_menu_item(common_local_url('doc', array('title' => 'help')),
262 common_menu_item(common_local_url('profilesettings'),
264 common_menu_item(common_local_url('logout'),
267 common_menu_item(common_local_url('login'), _t('Login'));
268 common_menu_item(common_local_url('register'), _t('Register'));
269 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
271 common_element_end('ul');
274 function common_foot_menu() {
275 common_element_start('ul', array('id' => 'nav_sub'));
276 common_menu_item(common_local_url('doc', array('title' => 'about')),
278 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
280 common_menu_item(common_local_url('doc', array('title' => 'source')),
282 common_element_end('ul');
285 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
288 $lattrs['class'] = 'current';
290 common_element_start('li', $lattrs);
291 $attrs['href'] = $url;
293 $attrs['title'] = $title;
295 common_element('a', $attrs, $text);
296 common_element_end('li');
299 function common_input($id, $label, $value=NULL,$instructions=NULL) {
300 common_element_start('p');
301 common_element('label', array('for' => $id), $label);
302 $attrs = array('name' => $id,
306 $attrs['value'] = htmlspecialchars($value);
308 common_element('input', $attrs);
310 common_element('span', 'input_instructions', $instructions);
312 common_element_end('p');
315 function common_hidden($id, $value) {
316 common_element('input', array('name' => $id,
322 function common_password($id, $label, $instructions=NULL) {
323 common_element_start('p');
324 common_element('label', array('for' => $id), $label);
325 $attrs = array('name' => $id,
326 'type' => 'password',
328 common_element('input', $attrs);
330 common_element('span', 'input_instructions', $instructions);
332 common_element_end('p');
335 function common_submit($id, $label) {
337 common_element_start('p');
338 common_element('input', array('type' => 'submit',
342 common_element_end('p');
345 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
346 common_element_start('p');
347 common_element('label', array('for' => $id), $label);
348 common_element('textarea', array('rows' => 3,
352 ($content) ? $content : ' ');
354 common_element('span', 'input_instructions', $instructions);
356 common_element_end('p');
359 # salted, hashed passwords are stored in the DB
361 function common_munge_password($id, $password) {
362 return md5($id . $password);
365 # check if a username exists and has matching password
366 function common_check_user($nickname, $password) {
367 $user = User::staticGet('nickname', $nickname);
368 if (is_null($user)) {
371 return (0 == strcmp(common_munge_password($password, $user->id),
376 # is the current user logged in?
377 function common_logged_in() {
378 return (!is_null(common_current_user()));
381 function common_have_session() {
382 return (0 != strcmp(session_id(), ''));
385 function common_ensure_session() {
386 if (!common_have_session()) {
391 function common_set_user($nickname) {
392 if (is_null($nickname) && common_have_session()) {
393 unset($_SESSION['userid']);
396 $user = User::staticGet('nickname', $nickname);
398 common_ensure_session();
399 $_SESSION['userid'] = $user->id;
408 # who is the current user?
409 function common_current_user() {
410 static $user = NULL; # FIXME: global memcached
411 if (is_null($user)) {
412 common_ensure_session();
413 $id = $_SESSION['userid'];
415 $user = User::staticGet($id);
421 # get canonical version of nickname for comparison
422 function common_canonical_nickname($nickname) {
423 # XXX: UTF-8 canonicalization (like combining chars)
424 return strtolower($nickname);
427 # get canonical version of email for comparison
428 function common_canonical_email($email) {
429 # XXX: canonicalize UTF-8
430 # XXX: lcase the domain part
434 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$_+!*();/?:~-]))');
436 function common_render_content($text, $notice) {
437 $r = htmlspecialchars($text);
438 $id = $notice->profile_id;
439 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
440 $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
446 function common_at_link($sender_id, $nickname) {
447 # Try to find profiles this profile is subscribed to that have this nickname
448 $recipient = new Profile();
449 # XXX: chokety and bad
450 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
451 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
452 if ($recipient->find(TRUE)) {
453 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
455 # Try to find profiles that listen to this profile and that have this nickname
456 $recipient = new Profile();
457 # XXX: chokety and bad
458 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
459 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
460 if ($recipient->find(TRUE)) {
461 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
463 # If this is a local user, try to find a local user with that nickname.
464 $sender = User::staticGet($sender_id);
466 $recipient_user = User::staticGet('nickname', $nickname);
467 if ($recipient_user) {
468 $recipient = $recipient->getProfile();
469 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
472 # Otherwise, no links. @messages from local users to remote users,
473 # or from remote users to other remote users, are just
474 # outside our ability to make intelligent guesses about
478 // where should the avatar go for this user?
480 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
484 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
486 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
490 function common_avatar_path($filename) {
492 return INSTALLDIR . '/avatar/' . $filename;
495 function common_avatar_url($filename) {
496 return common_path('avatar/'.$filename);
499 function common_default_avatar($size) {
500 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
501 AVATAR_STREAM_SIZE => 'stream',
502 AVATAR_MINI_SIZE => 'mini');
503 return theme_path('default-avatar-'.$sizenames[$size].'.png');
506 function common_local_url($action, $args=NULL) {
508 if ($config['site']['fancy']) {
509 return common_fancy_url($action, $args);
511 return common_simple_url($action, $args);
515 function common_fancy_url($action, $args=NULL) {
516 switch (strtolower($action)) {
518 if ($args && $args['page']) {
519 return common_path('?page=' . $args['page']);
521 return common_path('');
524 return common_path('rss');
526 return common_path('doc/'.$args['title']);
532 return common_path('main/'.$action);
534 return common_path('main/openid');
537 return common_path('settings/'.$action);
538 case 'profilesettings':
539 return common_path('settings/profile');
541 return common_path('notice/new');
543 return common_path('notice/'.$args['notice']);
546 return common_path($args['nickname'].'/'.$action);
547 case 'subscriptions':
550 if ($args && $args['page']) {
551 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
553 return common_path($args['nickname'].'/'.$action);
556 return common_path($args['nickname'].'/all/rss');
558 return common_path($args['nickname'].'/rss');
560 if ($args && $args['page']) {
561 return common_path($args['nickname'].'?page=' . $args['page']);
563 return common_path($args['nickname']);
566 return common_simple_url($action, $args);
570 function common_simple_url($action, $args=NULL) {
572 /* XXX: pretty URLs */
575 foreach ($args as $key => $value) {
576 $extra .= "&${key}=${value}";
579 return common_path("index.php?action=${action}${extra}");
582 function common_path($relative) {
584 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
585 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
588 function common_date_string($dt) {
589 // XXX: do some sexy date formatting
590 // return date(DATE_RFC822, $dt);
594 function common_date_w3dtf($dt) {
596 return date(DATE_W3C, $t);
599 function common_redirect($url, $code=307) {
600 static $status = array(301 => "Moved Permanently",
603 307 => "Temporary Redirect");
604 header("Status: ${code} $status[$code]");
605 header("Location: $url");
606 common_element('a', array('href' => $url), $url);
609 function common_broadcast_notice($notice, $remote=false) {
610 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
612 # Make sure we have the OMB stuff
613 require_once(INSTALLDIR.'/lib/omb.php');
614 omb_broadcast_remote_subscribers($notice);
616 // XXX: broadcast notices to Jabber
617 // XXX: broadcast notices to SMS
618 // XXX: broadcast notices to other IM
622 function common_broadcast_profile($profile) {
623 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
624 require_once(INSTALLDIR.'/lib/omb.php');
625 omb_broadcast_profile($profile);
626 // XXX: Other broadcasts...?
630 function common_profile_url($nickname) {
631 return common_local_url('showstream', array('nickname' => $nickname));
634 # Don't call if nobody's logged in
636 function common_notice_form() {
637 $user = common_current_user();
638 assert(!is_null($user));
639 common_element_start('form', array('id' => 'status_form',
641 'action' => common_local_url('newnotice')));
642 common_element_start('p');
643 common_element('label', array('for' => 'status_update',
644 'id' => 'status_label'),
645 _t('What\'s up, ').$user->nickname.'?');
646 common_element('textarea', array('id' => 'status_textarea',
647 'name' => 'status_textarea'));
648 common_element('input', array('id' => 'status_submit',
649 'name' => 'status_submit',
651 'value' => _t('Send')));
652 common_element_end('p');
653 common_element_end('form');
656 function common_mint_tag($extra) {
659 'tag:'.$config['tag']['authority'].','.
660 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
663 # Should make up a reasonable root URL
665 function common_root_url() {
666 return common_path('');
669 # returns $bytes bytes of random data as a hexadecimal string
670 # "good" here is a goal and not a guarantee
672 function common_good_rand($bytes) {
673 # XXX: use random.org...?
674 if (file_exists('/dev/urandom')) {
675 return common_urandom($bytes);
676 } else { # FIXME: this is probably not good enough
677 return common_mtrand($bytes);
681 function common_urandom($bytes) {
682 $h = fopen('/dev/urandom', 'rb');
684 $src = fread($h, $bytes);
687 for ($i = 0; $i < $bytes; $i++) {
688 $enc .= sprintf("%02x", (ord($src[$i])));
693 function common_mtrand($bytes) {
695 for ($i = 0; $i < $bytes; $i++) {
696 $enc .= sprintf("%02x", mt_rand(0, 255));
701 function common_set_returnto($url) {
702 common_ensure_session();
703 $_SESSION['returnto'] = $url;
706 function common_get_returnto() {
707 common_ensure_session();
708 return $_SESSION['returnto'];
711 function common_timestamp() {
712 return date('YmdHis');
715 // XXX: set up gettext
721 function common_ensure_syslog() {
722 static $initialized = false;
725 define_syslog_variables();
726 openlog($config['syslog']['appname'], 0, LOG_USER);
731 function common_log($priority, $msg, $filename=NULL) {
732 common_ensure_syslog();
733 syslog($priority, $msg);
736 function common_debug($msg, $filename=NULL) {
738 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
740 common_log(LOG_DEBUG, $msg);
744 function common_valid_http_url($url) {
745 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
748 function common_valid_tag($tag) {
749 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
750 return (Validate::email($matches[1]) ||
751 preg_match('/^([\w-\.]+)$/', $matches[1]));
756 # Does a little before-after block for next/prev page
758 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
760 if ($have_before || $have_after) {
761 common_element_start('div', array('id' => 'pagination'));
762 common_element_start('ul', array('id' => 'nav_pagination'));
766 $pargs = array('page' => $page-1);
767 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
769 common_element_start('li', 'before');
770 common_element('a', array('href' => common_local_url($action, $newargs)),
772 common_element_end('li');
776 $pargs = array('page' => $page+1);
777 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
778 common_element_start('li', 'after');
779 common_element('a', array('href' => common_local_url($action, $newargs)),
781 common_element_end('li');
784 if ($have_before || $have_after) {
785 common_element_end('ul');
786 common_element_end('div');
790 /* Following functions are copied from MediaWiki GlobalFunctions.php
791 * and written by Evan Prodromou. */
793 function common_accept_to_prefs($accept, $def = '*/*') {
794 # No arg means accept anything (per HTTP spec)
796 return array($def => 1);
801 $parts = explode(',', $accept);
803 foreach($parts as $part) {
804 # FIXME: doesn't deal with params like 'text/html; level=1'
805 @list($value, $qpart) = explode(';', $part);
809 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
810 $prefs[$value] = $match[1];
817 function common_mime_type_match($type, $avail) {
818 if(array_key_exists($type, $avail)) {
821 $parts = explode('/', $type);
822 if(array_key_exists($parts[0] . '/*', $avail)) {
823 return $parts[0] . '/*';
824 } elseif(array_key_exists('*/*', $avail)) {
832 function common_negotiate_type($cprefs, $sprefs) {
835 foreach(array_keys($sprefs) as $type) {
836 $parts = explode('/', $type);
837 if($parts[1] != '*') {
838 $ckey = common_mime_type_match($type, $cprefs);
840 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
845 foreach(array_keys($cprefs) as $type) {
846 $parts = explode('/', $type);
847 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
848 $skey = common_mime_type_match($type, $sprefs);
850 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
858 foreach(array_keys($combine) as $type) {
859 if($combine[$type] > $bestq) {
861 $bestq = $combine[$type];
868 function common_config($main, $sub) {
870 return $config[$main][$sub];