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 $language = common_language();
136 # So we don't have to make people install the gettext locales
137 putenv('LANGUAGE='.$language);
138 putenv('LANG='.$language);
139 $locale_set = setlocale(LC_ALL, $language . ".utf8",
141 $language . ".utf-8",
142 $language . ".UTF-8",
144 bindtextdomain("laconica", common_config('site','locale_path'));
145 bind_textdomain_codeset("laconica", "UTF-8");
146 textdomain("laconica");
147 setlocale(LC_CTYPE, 'C');
150 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
152 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
155 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
157 # XXX: allow content negotiation for RDF, RSS, or XRDS
159 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
160 common_accept_to_prefs(PAGE_TYPE_PREFS));
163 common_user_error(_('This page is not available in a media type you accept'), 406);
167 header('Content-Type: '.$type);
169 common_start_xml('html',
170 '-//W3C//DTD XHTML 1.0 Strict//EN',
171 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
173 # FIXME: correct language for interface
175 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
176 'xml:lang' => $language,
177 'lang' => $language));
179 common_element_start('head');
180 common_element('title', NULL,
181 $pagetitle . " - " . $config['site']['name']);
182 common_element('link', array('rel' => 'stylesheet',
183 'type' => 'text/css',
184 'href' => theme_path('display.css'),
185 'media' => 'screen, projection, tv'));
186 foreach (array(6,7) as $ver) {
187 if (file_exists(theme_file('ie'.$ver.'.css'))) {
188 # Yes, IE people should be put in jail.
189 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
190 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
194 common_element('script', array('type' => 'text/javascript',
195 'src' => common_path('js/jquery.min.js')),
197 common_element('script', array('type' => 'text/javascript',
198 'src' => common_path('js/util.js')),
200 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
201 'href' => common_local_url('opensearch', array('type' => 'people')),
202 'title' => common_config('site', 'name').' People Search'));
204 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
205 'href' => common_local_url('opensearch', array('type' => 'notice')),
206 'title' => common_config('site', 'name').' Notice Search'));
210 call_user_func($callable, $data);
212 call_user_func($callable);
215 common_element_end('head');
216 common_element_start('body');
217 common_element_start('div', array('id' => 'wrap'));
218 common_element_start('div', array('id' => 'header'));
220 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
221 || file_exists(theme_file('logo.png')))
223 common_element_start('a', array('href' => common_local_url('public')));
224 common_element('img', array('src' => isset($config['site']['logo']) ?
225 ($config['site']['logo']) : theme_path('logo.png'),
226 'alt' => $config['site']['name'],
228 common_element_end('a');
230 common_element_start('p', array('id' => 'branding'));
231 common_element('a', array('href' => common_local_url('public')),
232 $config['site']['name']);
233 common_element_end('p');
236 common_element('h1', 'pagetitle', $pagetitle);
240 call_user_func($headercall, $data);
242 call_user_func($headercall);
245 common_element_end('div');
246 common_element_start('div', array('id' => 'content'));
249 function common_show_footer() {
251 common_element_end('div'); # content div
253 common_element_start('div', array('id' => 'footer'));
254 common_element_start('div', 'laconica');
255 if (common_config('site', 'broughtby')) {
256 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
258 $instr = _('**%%site.name%%** is a microblogging service. ');
260 $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);
261 $output = common_markup_to_html($instr);
263 common_element_end('div');
264 common_element('img', array('id' => 'cc',
265 'src' => $config['license']['image'],
266 'alt' => $config['license']['title']));
267 common_element_start('p');
268 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
269 common_element('a', array('class' => 'license',
271 'href' => $config['license']['url']),
272 $config['license']['title']);
273 common_text(_('. Contributors should be attributed by full name or nickname.'));
274 common_element_end('p');
275 common_element_end('div');
276 common_element_end('div');
277 common_element_end('body');
278 common_element_end('html');
282 function common_text($txt) {
287 function common_raw($xml) {
292 function common_nav_menu() {
293 $user = common_current_user();
294 common_element_start('ul', array('id' => 'nav'));
296 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
299 common_menu_item(common_local_url('peoplesearch'), _('Search'));
300 common_menu_item(common_local_url('tags'), _('Tags'));
302 common_menu_item(common_local_url('profilesettings'),
304 common_menu_item(common_local_url('logout'),
307 common_menu_item(common_local_url('login'), _('Login'));
308 if (!common_config('site', 'closed')) {
309 common_menu_item(common_local_url('register'), _('Register'));
311 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
313 common_element_end('ul');
316 function common_foot_menu() {
317 common_element_start('ul', array('id' => 'nav_sub'));
318 common_menu_item(common_local_url('doc', array('title' => 'help')),
320 common_menu_item(common_local_url('doc', array('title' => 'about')),
322 common_menu_item(common_local_url('doc', array('title' => 'faq')),
324 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
326 common_menu_item(common_local_url('doc', array('title' => 'source')),
328 common_menu_item(common_local_url('doc', array('title' => 'contact')),
330 common_element_end('ul');
333 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
336 $lattrs['class'] = 'current';
338 common_element_start('li', $lattrs);
339 $attrs['href'] = $url;
341 $attrs['title'] = $title;
343 common_element('a', $attrs, $text);
344 common_element_end('li');
347 function common_input($id, $label, $value=NULL,$instructions=NULL) {
348 common_element_start('p');
349 common_element('label', array('for' => $id), $label);
350 $attrs = array('name' => $id,
352 'class' => 'input_text',
355 $attrs['value'] = htmlspecialchars($value);
357 common_element('input', $attrs);
359 common_element('span', 'input_instructions', $instructions);
361 common_element_end('p');
364 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
366 common_element_start('p');
367 $attrs = array('name' => $id,
368 'type' => 'checkbox',
369 'class' => 'checkbox',
372 $attrs['value'] = htmlspecialchars($value);
375 $attrs['checked'] = 'checked';
377 common_element('input', $attrs);
380 common_element('span', 'checkbox_label', $label);
383 common_element('span', 'input_instructions', $instructions);
385 common_element_end('p');
388 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
389 common_element_start('p');
390 common_element('label', array('for' => $id), $label);
391 common_element_start('select', array('id' => $id, 'name' => $id));
393 common_element('option', array('value' => ''));
395 foreach ($content as $value => $option) {
396 if ($value == $selected) {
397 common_element('option', array('value' => $value, 'selected' => $value), $option);
399 common_element('option', array('value' => $value), $option);
402 common_element_end('select');
404 common_element('span', 'input_instructions', $instructions);
406 common_element_end('p');
408 function common_hidden($id, $value) {
409 common_element('input', array('name' => $id,
415 function common_password($id, $label, $instructions=NULL) {
416 common_element_start('p');
417 common_element('label', array('for' => $id), $label);
418 $attrs = array('name' => $id,
419 'type' => 'password',
420 'class' => 'password',
422 common_element('input', $attrs);
424 common_element('span', 'input_instructions', $instructions);
426 common_element_end('p');
429 function common_submit($id, $label) {
431 common_element_start('p');
432 common_element('input', array('type' => 'submit',
437 common_element_end('p');
440 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
441 common_element_start('p');
442 common_element('label', array('for' => $id), $label);
443 common_element('textarea', array('rows' => 3,
447 ($content) ? $content : '');
449 common_element('span', 'input_instructions', $instructions);
451 common_element_end('p');
454 function common_timezone() {
455 if (common_logged_in()) {
456 $user = common_current_user();
457 if ($user->timezone) {
458 return $user->timezone;
463 return $config['site']['timezone'];
466 function common_language() {
467 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
469 $user_language = FALSE;
471 if (common_logged_in()) {
472 $user = common_current_user();
473 $user_language = $user->language;
476 if ($user_language) {
477 return $user_language;
478 } else if (!empty($httplang)) {
479 $language = client_prefered_language($httplang);
484 return $config['site']['language'];
487 # salted, hashed passwords are stored in the DB
489 function common_munge_password($password, $id) {
490 return md5($password . $id);
493 # check if a username exists and has matching password
494 function common_check_user($nickname, $password) {
495 $user = User::staticGet('nickname', $nickname);
496 if (is_null($user)) {
499 if (0 == strcmp(common_munge_password($password, $user->id),
508 # is the current user logged in?
509 function common_logged_in() {
510 return (!is_null(common_current_user()));
513 function common_have_session() {
514 return (0 != strcmp(session_id(), ''));
517 function common_ensure_session() {
518 if (!common_have_session()) {
523 # Three kinds of arguments:
528 function common_set_user($user) {
529 if (is_null($user) && common_have_session()) {
530 unset($_SESSION['userid']);
532 } else if (is_string($user)) {
534 $user = User::staticGet('nickname', $nickname);
535 } else if (!($user instanceof User)) {
540 common_ensure_session();
541 $_SESSION['userid'] = $user->id;
547 function common_set_cookie($key, $value, $expiration=0) {
548 $path = common_config('site', 'path');
549 $server = common_config('site', 'server');
551 if ($path && ($path != '/')) {
552 $cookiepath = '/' . $path . '/';
556 return setcookie($key,
563 define('REMEMBERME', 'rememberme');
564 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
566 function common_rememberme($user=NULL) {
568 $user = common_current_user();
570 common_debug('No current user to remember', __FILE__);
574 $rm = new Remember_me();
575 $rm->code = common_good_rand(16);
576 $rm->user_id = $user->id;
577 $result = $rm->insert();
579 common_log_db_error($rm, 'INSERT', __FILE__);
580 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
583 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
584 common_set_cookie(REMEMBERME,
585 implode(':', array($rm->user_id, $rm->code)),
586 time() + REMEMBERME_EXPIRY);
590 function common_remembered_user() {
593 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
595 list($id, $code) = explode(':', $packed);
597 $rm = Remember_me::staticGet($code);
598 if ($rm && ($rm->user_id == $id)) {
599 $user = User::staticGet($rm->user_id);
602 $result = $rm->delete();
604 common_log_db_error($rm, 'DELETE', __FILE__);
607 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
608 common_set_user($user->nickname);
609 common_real_login(false);
610 # We issue a new cookie, so they can log in
611 # automatically again after this session
612 common_rememberme($user);
621 # must be called with a valid user!
623 function common_forgetme() {
624 common_set_cookie(REMEMBERME, '', 0);
627 # who is the current user?
628 function common_current_user() {
629 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
630 common_ensure_session();
631 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
633 # note: this should cache
634 $user = User::staticGet($id);
638 # that didn't work; try to remember
639 $user = common_remembered_user();
641 common_debug("Got User " . $user->nickname);
642 common_debug("Faking session on remembered user");
643 $_SESSION['userid'] = $user->id;
648 # Logins that are 'remembered' aren't 'real' -- they're subject to
649 # cookie-stealing. So, we don't let them do certain things. New reg,
650 # OpenID, and password logins _are_ real.
652 function common_real_login($real=true) {
653 common_ensure_session();
654 $_SESSION['real_login'] = $real;
657 function common_is_real_login() {
658 return common_logged_in() && $_SESSION['real_login'];
661 # get canonical version of nickname for comparison
662 function common_canonical_nickname($nickname) {
663 # XXX: UTF-8 canonicalization (like combining chars)
664 return strtolower($nickname);
667 # get canonical version of email for comparison
668 function common_canonical_email($email) {
669 # XXX: canonicalize UTF-8
670 # XXX: lcase the domain part
674 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$_+!*();/?:~-]))');
676 function common_render_content($text, $notice) {
677 $r = htmlspecialchars($text);
679 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
680 $id = $notice->profile_id;
681 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
682 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
683 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
684 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
689 function common_tag_link($tag) {
690 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
693 function common_at_link($sender_id, $nickname) {
694 $sender = Profile::staticGet($sender_id);
695 $recipient = common_relative_profile($sender, $nickname);
697 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
703 function common_relative_profile($sender, $nickname, $dt=NULL) {
704 # Try to find profiles this profile is subscribed to that have this nickname
705 $recipient = new Profile();
706 # XXX: use a join instead of a subquery
707 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
708 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
709 if ($recipient->find(TRUE)) {
710 # XXX: should probably differentiate between profiles with
711 # the same name by date of most recent update
714 # Try to find profiles that listen to this profile and that have this nickname
715 $recipient = new Profile();
716 # XXX: use a join instead of a subquery
717 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
718 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
719 if ($recipient->find(TRUE)) {
720 # XXX: should probably differentiate between profiles with
721 # the same name by date of most recent update
724 # If this is a local user, try to find a local user with that nickname.
725 $sender = User::staticGet($sender->id);
727 $recipient_user = User::staticGet('nickname', $nickname);
728 if ($recipient_user) {
729 return $recipient_user->getProfile();
732 # Otherwise, no links. @messages from local users to remote users,
733 # or from remote users to other remote users, are just
734 # outside our ability to make intelligent guesses about
738 // where should the avatar go for this user?
740 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
744 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
746 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
750 function common_avatar_path($filename) {
752 return INSTALLDIR . '/avatar/' . $filename;
755 function common_avatar_url($filename) {
756 return common_path('avatar/'.$filename);
759 function common_avatar_display_url($avatar) {
760 $server = common_config('avatar', 'server');
762 return 'http://'.$server.'/'.$avatar->filename;
768 function common_default_avatar($size) {
769 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
770 AVATAR_STREAM_SIZE => 'stream',
771 AVATAR_MINI_SIZE => 'mini');
772 return theme_path('default-avatar-'.$sizenames[$size].'.png');
775 function common_local_url($action, $args=NULL) {
777 if ($config['site']['fancy']) {
778 return common_fancy_url($action, $args);
780 return common_simple_url($action, $args);
784 function common_fancy_url($action, $args=NULL) {
785 switch (strtolower($action)) {
787 if ($args && isset($args['page'])) {
788 return common_path('?page=' . $args['page']);
790 return common_path('');
793 return common_path('rss');
795 return common_path('xrds');
797 if ($args && $args['type']) {
798 return common_path('opensearch/'.$args['type']);
800 return common_path('opensearch/people');
803 return common_path('doc/'.$args['title']);
809 return common_path('main/'.$action);
810 case 'remotesubscribe':
811 if ($args && $args['nickname']) {
812 return common_path('main/remote?nickname=' . $args['nickname']);
814 return common_path('main/remote');
817 return common_path('main/openid');
820 return common_path('settings/'.$action);
821 case 'profilesettings':
822 return common_path('settings/profile');
823 case 'emailsettings':
824 return common_path('settings/email');
825 case 'openidsettings':
826 return common_path('settings/openid');
828 return common_path('settings/sms');
830 if ($args && $args['replyto']) {
831 return common_path('notice/new?replyto='.$args['replyto']);
833 return common_path('notice/new');
836 return common_path('notice/'.$args['notice']);
838 if ($args && $args['notice']) {
839 return common_path('notice/delete/'.$args['notice']);
841 return common_path('notice/delete');
845 return common_path($args['nickname'].'/'.$action);
846 case 'subscriptions':
850 if ($args && isset($args['page'])) {
851 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
853 return common_path($args['nickname'].'/'.$action);
856 return common_path($args['nickname'].'/all/rss');
858 return common_path($args['nickname'].'/replies/rss');
860 return common_path($args['nickname'].'/rss');
862 if ($args && isset($args['page'])) {
863 return common_path($args['nickname'].'?page=' . $args['page']);
865 return common_path($args['nickname']);
867 case 'confirmaddress':
868 return common_path('main/confirmaddress/'.$args['code']);
870 return common_path('user/'.$args['id']);
871 case 'recoverpassword':
872 $path = 'main/recoverpassword';
874 $path .= '/' . $args['code'];
876 return common_path($path);
878 return common_path('settings/im');
880 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
882 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
883 case 'noticesearchrss':
884 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
885 case 'avatarbynickname':
886 return common_path($args['nickname'].'/avatar/'.$args['size']);
888 if (isset($args['tag']) && $args['tag']) {
889 $path = 'tag/' . $args['tag'];
894 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
896 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
898 return common_simple_url($action, $args);
902 function common_simple_url($action, $args=NULL) {
904 /* XXX: pretty URLs */
907 foreach ($args as $key => $value) {
908 $extra .= "&${key}=${value}";
911 return common_path("index.php?action=${action}${extra}");
914 function common_path($relative) {
916 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
917 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
920 function common_date_string($dt) {
921 // XXX: do some sexy date formatting
922 // return date(DATE_RFC822, $dt);
927 if ($now < $t) { # that shouldn't happen!
928 return common_exact_date($dt);
929 } else if ($diff < 60) {
930 return _('a few seconds ago');
931 } else if ($diff < 92) {
932 return _('about a minute ago');
933 } else if ($diff < 3300) {
934 return sprintf(_('about %d minutes ago'), round($diff/60));
935 } else if ($diff < 5400) {
936 return _('about an hour ago');
937 } else if ($diff < 22 * 3600) {
938 return sprintf(_('about %d hours ago'), round($diff/3600));
939 } else if ($diff < 37 * 3600) {
940 return _('about a day ago');
941 } else if ($diff < 24 * 24 * 3600) {
942 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
943 } else if ($diff < 46 * 24 * 3600) {
944 return _('about a month ago');
945 } else if ($diff < 330 * 24 * 3600) {
946 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
947 } else if ($diff < 480 * 24 * 3600) {
948 return _('about a year ago');
950 return common_exact_date($dt);
954 function common_exact_date($dt) {
959 $_utc = new DateTimeZone('UTC');
960 $_siteTz = new DateTimeZone(common_timezone());
963 $dateStr = date('d F Y H:i:s', strtotime($dt));
964 $d = new DateTime($dateStr, $_utc);
965 $d->setTimezone($_siteTz);
966 return $d->format(DATE_RFC850);
969 function common_date_w3dtf($dt) {
970 $dateStr = date('d F Y H:i:s', strtotime($dt));
971 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
972 $d->setTimezone(new DateTimeZone(common_timezone()));
973 return $d->format(DATE_W3C);
976 function common_date_rfc2822($dt) {
977 $dateStr = date('d F Y H:i:s', strtotime($dt));
978 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
979 $d->setTimezone(new DateTimeZone(common_timezone()));
980 return $d->format('r');
983 function common_date_iso8601($dt) {
984 $dateStr = date('d F Y H:i:s', strtotime($dt));
985 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
986 $d->setTimezone(new DateTimeZone(common_timezone()));
987 return $d->format('c');
990 function common_redirect($url, $code=307) {
991 static $status = array(301 => "Moved Permanently",
994 307 => "Temporary Redirect");
995 header("Status: ${code} $status[$code]");
996 header("Location: $url");
998 common_start_xml('a',
999 '-//W3C//DTD XHTML 1.0 Strict//EN',
1000 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1001 common_element('a', array('href' => $url), $url);
1006 function common_save_replies($notice) {
1007 # Alternative reply format
1009 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1012 # extract all @messages
1013 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1014 if (!$cnt && !$tname) {
1017 # XXX: is there another way to make an array copy?
1018 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1019 $sender = Profile::staticGet($notice->profile_id);
1020 # store replied only for first @ (what user/notice what the reply directed,
1021 # we assume first @ is it)
1022 for ($i=0; $i<count($names); $i++) {
1023 $nickname = $names[$i];
1024 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1028 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1029 $reply_for = $recipient;
1030 $recipient_notice = $reply_for->getCurrentNotice();
1031 if ($recipient_notice) {
1032 $orig = clone($notice);
1033 $notice->reply_to = $recipient_notice->id;
1034 $notice->update($orig);
1037 $reply = new Reply();
1038 $reply->notice_id = $notice->id;
1039 $reply->profile_id = $recipient->id;
1040 $id = $reply->insert();
1042 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1043 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1044 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1050 function common_broadcast_notice($notice, $remote=false) {
1051 if (common_config('queue', 'enabled')) {
1053 return common_enqueue_notice($notice);
1055 return common_real_broadcast($notice, $remote);
1059 # Stick the notice on the queue
1061 function common_enqueue_notice($notice) {
1062 $qi = new Queue_item();
1063 $qi->notice_id = $notice->id;
1064 $qi->created = $notice->created;
1065 $result = $qi->insert();
1067 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1068 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1071 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1075 function common_dequeue_notice($notice) {
1076 $qi = Queue_item::staticGet($notice->id);
1078 $result = $qi->delete();
1080 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1081 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1084 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1091 function common_real_broadcast($notice, $remote=false) {
1094 # Make sure we have the OMB stuff
1095 require_once(INSTALLDIR.'/lib/omb.php');
1096 $success = omb_broadcast_remote_subscribers($notice);
1098 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1102 require_once(INSTALLDIR.'/lib/jabber.php');
1103 $success = jabber_broadcast_notice($notice);
1105 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1109 require_once(INSTALLDIR.'/lib/mail.php');
1110 $success = mail_broadcast_notice_sms($notice);
1112 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1115 // XXX: broadcast notices to other IM
1119 function common_broadcast_profile($profile) {
1120 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1121 require_once(INSTALLDIR.'/lib/omb.php');
1122 omb_broadcast_profile($profile);
1123 // XXX: Other broadcasts...?
1127 function common_profile_url($nickname) {
1128 return common_local_url('showstream', array('nickname' => $nickname));
1131 # Don't call if nobody's logged in
1133 function common_notice_form($action=NULL, $content=NULL) {
1134 $user = common_current_user();
1135 assert(!is_null($user));
1136 common_element_start('form', array('id' => 'status_form',
1138 'action' => common_local_url('newnotice')));
1139 common_element_start('p');
1140 common_element('label', array('for' => 'status_textarea',
1141 'id' => 'status_label'),
1142 sprintf(_('What\'s up, %s?'), $user->nickname));
1143 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1144 common_element('textarea', array('id' => 'status_textarea',
1147 'name' => 'status_textarea'),
1148 ($content) ? $content : '');
1150 common_hidden('returnto', $action);
1152 common_element('input', array('id' => 'status_submit',
1153 'name' => 'status_submit',
1155 'value' => _('Send')));
1156 common_element_end('p');
1157 common_element_end('form');
1160 # Should make up a reasonable root URL
1162 function common_root_url() {
1163 return common_path('');
1166 # returns $bytes bytes of random data as a hexadecimal string
1167 # "good" here is a goal and not a guarantee
1169 function common_good_rand($bytes) {
1170 # XXX: use random.org...?
1171 if (file_exists('/dev/urandom')) {
1172 return common_urandom($bytes);
1173 } else { # FIXME: this is probably not good enough
1174 return common_mtrand($bytes);
1178 function common_urandom($bytes) {
1179 $h = fopen('/dev/urandom', 'rb');
1181 $src = fread($h, $bytes);
1184 for ($i = 0; $i < $bytes; $i++) {
1185 $enc .= sprintf("%02x", (ord($src[$i])));
1190 function common_mtrand($bytes) {
1192 for ($i = 0; $i < $bytes; $i++) {
1193 $enc .= sprintf("%02x", mt_rand(0, 255));
1198 function common_set_returnto($url) {
1199 common_ensure_session();
1200 $_SESSION['returnto'] = $url;
1203 function common_get_returnto() {
1204 common_ensure_session();
1205 return $_SESSION['returnto'];
1208 function common_timestamp() {
1209 return date('YmdHis');
1212 function common_ensure_syslog() {
1213 static $initialized = false;
1214 if (!$initialized) {
1216 openlog($config['syslog']['appname'], 0, LOG_USER);
1217 $initialized = true;
1221 function common_log($priority, $msg, $filename=NULL) {
1222 $logfile = common_config('site', 'logfile');
1224 $log = fopen($logfile, "a");
1226 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1227 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1228 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1229 fwrite($log, $output);
1233 common_ensure_syslog();
1234 syslog($priority, $msg);
1238 function common_debug($msg, $filename=NULL) {
1240 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1242 common_log(LOG_DEBUG, $msg);
1246 function common_log_db_error(&$object, $verb, $filename=NULL) {
1247 $objstr = common_log_objstring($object);
1248 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1249 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1252 function common_log_objstring(&$object) {
1253 if (is_null($object)) {
1256 $arr = $object->toArray();
1258 foreach ($arr as $k => $v) {
1259 $fields[] = "$k='$v'";
1261 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1265 function common_valid_http_url($url) {
1266 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1269 function common_valid_tag($tag) {
1270 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1271 return (Validate::email($matches[1]) ||
1272 preg_match('/^([\w-\.]+)$/', $matches[1]));
1277 # Does a little before-after block for next/prev page
1279 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1281 if ($have_before || $have_after) {
1282 common_element_start('div', array('id' => 'pagination'));
1283 common_element_start('ul', array('id' => 'nav_pagination'));
1287 $pargs = array('page' => $page-1);
1288 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1290 common_element_start('li', 'before');
1291 common_element('a', array('href' => common_local_url($action, $newargs)),
1293 common_element_end('li');
1297 $pargs = array('page' => $page+1);
1298 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1299 common_element_start('li', 'after');
1300 common_element('a', array('href' => common_local_url($action, $newargs)),
1302 common_element_end('li');
1305 if ($have_before || $have_after) {
1306 common_element_end('ul');
1307 common_element_end('div');
1311 /* Following functions are copied from MediaWiki GlobalFunctions.php
1312 * and written by Evan Prodromou. */
1314 function common_accept_to_prefs($accept, $def = '*/*') {
1315 # No arg means accept anything (per HTTP spec)
1317 return array($def => 1);
1322 $parts = explode(',', $accept);
1324 foreach($parts as $part) {
1325 # FIXME: doesn't deal with params like 'text/html; level=1'
1326 @list($value, $qpart) = explode(';', $part);
1328 if(!isset($qpart)) {
1330 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1331 $prefs[$value] = $match[1];
1338 function common_mime_type_match($type, $avail) {
1339 if(array_key_exists($type, $avail)) {
1342 $parts = explode('/', $type);
1343 if(array_key_exists($parts[0] . '/*', $avail)) {
1344 return $parts[0] . '/*';
1345 } elseif(array_key_exists('*/*', $avail)) {
1353 function common_negotiate_type($cprefs, $sprefs) {
1356 foreach(array_keys($sprefs) as $type) {
1357 $parts = explode('/', $type);
1358 if($parts[1] != '*') {
1359 $ckey = common_mime_type_match($type, $cprefs);
1361 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1366 foreach(array_keys($cprefs) as $type) {
1367 $parts = explode('/', $type);
1368 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1369 $skey = common_mime_type_match($type, $sprefs);
1371 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1377 $besttype = "text/html";
1379 foreach(array_keys($combine) as $type) {
1380 if($combine[$type] > $bestq) {
1382 $bestq = $combine[$type];
1389 function common_config($main, $sub) {
1391 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1394 function common_copy_args($from) {
1396 $strip = get_magic_quotes_gpc();
1397 foreach ($from as $k => $v) {
1398 $to[$k] = ($strip) ? stripslashes($v) : $v;
1403 function common_user_uri(&$user) {
1404 return common_local_url('userbyid', array('id' => $user->id));
1407 function common_notice_uri(&$notice) {
1408 return common_local_url('shownotice',
1409 array('notice' => $notice->id));
1412 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1414 function common_confirmation_code($bits) {
1415 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1416 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1417 $chars = ceil($bits/5);
1419 for ($i = 0; $i < $chars; $i++) {
1420 # XXX: convert to string and back
1421 $num = hexdec(common_good_rand(1));
1422 # XXX: randomness is too precious to throw away almost
1423 # 40% of the bits we get!
1424 $code .= $codechars[$num%32];
1429 # convert markup to HTML
1431 function common_markup_to_html($c) {
1432 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1433 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1434 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1435 return Markdown($c);
1438 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1439 $avatar = $profile->getAvatar($size);
1441 return common_avatar_display_url($avatar);
1443 return common_default_avatar($size);
1447 function common_profile_uri($profile) {
1451 $user = User::staticGet($profile->id);
1456 $remote = Remote_profile::staticGet($profile->id);
1458 return $remote->uri;
1460 # XXX: this is a very bad profile!
1464 function common_canonical_sms($sms) {
1466 preg_replace('/\D/', '', $sms);