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/jquery.form.js')),
203 common_element('script', array('type' => 'text/javascript',
204 'src' => common_path('js/util.js')),
206 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
207 'href' => common_local_url('opensearch', array('type' => 'people')),
208 'title' => common_config('site', 'name').' People Search'));
210 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
211 'href' => common_local_url('opensearch', array('type' => 'notice')),
212 'title' => common_config('site', 'name').' Notice Search'));
216 call_user_func($callable, $data);
218 call_user_func($callable);
221 common_element_end('head');
222 common_element_start('body');
223 common_element_start('div', array('id' => 'wrap'));
224 common_element_start('div', array('id' => 'header'));
226 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
227 || file_exists(theme_file('logo.png')))
229 common_element_start('a', array('href' => common_local_url('public')));
230 common_element('img', array('src' => isset($config['site']['logo']) ?
231 ($config['site']['logo']) : theme_path('logo.png'),
232 'alt' => $config['site']['name'],
234 common_element_end('a');
236 common_element_start('p', array('id' => 'branding'));
237 common_element('a', array('href' => common_local_url('public')),
238 $config['site']['name']);
239 common_element_end('p');
242 common_element('h1', 'pagetitle', $pagetitle);
246 call_user_func($headercall, $data);
248 call_user_func($headercall);
251 common_element_end('div');
252 common_element_start('div', array('id' => 'content'));
255 function common_show_footer() {
257 common_element_end('div'); # content div
259 common_element_start('div', array('id' => 'footer'));
260 common_element_start('div', 'laconica');
261 if (common_config('site', 'broughtby')) {
262 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
264 $instr = _('**%%site.name%%** is a microblogging service. ');
266 $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);
267 $output = common_markup_to_html($instr);
269 common_element_end('div');
270 common_element('img', array('id' => 'cc',
271 'src' => $config['license']['image'],
272 'alt' => $config['license']['title']));
273 common_element_start('p');
274 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
275 common_element('a', array('class' => 'license',
277 'href' => $config['license']['url']),
278 $config['license']['title']);
279 common_text(_('. Contributors should be attributed by full name or nickname.'));
280 common_element_end('p');
281 common_element_end('div');
282 common_element_end('div');
283 common_element_end('body');
284 common_element_end('html');
288 function common_text($txt) {
293 function common_raw($xml) {
298 function common_nav_menu() {
299 $user = common_current_user();
300 common_element_start('ul', array('id' => 'nav'));
302 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
305 common_menu_item(common_local_url('peoplesearch'), _('Search'));
306 common_menu_item(common_local_url('tags'), _('Tags'));
308 common_menu_item(common_local_url('profilesettings'),
310 common_menu_item(common_local_url('invite'),
312 common_menu_item(common_local_url('logout'),
315 common_menu_item(common_local_url('login'), _('Login'));
316 if (!common_config('site', 'closed')) {
317 common_menu_item(common_local_url('register'), _('Register'));
319 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
321 common_element_end('ul');
324 function common_foot_menu() {
325 common_element_start('ul', array('id' => 'nav_sub'));
326 common_menu_item(common_local_url('doc', array('title' => 'help')),
328 common_menu_item(common_local_url('doc', array('title' => 'about')),
330 common_menu_item(common_local_url('doc', array('title' => 'faq')),
332 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
334 common_menu_item(common_local_url('doc', array('title' => 'source')),
336 common_menu_item(common_local_url('doc', array('title' => 'contact')),
338 common_element_end('ul');
341 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
344 $lattrs['class'] = 'current';
346 common_element_start('li', $lattrs);
347 $attrs['href'] = $url;
349 $attrs['title'] = $title;
351 common_element('a', $attrs, $text);
352 common_element_end('li');
355 function common_input($id, $label, $value=NULL,$instructions=NULL) {
356 common_element_start('p');
357 common_element('label', array('for' => $id), $label);
358 $attrs = array('name' => $id,
360 'class' => 'input_text',
363 $attrs['value'] = htmlspecialchars($value);
365 common_element('input', $attrs);
367 common_element('span', 'input_instructions', $instructions);
369 common_element_end('p');
372 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
374 common_element_start('p');
375 $attrs = array('name' => $id,
376 'type' => 'checkbox',
377 'class' => 'checkbox',
380 $attrs['value'] = htmlspecialchars($value);
383 $attrs['checked'] = 'checked';
385 common_element('input', $attrs);
388 common_element('span', 'checkbox_label', $label);
391 common_element('span', 'input_instructions', $instructions);
393 common_element_end('p');
396 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
397 common_element_start('p');
398 common_element('label', array('for' => $id), $label);
399 common_element_start('select', array('id' => $id, 'name' => $id));
401 common_element('option', array('value' => ''));
403 foreach ($content as $value => $option) {
404 if ($value == $selected) {
405 common_element('option', array('value' => $value, 'selected' => $value), $option);
407 common_element('option', array('value' => $value), $option);
410 common_element_end('select');
412 common_element('span', 'input_instructions', $instructions);
414 common_element_end('p');
416 function common_hidden($id, $value) {
417 common_element('input', array('name' => $id,
423 function common_password($id, $label, $instructions=NULL) {
424 common_element_start('p');
425 common_element('label', array('for' => $id), $label);
426 $attrs = array('name' => $id,
427 'type' => 'password',
428 'class' => 'password',
430 common_element('input', $attrs);
432 common_element('span', 'input_instructions', $instructions);
434 common_element_end('p');
437 function common_submit($id, $label, $cls='submit') {
439 common_element_start('p');
440 common_element('input', array('type' => 'submit',
445 common_element_end('p');
448 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
449 common_element_start('p');
450 common_element('label', array('for' => $id), $label);
451 common_element('textarea', array('rows' => 3,
455 ($content) ? $content : '');
457 common_element('span', 'input_instructions', $instructions);
459 common_element_end('p');
462 function common_timezone() {
463 if (common_logged_in()) {
464 $user = common_current_user();
465 if ($user->timezone) {
466 return $user->timezone;
471 return $config['site']['timezone'];
474 function common_language() {
475 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
477 $user_language = FALSE;
479 if (common_logged_in()) {
480 $user = common_current_user();
481 $user_language = $user->language;
484 if ($user_language) {
485 return $user_language;
486 } else if (!empty($httplang)) {
487 $language = client_prefered_language($httplang);
492 return $config['site']['language'];
495 # salted, hashed passwords are stored in the DB
497 function common_munge_password($password, $id) {
498 return md5($password . $id);
501 # check if a username exists and has matching password
502 function common_check_user($nickname, $password) {
503 # NEVER allow blank passwords, even if they match the DB
504 if (mb_strlen($password) == 0) {
507 $user = User::staticGet('nickname', $nickname);
508 if (is_null($user)) {
511 if (0 == strcmp(common_munge_password($password, $user->id),
520 # is the current user logged in?
521 function common_logged_in() {
522 return (!is_null(common_current_user()));
525 function common_have_session() {
526 return (0 != strcmp(session_id(), ''));
529 function common_ensure_session() {
530 if (!common_have_session()) {
535 # Three kinds of arguments:
540 function common_set_user($user) {
541 if (is_null($user) && common_have_session()) {
542 unset($_SESSION['userid']);
544 } else if (is_string($user)) {
546 $user = User::staticGet('nickname', $nickname);
547 } else if (!($user instanceof User)) {
552 common_ensure_session();
553 $_SESSION['userid'] = $user->id;
559 function common_set_cookie($key, $value, $expiration=0) {
560 $path = common_config('site', 'path');
561 $server = common_config('site', 'server');
563 if ($path && ($path != '/')) {
564 $cookiepath = '/' . $path . '/';
568 return setcookie($key,
575 define('REMEMBERME', 'rememberme');
576 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
578 function common_rememberme($user=NULL) {
580 $user = common_current_user();
582 common_debug('No current user to remember', __FILE__);
586 $rm = new Remember_me();
587 $rm->code = common_good_rand(16);
588 $rm->user_id = $user->id;
589 $result = $rm->insert();
591 common_log_db_error($rm, 'INSERT', __FILE__);
592 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
595 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
596 common_set_cookie(REMEMBERME,
597 implode(':', array($rm->user_id, $rm->code)),
598 time() + REMEMBERME_EXPIRY);
602 function common_remembered_user() {
605 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
607 list($id, $code) = explode(':', $packed);
609 $rm = Remember_me::staticGet($code);
610 if ($rm && ($rm->user_id == $id)) {
611 $user = User::staticGet($rm->user_id);
614 $result = $rm->delete();
616 common_log_db_error($rm, 'DELETE', __FILE__);
619 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
620 common_set_user($user->nickname);
621 common_real_login(false);
622 # We issue a new cookie, so they can log in
623 # automatically again after this session
624 common_rememberme($user);
633 # must be called with a valid user!
635 function common_forgetme() {
636 common_set_cookie(REMEMBERME, '', 0);
639 # who is the current user?
640 function common_current_user() {
641 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
642 common_ensure_session();
643 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
645 # note: this should cache
646 $user = User::staticGet($id);
650 # that didn't work; try to remember
651 $user = common_remembered_user();
653 common_debug("Got User " . $user->nickname);
654 common_debug("Faking session on remembered user");
655 $_SESSION['userid'] = $user->id;
660 # Logins that are 'remembered' aren't 'real' -- they're subject to
661 # cookie-stealing. So, we don't let them do certain things. New reg,
662 # OpenID, and password logins _are_ real.
664 function common_real_login($real=true) {
665 common_ensure_session();
666 $_SESSION['real_login'] = $real;
669 function common_is_real_login() {
670 return common_logged_in() && $_SESSION['real_login'];
673 # get canonical version of nickname for comparison
674 function common_canonical_nickname($nickname) {
675 # XXX: UTF-8 canonicalization (like combining chars)
676 return strtolower($nickname);
679 # get canonical version of email for comparison
680 function common_canonical_email($email) {
681 # XXX: canonicalize UTF-8
682 # XXX: lcase the domain part
686 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$_+!*();/?:~-]))');
688 function common_render_content($text, $notice) {
689 $r = htmlspecialchars($text);
691 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
692 $id = $notice->profile_id;
693 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
694 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
695 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
696 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
701 function common_tag_link($tag) {
702 $canonical = common_canonical_tag($tag);
703 $url = common_local_url('tag', array('tag' => $canonical));
704 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
707 function common_canonical_tag($tag) {
708 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
711 function common_at_link($sender_id, $nickname) {
712 $sender = Profile::staticGet($sender_id);
713 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
715 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
721 function common_relative_profile($sender, $nickname, $dt=NULL) {
722 # Try to find profiles this profile is subscribed to that have this nickname
723 $recipient = new Profile();
724 # XXX: use a join instead of a subquery
725 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
726 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
727 if ($recipient->find(TRUE)) {
728 # XXX: should probably differentiate between profiles with
729 # the same name by date of most recent update
732 # Try to find profiles that listen to this profile and that have this nickname
733 $recipient = new Profile();
734 # XXX: use a join instead of a subquery
735 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
736 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
737 if ($recipient->find(TRUE)) {
738 # XXX: should probably differentiate between profiles with
739 # the same name by date of most recent update
742 # If this is a local user, try to find a local user with that nickname.
743 $sender = User::staticGet($sender->id);
745 $recipient_user = User::staticGet('nickname', $nickname);
746 if ($recipient_user) {
747 return $recipient_user->getProfile();
750 # Otherwise, no links. @messages from local users to remote users,
751 # or from remote users to other remote users, are just
752 # outside our ability to make intelligent guesses about
756 // where should the avatar go for this user?
758 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
762 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
764 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
768 function common_avatar_path($filename) {
770 return INSTALLDIR . '/avatar/' . $filename;
773 function common_avatar_url($filename) {
774 return common_path('avatar/'.$filename);
777 function common_avatar_display_url($avatar) {
778 $server = common_config('avatar', 'server');
780 return 'http://'.$server.'/'.$avatar->filename;
786 function common_default_avatar($size) {
787 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
788 AVATAR_STREAM_SIZE => 'stream',
789 AVATAR_MINI_SIZE => 'mini');
790 return theme_path('default-avatar-'.$sizenames[$size].'.png');
793 function common_local_url($action, $args=NULL) {
795 if ($config['site']['fancy']) {
796 return common_fancy_url($action, $args);
798 return common_simple_url($action, $args);
802 function common_fancy_url($action, $args=NULL) {
803 switch (strtolower($action)) {
805 if ($args && isset($args['page'])) {
806 return common_path('?page=' . $args['page']);
808 return common_path('');
811 return common_path('rss');
813 return common_path('xrds');
815 if ($args && $args['type']) {
816 return common_path('opensearch/'.$args['type']);
818 return common_path('opensearch/people');
821 return common_path('doc/'.$args['title']);
827 return common_path('main/'.$action);
829 if ($args && $args['code']) {
830 return common_path('main/register/'.$args['code']);
832 return common_path('main/register');
834 case 'remotesubscribe':
835 if ($args && $args['nickname']) {
836 return common_path('main/remote?nickname=' . $args['nickname']);
838 return common_path('main/remote');
841 return common_path('main/openid');
842 case 'profilesettings':
843 return common_path('settings/profile');
844 case 'emailsettings':
845 return common_path('settings/email');
846 case 'openidsettings':
847 return common_path('settings/openid');
849 return common_path('settings/sms');
850 case 'twittersettings':
851 return common_path('settings/twitter');
853 if ($args && $args['replyto']) {
854 return common_path('notice/new?replyto='.$args['replyto']);
856 return common_path('notice/new');
859 return common_path('notice/'.$args['notice']);
861 if ($args && $args['notice']) {
862 return common_path('notice/delete/'.$args['notice']);
864 return common_path('notice/delete');
868 return common_path($args['nickname'].'/'.$action);
869 case 'subscriptions':
875 if ($args && isset($args['page'])) {
876 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
878 return common_path($args['nickname'].'/'.$action);
881 return common_path($args['nickname'].'/all/rss');
883 return common_path($args['nickname'].'/replies/rss');
885 return common_path($args['nickname'].'/rss');
887 if ($args && isset($args['page'])) {
888 return common_path($args['nickname'].'?page=' . $args['page']);
890 return common_path($args['nickname']);
892 case 'confirmaddress':
893 return common_path('main/confirmaddress/'.$args['code']);
895 return common_path('user/'.$args['id']);
896 case 'recoverpassword':
897 $path = 'main/recoverpassword';
899 $path .= '/' . $args['code'];
901 return common_path($path);
903 return common_path('settings/im');
905 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
907 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
908 case 'noticesearchrss':
909 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
910 case 'avatarbynickname':
911 return common_path($args['nickname'].'/avatar/'.$args['size']);
913 if (isset($args['tag']) && $args['tag']) {
914 $path = 'tag/' . $args['tag'];
919 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
921 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
923 return common_path('main/favor');
925 return common_path('main/disfavor');
926 case 'showfavorites':
927 if ($args && isset($args['page'])) {
928 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
930 return common_path($args['nickname'].'/favorites');
933 return common_simple_url($action, $args);
937 function common_simple_url($action, $args=NULL) {
939 /* XXX: pretty URLs */
942 foreach ($args as $key => $value) {
943 $extra .= "&${key}=${value}";
946 return common_path("index.php?action=${action}${extra}");
949 function common_path($relative) {
951 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
952 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
955 function common_date_string($dt) {
956 // XXX: do some sexy date formatting
957 // return date(DATE_RFC822, $dt);
962 if ($now < $t) { # that shouldn't happen!
963 return common_exact_date($dt);
964 } else if ($diff < 60) {
965 return _('a few seconds ago');
966 } else if ($diff < 92) {
967 return _('about a minute ago');
968 } else if ($diff < 3300) {
969 return sprintf(_('about %d minutes ago'), round($diff/60));
970 } else if ($diff < 5400) {
971 return _('about an hour ago');
972 } else if ($diff < 22 * 3600) {
973 return sprintf(_('about %d hours ago'), round($diff/3600));
974 } else if ($diff < 37 * 3600) {
975 return _('about a day ago');
976 } else if ($diff < 24 * 24 * 3600) {
977 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
978 } else if ($diff < 46 * 24 * 3600) {
979 return _('about a month ago');
980 } else if ($diff < 330 * 24 * 3600) {
981 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
982 } else if ($diff < 480 * 24 * 3600) {
983 return _('about a year ago');
985 return common_exact_date($dt);
989 function common_exact_date($dt) {
994 $_utc = new DateTimeZone('UTC');
995 $_siteTz = new DateTimeZone(common_timezone());
998 $dateStr = date('d F Y H:i:s', strtotime($dt));
999 $d = new DateTime($dateStr, $_utc);
1000 $d->setTimezone($_siteTz);
1001 return $d->format(DATE_RFC850);
1004 function common_date_w3dtf($dt) {
1005 $dateStr = date('d F Y H:i:s', strtotime($dt));
1006 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1007 $d->setTimezone(new DateTimeZone(common_timezone()));
1008 return $d->format(DATE_W3C);
1011 function common_date_rfc2822($dt) {
1012 $dateStr = date('d F Y H:i:s', strtotime($dt));
1013 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1014 $d->setTimezone(new DateTimeZone(common_timezone()));
1015 return $d->format('r');
1018 function common_date_iso8601($dt) {
1019 $dateStr = date('d F Y H:i:s', strtotime($dt));
1020 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1021 $d->setTimezone(new DateTimeZone(common_timezone()));
1022 return $d->format('c');
1025 function common_sql_now() {
1026 return strftime('%Y-%m-%d %H:%M:%S', time());
1029 function common_redirect($url, $code=307) {
1030 static $status = array(301 => "Moved Permanently",
1033 307 => "Temporary Redirect");
1034 header("Status: ${code} $status[$code]");
1035 header("Location: $url");
1037 common_start_xml('a',
1038 '-//W3C//DTD XHTML 1.0 Strict//EN',
1039 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1040 common_element('a', array('href' => $url), $url);
1045 function common_save_replies($notice) {
1046 # Alternative reply format
1048 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1051 # extract all @messages
1052 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1053 if (!$cnt && !$tname) {
1056 # XXX: is there another way to make an array copy?
1057 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1058 $sender = Profile::staticGet($notice->profile_id);
1059 # store replied only for first @ (what user/notice what the reply directed,
1060 # we assume first @ is it)
1061 for ($i=0; $i<count($names); $i++) {
1062 $nickname = $names[$i];
1063 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1067 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1068 $reply_for = $recipient;
1069 $recipient_notice = $reply_for->getCurrentNotice();
1070 if ($recipient_notice) {
1071 $orig = clone($notice);
1072 $notice->reply_to = $recipient_notice->id;
1073 $notice->update($orig);
1076 $reply = new Reply();
1077 $reply->notice_id = $notice->id;
1078 $reply->profile_id = $recipient->id;
1079 $id = $reply->insert();
1081 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1082 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1083 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1089 function common_broadcast_notice($notice, $remote=false) {
1091 // Check to see if notice should go to Twitter
1092 $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1095 if (!common_twitter_broadcast($notice, $flink)) {
1096 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1100 if (common_config('queue', 'enabled')) {
1102 return common_enqueue_notice($notice);
1104 return common_real_broadcast($notice, $remote);
1108 function common_twitter_broadcast($notice, $flink) {
1111 $fuser = $flink->getForeignUser();
1112 $twitter_user = $fuser->nickname;
1113 $twitter_password = $flink->credentials;
1114 $uri = 'http://www.twitter.com/statuses/update.json';
1115 $statustxt = $notice->content;
1118 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1119 CURLOPT_POST => true,
1120 CURLOPT_POSTFIELDS => array(
1121 'status' => $statustxt,
1122 'source' => $config['integration']['source']
1124 CURLOPT_RETURNTRANSFER => true,
1125 CURLOPT_FAILONERROR => true,
1126 CURLOPT_HEADER => false,
1127 CURLOPT_FOLLOWLOCATION => true,
1128 CURLOPT_USERAGENT => "Laconica",
1129 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1130 CURLOPT_TIMEOUT => 120
1133 $ch = curl_init($uri);
1134 curl_setopt_array($ch, $options);
1135 $data = curl_exec($ch);
1136 $errmsg = curl_error($ch);
1139 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1147 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1152 // Twitter should return a status
1153 $status = json_decode($data);
1156 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1164 # Stick the notice on the queue
1166 function common_enqueue_notice($notice) {
1167 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1168 $qi = new Queue_item();
1169 $qi->notice_id = $notice->id;
1170 $qi->transport = $transport;
1171 $qi->created = $notice->created;
1172 $result = $qi->insert();
1174 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1175 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1178 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1183 function common_dequeue_notice($notice) {
1184 $qi = Queue_item::staticGet($notice->id);
1186 $result = $qi->delete();
1188 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1189 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1192 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1199 function common_real_broadcast($notice, $remote=false) {
1202 # Make sure we have the OMB stuff
1203 require_once(INSTALLDIR.'/lib/omb.php');
1204 $success = omb_broadcast_remote_subscribers($notice);
1206 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1210 require_once(INSTALLDIR.'/lib/jabber.php');
1211 $success = jabber_broadcast_notice($notice);
1213 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1217 require_once(INSTALLDIR.'/lib/mail.php');
1218 $success = mail_broadcast_notice_sms($notice);
1220 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1224 $success = jabber_public_notice($notice);
1226 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1229 // XXX: broadcast notices to other IM
1233 function common_broadcast_profile($profile) {
1234 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1235 require_once(INSTALLDIR.'/lib/omb.php');
1236 omb_broadcast_profile($profile);
1237 // XXX: Other broadcasts...?
1241 function common_profile_url($nickname) {
1242 return common_local_url('showstream', array('nickname' => $nickname));
1245 # Don't call if nobody's logged in
1247 function common_notice_form($action=NULL, $content=NULL) {
1248 $user = common_current_user();
1249 assert(!is_null($user));
1250 common_element_start('form', array('id' => 'status_form',
1252 'action' => common_local_url('newnotice')));
1253 common_element_start('p');
1254 common_element('label', array('for' => 'status_textarea',
1255 'id' => 'status_label'),
1256 sprintf(_('What\'s up, %s?'), $user->nickname));
1257 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1258 common_element('textarea', array('id' => 'status_textarea',
1261 'name' => 'status_textarea'),
1262 ($content) ? $content : '');
1264 common_hidden('returnto', $action);
1266 common_element('input', array('id' => 'status_submit',
1267 'name' => 'status_submit',
1269 'value' => _('Send')));
1270 common_element_end('p');
1271 common_element_end('form');
1274 # Should make up a reasonable root URL
1276 function common_root_url() {
1277 return common_path('');
1280 # returns $bytes bytes of random data as a hexadecimal string
1281 # "good" here is a goal and not a guarantee
1283 function common_good_rand($bytes) {
1284 # XXX: use random.org...?
1285 if (file_exists('/dev/urandom')) {
1286 return common_urandom($bytes);
1287 } else { # FIXME: this is probably not good enough
1288 return common_mtrand($bytes);
1292 function common_urandom($bytes) {
1293 $h = fopen('/dev/urandom', 'rb');
1295 $src = fread($h, $bytes);
1298 for ($i = 0; $i < $bytes; $i++) {
1299 $enc .= sprintf("%02x", (ord($src[$i])));
1304 function common_mtrand($bytes) {
1306 for ($i = 0; $i < $bytes; $i++) {
1307 $enc .= sprintf("%02x", mt_rand(0, 255));
1312 function common_set_returnto($url) {
1313 common_ensure_session();
1314 $_SESSION['returnto'] = $url;
1317 function common_get_returnto() {
1318 common_ensure_session();
1319 return $_SESSION['returnto'];
1322 function common_timestamp() {
1323 return date('YmdHis');
1326 function common_ensure_syslog() {
1327 static $initialized = false;
1328 if (!$initialized) {
1330 openlog($config['syslog']['appname'], 0, LOG_USER);
1331 $initialized = true;
1335 function common_log($priority, $msg, $filename=NULL) {
1336 $logfile = common_config('site', 'logfile');
1338 $log = fopen($logfile, "a");
1340 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1341 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1342 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1343 fwrite($log, $output);
1347 common_ensure_syslog();
1348 syslog($priority, $msg);
1352 function common_debug($msg, $filename=NULL) {
1354 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1356 common_log(LOG_DEBUG, $msg);
1360 function common_log_db_error(&$object, $verb, $filename=NULL) {
1361 $objstr = common_log_objstring($object);
1362 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1363 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1366 function common_log_objstring(&$object) {
1367 if (is_null($object)) {
1370 $arr = $object->toArray();
1372 foreach ($arr as $k => $v) {
1373 $fields[] = "$k='$v'";
1375 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1379 function common_valid_http_url($url) {
1380 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1383 function common_valid_tag($tag) {
1384 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1385 return (Validate::email($matches[1]) ||
1386 preg_match('/^([\w-\.]+)$/', $matches[1]));
1391 # Does a little before-after block for next/prev page
1393 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1395 if ($have_before || $have_after) {
1396 common_element_start('div', array('id' => 'pagination'));
1397 common_element_start('ul', array('id' => 'nav_pagination'));
1401 $pargs = array('page' => $page-1);
1402 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1404 common_element_start('li', 'before');
1405 common_element('a', array('href' => common_local_url($action, $newargs)),
1407 common_element_end('li');
1411 $pargs = array('page' => $page+1);
1412 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1413 common_element_start('li', 'after');
1414 common_element('a', array('href' => common_local_url($action, $newargs)),
1416 common_element_end('li');
1419 if ($have_before || $have_after) {
1420 common_element_end('ul');
1421 common_element_end('div');
1425 /* Following functions are copied from MediaWiki GlobalFunctions.php
1426 * and written by Evan Prodromou. */
1428 function common_accept_to_prefs($accept, $def = '*/*') {
1429 # No arg means accept anything (per HTTP spec)
1431 return array($def => 1);
1436 $parts = explode(',', $accept);
1438 foreach($parts as $part) {
1439 # FIXME: doesn't deal with params like 'text/html; level=1'
1440 @list($value, $qpart) = explode(';', $part);
1442 if(!isset($qpart)) {
1444 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1445 $prefs[$value] = $match[1];
1452 function common_mime_type_match($type, $avail) {
1453 if(array_key_exists($type, $avail)) {
1456 $parts = explode('/', $type);
1457 if(array_key_exists($parts[0] . '/*', $avail)) {
1458 return $parts[0] . '/*';
1459 } elseif(array_key_exists('*/*', $avail)) {
1467 function common_negotiate_type($cprefs, $sprefs) {
1470 foreach(array_keys($sprefs) as $type) {
1471 $parts = explode('/', $type);
1472 if($parts[1] != '*') {
1473 $ckey = common_mime_type_match($type, $cprefs);
1475 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1480 foreach(array_keys($cprefs) as $type) {
1481 $parts = explode('/', $type);
1482 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1483 $skey = common_mime_type_match($type, $sprefs);
1485 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1491 $besttype = "text/html";
1493 foreach(array_keys($combine) as $type) {
1494 if($combine[$type] > $bestq) {
1496 $bestq = $combine[$type];
1503 function common_config($main, $sub) {
1505 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1508 function common_copy_args($from) {
1510 $strip = get_magic_quotes_gpc();
1511 foreach ($from as $k => $v) {
1512 $to[$k] = ($strip) ? stripslashes($v) : $v;
1517 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1518 // This is used before handing a request off to OAuthRequest::from_request.
1519 function common_remove_magic_from_request() {
1520 if(get_magic_quotes_gpc()) {
1521 $_POST=array_map('stripslashes',$_POST);
1522 $_GET=array_map('stripslashes',$_GET);
1526 function common_user_uri(&$user) {
1527 return common_local_url('userbyid', array('id' => $user->id));
1530 function common_notice_uri(&$notice) {
1531 return common_local_url('shownotice',
1532 array('notice' => $notice->id));
1535 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1537 function common_confirmation_code($bits) {
1538 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1539 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1540 $chars = ceil($bits/5);
1542 for ($i = 0; $i < $chars; $i++) {
1543 # XXX: convert to string and back
1544 $num = hexdec(common_good_rand(1));
1545 # XXX: randomness is too precious to throw away almost
1546 # 40% of the bits we get!
1547 $code .= $codechars[$num%32];
1552 # convert markup to HTML
1554 function common_markup_to_html($c) {
1555 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1556 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1557 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1558 return Markdown($c);
1561 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1562 $avatar = $profile->getAvatar($size);
1564 return common_avatar_display_url($avatar);
1566 return common_default_avatar($size);
1570 function common_profile_uri($profile) {
1574 $user = User::staticGet($profile->id);
1579 $remote = Remote_profile::staticGet($profile->id);
1581 return $remote->uri;
1583 # XXX: this is a very bad profile!
1587 function common_canonical_sms($sms) {
1589 preg_replace('/\D/', '', $sms);
1593 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1596 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1600 case E_USER_WARNING:
1601 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1605 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1609 # FIXME: show error page if we're on the Web
1610 /* Don't execute PHP internal error handler */
1614 function common_session_token() {
1615 common_ensure_session();
1616 if (!array_key_exists('token', $_SESSION)) {
1617 $_SESSION['token'] = common_good_rand(64);
1619 return $_SESSION['token'];
1622 function common_disfavor_form($notice) {
1623 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1625 'class' => 'disfavor',
1626 'action' => common_local_url('disfavor')));
1627 common_hidden('token', common_session_token());
1628 common_hidden('notice', $notice->id);
1629 common_element('input', array('type' => 'submit',
1630 'id' => 'disfavor-submit-' . $notice->id,
1631 'name' => 'disfavor-submit-' . $notice->id,
1632 'class' => 'disfavor',
1634 common_element_end('form');
1637 function common_favor_form($notice) {
1638 common_element_start('form', array('id' => 'favor-' . $notice->id,
1641 'action' => common_local_url('favor')));
1642 common_hidden('token', common_session_token());
1643 common_hidden('notice', $notice->id);
1644 common_element('input', array('type' => 'submit',
1645 'id' => 'favor-submit-' . $notice->id,
1646 'name' => 'favor-submit-' . $notice->id,
1649 common_element_end('form');
1652 function common_cache_key($extra) {
1653 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1656 function common_keyize($str) {
1657 $str = strtolower($str);
1658 $str = preg_replace('/\s/', '_', $str);