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) {
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' => common_path('theme/default/style/html.css'),
147 'media' => 'screen, projection, tv'));
148 common_element('link', array('rel' => 'stylesheet',
149 'type' => 'text/css',
150 'href' => common_path('theme/default/style/layout.css'),
151 'media' => 'screen, projection, tv'));
152 common_element('link', array('rel' => 'stylesheet',
153 'type' => 'text/css',
154 'href' => common_path('theme/default/style/print.css'),
155 'media' => 'print'));
158 call_user_func($callable, $data);
160 call_user_func($callable);
163 common_element_end('head');
164 common_element_start('body');
165 common_element_start('div', array('id' => 'wrapper'));
166 common_element_start('div', array('id' => 'content'));
167 common_element_start('div', array('id' => 'header'));
168 common_element('h1', 'title', $pagetitle);
169 common_element('h2', 'subtitle', $config['site']['name']);
170 common_element_end('div');
172 common_element_start('div', array('id' => 'page'));
175 function common_show_footer() {
177 common_element_start('div', 'footer');
179 common_license_block();
180 common_element_end('div');
181 common_element_end('div');
182 common_element_end('div');
183 common_element_end('div');
184 common_element_end('body');
185 common_element_end('html');
189 function common_text($txt) {
194 function common_raw($xml) {
199 function common_license_block() {
201 common_element_start('p', 'license greenBg');
202 common_element_start('span', 'floatLeft width25');
203 common_element_start('a', array('class' => 'license',
205 href => $config['license']['url']));
206 common_element('img', array('class' => 'license',
207 'src' => $config['license']['image'],
208 'alt' => $config['license']['title']));
209 common_element_end('a');
210 common_element_end('span');
211 common_element_start('span', 'floatRight width75');
212 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
213 common_element('a', array('class' => 'license',
215 href => $config['license']['url']),
216 $config['license']['title']);
217 common_text(_t('. Contributors should be attributed by full name or nickname.'));
218 common_element_end('span');
219 common_element_end('p');
222 function common_head_menu() {
223 $user = common_current_user();
224 common_element_start('ul', array('id' => 'menu', 'class' => ($user) ? 'five' : 'three'));
225 common_menu_item(common_local_url('public'), _t('Public'));
227 common_menu_item(common_local_url('all', array('nickname' =>
230 common_menu_item(common_local_url('showstream', array('nickname' =>
232 _t('Profile'), $user->fullname || $user->nickname);
233 common_menu_item(common_local_url('profilesettings'),
235 common_menu_item(common_local_url('logout'),
238 common_menu_item(common_local_url('login'),
240 common_menu_item(common_local_url('register'),
243 common_element_end('ul');
246 function common_foot_menu() {
247 common_element_start('ul', 'footmenu menuish');
248 common_menu_item(common_local_url('doc', array('title' => 'about')),
250 common_menu_item(common_local_url('doc', array('title' => 'help')),
252 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
254 common_menu_item(common_local_url('doc', array('title' => 'source')),
256 common_element_end('ul');
259 function common_menu_item($url, $text, $title=NULL) {
260 $attrs['href'] = $url;
262 $attrs['title'] = $title;
264 common_element_start('li', 'menuitem');
265 common_element('a', $attrs, $text);
266 common_element_end('li');
269 function common_input($id, $label, $value=NULL) {
270 common_element_start('p');
271 common_element('label', array('for' => $id), $label);
272 $attrs = array('name' => $id,
276 $attrs['value'] = htmlspecialchars($value);
278 common_element('input', $attrs);
279 common_element_end('p');
282 function common_hidden($id, $value) {
283 common_element('input', array('name' => $id,
289 function common_password($id, $label) {
290 common_element_start('p');
291 common_element('label', array('for' => $id), $label);
292 $attrs = array('name' => $id,
293 'type' => 'password',
295 common_element('input', $attrs);
296 common_element_end('p');
299 function common_submit($id, $label) {
301 common_element_start('p');
302 common_element_start('label', array('for' => $id));
303 $xw->writeRaw(' ');
304 common_element_end('label');
305 common_element('input', array('type' => 'submit',
309 'class' => 'button'));
310 common_element_end('p');
313 function common_textarea($id, $label, $content=NULL) {
314 common_element_start('p');
315 common_element('label', array('for' => $id), $label);
316 common_element('textarea', array('rows' => 3,
320 'class' => 'width50'),
321 ($content) ? $content : ' ');
322 common_element_end('p');
325 # salted, hashed passwords are stored in the DB
327 function common_munge_password($id, $password) {
328 return md5($id . $password);
331 # check if a username exists and has matching password
332 function common_check_user($nickname, $password) {
333 $user = User::staticGet('nickname', $nickname);
334 if (is_null($user)) {
337 return (0 == strcmp(common_munge_password($password, $user->id),
342 # is the current user logged in?
343 function common_logged_in() {
344 return (!is_null(common_current_user()));
347 function common_have_session() {
348 return (0 != strcmp(session_id(), ''));
351 function common_ensure_session() {
352 if (!common_have_session()) {
357 function common_set_user($nickname) {
358 if (is_null($nickname) && common_have_session()) {
359 unset($_SESSION['userid']);
362 $user = User::staticGet('nickname', $nickname);
364 common_ensure_session();
365 $_SESSION['userid'] = $user->id;
374 # who is the current user?
375 function common_current_user() {
376 static $user = NULL; # FIXME: global memcached
377 if (is_null($user)) {
378 common_ensure_session();
379 $id = $_SESSION['userid'];
381 $user = User::staticGet($id);
387 # get canonical version of nickname for comparison
388 function common_canonical_nickname($nickname) {
389 # XXX: UTF-8 canonicalization (like combining chars)
393 # get canonical version of email for comparison
394 function common_canonical_email($email) {
395 # XXX: canonicalize UTF-8
396 # XXX: lcase the domain part
400 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$_+!*();/?:~-]))');
402 function common_render_content($text, $notice) {
403 $r = htmlspecialchars($text);
404 $id = $notice->profile_id;
405 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
406 $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
412 function common_at_link($sender_id, $nickname) {
413 # Try to find profiles this profile is subscribed to that have this nickname
414 $recipient = new Profile();
415 # XXX: chokety and bad
416 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
417 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
418 if ($recipient->find(TRUE)) {
419 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
421 # Try to find profiles that listen to this profile and that have this nickname
422 $recipient = new Profile();
423 # XXX: chokety and bad
424 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
425 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
426 if ($recipient->find(TRUE)) {
427 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
429 # If this is a local user, try to find a local user with that nickname.
430 $sender = User::staticGet($sender_id);
432 $recipient_user = User::staticGet('nickname', $nickname);
433 if ($recipient_user) {
434 $recipient = $recipient->getProfile();
435 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
438 # Otherwise, no links. @messages from local users to remote users,
439 # or from remote users to other remote users, are just
440 # outside our ability to make intelligent guesses about
444 // where should the avatar go for this user?
446 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
450 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
452 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
456 function common_avatar_path($filename) {
458 return INSTALLDIR . '/avatar/' . $filename;
461 function common_avatar_url($filename) {
462 return common_path('avatar/'.$filename);
465 function common_default_avatar($size) {
466 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
467 AVATAR_STREAM_SIZE => 'stream',
468 AVATAR_MINI_SIZE => 'mini');
471 return common_path($config['avatar']['default'][$sizenames[$size]]);
474 function common_local_url($action, $args=NULL) {
476 if ($config['site']['fancy']) {
477 return common_fancy_url($action, $args);
479 return common_simple_url($action, $args);
483 function common_fancy_url($action, $args=NULL) {
484 switch (strtolower($action)) {
486 return common_path('');
488 return common_path('rss');
490 return common_path('doc/'.$args['title']);
496 return common_path('main/'.$action);
500 case 'userauthorization':
501 return common_path('omb/'.$action);
502 case 'remotesubscribe':
503 return common_path('omb/subscribe');
504 case 'finishremotesubscribe':
505 return common_path('omb/finish');
508 return common_path('settings/'.$action);
509 case 'profilesettings':
510 return common_path('settings/profile');
512 return common_path('notice/new');
514 return common_path('notice/'.$args['notice']);
515 case 'subscriptions':
519 return common_path($args['nickname'].'/'.$action);
521 return common_path($args['nickname'].'/all/rss');
523 return common_path($args['nickname'].'/rss');
525 return common_path($args['nickname']);
527 return common_simple_url($action, $args);
531 function common_simple_url($action, $args=NULL) {
533 /* XXX: pretty URLs */
536 foreach ($args as $key => $value) {
537 $extra .= "&${key}=${value}";
540 return common_path("index.php?action=${action}${extra}");
543 function common_path($relative) {
545 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
546 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
549 function common_date_string($dt) {
550 // XXX: do some sexy date formatting
551 // return date(DATE_RFC822, $dt);
555 function common_date_w3dtf($dt) {
557 return date(DATE_W3C, $t);
560 function common_redirect($url, $code=307) {
561 static $status = array(301 => "Moved Permanently",
564 307 => "Temporary Redirect");
565 header("Status: ${code} $status[$code]");
566 header("Location: $url");
567 common_element('a', array('href' => $url), $url);
570 function common_broadcast_notice($notice, $remote=false) {
571 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
573 # Make sure we have the OMB stuff
574 require_once(INSTALLDIR.'/lib/omb.php');
575 omb_broadcast_remote_subscribers($notice);
577 // XXX: broadcast notices to Jabber
578 // XXX: broadcast notices to SMS
579 // XXX: broadcast notices to other IM
584 function common_profile_url($nickname) {
585 return common_local_url('showstream', array('nickname' => $nickname));
588 function common_notice_form() {
589 common_element_start('form', array('id' => 'newnotice', 'method' => 'POST',
590 'action' => common_local_url('newnotice')));
591 common_textarea('noticecontent', _t('What\'s up?'));
592 common_submit('submit', _t('Send'));
593 common_element_end('form');
596 function common_mint_tag($extra) {
599 'tag:'.$config['tag']['authority'].','.
600 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
603 # Should make up a reasonable root URL
605 function common_root_url() {
606 return common_path('');
609 # returns $bytes bytes of random data as a hexadecimal string
610 # "good" here is a goal and not a guarantee
612 function common_good_rand($bytes) {
613 # XXX: use random.org...?
614 if (file_exists('/dev/urandom')) {
615 return common_urandom($bytes);
616 } else { # FIXME: this is probably not good enough
617 return common_mtrand($bytes);
621 function common_urandom($bytes) {
622 $h = fopen('/dev/urandom', 'rb');
624 $src = fread($h, $bytes);
627 for ($i = 0; $i < $bytes; $i++) {
628 $enc .= sprintf("%02x", (ord($src[$i])));
633 function common_mtrand($bytes) {
635 for ($i = 0; $i < $bytes; $i++) {
636 $enc .= sprintf("%02x", mt_rand(0, 255));
641 function common_set_returnto($url) {
642 common_ensure_session();
643 $_SESSION['returnto'] = $url;
646 function common_get_returnto() {
647 common_ensure_session();
648 return $_SESSION['returnto'];
651 function common_timestamp() {
652 return date('YmdHis');
655 // XXX: set up gettext
661 function common_ensure_syslog() {
662 static $initialized = false;
665 define_syslog_variables();
666 openlog($config['syslog']['appname'], 0, LOG_USER);
671 function common_log($priority, $msg, $filename=NULL) {
672 common_ensure_syslog();
673 syslog($priority, $msg);
676 function common_debug($msg, $filename=NULL) {
678 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
680 common_log(LOG_DEBUG, $msg);
684 function common_valid_http_url($url) {
685 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
688 function common_valid_tag($tag) {
689 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
690 return (Validate::email($matches[1]) ||
691 preg_match('/^([\w-\.]+)$/', $matches[1]));