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 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
136 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
139 $language = common_language();
140 # So we don't have to make people install the gettext locales
141 putenv('LANGUAGE='.$language);
142 putenv('LANG='.$language);
143 $locale_set = setlocale(LC_ALL, $language . ".utf8",
145 $language . ".utf-8",
146 $language . ".UTF-8",
148 bindtextdomain("laconica", $config['site']['locale_path']);
149 bind_textdomain_codeset("laconica", "UTF-8");
150 textdomain("laconica");
152 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
154 # XXX: allow content negotiation for RDF, RSS, or XRDS
156 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
157 common_accept_to_prefs(PAGE_TYPE_PREFS));
160 common_user_error(_('This page is not available in a media type you accept'), 406);
164 header('Content-Type: '.$type);
166 common_start_xml('html',
167 '-//W3C//DTD XHTML 1.0 Strict//EN',
168 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
170 # FIXME: correct language for interface
172 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
173 'xml:lang' => $language,
174 'lang' => $language));
176 common_element_start('head');
177 common_element('title', NULL,
178 $pagetitle . " - " . $config['site']['name']);
179 common_element('link', array('rel' => 'stylesheet',
180 'type' => 'text/css',
181 'href' => theme_path('display.css'),
182 'media' => 'screen, projection, tv'));
183 foreach (array(6,7) as $ver) {
184 if (file_exists(theme_file('ie'.$ver.'.css'))) {
185 # Yes, IE people should be put in jail.
186 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
187 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
191 common_element('script', array('type' => 'text/javascript',
192 'src' => common_path('js/jquery.min.js')),
194 common_element('script', array('type' => 'text/javascript',
195 'src' => common_path('js/util.js')),
197 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
198 'href' => common_local_url('opensearch', array('type' => 'people')),
199 'title' => common_config('site', 'name').' People Search'));
201 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
202 'href' => common_local_url('opensearch', array('type' => 'notice')),
203 'title' => common_config('site', 'name').' Notice Search'));
207 call_user_func($callable, $data);
209 call_user_func($callable);
212 common_element_end('head');
213 common_element_start('body');
214 common_element_start('div', array('id' => 'wrap'));
215 common_element_start('div', array('id' => 'header'));
217 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
218 || file_exists(theme_file('logo.png')))
220 common_element_start('a', array('href' => common_local_url('public')));
221 common_element('img', array('src' => isset($config['site']['logo']) ?
222 ($config['site']['logo']) : theme_path('logo.png'),
223 'alt' => $config['site']['name'],
225 common_element_end('a');
227 common_element_start('p', array('id' => 'branding'));
228 common_element('a', array('href' => common_local_url('public')),
229 $config['site']['name']);
230 common_element_end('p');
233 common_element('h1', 'pagetitle', $pagetitle);
237 call_user_func($headercall, $data);
239 call_user_func($headercall);
242 common_element_end('div');
243 common_element_start('div', array('id' => 'content'));
246 function common_show_footer() {
248 common_element_end('div'); # content div
250 common_element_start('div', array('id' => 'footer'));
251 common_element_start('div', 'laconica');
252 if (common_config('site', 'broughtby')) {
253 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
255 $instr = _('**%%site.name%%** is a microblogging service. ');
257 $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);
258 $output = common_markup_to_html($instr);
260 common_element_end('div');
261 common_element('img', array('id' => 'cc',
262 'src' => $config['license']['image'],
263 'alt' => $config['license']['title']));
264 common_element_start('p');
265 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
266 common_element('a', array('class' => 'license',
268 'href' => $config['license']['url']),
269 $config['license']['title']);
270 common_text(_('. Contributors should be attributed by full name or nickname.'));
271 common_element_end('p');
272 common_element_end('div');
273 common_element_end('div');
274 common_element_end('body');
275 common_element_end('html');
279 function common_text($txt) {
284 function common_raw($xml) {
289 function common_nav_menu() {
290 $user = common_current_user();
291 common_element_start('ul', array('id' => 'nav'));
293 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
296 common_menu_item(common_local_url('peoplesearch'), _('Search'));
297 common_menu_item(common_local_url('tags'), _('Tags'));
299 common_menu_item(common_local_url('profilesettings'),
301 common_menu_item(common_local_url('logout'),
304 common_menu_item(common_local_url('login'), _('Login'));
305 if (!common_config('site', 'closed')) {
306 common_menu_item(common_local_url('register'), _('Register'));
308 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
310 common_element_end('ul');
313 function common_foot_menu() {
314 common_element_start('ul', array('id' => 'nav_sub'));
315 common_menu_item(common_local_url('doc', array('title' => 'help')),
317 common_menu_item(common_local_url('doc', array('title' => 'about')),
319 common_menu_item(common_local_url('doc', array('title' => 'faq')),
321 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
323 common_menu_item(common_local_url('doc', array('title' => 'source')),
325 common_menu_item(common_local_url('doc', array('title' => 'contact')),
327 common_element_end('ul');
330 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
333 $lattrs['class'] = 'current';
335 common_element_start('li', $lattrs);
336 $attrs['href'] = $url;
338 $attrs['title'] = $title;
340 common_element('a', $attrs, $text);
341 common_element_end('li');
344 function common_input($id, $label, $value=NULL,$instructions=NULL) {
345 common_element_start('p');
346 common_element('label', array('for' => $id), $label);
347 $attrs = array('name' => $id,
349 'class' => 'input_text',
352 $attrs['value'] = htmlspecialchars($value);
354 common_element('input', $attrs);
356 common_element('span', 'input_instructions', $instructions);
358 common_element_end('p');
361 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
363 common_element_start('p');
364 $attrs = array('name' => $id,
365 'type' => 'checkbox',
366 'class' => 'checkbox',
369 $attrs['value'] = htmlspecialchars($value);
372 $attrs['checked'] = 'checked';
374 common_element('input', $attrs);
377 common_element('span', 'checkbox_label', $label);
380 common_element('span', 'input_instructions', $instructions);
382 common_element_end('p');
385 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
386 common_element_start('p');
387 common_element('label', array('for' => $id), $label);
388 common_element_start('select', array('id' => $id, 'name' => $id));
390 common_element('option', array('value' => ''));
392 foreach ($content as $value => $option) {
393 if ($value == $selected) {
394 common_element('option', array('value' => $value, 'selected' => $value), $option);
396 common_element('option', array('value' => $value), $option);
399 common_element_end('select');
401 common_element('span', 'input_instructions', $instructions);
403 common_element_end('p');
405 function common_hidden($id, $value) {
406 common_element('input', array('name' => $id,
412 function common_password($id, $label, $instructions=NULL) {
413 common_element_start('p');
414 common_element('label', array('for' => $id), $label);
415 $attrs = array('name' => $id,
416 'type' => 'password',
417 'class' => 'password',
419 common_element('input', $attrs);
421 common_element('span', 'input_instructions', $instructions);
423 common_element_end('p');
426 function common_submit($id, $label) {
428 common_element_start('p');
429 common_element('input', array('type' => 'submit',
434 common_element_end('p');
437 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
438 common_element_start('p');
439 common_element('label', array('for' => $id), $label);
440 common_element('textarea', array('rows' => 3,
444 ($content) ? $content : '');
446 common_element('span', 'input_instructions', $instructions);
448 common_element_end('p');
451 function common_timezone() {
452 if (common_logged_in()) {
453 $user = common_current_user();
454 if ($user->timezone) {
455 return $user->timezone;
460 return $config['site']['timezone'];
463 function common_language() {
464 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
466 $user_language = FALSE;
468 if (common_logged_in()) {
469 $user = common_current_user();
470 $user_language = $user->language;
473 if ($user_language) {
474 return $user_language;
475 } else if (!empty($httplang)) {
476 $language = client_prefered_language($httplang);
481 return $config['site']['language'];
484 # salted, hashed passwords are stored in the DB
486 function common_munge_password($password, $id) {
487 return md5($password . $id);
490 # check if a username exists and has matching password
491 function common_check_user($nickname, $password) {
492 $user = User::staticGet('nickname', $nickname);
493 if (is_null($user)) {
496 if (0 == strcmp(common_munge_password($password, $user->id),
505 # is the current user logged in?
506 function common_logged_in() {
507 return (!is_null(common_current_user()));
510 function common_have_session() {
511 return (0 != strcmp(session_id(), ''));
514 function common_ensure_session() {
515 if (!common_have_session()) {
520 # Three kinds of arguments:
525 function common_set_user($user) {
526 if (is_null($user) && common_have_session()) {
527 unset($_SESSION['userid']);
529 } else if (is_string($user)) {
531 $user = User::staticGet('nickname', $nickname);
532 } else if (!($user instanceof User)) {
537 common_ensure_session();
538 $_SESSION['userid'] = $user->id;
544 function common_set_cookie($key, $value, $expiration=0) {
545 $path = common_config('site', 'path');
546 $server = common_config('site', 'server');
548 if ($path && ($path != '/')) {
549 $cookiepath = '/' . $path . '/';
553 return setcookie($key,
560 define('REMEMBERME', 'rememberme');
561 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
563 function common_rememberme($user=NULL) {
565 $user = common_current_user();
567 common_debug('No current user to remember', __FILE__);
571 $rm = new Remember_me();
572 $rm->code = common_good_rand(16);
573 $rm->user_id = $user->id;
574 $result = $rm->insert();
576 common_log_db_error($rm, 'INSERT', __FILE__);
577 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
580 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
581 common_set_cookie(REMEMBERME,
582 implode(':', array($rm->user_id, $rm->code)),
583 time() + REMEMBERME_EXPIRY);
587 function common_remembered_user() {
590 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
592 list($id, $code) = explode(':', $packed);
594 $rm = Remember_me::staticGet($code);
595 if ($rm && ($rm->user_id == $id)) {
596 $user = User::staticGet($rm->user_id);
599 $result = $rm->delete();
601 common_log_db_error($rm, 'DELETE', __FILE__);
604 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
605 common_set_user($user->nickname);
606 common_real_login(false);
607 # We issue a new cookie, so they can log in
608 # automatically again after this session
609 common_rememberme($user);
618 # must be called with a valid user!
620 function common_forgetme() {
621 common_set_cookie(REMEMBERME, '', 0);
624 # who is the current user?
625 function common_current_user() {
626 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
627 common_ensure_session();
628 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
630 # note: this should cache
631 $user = User::staticGet($id);
635 # that didn't work; try to remember
636 $user = common_remembered_user();
638 common_debug("Got User " . $user->nickname);
639 common_debug("Faking session on remembered user");
640 $_SESSION['userid'] = $user->id;
645 # Logins that are 'remembered' aren't 'real' -- they're subject to
646 # cookie-stealing. So, we don't let them do certain things. New reg,
647 # OpenID, and password logins _are_ real.
649 function common_real_login($real=true) {
650 common_ensure_session();
651 $_SESSION['real_login'] = $real;
654 function common_is_real_login() {
655 return common_logged_in() && $_SESSION['real_login'];
658 # get canonical version of nickname for comparison
659 function common_canonical_nickname($nickname) {
660 # XXX: UTF-8 canonicalization (like combining chars)
661 return strtolower($nickname);
664 # get canonical version of email for comparison
665 function common_canonical_email($email) {
666 # XXX: canonicalize UTF-8
667 # XXX: lcase the domain part
671 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$_+!*();/?:~-]))');
673 function common_render_content($text, $notice) {
674 $r = htmlspecialchars($text);
676 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
677 $id = $notice->profile_id;
678 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
679 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
680 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
681 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
686 function common_tag_link($tag) {
687 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
690 function common_at_link($sender_id, $nickname) {
691 $sender = Profile::staticGet($sender_id);
692 $recipient = common_relative_profile($sender, $nickname);
694 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
700 function common_relative_profile($sender, $nickname, $dt=NULL) {
701 # Try to find profiles this profile is subscribed to that have this nickname
702 $recipient = new Profile();
703 # XXX: use a join instead of a subquery
704 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
705 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
706 if ($recipient->find(TRUE)) {
707 # XXX: should probably differentiate between profiles with
708 # the same name by date of most recent update
711 # Try to find profiles that listen to this profile and that have this nickname
712 $recipient = new Profile();
713 # XXX: use a join instead of a subquery
714 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = 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 # If this is a local user, try to find a local user with that nickname.
722 $sender = User::staticGet($sender->id);
724 $recipient_user = User::staticGet('nickname', $nickname);
725 if ($recipient_user) {
726 return $recipient_user->getProfile();
729 # Otherwise, no links. @messages from local users to remote users,
730 # or from remote users to other remote users, are just
731 # outside our ability to make intelligent guesses about
735 // where should the avatar go for this user?
737 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
741 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
743 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
747 function common_avatar_path($filename) {
749 return INSTALLDIR . '/avatar/' . $filename;
752 function common_avatar_url($filename) {
753 return common_path('avatar/'.$filename);
756 function common_avatar_display_url($avatar) {
757 $server = common_config('avatar', 'server');
759 return 'http://'.$server.'/'.$avatar->filename;
765 function common_default_avatar($size) {
766 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
767 AVATAR_STREAM_SIZE => 'stream',
768 AVATAR_MINI_SIZE => 'mini');
769 return theme_path('default-avatar-'.$sizenames[$size].'.png');
772 function common_local_url($action, $args=NULL) {
774 if ($config['site']['fancy']) {
775 return common_fancy_url($action, $args);
777 return common_simple_url($action, $args);
781 function common_fancy_url($action, $args=NULL) {
782 switch (strtolower($action)) {
784 if ($args && isset($args['page'])) {
785 return common_path('?page=' . $args['page']);
787 return common_path('');
790 return common_path('rss');
792 return common_path('xrds');
794 if ($args && $args['type']) {
795 return common_path('opensearch/'.$args['type']);
797 return common_path('opensearch/people');
800 return common_path('doc/'.$args['title']);
806 return common_path('main/'.$action);
807 case 'remotesubscribe':
808 if ($args && $args['nickname']) {
809 return common_path('main/remote?nickname=' . $args['nickname']);
811 return common_path('main/remote');
814 return common_path('main/openid');
817 return common_path('settings/'.$action);
818 case 'profilesettings':
819 return common_path('settings/profile');
820 case 'emailsettings':
821 return common_path('settings/email');
822 case 'openidsettings':
823 return common_path('settings/openid');
825 return common_path('settings/sms');
827 if ($args && $args['replyto']) {
828 return common_path('notice/new?replyto='.$args['replyto']);
830 return common_path('notice/new');
833 return common_path('notice/'.$args['notice']);
835 if ($args && $args['notice']) {
836 return common_path('notice/delete/'.$args['notice']);
838 return common_path('notice/delete');
842 return common_path($args['nickname'].'/'.$action);
843 case 'subscriptions':
847 if ($args && isset($args['page'])) {
848 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
850 return common_path($args['nickname'].'/'.$action);
853 return common_path($args['nickname'].'/all/rss');
855 return common_path($args['nickname'].'/replies/rss');
857 return common_path($args['nickname'].'/rss');
859 if ($args && isset($args['page'])) {
860 return common_path($args['nickname'].'?page=' . $args['page']);
862 return common_path($args['nickname']);
864 case 'confirmaddress':
865 return common_path('main/confirmaddress/'.$args['code']);
867 return common_path('user/'.$args['id']);
868 case 'recoverpassword':
869 $path = 'main/recoverpassword';
871 $path .= '/' . $args['code'];
873 return common_path($path);
875 return common_path('settings/im');
877 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
879 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
880 case 'noticesearchrss':
881 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
882 case 'avatarbynickname':
883 return common_path($args['nickname'].'/avatar/'.$args['size']);
885 if (isset($args['tag']) && $args['tag']) {
886 $path = 'tag/' . $args['tag'];
891 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
893 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
895 return common_simple_url($action, $args);
899 function common_simple_url($action, $args=NULL) {
901 /* XXX: pretty URLs */
904 foreach ($args as $key => $value) {
905 $extra .= "&${key}=${value}";
908 return common_path("index.php?action=${action}${extra}");
911 function common_path($relative) {
913 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
914 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
917 function common_date_string($dt) {
918 // XXX: do some sexy date formatting
919 // return date(DATE_RFC822, $dt);
924 if ($now < $t) { # that shouldn't happen!
925 return common_exact_date($dt);
926 } else if ($diff < 60) {
927 return _('a few seconds ago');
928 } else if ($diff < 92) {
929 return _('about a minute ago');
930 } else if ($diff < 3300) {
931 return sprintf(_('about %d minutes ago'), round($diff/60));
932 } else if ($diff < 5400) {
933 return _('about an hour ago');
934 } else if ($diff < 22 * 3600) {
935 return sprintf(_('about %d hours ago'), round($diff/3600));
936 } else if ($diff < 37 * 3600) {
937 return _('about a day ago');
938 } else if ($diff < 24 * 24 * 3600) {
939 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
940 } else if ($diff < 46 * 24 * 3600) {
941 return _('about a month ago');
942 } else if ($diff < 330 * 24 * 3600) {
943 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
944 } else if ($diff < 480 * 24 * 3600) {
945 return _('about a year ago');
947 return common_exact_date($dt);
951 function common_exact_date($dt) {
956 $_utc = new DateTimeZone('UTC');
957 $_siteTz = new DateTimeZone(common_timezone());
960 $dateStr = date('d F Y H:i:s', strtotime($dt));
961 $d = new DateTime($dateStr, $_utc);
962 $d->setTimezone($_siteTz);
963 return $d->format(DATE_RFC850);
966 function common_date_w3dtf($dt) {
967 $dateStr = date('d F Y H:i:s', strtotime($dt));
968 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
969 $d->setTimezone(new DateTimeZone(common_timezone()));
970 return $d->format(DATE_W3C);
973 function common_date_rfc2822($dt) {
974 $dateStr = date('d F Y H:i:s', strtotime($dt));
975 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
976 $d->setTimezone(new DateTimeZone(common_timezone()));
977 return $d->format('r');
980 function common_date_iso8601($dt) {
981 $dateStr = date('d F Y H:i:s', strtotime($dt));
982 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
983 $d->setTimezone(new DateTimeZone(common_timezone()));
984 return $d->format('c');
987 function common_redirect($url, $code=307) {
988 static $status = array(301 => "Moved Permanently",
991 307 => "Temporary Redirect");
992 header("Status: ${code} $status[$code]");
993 header("Location: $url");
995 common_start_xml('a',
996 '-//W3C//DTD XHTML 1.0 Strict//EN',
997 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
998 common_element('a', array('href' => $url), $url);
1003 function common_save_replies($notice) {
1004 # Alternative reply format
1006 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1009 # extract all @messages
1010 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1011 if (!$cnt && !$tname) {
1014 # XXX: is there another way to make an array copy?
1015 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1016 $sender = Profile::staticGet($notice->profile_id);
1017 # store replied only for first @ (what user/notice what the reply directed,
1018 # we assume first @ is it)
1019 for ($i=0; $i<count($names); $i++) {
1020 $nickname = $names[$i];
1021 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1025 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1026 $reply_for = $recipient;
1027 $recipient_notice = $reply_for->getCurrentNotice();
1028 if ($recipient_notice) {
1029 $orig = clone($notice);
1030 $notice->reply_to = $recipient_notice->id;
1031 $notice->update($orig);
1034 $reply = new Reply();
1035 $reply->notice_id = $notice->id;
1036 $reply->profile_id = $recipient->id;
1037 $id = $reply->insert();
1039 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1040 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1041 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1047 function common_broadcast_notice($notice, $remote=false) {
1048 if (common_config('queue', 'enabled')) {
1050 return common_enqueue_notice($notice);
1052 return common_real_broadcast($notice, $remote);
1056 # Stick the notice on the queue
1058 function common_enqueue_notice($notice) {
1059 $qi = new Queue_item();
1060 $qi->notice_id = $notice->id;
1061 $qi->created = $notice->created;
1062 $result = $qi->insert();
1064 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1065 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1068 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1072 function common_dequeue_notice($notice) {
1073 $qi = Queue_item::staticGet($notice->id);
1075 $result = $qi->delete();
1077 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1078 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1081 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1088 function common_real_broadcast($notice, $remote=false) {
1091 # Make sure we have the OMB stuff
1092 require_once(INSTALLDIR.'/lib/omb.php');
1093 $success = omb_broadcast_remote_subscribers($notice);
1095 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1099 require_once(INSTALLDIR.'/lib/jabber.php');
1100 $success = jabber_broadcast_notice($notice);
1102 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1106 require_once(INSTALLDIR.'/lib/mail.php');
1107 $success = mail_broadcast_notice_sms($notice);
1109 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1112 // XXX: broadcast notices to other IM
1116 function common_broadcast_profile($profile) {
1117 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1118 require_once(INSTALLDIR.'/lib/omb.php');
1119 omb_broadcast_profile($profile);
1120 // XXX: Other broadcasts...?
1124 function common_profile_url($nickname) {
1125 return common_local_url('showstream', array('nickname' => $nickname));
1128 # Don't call if nobody's logged in
1130 function common_notice_form($action=NULL, $content=NULL) {
1131 $user = common_current_user();
1132 assert(!is_null($user));
1133 common_element_start('form', array('id' => 'status_form',
1135 'action' => common_local_url('newnotice')));
1136 common_element_start('p');
1137 common_element('label', array('for' => 'status_textarea',
1138 'id' => 'status_label'),
1139 sprintf(_('What\'s up, %s?'), $user->nickname));
1140 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1141 common_element('textarea', array('id' => 'status_textarea',
1144 'name' => 'status_textarea'),
1145 ($content) ? $content : '');
1147 common_hidden('returnto', $action);
1149 common_element('input', array('id' => 'status_submit',
1150 'name' => 'status_submit',
1152 'value' => _('Send')));
1153 common_element_end('p');
1154 common_element_end('form');
1157 # Should make up a reasonable root URL
1159 function common_root_url() {
1160 return common_path('');
1163 # returns $bytes bytes of random data as a hexadecimal string
1164 # "good" here is a goal and not a guarantee
1166 function common_good_rand($bytes) {
1167 # XXX: use random.org...?
1168 if (file_exists('/dev/urandom')) {
1169 return common_urandom($bytes);
1170 } else { # FIXME: this is probably not good enough
1171 return common_mtrand($bytes);
1175 function common_urandom($bytes) {
1176 $h = fopen('/dev/urandom', 'rb');
1178 $src = fread($h, $bytes);
1181 for ($i = 0; $i < $bytes; $i++) {
1182 $enc .= sprintf("%02x", (ord($src[$i])));
1187 function common_mtrand($bytes) {
1189 for ($i = 0; $i < $bytes; $i++) {
1190 $enc .= sprintf("%02x", mt_rand(0, 255));
1195 function common_set_returnto($url) {
1196 common_ensure_session();
1197 $_SESSION['returnto'] = $url;
1200 function common_get_returnto() {
1201 common_ensure_session();
1202 return $_SESSION['returnto'];
1205 function common_timestamp() {
1206 return date('YmdHis');
1209 function common_ensure_syslog() {
1210 static $initialized = false;
1211 if (!$initialized) {
1213 openlog($config['syslog']['appname'], 0, LOG_USER);
1214 $initialized = true;
1218 function common_log($priority, $msg, $filename=NULL) {
1219 $logfile = common_config('site', 'logfile');
1221 $log = fopen($logfile, "a");
1223 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1224 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1225 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1226 fwrite($log, $output);
1230 common_ensure_syslog();
1231 syslog($priority, $msg);
1235 function common_debug($msg, $filename=NULL) {
1237 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1239 common_log(LOG_DEBUG, $msg);
1243 function common_log_db_error(&$object, $verb, $filename=NULL) {
1244 $objstr = common_log_objstring($object);
1245 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1246 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1249 function common_log_objstring(&$object) {
1250 if (is_null($object)) {
1253 $arr = $object->toArray();
1255 foreach ($arr as $k => $v) {
1256 $fields[] = "$k='$v'";
1258 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1262 function common_valid_http_url($url) {
1263 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1266 function common_valid_tag($tag) {
1267 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1268 return (Validate::email($matches[1]) ||
1269 preg_match('/^([\w-\.]+)$/', $matches[1]));
1274 # Does a little before-after block for next/prev page
1276 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1278 if ($have_before || $have_after) {
1279 common_element_start('div', array('id' => 'pagination'));
1280 common_element_start('ul', array('id' => 'nav_pagination'));
1284 $pargs = array('page' => $page-1);
1285 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1287 common_element_start('li', 'before');
1288 common_element('a', array('href' => common_local_url($action, $newargs)),
1290 common_element_end('li');
1294 $pargs = array('page' => $page+1);
1295 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1296 common_element_start('li', 'after');
1297 common_element('a', array('href' => common_local_url($action, $newargs)),
1299 common_element_end('li');
1302 if ($have_before || $have_after) {
1303 common_element_end('ul');
1304 common_element_end('div');
1308 /* Following functions are copied from MediaWiki GlobalFunctions.php
1309 * and written by Evan Prodromou. */
1311 function common_accept_to_prefs($accept, $def = '*/*') {
1312 # No arg means accept anything (per HTTP spec)
1314 return array($def => 1);
1319 $parts = explode(',', $accept);
1321 foreach($parts as $part) {
1322 # FIXME: doesn't deal with params like 'text/html; level=1'
1323 @list($value, $qpart) = explode(';', $part);
1325 if(!isset($qpart)) {
1327 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1328 $prefs[$value] = $match[1];
1335 function common_mime_type_match($type, $avail) {
1336 if(array_key_exists($type, $avail)) {
1339 $parts = explode('/', $type);
1340 if(array_key_exists($parts[0] . '/*', $avail)) {
1341 return $parts[0] . '/*';
1342 } elseif(array_key_exists('*/*', $avail)) {
1350 function common_negotiate_type($cprefs, $sprefs) {
1353 foreach(array_keys($sprefs) as $type) {
1354 $parts = explode('/', $type);
1355 if($parts[1] != '*') {
1356 $ckey = common_mime_type_match($type, $cprefs);
1358 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1363 foreach(array_keys($cprefs) as $type) {
1364 $parts = explode('/', $type);
1365 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1366 $skey = common_mime_type_match($type, $sprefs);
1368 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1374 $besttype = "text/html";
1376 foreach(array_keys($combine) as $type) {
1377 if($combine[$type] > $bestq) {
1379 $bestq = $combine[$type];
1386 function common_config($main, $sub) {
1388 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1391 function common_copy_args($from) {
1393 $strip = get_magic_quotes_gpc();
1394 foreach ($from as $k => $v) {
1395 $to[$k] = ($strip) ? stripslashes($v) : $v;
1400 function common_user_uri(&$user) {
1401 return common_local_url('userbyid', array('id' => $user->id));
1404 function common_notice_uri(&$notice) {
1405 return common_local_url('shownotice',
1406 array('notice' => $notice->id));
1409 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1411 function common_confirmation_code($bits) {
1412 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1413 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1414 $chars = ceil($bits/5);
1416 for ($i = 0; $i < $chars; $i++) {
1417 # XXX: convert to string and back
1418 $num = hexdec(common_good_rand(1));
1419 # XXX: randomness is too precious to throw away almost
1420 # 40% of the bits we get!
1421 $code .= $codechars[$num%32];
1426 # convert markup to HTML
1428 function common_markup_to_html($c) {
1429 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1430 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1431 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1432 return Markdown($c);
1435 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1436 $avatar = $profile->getAvatar($size);
1438 return common_avatar_display_url($avatar);
1440 return common_default_avatar($size);
1444 function common_profile_uri($profile) {
1448 $user = User::staticGet($profile->id);
1453 $remote = Remote_profile::staticGet($profile->id);
1455 return $remote->uri;
1457 # XXX: this is a very bad profile!
1461 function common_canonical_sms($sms) {
1463 preg_replace('/\D/', '', $sms);