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_simple_url($action, $args);
490 function common_simple_url($action, $args=NULL) {
492 /* XXX: pretty URLs */
495 foreach ($args as $key => $value) {
496 $extra .= "&${key}=${value}";
499 return common_path("index.php?action=${action}${extra}");
502 function common_path($relative) {
504 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
505 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
508 function common_date_string($dt) {
509 // XXX: do some sexy date formatting
510 // return date(DATE_RFC822, $dt);
514 function common_date_w3dtf($dt) {
516 return date(DATE_W3C, $t);
519 function common_redirect($url, $code=307) {
520 static $status = array(301 => "Moved Permanently",
523 307 => "Temporary Redirect");
524 header("Status: ${code} $status[$code]");
525 header("Location: $url");
526 common_element('a', array('href' => $url), $url);
529 function common_broadcast_notice($notice, $remote=false) {
530 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
532 common_broadcast_remote_subscribers($notice);
534 // XXX: broadcast notices to Jabber
535 // XXX: broadcast notices to SMS
536 // XXX: broadcast notices to other IM
540 function common_broadcast_remote_subscribers($notice) {
541 # First, get remote users subscribed to this profile
542 $sub = new Subscription();
543 $sub->subscribed = $notice->profile_id;
544 $rp = new Remote_profile();
545 $sub->addJoin($rp, 'INNER', NULL, 'subscriber');
548 while ($sub->fetch()) {
549 if (!$posted[$rp->postnoticeurl]) {
550 if (common_post_notice($notice, $rp, $sub)) {
551 $posted[$rp->postnoticeurl] = TRUE;
558 function common_post_notice($notice, $remote_profile, $subscription) {
559 global $config; # for license URL
560 $user = User::staticGet('id', $notice->profile_id);
561 $con = omb_oauth_consumer();
562 $token = new OAuthToken($subscription->token, $subscription->secret);
563 $url = $remote_profile->postnoticeurl;
564 $parsed = parse_url($url);
566 parse_str($parsed['query'], $params);
567 $req = OAuthRequest::from_consumer_and_token($con, $token,
568 "POST", $url, $params);
569 $req->set_parameter('omb_version', OMB_VERSION_01);
570 $req->set_parameter('omb_listenee', $user->uri);
571 $req->set_parameter('omb_notice', $notice->uri);
572 $req->set_parameter('omb_notice_content', $notice->content);
573 $req->set_parameter('omb_notice_url', common_local_url('shownotice',
576 $req->set_parameter('omb_notice_license', $config['license']['url']);
577 $req->sign_request(omb_hmac_sha1(), $con, $tok);
579 # We re-use this tool's fetcher, since it's pretty good
581 $fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
583 $result = $fetcher->post($req->get_normalized_http_url(),
584 $req->to_postdata());
586 if ($result->status == 403) { # not authorized, don't send again
587 $subscription->delete();
589 } else if ($result->status != 200) {
592 parse_str($result->body, $return);
593 if ($return['omb_version'] == OMB_VERSION_01) {
601 function common_profile_url($nickname) {
602 return common_local_url('showstream', array('nickname' => $nickname));
605 function common_notice_form() {
606 common_element_start('form', array('id' => 'newnotice', 'method' => 'POST',
607 'action' => common_local_url('newnotice')));
608 common_textarea('noticecontent', _t('What\'s up?'));
609 common_submit('submit', _t('Send'));
610 common_element_end('form');
613 function common_mint_tag($extra) {
616 'tag:'.$config['tag']['authority'].','.
617 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
620 # Should make up a reasonable root URL
622 function common_root_url() {
623 return common_path('');
626 # returns $bytes bytes of random data as a hexadecimal string
627 # "good" here is a goal and not a guarantee
629 function common_good_rand($bytes) {
630 # XXX: use random.org...?
631 if (file_exists('/dev/urandom')) {
632 return common_urandom($bytes);
633 } else { # FIXME: this is probably not good enough
634 return common_mtrand($bytes);
638 function common_urandom($bytes) {
639 $h = fopen('/dev/urandom', 'rb');
641 $src = fread($h, $bytes);
644 for ($i = 0; $i < $bytes; $i++) {
645 $enc .= sprintf("%02x", (ord($src[$i])));
650 function common_mtrand($bytes) {
652 for ($i = 0; $i < $bytes; $i++) {
653 $enc .= sprintf("%02x", mt_rand(0, 255));
658 function common_set_returnto($url) {
659 common_ensure_session();
660 $_SESSION['returnto'] = $url;
663 function common_get_returnto() {
664 common_ensure_session();
665 return $_SESSION['returnto'];
668 function common_timestamp() {
669 return date('YmdHis');
672 // XXX: set up gettext
678 function common_ensure_syslog() {
679 static $initialized = false;
682 define_syslog_variables();
683 openlog($config['syslog']['appname'], 0, LOG_USER);
688 function common_log($priority, $msg, $filename=NULL) {
689 common_ensure_syslog();
690 syslog($priority, $msg);
693 function common_debug($msg, $filename=NULL) {
695 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
697 common_log(LOG_DEBUG, $msg);
701 function common_valid_http_url($url) {
702 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
705 function common_valid_tag($tag) {
706 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
707 return (Validate::email($matches[1]) ||
708 preg_match('/^([\w-\.]+)$/', $matches[1]));