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) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 # XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109 common_element_start($tag, $attrs);
111 if (!is_null($content)) {
114 common_element_end($tag);
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 function common_init_language() {
135 mb_internal_encoding('UTF-8');
136 $language = common_language();
137 # So we don't have to make people install the gettext locales
138 putenv('LANGUAGE='.$language);
139 putenv('LANG='.$language);
140 $locale_set = setlocale(LC_ALL, $language . ".utf8",
142 $language . ".utf-8",
143 $language . ".UTF-8",
145 bindtextdomain("laconica", common_config('site','locale_path'));
146 bind_textdomain_codeset("laconica", "UTF-8");
147 textdomain("laconica");
148 setlocale(LC_CTYPE, 'C');
151 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
153 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
156 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
158 # XXX: allow content negotiation for RDF, RSS, or XRDS
160 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
161 common_accept_to_prefs(PAGE_TYPE_PREFS));
164 common_user_error(_('This page is not available in a media type you accept'), 406);
168 header('Content-Type: '.$type);
170 common_start_xml('html',
171 '-//W3C//DTD XHTML 1.0 Strict//EN',
172 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
174 # FIXME: correct language for interface
176 $language = common_language();
178 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
179 'xml:lang' => $language,
180 'lang' => $language));
182 common_element_start('head');
183 common_element('title', NULL,
184 $pagetitle . " - " . $config['site']['name']);
185 common_element('link', array('rel' => 'stylesheet',
186 'type' => 'text/css',
187 'href' => theme_path('display.css'),
188 'media' => 'screen, projection, tv'));
189 foreach (array(6,7) as $ver) {
190 if (file_exists(theme_file('ie'.$ver.'.css'))) {
191 # Yes, IE people should be put in jail.
192 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
193 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
197 common_element('script', array('type' => 'text/javascript',
198 'src' => common_path('js/jquery.min.js')),
200 common_element('script', array('type' => 'text/javascript',
201 'src' => common_path('js/util.js')),
203 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
204 'href' => common_local_url('opensearch', array('type' => 'people')),
205 'title' => common_config('site', 'name').' People Search'));
207 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
208 'href' => common_local_url('opensearch', array('type' => 'notice')),
209 'title' => common_config('site', 'name').' Notice Search'));
213 call_user_func($callable, $data);
215 call_user_func($callable);
218 common_element_end('head');
219 common_element_start('body');
220 common_element_start('div', array('id' => 'wrap'));
221 common_element_start('div', array('id' => 'header'));
223 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
224 || file_exists(theme_file('logo.png')))
226 common_element_start('a', array('href' => common_local_url('public')));
227 common_element('img', array('src' => isset($config['site']['logo']) ?
228 ($config['site']['logo']) : theme_path('logo.png'),
229 'alt' => $config['site']['name'],
231 common_element_end('a');
233 common_element_start('p', array('id' => 'branding'));
234 common_element('a', array('href' => common_local_url('public')),
235 $config['site']['name']);
236 common_element_end('p');
239 common_element('h1', 'pagetitle', $pagetitle);
243 call_user_func($headercall, $data);
245 call_user_func($headercall);
248 common_element_end('div');
249 common_element_start('div', array('id' => 'content'));
252 function common_show_footer() {
254 common_element_end('div'); # content div
256 common_element_start('div', array('id' => 'footer'));
257 common_element_start('div', 'laconica');
258 if (common_config('site', 'broughtby')) {
259 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
261 $instr = _('**%%site.name%%** is a microblogging service. ');
263 $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION);
264 $output = common_markup_to_html($instr);
266 common_element_end('div');
267 common_element('img', array('id' => 'cc',
268 'src' => $config['license']['image'],
269 'alt' => $config['license']['title']));
270 common_element_start('p');
271 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
272 common_element('a', array('class' => 'license',
274 'href' => $config['license']['url']),
275 $config['license']['title']);
276 common_text(_('. Contributors should be attributed by full name or nickname.'));
277 common_element_end('p');
278 common_element_end('div');
279 common_element_end('div');
280 common_element_end('body');
281 common_element_end('html');
285 function common_text($txt) {
290 function common_raw($xml) {
295 function common_nav_menu() {
296 $user = common_current_user();
297 common_element_start('ul', array('id' => 'nav'));
299 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
302 common_menu_item(common_local_url('peoplesearch'), _('Search'));
303 common_menu_item(common_local_url('tags'), _('Tags'));
305 common_menu_item(common_local_url('profilesettings'),
307 common_menu_item(common_local_url('logout'),
310 common_menu_item(common_local_url('login'), _('Login'));
311 if (!common_config('site', 'closed')) {
312 common_menu_item(common_local_url('register'), _('Register'));
314 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
316 common_element_end('ul');
319 function common_foot_menu() {
320 common_element_start('ul', array('id' => 'nav_sub'));
321 common_menu_item(common_local_url('doc', array('title' => 'help')),
323 common_menu_item(common_local_url('doc', array('title' => 'about')),
325 common_menu_item(common_local_url('doc', array('title' => 'faq')),
327 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
329 common_menu_item(common_local_url('doc', array('title' => 'source')),
331 common_menu_item(common_local_url('doc', array('title' => 'contact')),
333 common_element_end('ul');
336 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
339 $lattrs['class'] = 'current';
341 common_element_start('li', $lattrs);
342 $attrs['href'] = $url;
344 $attrs['title'] = $title;
346 common_element('a', $attrs, $text);
347 common_element_end('li');
350 function common_input($id, $label, $value=NULL,$instructions=NULL) {
351 common_element_start('p');
352 common_element('label', array('for' => $id), $label);
353 $attrs = array('name' => $id,
355 'class' => 'input_text',
358 $attrs['value'] = htmlspecialchars($value);
360 common_element('input', $attrs);
362 common_element('span', 'input_instructions', $instructions);
364 common_element_end('p');
367 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
369 common_element_start('p');
370 $attrs = array('name' => $id,
371 'type' => 'checkbox',
372 'class' => 'checkbox',
375 $attrs['value'] = htmlspecialchars($value);
378 $attrs['checked'] = 'checked';
380 common_element('input', $attrs);
383 common_element('span', 'checkbox_label', $label);
386 common_element('span', 'input_instructions', $instructions);
388 common_element_end('p');
391 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
392 common_element_start('p');
393 common_element('label', array('for' => $id), $label);
394 common_element_start('select', array('id' => $id, 'name' => $id));
396 common_element('option', array('value' => ''));
398 foreach ($content as $value => $option) {
399 if ($value == $selected) {
400 common_element('option', array('value' => $value, 'selected' => $value), $option);
402 common_element('option', array('value' => $value), $option);
405 common_element_end('select');
407 common_element('span', 'input_instructions', $instructions);
409 common_element_end('p');
411 function common_hidden($id, $value) {
412 common_element('input', array('name' => $id,
418 function common_password($id, $label, $instructions=NULL) {
419 common_element_start('p');
420 common_element('label', array('for' => $id), $label);
421 $attrs = array('name' => $id,
422 'type' => 'password',
423 'class' => 'password',
425 common_element('input', $attrs);
427 common_element('span', 'input_instructions', $instructions);
429 common_element_end('p');
432 function common_submit($id, $label) {
434 common_element_start('p');
435 common_element('input', array('type' => 'submit',
440 common_element_end('p');
443 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
444 common_element_start('p');
445 common_element('label', array('for' => $id), $label);
446 common_element('textarea', array('rows' => 3,
450 ($content) ? $content : '');
452 common_element('span', 'input_instructions', $instructions);
454 common_element_end('p');
457 function common_timezone() {
458 if (common_logged_in()) {
459 $user = common_current_user();
460 if ($user->timezone) {
461 return $user->timezone;
466 return $config['site']['timezone'];
469 function common_language() {
470 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
472 $user_language = FALSE;
474 if (common_logged_in()) {
475 $user = common_current_user();
476 $user_language = $user->language;
479 if ($user_language) {
480 return $user_language;
481 } else if (!empty($httplang)) {
482 $language = client_prefered_language($httplang);
487 return $config['site']['language'];
490 # salted, hashed passwords are stored in the DB
492 function common_munge_password($password, $id) {
493 return md5($password . $id);
496 # check if a username exists and has matching password
497 function common_check_user($nickname, $password) {
498 # NEVER allow blank passwords, even if they match the DB
499 if (mb_strlen($password) == 0) {
502 $user = User::staticGet('nickname', $nickname);
503 if (is_null($user)) {
506 if (0 == strcmp(common_munge_password($password, $user->id),
515 # is the current user logged in?
516 function common_logged_in() {
517 return (!is_null(common_current_user()));
520 function common_have_session() {
521 return (0 != strcmp(session_id(), ''));
524 function common_ensure_session() {
525 if (!common_have_session()) {
530 # Three kinds of arguments:
535 function common_set_user($user) {
536 if (is_null($user) && common_have_session()) {
537 unset($_SESSION['userid']);
539 } else if (is_string($user)) {
541 $user = User::staticGet('nickname', $nickname);
542 } else if (!($user instanceof User)) {
547 common_ensure_session();
548 $_SESSION['userid'] = $user->id;
554 function common_set_cookie($key, $value, $expiration=0) {
555 $path = common_config('site', 'path');
556 $server = common_config('site', 'server');
558 if ($path && ($path != '/')) {
559 $cookiepath = '/' . $path . '/';
563 return setcookie($key,
570 define('REMEMBERME', 'rememberme');
571 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
573 function common_rememberme($user=NULL) {
575 $user = common_current_user();
577 common_debug('No current user to remember', __FILE__);
581 $rm = new Remember_me();
582 $rm->code = common_good_rand(16);
583 $rm->user_id = $user->id;
584 $result = $rm->insert();
586 common_log_db_error($rm, 'INSERT', __FILE__);
587 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
590 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
591 common_set_cookie(REMEMBERME,
592 implode(':', array($rm->user_id, $rm->code)),
593 time() + REMEMBERME_EXPIRY);
597 function common_remembered_user() {
600 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
602 list($id, $code) = explode(':', $packed);
604 $rm = Remember_me::staticGet($code);
605 if ($rm && ($rm->user_id == $id)) {
606 $user = User::staticGet($rm->user_id);
609 $result = $rm->delete();
611 common_log_db_error($rm, 'DELETE', __FILE__);
614 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
615 common_set_user($user->nickname);
616 common_real_login(false);
617 # We issue a new cookie, so they can log in
618 # automatically again after this session
619 common_rememberme($user);
628 # must be called with a valid user!
630 function common_forgetme() {
631 common_set_cookie(REMEMBERME, '', 0);
634 # who is the current user?
635 function common_current_user() {
636 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
637 common_ensure_session();
638 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
640 # note: this should cache
641 $user = User::staticGet($id);
645 # that didn't work; try to remember
646 $user = common_remembered_user();
648 common_debug("Got User " . $user->nickname);
649 common_debug("Faking session on remembered user");
650 $_SESSION['userid'] = $user->id;
655 # Logins that are 'remembered' aren't 'real' -- they're subject to
656 # cookie-stealing. So, we don't let them do certain things. New reg,
657 # OpenID, and password logins _are_ real.
659 function common_real_login($real=true) {
660 common_ensure_session();
661 $_SESSION['real_login'] = $real;
664 function common_is_real_login() {
665 return common_logged_in() && $_SESSION['real_login'];
668 # get canonical version of nickname for comparison
669 function common_canonical_nickname($nickname) {
670 # XXX: UTF-8 canonicalization (like combining chars)
671 return strtolower($nickname);
674 # get canonical version of email for comparison
675 function common_canonical_email($email) {
676 # XXX: canonicalize UTF-8
677 # XXX: lcase the domain part
681 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$_+!*();/?:~-]))');
683 function common_render_content($text, $notice) {
684 $r = htmlspecialchars($text);
686 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
687 $id = $notice->profile_id;
688 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
689 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
690 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
691 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
696 function common_tag_link($tag) {
697 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
700 function common_at_link($sender_id, $nickname) {
701 $sender = Profile::staticGet($sender_id);
702 $recipient = common_relative_profile($sender, $nickname);
704 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
710 function common_relative_profile($sender, $nickname, $dt=NULL) {
711 # Try to find profiles this profile is subscribed to that have this nickname
712 $recipient = new Profile();
713 # XXX: use a join instead of a subquery
714 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
715 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
716 if ($recipient->find(TRUE)) {
717 # XXX: should probably differentiate between profiles with
718 # the same name by date of most recent update
721 # Try to find profiles that listen to this profile and that have this nickname
722 $recipient = new Profile();
723 # XXX: use a join instead of a subquery
724 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
725 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
726 if ($recipient->find(TRUE)) {
727 # XXX: should probably differentiate between profiles with
728 # the same name by date of most recent update
731 # If this is a local user, try to find a local user with that nickname.
732 $sender = User::staticGet($sender->id);
734 $recipient_user = User::staticGet('nickname', $nickname);
735 if ($recipient_user) {
736 return $recipient_user->getProfile();
739 # Otherwise, no links. @messages from local users to remote users,
740 # or from remote users to other remote users, are just
741 # outside our ability to make intelligent guesses about
745 // where should the avatar go for this user?
747 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
751 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
753 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
757 function common_avatar_path($filename) {
759 return INSTALLDIR . '/avatar/' . $filename;
762 function common_avatar_url($filename) {
763 return common_path('avatar/'.$filename);
766 function common_avatar_display_url($avatar) {
767 $server = common_config('avatar', 'server');
769 return 'http://'.$server.'/'.$avatar->filename;
775 function common_default_avatar($size) {
776 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
777 AVATAR_STREAM_SIZE => 'stream',
778 AVATAR_MINI_SIZE => 'mini');
779 return theme_path('default-avatar-'.$sizenames[$size].'.png');
782 function common_local_url($action, $args=NULL) {
784 if ($config['site']['fancy']) {
785 return common_fancy_url($action, $args);
787 return common_simple_url($action, $args);
791 function common_fancy_url($action, $args=NULL) {
792 switch (strtolower($action)) {
794 if ($args && isset($args['page'])) {
795 return common_path('?page=' . $args['page']);
797 return common_path('');
800 return common_path('rss');
802 return common_path('xrds');
804 if ($args && $args['type']) {
805 return common_path('opensearch/'.$args['type']);
807 return common_path('opensearch/people');
810 return common_path('doc/'.$args['title']);
816 return common_path('main/'.$action);
817 case 'remotesubscribe':
818 if ($args && $args['nickname']) {
819 return common_path('main/remote?nickname=' . $args['nickname']);
821 return common_path('main/remote');
824 return common_path('main/openid');
827 return common_path('settings/'.$action);
828 case 'profilesettings':
829 return common_path('settings/profile');
830 case 'emailsettings':
831 return common_path('settings/email');
832 case 'openidsettings':
833 return common_path('settings/openid');
835 return common_path('settings/sms');
837 if ($args && $args['replyto']) {
838 return common_path('notice/new?replyto='.$args['replyto']);
840 return common_path('notice/new');
843 return common_path('notice/'.$args['notice']);
845 if ($args && $args['notice']) {
846 return common_path('notice/delete/'.$args['notice']);
848 return common_path('notice/delete');
852 return common_path($args['nickname'].'/'.$action);
853 case 'subscriptions':
857 if ($args && isset($args['page'])) {
858 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
860 return common_path($args['nickname'].'/'.$action);
863 return common_path($args['nickname'].'/all/rss');
865 return common_path($args['nickname'].'/replies/rss');
867 return common_path($args['nickname'].'/rss');
869 if ($args && isset($args['page'])) {
870 return common_path($args['nickname'].'?page=' . $args['page']);
872 return common_path($args['nickname']);
874 case 'confirmaddress':
875 return common_path('main/confirmaddress/'.$args['code']);
877 return common_path('user/'.$args['id']);
878 case 'recoverpassword':
879 $path = 'main/recoverpassword';
881 $path .= '/' . $args['code'];
883 return common_path($path);
885 return common_path('settings/im');
887 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
889 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
890 case 'noticesearchrss':
891 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
892 case 'avatarbynickname':
893 return common_path($args['nickname'].'/avatar/'.$args['size']);
895 if (isset($args['tag']) && $args['tag']) {
896 $path = 'tag/' . $args['tag'];
901 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
903 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
905 return common_simple_url($action, $args);
909 function common_simple_url($action, $args=NULL) {
911 /* XXX: pretty URLs */
914 foreach ($args as $key => $value) {
915 $extra .= "&${key}=${value}";
918 return common_path("index.php?action=${action}${extra}");
921 function common_path($relative) {
923 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
924 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
927 function common_date_string($dt) {
928 // XXX: do some sexy date formatting
929 // return date(DATE_RFC822, $dt);
934 if ($now < $t) { # that shouldn't happen!
935 return common_exact_date($dt);
936 } else if ($diff < 60) {
937 return _('a few seconds ago');
938 } else if ($diff < 92) {
939 return _('about a minute ago');
940 } else if ($diff < 3300) {
941 return sprintf(_('about %d minutes ago'), round($diff/60));
942 } else if ($diff < 5400) {
943 return _('about an hour ago');
944 } else if ($diff < 22 * 3600) {
945 return sprintf(_('about %d hours ago'), round($diff/3600));
946 } else if ($diff < 37 * 3600) {
947 return _('about a day ago');
948 } else if ($diff < 24 * 24 * 3600) {
949 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
950 } else if ($diff < 46 * 24 * 3600) {
951 return _('about a month ago');
952 } else if ($diff < 330 * 24 * 3600) {
953 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
954 } else if ($diff < 480 * 24 * 3600) {
955 return _('about a year ago');
957 return common_exact_date($dt);
961 function common_exact_date($dt) {
966 $_utc = new DateTimeZone('UTC');
967 $_siteTz = new DateTimeZone(common_timezone());
970 $dateStr = date('d F Y H:i:s', strtotime($dt));
971 $d = new DateTime($dateStr, $_utc);
972 $d->setTimezone($_siteTz);
973 return $d->format(DATE_RFC850);
976 function common_date_w3dtf($dt) {
977 $dateStr = date('d F Y H:i:s', strtotime($dt));
978 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
979 $d->setTimezone(new DateTimeZone(common_timezone()));
980 return $d->format(DATE_W3C);
983 function common_date_rfc2822($dt) {
984 $dateStr = date('d F Y H:i:s', strtotime($dt));
985 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
986 $d->setTimezone(new DateTimeZone(common_timezone()));
987 return $d->format('r');
990 function common_date_iso8601($dt) {
991 $dateStr = date('d F Y H:i:s', strtotime($dt));
992 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
993 $d->setTimezone(new DateTimeZone(common_timezone()));
994 return $d->format('c');
997 function common_sql_now() {
998 return strftime('%Y-%m-%d %H:%M:%S', time());
1001 function common_redirect($url, $code=307) {
1002 static $status = array(301 => "Moved Permanently",
1005 307 => "Temporary Redirect");
1006 header("Status: ${code} $status[$code]");
1007 header("Location: $url");
1009 common_start_xml('a',
1010 '-//W3C//DTD XHTML 1.0 Strict//EN',
1011 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1012 common_element('a', array('href' => $url), $url);
1017 function common_save_replies($notice) {
1018 # Alternative reply format
1020 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1023 # extract all @messages
1024 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1025 if (!$cnt && !$tname) {
1028 # XXX: is there another way to make an array copy?
1029 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1030 $sender = Profile::staticGet($notice->profile_id);
1031 # store replied only for first @ (what user/notice what the reply directed,
1032 # we assume first @ is it)
1033 for ($i=0; $i<count($names); $i++) {
1034 $nickname = $names[$i];
1035 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1039 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1040 $reply_for = $recipient;
1041 $recipient_notice = $reply_for->getCurrentNotice();
1042 if ($recipient_notice) {
1043 $orig = clone($notice);
1044 $notice->reply_to = $recipient_notice->id;
1045 $notice->update($orig);
1048 $reply = new Reply();
1049 $reply->notice_id = $notice->id;
1050 $reply->profile_id = $recipient->id;
1051 $id = $reply->insert();
1053 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1054 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1055 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1061 function common_broadcast_notice($notice, $remote=false) {
1062 if (common_config('queue', 'enabled')) {
1064 return common_enqueue_notice($notice);
1066 return common_real_broadcast($notice, $remote);
1070 # Stick the notice on the queue
1072 function common_enqueue_notice($notice) {
1073 foreach (array('jabber', 'oms', 'sms') as $transport) {
1074 $qi = new Queue_item();
1075 $qi->notice_id = $notice->id;
1076 $qi->transport = $transport;
1077 $qi->created = $notice->created;
1078 $result = $qi->insert();
1080 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1081 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1084 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1089 function common_dequeue_notice($notice) {
1090 $qi = Queue_item::staticGet($notice->id);
1092 $result = $qi->delete();
1094 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1095 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1098 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1105 function common_real_broadcast($notice, $remote=false) {
1108 # Make sure we have the OMB stuff
1109 require_once(INSTALLDIR.'/lib/omb.php');
1110 $success = omb_broadcast_remote_subscribers($notice);
1112 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1116 require_once(INSTALLDIR.'/lib/jabber.php');
1117 $success = jabber_broadcast_notice($notice);
1119 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1123 require_once(INSTALLDIR.'/lib/mail.php');
1124 $success = mail_broadcast_notice_sms($notice);
1126 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1129 // XXX: broadcast notices to other IM
1133 function common_broadcast_profile($profile) {
1134 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1135 require_once(INSTALLDIR.'/lib/omb.php');
1136 omb_broadcast_profile($profile);
1137 // XXX: Other broadcasts...?
1141 function common_profile_url($nickname) {
1142 return common_local_url('showstream', array('nickname' => $nickname));
1145 # Don't call if nobody's logged in
1147 function common_notice_form($action=NULL, $content=NULL) {
1148 $user = common_current_user();
1149 assert(!is_null($user));
1150 common_element_start('form', array('id' => 'status_form',
1152 'action' => common_local_url('newnotice')));
1153 common_element_start('p');
1154 common_element('label', array('for' => 'status_textarea',
1155 'id' => 'status_label'),
1156 sprintf(_('What\'s up, %s?'), $user->nickname));
1157 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1158 common_element('textarea', array('id' => 'status_textarea',
1161 'name' => 'status_textarea'),
1162 ($content) ? $content : '');
1164 common_hidden('returnto', $action);
1166 common_element('input', array('id' => 'status_submit',
1167 'name' => 'status_submit',
1169 'value' => _('Send')));
1170 common_element_end('p');
1171 common_element_end('form');
1174 # Should make up a reasonable root URL
1176 function common_root_url() {
1177 return common_path('');
1180 # returns $bytes bytes of random data as a hexadecimal string
1181 # "good" here is a goal and not a guarantee
1183 function common_good_rand($bytes) {
1184 # XXX: use random.org...?
1185 if (file_exists('/dev/urandom')) {
1186 return common_urandom($bytes);
1187 } else { # FIXME: this is probably not good enough
1188 return common_mtrand($bytes);
1192 function common_urandom($bytes) {
1193 $h = fopen('/dev/urandom', 'rb');
1195 $src = fread($h, $bytes);
1198 for ($i = 0; $i < $bytes; $i++) {
1199 $enc .= sprintf("%02x", (ord($src[$i])));
1204 function common_mtrand($bytes) {
1206 for ($i = 0; $i < $bytes; $i++) {
1207 $enc .= sprintf("%02x", mt_rand(0, 255));
1212 function common_set_returnto($url) {
1213 common_ensure_session();
1214 $_SESSION['returnto'] = $url;
1217 function common_get_returnto() {
1218 common_ensure_session();
1219 return $_SESSION['returnto'];
1222 function common_timestamp() {
1223 return date('YmdHis');
1226 function common_ensure_syslog() {
1227 static $initialized = false;
1228 if (!$initialized) {
1230 openlog($config['syslog']['appname'], 0, LOG_USER);
1231 $initialized = true;
1235 function common_log($priority, $msg, $filename=NULL) {
1236 $logfile = common_config('site', 'logfile');
1238 $log = fopen($logfile, "a");
1240 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1241 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1242 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1243 fwrite($log, $output);
1247 common_ensure_syslog();
1248 syslog($priority, $msg);
1252 function common_debug($msg, $filename=NULL) {
1254 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1256 common_log(LOG_DEBUG, $msg);
1260 function common_log_db_error(&$object, $verb, $filename=NULL) {
1261 $objstr = common_log_objstring($object);
1262 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1263 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1266 function common_log_objstring(&$object) {
1267 if (is_null($object)) {
1270 $arr = $object->toArray();
1272 foreach ($arr as $k => $v) {
1273 $fields[] = "$k='$v'";
1275 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1279 function common_valid_http_url($url) {
1280 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1283 function common_valid_tag($tag) {
1284 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1285 return (Validate::email($matches[1]) ||
1286 preg_match('/^([\w-\.]+)$/', $matches[1]));
1291 # Does a little before-after block for next/prev page
1293 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1295 if ($have_before || $have_after) {
1296 common_element_start('div', array('id' => 'pagination'));
1297 common_element_start('ul', array('id' => 'nav_pagination'));
1301 $pargs = array('page' => $page-1);
1302 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1304 common_element_start('li', 'before');
1305 common_element('a', array('href' => common_local_url($action, $newargs)),
1307 common_element_end('li');
1311 $pargs = array('page' => $page+1);
1312 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1313 common_element_start('li', 'after');
1314 common_element('a', array('href' => common_local_url($action, $newargs)),
1316 common_element_end('li');
1319 if ($have_before || $have_after) {
1320 common_element_end('ul');
1321 common_element_end('div');
1325 /* Following functions are copied from MediaWiki GlobalFunctions.php
1326 * and written by Evan Prodromou. */
1328 function common_accept_to_prefs($accept, $def = '*/*') {
1329 # No arg means accept anything (per HTTP spec)
1331 return array($def => 1);
1336 $parts = explode(',', $accept);
1338 foreach($parts as $part) {
1339 # FIXME: doesn't deal with params like 'text/html; level=1'
1340 @list($value, $qpart) = explode(';', $part);
1342 if(!isset($qpart)) {
1344 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1345 $prefs[$value] = $match[1];
1352 function common_mime_type_match($type, $avail) {
1353 if(array_key_exists($type, $avail)) {
1356 $parts = explode('/', $type);
1357 if(array_key_exists($parts[0] . '/*', $avail)) {
1358 return $parts[0] . '/*';
1359 } elseif(array_key_exists('*/*', $avail)) {
1367 function common_negotiate_type($cprefs, $sprefs) {
1370 foreach(array_keys($sprefs) as $type) {
1371 $parts = explode('/', $type);
1372 if($parts[1] != '*') {
1373 $ckey = common_mime_type_match($type, $cprefs);
1375 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1380 foreach(array_keys($cprefs) as $type) {
1381 $parts = explode('/', $type);
1382 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1383 $skey = common_mime_type_match($type, $sprefs);
1385 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1391 $besttype = "text/html";
1393 foreach(array_keys($combine) as $type) {
1394 if($combine[$type] > $bestq) {
1396 $bestq = $combine[$type];
1403 function common_config($main, $sub) {
1405 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1408 function common_copy_args($from) {
1410 $strip = get_magic_quotes_gpc();
1411 foreach ($from as $k => $v) {
1412 $to[$k] = ($strip) ? stripslashes($v) : $v;
1417 function common_user_uri(&$user) {
1418 return common_local_url('userbyid', array('id' => $user->id));
1421 function common_notice_uri(&$notice) {
1422 return common_local_url('shownotice',
1423 array('notice' => $notice->id));
1426 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1428 function common_confirmation_code($bits) {
1429 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1430 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1431 $chars = ceil($bits/5);
1433 for ($i = 0; $i < $chars; $i++) {
1434 # XXX: convert to string and back
1435 $num = hexdec(common_good_rand(1));
1436 # XXX: randomness is too precious to throw away almost
1437 # 40% of the bits we get!
1438 $code .= $codechars[$num%32];
1443 # convert markup to HTML
1445 function common_markup_to_html($c) {
1446 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1447 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1448 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1449 return Markdown($c);
1452 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1453 $avatar = $profile->getAvatar($size);
1455 return common_avatar_display_url($avatar);
1457 return common_default_avatar($size);
1461 function common_profile_uri($profile) {
1465 $user = User::staticGet($profile->id);
1470 $remote = Remote_profile::staticGet($profile->id);
1472 return $remote->uri;
1474 # XXX: this is a very bad profile!
1478 function common_canonical_sms($sms) {
1480 preg_replace('/\D/', '', $sms);