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 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
129 header('Content-Type: application/xhtml+xml');
131 common_start_xml('html',
132 '-//W3C//DTD XHTML 1.0 Strict//EN',
133 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
135 # FIXME: correct language for interface
137 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
141 common_element_start('head');
142 common_element('title', NULL,
143 $pagetitle . " - " . $config['site']['name']);
144 common_element('link', array('rel' => 'stylesheet',
145 'type' => 'text/css',
146 'href' => theme_path('display.css'),
147 'media' => 'screen, projection, tv'));
148 foreach (array(6,7) as $ver) {
149 if (file_exists(theme_file('ie'.$ver.'.css'))) {
150 # Yes, IE people should be put in jail.
151 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
152 'href="'.theme_path('ie'.$ver.'.css').' /><![endif]');
157 call_user_func($callable, $data);
159 call_user_func($callable);
162 common_element_end('head');
163 common_element_start('body');
164 common_element_start('div', array('id' => 'wrap'));
165 common_element_start('div', array('id' => 'header'));
167 common_element_start('a', array('href' => common_local_url('public')));
168 common_element('img', array('src' => ($config['site']['logo']) ?
169 ($config['site']['logo']) : theme_path('logo.png'),
170 'alt' => $config['site']['name'],
172 common_element_end('a');
175 call_user_func($headercall, $data);
177 call_user_func($headercall);
180 common_element_end('div');
181 common_element_start('div', array('id' => 'content'));
184 function common_show_footer() {
186 common_element_end('div'); # content div
188 common_element_start('div', array('id' => 'footer'));
189 common_element('img', array('id' => 'cc',
190 'src' => $config['license']['image'],
191 'alt' => $config['license']['title']));
192 common_element_start('p');
193 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
194 common_element('a', array('class' => 'license',
196 href => $config['license']['url']),
197 $config['license']['title']);
198 common_text(_t('. Contributors should be attributed by full name or nickname.'));
199 common_element_end('p');
200 common_element_end('div');
201 common_element_end('div');
202 common_element_end('body');
203 common_element_end('html');
207 function common_text($txt) {
212 function common_raw($xml) {
217 function common_nav_menu() {
218 $user = common_current_user();
219 common_element_start('ul', array('id' => 'nav'));
221 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
224 common_menu_item(common_local_url('public'), _t('Public'));
225 common_menu_item(common_local_url('doc', array('title' => 'help')),
228 common_menu_item(common_local_url('profilesettings'),
230 common_menu_item(common_local_url('logout'),
233 common_menu_item(common_local_url('login'), _t('Login'));
234 common_menu_item(common_local_url('register'), _t('Register'));
236 common_element_end('ul');
239 function common_foot_menu() {
240 common_element_start('ul', array('id' => 'nav_sub'));
241 common_menu_item(common_local_url('doc', array('title' => 'about')),
243 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
245 common_menu_item(common_local_url('doc', array('title' => 'source')),
247 common_element_end('ul');
250 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
253 $lattrs['class'] = 'current';
255 common_element_start('li', $lattrs);
256 $attrs['href'] = $url;
258 $attrs['title'] = $title;
260 common_element('a', $attrs, $text);
261 common_element_end('li');
264 function common_input($id, $label, $value=NULL) {
265 common_element_start('p');
266 common_element('label', array('for' => $id), $label);
267 $attrs = array('name' => $id,
271 $attrs['value'] = htmlspecialchars($value);
273 common_element('input', $attrs);
274 common_element_end('p');
277 function common_hidden($id, $value) {
278 common_element('input', array('name' => $id,
284 function common_password($id, $label) {
285 common_element_start('p');
286 common_element('label', array('for' => $id), $label);
287 $attrs = array('name' => $id,
288 'type' => 'password',
290 common_element('input', $attrs);
291 common_element_end('p');
294 function common_submit($id, $label) {
296 common_element_start('p');
297 common_element('input', array('type' => 'submit',
301 common_element_end('p');
304 function common_textarea($id, $label, $content=NULL) {
305 common_element_start('p');
306 common_element('label', array('for' => $id), $label);
307 common_element('textarea', array('rows' => 3,
311 ($content) ? $content : ' ');
312 common_element_end('p');
315 # salted, hashed passwords are stored in the DB
317 function common_munge_password($id, $password) {
318 return md5($id . $password);
321 # check if a username exists and has matching password
322 function common_check_user($nickname, $password) {
323 $user = User::staticGet('nickname', $nickname);
324 if (is_null($user)) {
327 return (0 == strcmp(common_munge_password($password, $user->id),
332 # is the current user logged in?
333 function common_logged_in() {
334 return (!is_null(common_current_user()));
337 function common_have_session() {
338 return (0 != strcmp(session_id(), ''));
341 function common_ensure_session() {
342 if (!common_have_session()) {
347 function common_set_user($nickname) {
348 if (is_null($nickname) && common_have_session()) {
349 unset($_SESSION['userid']);
352 $user = User::staticGet('nickname', $nickname);
354 common_ensure_session();
355 $_SESSION['userid'] = $user->id;
364 # who is the current user?
365 function common_current_user() {
366 static $user = NULL; # FIXME: global memcached
367 if (is_null($user)) {
368 common_ensure_session();
369 $id = $_SESSION['userid'];
371 $user = User::staticGet($id);
377 # get canonical version of nickname for comparison
378 function common_canonical_nickname($nickname) {
379 # XXX: UTF-8 canonicalization (like combining chars)
380 return strtolower($nickname);
383 # get canonical version of email for comparison
384 function common_canonical_email($email) {
385 # XXX: canonicalize UTF-8
386 # XXX: lcase the domain part
390 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$_+!*();/?:~-]))');
392 function common_render_content($text, $notice) {
393 $r = htmlspecialchars($text);
394 $id = $notice->profile_id;
395 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
396 $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
402 function common_at_link($sender_id, $nickname) {
403 # Try to find profiles this profile is subscribed to that have this nickname
404 $recipient = new Profile();
405 # XXX: chokety and bad
406 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
407 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
408 if ($recipient->find(TRUE)) {
409 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
411 # Try to find profiles that listen to this profile and that have this nickname
412 $recipient = new Profile();
413 # XXX: chokety and bad
414 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
415 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
416 if ($recipient->find(TRUE)) {
417 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
419 # If this is a local user, try to find a local user with that nickname.
420 $sender = User::staticGet($sender_id);
422 $recipient_user = User::staticGet('nickname', $nickname);
423 if ($recipient_user) {
424 $recipient = $recipient->getProfile();
425 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
428 # Otherwise, no links. @messages from local users to remote users,
429 # or from remote users to other remote users, are just
430 # outside our ability to make intelligent guesses about
434 // where should the avatar go for this user?
436 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
440 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
442 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
446 function common_avatar_path($filename) {
448 return INSTALLDIR . '/avatar/' . $filename;
451 function common_avatar_url($filename) {
452 return common_path('avatar/'.$filename);
455 function common_default_avatar($size) {
456 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
457 AVATAR_STREAM_SIZE => 'stream',
458 AVATAR_MINI_SIZE => 'mini');
459 return theme_path('default-avatar-'.$sizenames[$size].'.png');
462 function common_local_url($action, $args=NULL) {
464 if ($config['site']['fancy']) {
465 return common_fancy_url($action, $args);
467 return common_simple_url($action, $args);
471 function common_fancy_url($action, $args=NULL) {
472 switch (strtolower($action)) {
474 return common_path('');
476 return common_path('rss');
478 return common_path('doc/'.$args['title']);
484 return common_path('main/'.$action);
487 return common_path('settings/'.$action);
488 case 'profilesettings':
489 return common_path('settings/profile');
491 return common_path('notice/new');
493 return common_path('notice/'.$args['notice']);
494 case 'subscriptions':
499 return common_path($args['nickname'].'/'.$action);
501 return common_path($args['nickname'].'/all/rss');
503 return common_path($args['nickname'].'/rss');
505 return common_path($args['nickname']);
507 return common_simple_url($action, $args);
511 function common_simple_url($action, $args=NULL) {
513 /* XXX: pretty URLs */
516 foreach ($args as $key => $value) {
517 $extra .= "&${key}=${value}";
520 return common_path("index.php?action=${action}${extra}");
523 function common_path($relative) {
525 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
526 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
529 function common_date_string($dt) {
530 // XXX: do some sexy date formatting
531 // return date(DATE_RFC822, $dt);
535 function common_date_w3dtf($dt) {
537 return date(DATE_W3C, $t);
540 function common_redirect($url, $code=307) {
541 static $status = array(301 => "Moved Permanently",
544 307 => "Temporary Redirect");
545 header("Status: ${code} $status[$code]");
546 header("Location: $url");
547 common_element('a', array('href' => $url), $url);
550 function common_broadcast_notice($notice, $remote=false) {
551 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
553 # Make sure we have the OMB stuff
554 require_once(INSTALLDIR.'/lib/omb.php');
555 omb_broadcast_remote_subscribers($notice);
557 // XXX: broadcast notices to Jabber
558 // XXX: broadcast notices to SMS
559 // XXX: broadcast notices to other IM
564 function common_profile_url($nickname) {
565 return common_local_url('showstream', array('nickname' => $nickname));
568 # Don't call if nobody's logged in
570 function common_notice_form() {
571 $user = common_current_user();
572 assert(!is_null($user));
573 common_element_start('form', array('id' => 'status_form',
575 'action' => common_local_url('newnotice')));
576 common_element_start('p');
577 common_element('label', array('for' => 'status_update',
578 'id' => 'status_label'),
579 _t('What\'s up, ').$user->nickname.'?');
580 common_element('textarea', array('id' => 'status_textarea',
581 'name' => 'status_textarea'));
582 common_element('input', array('id' => 'status_submit',
583 'name' => 'status_submit',
585 'value' => _t('Send')));
586 common_element_end('p');
587 common_element_end('form');
590 function common_mint_tag($extra) {
593 'tag:'.$config['tag']['authority'].','.
594 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
597 # Should make up a reasonable root URL
599 function common_root_url() {
600 return common_path('');
603 # returns $bytes bytes of random data as a hexadecimal string
604 # "good" here is a goal and not a guarantee
606 function common_good_rand($bytes) {
607 # XXX: use random.org...?
608 if (file_exists('/dev/urandom')) {
609 return common_urandom($bytes);
610 } else { # FIXME: this is probably not good enough
611 return common_mtrand($bytes);
615 function common_urandom($bytes) {
616 $h = fopen('/dev/urandom', 'rb');
618 $src = fread($h, $bytes);
621 for ($i = 0; $i < $bytes; $i++) {
622 $enc .= sprintf("%02x", (ord($src[$i])));
627 function common_mtrand($bytes) {
629 for ($i = 0; $i < $bytes; $i++) {
630 $enc .= sprintf("%02x", mt_rand(0, 255));
635 function common_set_returnto($url) {
636 common_ensure_session();
637 $_SESSION['returnto'] = $url;
640 function common_get_returnto() {
641 common_ensure_session();
642 return $_SESSION['returnto'];
645 function common_timestamp() {
646 return date('YmdHis');
649 // XXX: set up gettext
655 function common_ensure_syslog() {
656 static $initialized = false;
659 define_syslog_variables();
660 openlog($config['syslog']['appname'], 0, LOG_USER);
665 function common_log($priority, $msg, $filename=NULL) {
666 common_ensure_syslog();
667 syslog($priority, $msg);
670 function common_debug($msg, $filename=NULL) {
672 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
674 common_log(LOG_DEBUG, $msg);
678 function common_valid_http_url($url) {
679 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
682 function common_valid_tag($tag) {
683 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
684 return (Validate::email($matches[1]) ||
685 preg_match('/^([\w-\.]+)$/', $matches[1]));
690 # Does a little before-after block for next/prev page
692 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
694 if ($have_before || $have_after) {
695 common_element_start('div', array('id' => 'pagination'));
696 common_element_start('ul', array('id' => 'nav_pagination'));
700 $pargs = array('page' => $page-1);
701 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
703 common_element_start('li', 'before');
704 common_element('a', array('href' => common_local_url($action, $newargs)),
706 common_element_end('li');
710 $pargs = array('page' => $page+1);
711 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
712 common_element_start('li', 'after');
713 common_element('a', array('href' => common_local_url($action, $newargs)),
715 common_element_end('li');
718 if ($have_before || $have_after) {
719 common_element_end('ul');
720 common_element_end('div');