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('invite'),
309 common_menu_item(common_local_url('logout'),
312 common_menu_item(common_local_url('login'), _('Login'));
313 if (!common_config('site', 'closed')) {
314 common_menu_item(common_local_url('register'), _('Register'));
316 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
318 common_element_end('ul');
321 function common_foot_menu() {
322 common_element_start('ul', array('id' => 'nav_sub'));
323 common_menu_item(common_local_url('doc', array('title' => 'help')),
325 common_menu_item(common_local_url('doc', array('title' => 'about')),
327 common_menu_item(common_local_url('doc', array('title' => 'faq')),
329 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
331 common_menu_item(common_local_url('doc', array('title' => 'source')),
333 common_menu_item(common_local_url('doc', array('title' => 'contact')),
335 common_element_end('ul');
338 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
341 $lattrs['class'] = 'current';
343 common_element_start('li', $lattrs);
344 $attrs['href'] = $url;
346 $attrs['title'] = $title;
348 common_element('a', $attrs, $text);
349 common_element_end('li');
352 function common_input($id, $label, $value=NULL,$instructions=NULL) {
353 common_element_start('p');
354 common_element('label', array('for' => $id), $label);
355 $attrs = array('name' => $id,
357 'class' => 'input_text',
360 $attrs['value'] = htmlspecialchars($value);
362 common_element('input', $attrs);
364 common_element('span', 'input_instructions', $instructions);
366 common_element_end('p');
369 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
371 common_element_start('p');
372 $attrs = array('name' => $id,
373 'type' => 'checkbox',
374 'class' => 'checkbox',
377 $attrs['value'] = htmlspecialchars($value);
380 $attrs['checked'] = 'checked';
382 common_element('input', $attrs);
385 common_element('span', 'checkbox_label', $label);
388 common_element('span', 'input_instructions', $instructions);
390 common_element_end('p');
393 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
394 common_element_start('p');
395 common_element('label', array('for' => $id), $label);
396 common_element_start('select', array('id' => $id, 'name' => $id));
398 common_element('option', array('value' => ''));
400 foreach ($content as $value => $option) {
401 if ($value == $selected) {
402 common_element('option', array('value' => $value, 'selected' => $value), $option);
404 common_element('option', array('value' => $value), $option);
407 common_element_end('select');
409 common_element('span', 'input_instructions', $instructions);
411 common_element_end('p');
413 function common_hidden($id, $value) {
414 common_element('input', array('name' => $id,
420 function common_password($id, $label, $instructions=NULL) {
421 common_element_start('p');
422 common_element('label', array('for' => $id), $label);
423 $attrs = array('name' => $id,
424 'type' => 'password',
425 'class' => 'password',
427 common_element('input', $attrs);
429 common_element('span', 'input_instructions', $instructions);
431 common_element_end('p');
434 function common_submit($id, $label, $cls='submit') {
436 common_element_start('p');
437 common_element('input', array('type' => 'submit',
442 common_element_end('p');
445 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
446 common_element_start('p');
447 common_element('label', array('for' => $id), $label);
448 common_element('textarea', array('rows' => 3,
452 ($content) ? $content : '');
454 common_element('span', 'input_instructions', $instructions);
456 common_element_end('p');
459 function common_timezone() {
460 if (common_logged_in()) {
461 $user = common_current_user();
462 if ($user->timezone) {
463 return $user->timezone;
468 return $config['site']['timezone'];
471 function common_language() {
472 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
474 $user_language = FALSE;
476 if (common_logged_in()) {
477 $user = common_current_user();
478 $user_language = $user->language;
481 if ($user_language) {
482 return $user_language;
483 } else if (!empty($httplang)) {
484 $language = client_prefered_language($httplang);
489 return common_config('site', 'language');
492 # salted, hashed passwords are stored in the DB
494 function common_munge_password($password, $id) {
495 return md5($password . $id);
498 # check if a username exists and has matching password
499 function common_check_user($nickname, $password) {
500 # NEVER allow blank passwords, even if they match the DB
501 if (mb_strlen($password) == 0) {
504 $user = User::staticGet('nickname', $nickname);
505 if (is_null($user)) {
508 if (0 == strcmp(common_munge_password($password, $user->id),
517 # is the current user logged in?
518 function common_logged_in() {
519 return (!is_null(common_current_user()));
522 function common_have_session() {
523 return (0 != strcmp(session_id(), ''));
526 function common_ensure_session() {
527 if (!common_have_session()) {
532 # Three kinds of arguments:
537 function common_set_user($user) {
538 if (is_null($user) && common_have_session()) {
539 unset($_SESSION['userid']);
541 } else if (is_string($user)) {
543 $user = User::staticGet('nickname', $nickname);
544 } else if (!($user instanceof User)) {
549 common_ensure_session();
550 $_SESSION['userid'] = $user->id;
556 function common_set_cookie($key, $value, $expiration=0) {
557 $path = common_config('site', 'path');
558 $server = common_config('site', 'server');
560 if ($path && ($path != '/')) {
561 $cookiepath = '/' . $path . '/';
565 return setcookie($key,
572 define('REMEMBERME', 'rememberme');
573 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
575 function common_rememberme($user=NULL) {
577 $user = common_current_user();
579 common_debug('No current user to remember', __FILE__);
583 $rm = new Remember_me();
584 $rm->code = common_good_rand(16);
585 $rm->user_id = $user->id;
586 $result = $rm->insert();
588 common_log_db_error($rm, 'INSERT', __FILE__);
589 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
592 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
593 common_set_cookie(REMEMBERME,
594 implode(':', array($rm->user_id, $rm->code)),
595 time() + REMEMBERME_EXPIRY);
599 function common_remembered_user() {
602 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
604 list($id, $code) = explode(':', $packed);
606 $rm = Remember_me::staticGet($code);
607 if ($rm && ($rm->user_id == $id)) {
608 $user = User::staticGet($rm->user_id);
611 $result = $rm->delete();
613 common_log_db_error($rm, 'DELETE', __FILE__);
616 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
617 common_set_user($user->nickname);
618 common_real_login(false);
619 # We issue a new cookie, so they can log in
620 # automatically again after this session
621 common_rememberme($user);
630 # must be called with a valid user!
632 function common_forgetme() {
633 common_set_cookie(REMEMBERME, '', 0);
636 # who is the current user?
637 function common_current_user() {
638 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
639 common_ensure_session();
640 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
642 # note: this should cache
643 $user = User::staticGet($id);
647 # that didn't work; try to remember
648 $user = common_remembered_user();
650 common_debug("Got User " . $user->nickname);
651 common_debug("Faking session on remembered user");
652 $_SESSION['userid'] = $user->id;
657 # Logins that are 'remembered' aren't 'real' -- they're subject to
658 # cookie-stealing. So, we don't let them do certain things. New reg,
659 # OpenID, and password logins _are_ real.
661 function common_real_login($real=true) {
662 common_ensure_session();
663 $_SESSION['real_login'] = $real;
666 function common_is_real_login() {
667 return common_logged_in() && $_SESSION['real_login'];
670 # get canonical version of nickname for comparison
671 function common_canonical_nickname($nickname) {
672 # XXX: UTF-8 canonicalization (like combining chars)
673 return strtolower($nickname);
676 # get canonical version of email for comparison
677 function common_canonical_email($email) {
678 # XXX: canonicalize UTF-8
679 # XXX: lcase the domain part
683 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$_+!*();/?:~-]))');
685 function common_render_content($text, $notice) {
686 $r = htmlspecialchars($text);
688 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
689 $id = $notice->profile_id;
690 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
691 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
692 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
693 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
698 function common_tag_link($tag) {
699 if(common_config('site', 'fancy')) {
700 return '<a href="' . htmlspecialchars(common_path('tag/' . strtolower(str_replace(array('-', '_', '.'), '', $tag)))) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
702 return '<a href="' . htmlspecialchars(common_path('index.php?action=tag&tag=' . strtolower(str_replace(array('-', '_', '.'), '', $tag)))) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
706 function common_at_link($sender_id, $nickname) {
707 $sender = Profile::staticGet($sender_id);
708 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
710 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
716 function common_relative_profile($sender, $nickname, $dt=NULL) {
717 # Try to find profiles this profile is subscribed to that have this nickname
718 $recipient = new Profile();
719 # XXX: use a join instead of a subquery
720 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
721 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
722 if ($recipient->find(TRUE)) {
723 # XXX: should probably differentiate between profiles with
724 # the same name by date of most recent update
727 # Try to find profiles that listen to this profile and that have this nickname
728 $recipient = new Profile();
729 # XXX: use a join instead of a subquery
730 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
731 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
732 if ($recipient->find(TRUE)) {
733 # XXX: should probably differentiate between profiles with
734 # the same name by date of most recent update
737 # If this is a local user, try to find a local user with that nickname.
738 $sender = User::staticGet($sender->id);
740 $recipient_user = User::staticGet('nickname', $nickname);
741 if ($recipient_user) {
742 return $recipient_user->getProfile();
745 # Otherwise, no links. @messages from local users to remote users,
746 # or from remote users to other remote users, are just
747 # outside our ability to make intelligent guesses about
751 // where should the avatar go for this user?
753 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
757 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
759 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
763 function common_avatar_path($filename) {
765 return INSTALLDIR . '/avatar/' . $filename;
768 function common_avatar_url($filename) {
769 return common_path('avatar/'.$filename);
772 function common_avatar_display_url($avatar) {
773 $server = common_config('avatar', 'server');
775 return 'http://'.$server.'/'.$avatar->filename;
781 function common_default_avatar($size) {
782 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
783 AVATAR_STREAM_SIZE => 'stream',
784 AVATAR_MINI_SIZE => 'mini');
785 return theme_path('default-avatar-'.$sizenames[$size].'.png');
788 function common_local_url($action, $args=NULL) {
790 if ($config['site']['fancy']) {
791 return common_fancy_url($action, $args);
793 return common_simple_url($action, $args);
797 function common_fancy_url($action, $args=NULL) {
798 switch (strtolower($action)) {
800 if ($args && isset($args['page'])) {
801 return common_path('?page=' . $args['page']);
803 return common_path('');
806 return common_path('rss');
808 return common_path('xrds');
810 if ($args && $args['type']) {
811 return common_path('opensearch/'.$args['type']);
813 return common_path('opensearch/people');
816 return common_path('doc/'.$args['title']);
822 return common_path('main/'.$action);
824 if ($args && $args['code']) {
825 return common_path('main/register/'.$args['code']);
827 return common_path('main/register');
829 case 'remotesubscribe':
830 if ($args && $args['nickname']) {
831 return common_path('main/remote?nickname=' . $args['nickname']);
833 return common_path('main/remote');
836 return common_path('main/openid');
839 return common_path('settings/'.$action);
840 case 'profilesettings':
841 return common_path('settings/profile');
842 case 'emailsettings':
843 return common_path('settings/email');
844 case 'openidsettings':
845 return common_path('settings/openid');
847 return common_path('settings/sms');
849 if ($args && $args['replyto']) {
850 return common_path('notice/new?replyto='.$args['replyto']);
852 return common_path('notice/new');
855 return common_path('notice/'.$args['notice']);
857 if ($args && $args['notice']) {
858 return common_path('notice/delete/'.$args['notice']);
860 return common_path('notice/delete');
864 return common_path($args['nickname'].'/'.$action);
865 case 'subscriptions':
869 if ($args && isset($args['page'])) {
870 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
872 return common_path($args['nickname'].'/'.$action);
875 return common_path($args['nickname'].'/all/rss');
877 return common_path($args['nickname'].'/replies/rss');
879 return common_path($args['nickname'].'/rss');
881 if ($args && isset($args['page'])) {
882 return common_path($args['nickname'].'?page=' . $args['page']);
884 return common_path($args['nickname']);
886 case 'confirmaddress':
887 return common_path('main/confirmaddress/'.$args['code']);
889 return common_path('user/'.$args['id']);
890 case 'recoverpassword':
891 $path = 'main/recoverpassword';
893 $path .= '/' . $args['code'];
895 return common_path($path);
897 return common_path('settings/im');
899 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
901 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
902 case 'noticesearchrss':
903 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
904 case 'avatarbynickname':
905 return common_path($args['nickname'].'/avatar/'.$args['size']);
907 if (isset($args['tag']) && $args['tag']) {
908 $path = 'tag/' . $args['tag'];
913 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
915 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
917 return common_path('main/favor');
919 return common_path('main/disfavor');
920 case 'showfavorites':
921 if ($args && isset($args['page'])) {
922 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
924 return common_path($args['nickname'].'/favorites');
927 return common_simple_url($action, $args);
931 function common_simple_url($action, $args=NULL) {
933 /* XXX: pretty URLs */
936 foreach ($args as $key => $value) {
937 $extra .= "&${key}=${value}";
940 return common_path("index.php?action=${action}${extra}");
943 function common_path($relative) {
945 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
946 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
949 function common_date_string($dt) {
950 // XXX: do some sexy date formatting
951 // return date(DATE_RFC822, $dt);
956 if ($now < $t) { # that shouldn't happen!
957 return common_exact_date($dt);
958 } else if ($diff < 60) {
959 return _('a few seconds ago');
960 } else if ($diff < 92) {
961 return _('about a minute ago');
962 } else if ($diff < 3300) {
963 return sprintf(_('about %d minutes ago'), round($diff/60));
964 } else if ($diff < 5400) {
965 return _('about an hour ago');
966 } else if ($diff < 22 * 3600) {
967 return sprintf(_('about %d hours ago'), round($diff/3600));
968 } else if ($diff < 37 * 3600) {
969 return _('about a day ago');
970 } else if ($diff < 24 * 24 * 3600) {
971 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
972 } else if ($diff < 46 * 24 * 3600) {
973 return _('about a month ago');
974 } else if ($diff < 330 * 24 * 3600) {
975 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
976 } else if ($diff < 480 * 24 * 3600) {
977 return _('about a year ago');
979 return common_exact_date($dt);
983 function common_exact_date($dt) {
988 $_utc = new DateTimeZone('UTC');
989 $_siteTz = new DateTimeZone(common_timezone());
992 $dateStr = date('d F Y H:i:s', strtotime($dt));
993 $d = new DateTime($dateStr, $_utc);
994 $d->setTimezone($_siteTz);
995 return $d->format(DATE_RFC850);
998 function common_date_w3dtf($dt) {
999 $dateStr = date('d F Y H:i:s', strtotime($dt));
1000 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1001 $d->setTimezone(new DateTimeZone(common_timezone()));
1002 return $d->format(DATE_W3C);
1005 function common_date_rfc2822($dt) {
1006 $dateStr = date('d F Y H:i:s', strtotime($dt));
1007 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1008 $d->setTimezone(new DateTimeZone(common_timezone()));
1009 return $d->format('r');
1012 function common_date_iso8601($dt) {
1013 $dateStr = date('d F Y H:i:s', strtotime($dt));
1014 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1015 $d->setTimezone(new DateTimeZone(common_timezone()));
1016 return $d->format('c');
1019 function common_sql_now() {
1020 return strftime('%Y-%m-%d %H:%M:%S', time());
1023 function common_redirect($url, $code=307) {
1024 static $status = array(301 => "Moved Permanently",
1027 307 => "Temporary Redirect");
1028 header("Status: ${code} $status[$code]");
1029 header("Location: $url");
1031 common_start_xml('a',
1032 '-//W3C//DTD XHTML 1.0 Strict//EN',
1033 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1034 common_element('a', array('href' => $url), $url);
1039 function common_save_replies($notice) {
1040 # Alternative reply format
1042 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1045 # extract all @messages
1046 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1047 if (!$cnt && !$tname) {
1050 # XXX: is there another way to make an array copy?
1051 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1052 $sender = Profile::staticGet($notice->profile_id);
1053 # store replied only for first @ (what user/notice what the reply directed,
1054 # we assume first @ is it)
1055 for ($i=0; $i<count($names); $i++) {
1056 $nickname = $names[$i];
1057 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1061 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1062 $reply_for = $recipient;
1063 $recipient_notice = $reply_for->getCurrentNotice();
1064 if ($recipient_notice) {
1065 $orig = clone($notice);
1066 $notice->reply_to = $recipient_notice->id;
1067 $notice->update($orig);
1070 $reply = new Reply();
1071 $reply->notice_id = $notice->id;
1072 $reply->profile_id = $recipient->id;
1073 $id = $reply->insert();
1075 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1076 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1077 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1083 function common_broadcast_notice($notice, $remote=false) {
1084 if (common_config('queue', 'enabled')) {
1086 return common_enqueue_notice($notice);
1088 return common_real_broadcast($notice, $remote);
1092 # Stick the notice on the queue
1094 function common_enqueue_notice($notice) {
1095 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1096 $qi = new Queue_item();
1097 $qi->notice_id = $notice->id;
1098 $qi->transport = $transport;
1099 $qi->created = $notice->created;
1100 $result = $qi->insert();
1102 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1103 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1106 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1111 function common_dequeue_notice($notice) {
1112 $qi = Queue_item::staticGet($notice->id);
1114 $result = $qi->delete();
1116 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1117 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1120 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1127 function common_real_broadcast($notice, $remote=false) {
1130 # Make sure we have the OMB stuff
1131 require_once(INSTALLDIR.'/lib/omb.php');
1132 $success = omb_broadcast_remote_subscribers($notice);
1134 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1138 require_once(INSTALLDIR.'/lib/jabber.php');
1139 $success = jabber_broadcast_notice($notice);
1141 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1145 require_once(INSTALLDIR.'/lib/mail.php');
1146 $success = mail_broadcast_notice_sms($notice);
1148 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1152 $success = jabber_public_notice($notice);
1154 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1157 // XXX: broadcast notices to other IM
1161 function common_broadcast_profile($profile) {
1162 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1163 require_once(INSTALLDIR.'/lib/omb.php');
1164 omb_broadcast_profile($profile);
1165 // XXX: Other broadcasts...?
1169 function common_profile_url($nickname) {
1170 return common_local_url('showstream', array('nickname' => $nickname));
1173 # Don't call if nobody's logged in
1175 function common_notice_form($action=NULL, $content=NULL) {
1176 $user = common_current_user();
1177 assert(!is_null($user));
1178 common_element_start('form', array('id' => 'status_form',
1180 'action' => common_local_url('newnotice')));
1181 common_element_start('p');
1182 common_element('label', array('for' => 'status_textarea',
1183 'id' => 'status_label'),
1184 sprintf(_('What\'s up, %s?'), $user->nickname));
1185 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1186 common_element('textarea', array('id' => 'status_textarea',
1189 'name' => 'status_textarea'),
1190 ($content) ? $content : '');
1192 common_hidden('returnto', $action);
1194 common_element('input', array('id' => 'status_submit',
1195 'name' => 'status_submit',
1197 'value' => _('Send')));
1198 common_element_end('p');
1199 common_element_end('form');
1202 # Should make up a reasonable root URL
1204 function common_root_url() {
1205 return common_path('');
1208 # returns $bytes bytes of random data as a hexadecimal string
1209 # "good" here is a goal and not a guarantee
1211 function common_good_rand($bytes) {
1212 # XXX: use random.org...?
1213 if (file_exists('/dev/urandom')) {
1214 return common_urandom($bytes);
1215 } else { # FIXME: this is probably not good enough
1216 return common_mtrand($bytes);
1220 function common_urandom($bytes) {
1221 $h = fopen('/dev/urandom', 'rb');
1223 $src = fread($h, $bytes);
1226 for ($i = 0; $i < $bytes; $i++) {
1227 $enc .= sprintf("%02x", (ord($src[$i])));
1232 function common_mtrand($bytes) {
1234 for ($i = 0; $i < $bytes; $i++) {
1235 $enc .= sprintf("%02x", mt_rand(0, 255));
1240 function common_set_returnto($url) {
1241 common_ensure_session();
1242 $_SESSION['returnto'] = $url;
1245 function common_get_returnto() {
1246 common_ensure_session();
1247 return $_SESSION['returnto'];
1250 function common_timestamp() {
1251 return date('YmdHis');
1254 function common_ensure_syslog() {
1255 static $initialized = false;
1256 if (!$initialized) {
1258 openlog($config['syslog']['appname'], 0, LOG_USER);
1259 $initialized = true;
1263 function common_log($priority, $msg, $filename=NULL) {
1264 $logfile = common_config('site', 'logfile');
1266 $log = fopen($logfile, "a");
1268 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1269 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1270 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1271 fwrite($log, $output);
1275 common_ensure_syslog();
1276 syslog($priority, $msg);
1280 function common_debug($msg, $filename=NULL) {
1282 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1284 common_log(LOG_DEBUG, $msg);
1288 function common_log_db_error(&$object, $verb, $filename=NULL) {
1289 $objstr = common_log_objstring($object);
1290 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1291 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1294 function common_log_objstring(&$object) {
1295 if (is_null($object)) {
1298 $arr = $object->toArray();
1300 foreach ($arr as $k => $v) {
1301 $fields[] = "$k='$v'";
1303 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1307 function common_valid_http_url($url) {
1308 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1311 function common_valid_tag($tag) {
1312 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1313 return (Validate::email($matches[1]) ||
1314 preg_match('/^([\w-\.]+)$/', $matches[1]));
1319 # Does a little before-after block for next/prev page
1321 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1323 if ($have_before || $have_after) {
1324 common_element_start('div', array('id' => 'pagination'));
1325 common_element_start('ul', array('id' => 'nav_pagination'));
1329 $pargs = array('page' => $page-1);
1330 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1332 common_element_start('li', 'before');
1333 common_element('a', array('href' => common_local_url($action, $newargs)),
1335 common_element_end('li');
1339 $pargs = array('page' => $page+1);
1340 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1341 common_element_start('li', 'after');
1342 common_element('a', array('href' => common_local_url($action, $newargs)),
1344 common_element_end('li');
1347 if ($have_before || $have_after) {
1348 common_element_end('ul');
1349 common_element_end('div');
1353 /* Following functions are copied from MediaWiki GlobalFunctions.php
1354 * and written by Evan Prodromou. */
1356 function common_accept_to_prefs($accept, $def = '*/*') {
1357 # No arg means accept anything (per HTTP spec)
1359 return array($def => 1);
1364 $parts = explode(',', $accept);
1366 foreach($parts as $part) {
1367 # FIXME: doesn't deal with params like 'text/html; level=1'
1368 @list($value, $qpart) = explode(';', $part);
1370 if(!isset($qpart)) {
1372 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1373 $prefs[$value] = $match[1];
1380 function common_mime_type_match($type, $avail) {
1381 if(array_key_exists($type, $avail)) {
1384 $parts = explode('/', $type);
1385 if(array_key_exists($parts[0] . '/*', $avail)) {
1386 return $parts[0] . '/*';
1387 } elseif(array_key_exists('*/*', $avail)) {
1395 function common_negotiate_type($cprefs, $sprefs) {
1398 foreach(array_keys($sprefs) as $type) {
1399 $parts = explode('/', $type);
1400 if($parts[1] != '*') {
1401 $ckey = common_mime_type_match($type, $cprefs);
1403 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1408 foreach(array_keys($cprefs) as $type) {
1409 $parts = explode('/', $type);
1410 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1411 $skey = common_mime_type_match($type, $sprefs);
1413 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1419 $besttype = "text/html";
1421 foreach(array_keys($combine) as $type) {
1422 if($combine[$type] > $bestq) {
1424 $bestq = $combine[$type];
1431 function common_config($main, $sub) {
1433 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1436 function common_copy_args($from) {
1438 $strip = get_magic_quotes_gpc();
1439 foreach ($from as $k => $v) {
1440 $to[$k] = ($strip) ? stripslashes($v) : $v;
1445 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1446 // This is used before handing a request off to OAuthRequest::from_request.
1447 function common_remove_magic_from_request() {
1448 if(get_magic_quotes_gpc()) {
1449 $_POST=array_map('stripslashes',$_POST);
1450 $_GET=array_map('stripslashes',$_GET);
1454 function common_user_uri(&$user) {
1455 return common_local_url('userbyid', array('id' => $user->id));
1458 function common_notice_uri(&$notice) {
1459 return common_local_url('shownotice',
1460 array('notice' => $notice->id));
1463 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1465 function common_confirmation_code($bits) {
1466 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1467 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1468 $chars = ceil($bits/5);
1470 for ($i = 0; $i < $chars; $i++) {
1471 # XXX: convert to string and back
1472 $num = hexdec(common_good_rand(1));
1473 # XXX: randomness is too precious to throw away almost
1474 # 40% of the bits we get!
1475 $code .= $codechars[$num%32];
1480 # convert markup to HTML
1482 function common_markup_to_html($c) {
1483 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1484 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1485 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1486 return Markdown($c);
1489 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1490 $avatar = $profile->getAvatar($size);
1492 return common_avatar_display_url($avatar);
1494 return common_default_avatar($size);
1498 function common_profile_uri($profile) {
1502 $user = User::staticGet($profile->id);
1507 $remote = Remote_profile::staticGet($profile->id);
1509 return $remote->uri;
1511 # XXX: this is a very bad profile!
1515 function common_canonical_sms($sms) {
1517 preg_replace('/\D/', '', $sms);
1521 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1524 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1528 case E_USER_WARNING:
1529 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1533 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1537 # FIXME: show error page if we're on the Web
1538 /* Don't execute PHP internal error handler */
1542 function common_session_token() {
1543 common_ensure_session();
1544 if (!array_key_exists('token', $_SESSION)) {
1545 $_SESSION['token'] = common_good_rand(64);
1547 return $_SESSION['token'];
1550 function common_disfavor_form($notice) {
1551 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1553 'action' => common_local_url('disfavor')));
1554 common_hidden('token', common_session_token());
1555 common_hidden('notice', $notice->id);
1556 common_submit('disfavor-submit-' . $notice->id, '♥', 'disfavor');
1557 common_element_end('form');
1560 function common_favor_form($notice) {
1561 common_element_start('form', array('id' => 'favor-' . $notice->id,
1563 'action' => common_local_url('favor')));
1564 common_hidden('token', common_session_token());
1565 common_hidden('notice', $notice->id);
1566 common_submit('favor-submit-' . $notice->id, '♡', 'favor');
1567 common_element_end('form');
1570 function common_cache_key($extra) {
1571 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1574 function common_keyize($str) {
1575 $str = strtolower($str);
1576 $str = preg_replace('/\s/', '_', $str);