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]');
171 call_user_func($callable, $data);
173 call_user_func($callable);
176 common_element_end('head');
177 common_element_start('body');
178 common_element_start('div', array('id' => 'wrap'));
179 common_element_start('div', array('id' => 'header'));
181 common_element_start('a', array('href' => common_local_url('public')));
182 common_element('img', array('src' => ($config['site']['logo']) ?
183 ($config['site']['logo']) : theme_path('logo.png'),
184 'alt' => $config['site']['name'],
186 common_element_end('a');
189 call_user_func($headercall, $data);
191 call_user_func($headercall);
194 common_element_end('div');
195 common_element_start('div', array('id' => 'content'));
198 function common_show_footer() {
200 common_element_end('div'); # content div
202 common_element_start('div', array('id' => 'footer'));
203 common_element('img', array('id' => 'cc',
204 'src' => $config['license']['image'],
205 'alt' => $config['license']['title']));
206 common_element_start('p');
207 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
208 common_element('a', array('class' => 'license',
210 href => $config['license']['url']),
211 $config['license']['title']);
212 common_text(_t('. Contributors should be attributed by full name or nickname.'));
213 common_element_end('p');
214 common_element_end('div');
215 common_element_end('div');
216 common_element_end('body');
217 common_element_end('html');
221 function common_text($txt) {
226 function common_raw($xml) {
231 function common_nav_menu() {
232 $user = common_current_user();
233 common_element_start('ul', array('id' => 'nav'));
235 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
238 common_menu_item(common_local_url('public'), _t('Public'));
239 common_menu_item(common_local_url('doc', array('title' => 'help')),
242 common_menu_item(common_local_url('profilesettings'),
244 common_menu_item(common_local_url('logout'),
247 common_menu_item(common_local_url('login'), _t('Login'));
248 common_menu_item(common_local_url('register'), _t('Register'));
250 common_element_end('ul');
253 function common_foot_menu() {
254 common_element_start('ul', array('id' => 'nav_sub'));
255 common_menu_item(common_local_url('doc', array('title' => 'about')),
257 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
259 common_menu_item(common_local_url('doc', array('title' => 'source')),
261 common_element_end('ul');
264 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
267 $lattrs['class'] = 'current';
269 common_element_start('li', $lattrs);
270 $attrs['href'] = $url;
272 $attrs['title'] = $title;
274 common_element('a', $attrs, $text);
275 common_element_end('li');
278 function common_input($id, $label, $value=NULL,$instructions=NULL) {
279 common_element_start('p');
280 common_element('label', array('for' => $id), $label);
281 $attrs = array('name' => $id,
285 $attrs['value'] = htmlspecialchars($value);
287 common_element('input', $attrs);
289 common_element('span', 'input_instructions', $instructions);
291 common_element_end('p');
294 function common_hidden($id, $value) {
295 common_element('input', array('name' => $id,
301 function common_password($id, $label, $instructions=NULL) {
302 common_element_start('p');
303 common_element('label', array('for' => $id), $label);
304 $attrs = array('name' => $id,
305 'type' => 'password',
307 common_element('input', $attrs);
309 common_element('span', 'input_instructions', $instructions);
311 common_element_end('p');
314 function common_submit($id, $label) {
316 common_element_start('p');
317 common_element('input', array('type' => 'submit',
321 common_element_end('p');
324 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
325 common_element_start('p');
326 common_element('label', array('for' => $id), $label);
327 common_element('textarea', array('rows' => 3,
331 ($content) ? $content : ' ');
333 common_element('span', 'input_instructions', $instructions);
335 common_element_end('p');
338 # salted, hashed passwords are stored in the DB
340 function common_munge_password($id, $password) {
341 return md5($id . $password);
344 # check if a username exists and has matching password
345 function common_check_user($nickname, $password) {
346 $user = User::staticGet('nickname', $nickname);
347 if (is_null($user)) {
350 return (0 == strcmp(common_munge_password($password, $user->id),
355 # is the current user logged in?
356 function common_logged_in() {
357 return (!is_null(common_current_user()));
360 function common_have_session() {
361 return (0 != strcmp(session_id(), ''));
364 function common_ensure_session() {
365 if (!common_have_session()) {
370 function common_set_user($nickname) {
371 if (is_null($nickname) && common_have_session()) {
372 unset($_SESSION['userid']);
375 $user = User::staticGet('nickname', $nickname);
377 common_ensure_session();
378 $_SESSION['userid'] = $user->id;
387 # who is the current user?
388 function common_current_user() {
389 static $user = NULL; # FIXME: global memcached
390 if (is_null($user)) {
391 common_ensure_session();
392 $id = $_SESSION['userid'];
394 $user = User::staticGet($id);
400 # get canonical version of nickname for comparison
401 function common_canonical_nickname($nickname) {
402 # XXX: UTF-8 canonicalization (like combining chars)
403 return strtolower($nickname);
406 # get canonical version of email for comparison
407 function common_canonical_email($email) {
408 # XXX: canonicalize UTF-8
409 # XXX: lcase the domain part
413 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$_+!*();/?:~-]))');
415 function common_render_content($text, $notice) {
416 $r = htmlspecialchars($text);
417 $id = $notice->profile_id;
418 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
419 $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
425 function common_at_link($sender_id, $nickname) {
426 # Try to find profiles this profile is subscribed to that have this nickname
427 $recipient = new Profile();
428 # XXX: chokety and bad
429 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
430 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
431 if ($recipient->find(TRUE)) {
432 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
434 # Try to find profiles that listen to this profile and that have this nickname
435 $recipient = new Profile();
436 # XXX: chokety and bad
437 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
438 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
439 if ($recipient->find(TRUE)) {
440 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
442 # If this is a local user, try to find a local user with that nickname.
443 $sender = User::staticGet($sender_id);
445 $recipient_user = User::staticGet('nickname', $nickname);
446 if ($recipient_user) {
447 $recipient = $recipient->getProfile();
448 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
451 # Otherwise, no links. @messages from local users to remote users,
452 # or from remote users to other remote users, are just
453 # outside our ability to make intelligent guesses about
457 // where should the avatar go for this user?
459 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
463 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
465 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
469 function common_avatar_path($filename) {
471 return INSTALLDIR . '/avatar/' . $filename;
474 function common_avatar_url($filename) {
475 return common_path('avatar/'.$filename);
478 function common_default_avatar($size) {
479 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
480 AVATAR_STREAM_SIZE => 'stream',
481 AVATAR_MINI_SIZE => 'mini');
482 return theme_path('default-avatar-'.$sizenames[$size].'.png');
485 function common_local_url($action, $args=NULL) {
487 if ($config['site']['fancy']) {
488 return common_fancy_url($action, $args);
490 return common_simple_url($action, $args);
494 function common_fancy_url($action, $args=NULL) {
495 switch (strtolower($action)) {
497 return common_path('');
499 return common_path('rss');
501 return common_path('doc/'.$args['title']);
507 return common_path('main/'.$action);
510 return common_path('settings/'.$action);
511 case 'profilesettings':
512 return common_path('settings/profile');
514 return common_path('notice/new');
516 return common_path('notice/'.$args['notice']);
517 case 'subscriptions':
522 return common_path($args['nickname'].'/'.$action);
524 return common_path($args['nickname'].'/all/rss');
526 return common_path($args['nickname'].'/rss');
528 return common_path($args['nickname']);
530 return common_simple_url($action, $args);
534 function common_simple_url($action, $args=NULL) {
536 /* XXX: pretty URLs */
539 foreach ($args as $key => $value) {
540 $extra .= "&${key}=${value}";
543 return common_path("index.php?action=${action}${extra}");
546 function common_path($relative) {
548 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
549 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
552 function common_date_string($dt) {
553 // XXX: do some sexy date formatting
554 // return date(DATE_RFC822, $dt);
558 function common_date_w3dtf($dt) {
560 return date(DATE_W3C, $t);
563 function common_redirect($url, $code=307) {
564 static $status = array(301 => "Moved Permanently",
567 307 => "Temporary Redirect");
568 header("Status: ${code} $status[$code]");
569 header("Location: $url");
570 common_element('a', array('href' => $url), $url);
573 function common_broadcast_notice($notice, $remote=false) {
574 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
576 # Make sure we have the OMB stuff
577 require_once(INSTALLDIR.'/lib/omb.php');
578 omb_broadcast_remote_subscribers($notice);
580 // XXX: broadcast notices to Jabber
581 // XXX: broadcast notices to SMS
582 // XXX: broadcast notices to other IM
586 function common_broadcast_profile($profile) {
587 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
588 require_once(INSTALLDIR.'/lib/omb.php');
589 omb_broadcast_profile($profile);
590 // XXX: Other broadcasts...?
594 function common_profile_url($nickname) {
595 return common_local_url('showstream', array('nickname' => $nickname));
598 # Don't call if nobody's logged in
600 function common_notice_form() {
601 $user = common_current_user();
602 assert(!is_null($user));
603 common_element_start('form', array('id' => 'status_form',
605 'action' => common_local_url('newnotice')));
606 common_element_start('p');
607 common_element('label', array('for' => 'status_update',
608 'id' => 'status_label'),
609 _t('What\'s up, ').$user->nickname.'?');
610 common_element('textarea', array('id' => 'status_textarea',
611 'name' => 'status_textarea'));
612 common_element('input', array('id' => 'status_submit',
613 'name' => 'status_submit',
615 'value' => _t('Send')));
616 common_element_end('p');
617 common_element_end('form');
620 function common_mint_tag($extra) {
623 'tag:'.$config['tag']['authority'].','.
624 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
627 # Should make up a reasonable root URL
629 function common_root_url() {
630 return common_path('');
633 # returns $bytes bytes of random data as a hexadecimal string
634 # "good" here is a goal and not a guarantee
636 function common_good_rand($bytes) {
637 # XXX: use random.org...?
638 if (file_exists('/dev/urandom')) {
639 return common_urandom($bytes);
640 } else { # FIXME: this is probably not good enough
641 return common_mtrand($bytes);
645 function common_urandom($bytes) {
646 $h = fopen('/dev/urandom', 'rb');
648 $src = fread($h, $bytes);
651 for ($i = 0; $i < $bytes; $i++) {
652 $enc .= sprintf("%02x", (ord($src[$i])));
657 function common_mtrand($bytes) {
659 for ($i = 0; $i < $bytes; $i++) {
660 $enc .= sprintf("%02x", mt_rand(0, 255));
665 function common_set_returnto($url) {
666 common_ensure_session();
667 $_SESSION['returnto'] = $url;
670 function common_get_returnto() {
671 common_ensure_session();
672 return $_SESSION['returnto'];
675 function common_timestamp() {
676 return date('YmdHis');
679 // XXX: set up gettext
685 function common_ensure_syslog() {
686 static $initialized = false;
689 define_syslog_variables();
690 openlog($config['syslog']['appname'], 0, LOG_USER);
695 function common_log($priority, $msg, $filename=NULL) {
696 common_ensure_syslog();
697 syslog($priority, $msg);
700 function common_debug($msg, $filename=NULL) {
702 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
704 common_log(LOG_DEBUG, $msg);
708 function common_valid_http_url($url) {
709 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
712 function common_valid_tag($tag) {
713 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
714 return (Validate::email($matches[1]) ||
715 preg_match('/^([\w-\.]+)$/', $matches[1]));
720 # Does a little before-after block for next/prev page
722 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
724 if ($have_before || $have_after) {
725 common_element_start('div', array('id' => 'pagination'));
726 common_element_start('ul', array('id' => 'nav_pagination'));
730 $pargs = array('page' => $page-1);
731 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
733 common_element_start('li', 'before');
734 common_element('a', array('href' => common_local_url($action, $newargs)),
736 common_element_end('li');
740 $pargs = array('page' => $page+1);
741 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
742 common_element_start('li', 'after');
743 common_element('a', array('href' => common_local_url($action, $newargs)),
745 common_element_end('li');
748 if ($have_before || $have_after) {
749 common_element_end('ul');
750 common_element_end('div');
754 /* Following functions are copied from MediaWiki GlobalFunctions.php
755 * and written by Evan Prodromou. */
757 function common_accept_to_prefs($accept, $def = '*/*') {
758 # No arg means accept anything (per HTTP spec)
760 return array($def => 1);
765 $parts = explode(',', $accept);
767 foreach($parts as $part) {
768 # FIXME: doesn't deal with params like 'text/html; level=1'
769 @list($value, $qpart) = explode(';', $part);
773 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
774 $prefs[$value] = $match[1];
781 function common_mime_type_match($type, $avail) {
782 if(array_key_exists($type, $avail)) {
785 $parts = explode('/', $type);
786 if(array_key_exists($parts[0] . '/*', $avail)) {
787 return $parts[0] . '/*';
788 } elseif(array_key_exists('*/*', $avail)) {
796 function common_negotiate_type($cprefs, $sprefs) {
799 foreach(array_keys($sprefs) as $type) {
800 $parts = explode('/', $type);
801 if($parts[1] != '*') {
802 $ckey = common_mime_type_match($type, $cprefs);
804 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
809 foreach(array_keys($cprefs) as $type) {
810 $parts = explode('/', $type);
811 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
812 $skey = common_mime_type_match($type, $sprefs);
814 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
822 foreach(array_keys($combine) as $type) {
823 if($combine[$type] > $bestq) {
825 $bestq = $combine[$type];