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 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
140 $language = common_language();
141 setlocale(LC_ALL, $language);
142 bindtextdomain("laconica", $config['site']['locale_path']);
143 textdomain("laconica");
145 # XXX: allow content negotiation for RDF, RSS, or XRDS
147 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
148 common_accept_to_prefs(PAGE_TYPE_PREFS));
151 common_user_error(_('This page is not available in a media type you accept'), 406);
155 header('Content-Type: '.$type);
157 common_start_xml('html',
158 '-//W3C//DTD XHTML 1.0 Strict//EN',
159 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
161 # FIXME: correct language for interface
163 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
164 'xml:lang' => $language,
165 'lang' => $language));
167 common_element_start('head');
168 common_element('title', NULL,
169 $pagetitle . " - " . $config['site']['name']);
170 common_element('link', array('rel' => 'stylesheet',
171 'type' => 'text/css',
172 'href' => theme_path('display.css'),
173 'media' => 'screen, projection, tv'));
174 foreach (array(6,7) as $ver) {
175 if (file_exists(theme_file('ie'.$ver.'.css'))) {
176 # Yes, IE people should be put in jail.
177 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
178 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
182 common_element('script', array('type' => 'text/javascript',
183 'src' => common_path('js/jquery.min.js')),
185 common_element('script', array('type' => 'text/javascript',
186 'src' => common_path('js/util.js')),
188 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
189 'href' => common_local_url('opensearch'), 'title' => common_config('site', 'name').' Search'));
193 call_user_func($callable, $data);
195 call_user_func($callable);
198 common_element_end('head');
199 common_element_start('body');
200 common_element_start('div', array('id' => 'wrap'));
201 common_element_start('div', array('id' => 'header'));
203 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
204 || file_exists(theme_file('logo.png')))
206 common_element_start('a', array('href' => common_local_url('public')));
207 common_element('img', array('src' => isset($config['site']['logo']) ?
208 ($config['site']['logo']) : theme_path('logo.png'),
209 'alt' => $config['site']['name'],
211 common_element_end('a');
213 common_element_start('p', array('id' => 'branding'));
214 common_element('a', array('href' => common_local_url('public')),
215 $config['site']['name']);
216 common_element_end('p');
219 common_element('h1', 'pagetitle', $pagetitle);
223 call_user_func($headercall, $data);
225 call_user_func($headercall);
228 common_element_end('div');
229 common_element_start('div', array('id' => 'content'));
232 function common_show_footer() {
234 common_element_end('div'); # content div
236 common_element_start('div', array('id' => 'footer'));
237 common_element_start('div', 'laconica');
238 if (common_config('site', 'broughtby')) {
239 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
241 $instr = _('**%%site.name%%** is a microblogging service. ');
243 $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);
244 $output = common_markup_to_html($instr);
246 common_element_end('div');
247 common_element('img', array('id' => 'cc',
248 'src' => $config['license']['image'],
249 'alt' => $config['license']['title']));
250 common_element_start('p');
251 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
252 common_element('a', array('class' => 'license',
254 'href' => $config['license']['url']),
255 $config['license']['title']);
256 common_text(_('. Contributors should be attributed by full name or nickname.'));
257 common_element_end('p');
258 common_element_end('div');
259 common_element_end('div');
260 common_element_end('body');
261 common_element_end('html');
265 function common_text($txt) {
270 function common_raw($xml) {
275 function common_nav_menu() {
276 $user = common_current_user();
277 common_element_start('ul', array('id' => 'nav'));
279 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
282 common_menu_item(common_local_url('public'), _('Public'));
283 common_menu_item(common_local_url('peoplesearch'), _('Search'));
284 common_menu_item(common_local_url('tags'), _('Tags'));
285 common_menu_item(common_local_url('doc', array('title' => 'help')),
288 common_menu_item(common_local_url('profilesettings'),
290 common_menu_item(common_local_url('logout'),
293 common_menu_item(common_local_url('login'), _('Login'));
294 if (!common_config('site', 'closed')) {
295 common_menu_item(common_local_url('register'), _('Register'));
297 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
299 common_element_end('ul');
302 function common_foot_menu() {
303 common_element_start('ul', array('id' => 'nav_sub'));
304 common_menu_item(common_local_url('doc', array('title' => 'about')),
306 common_menu_item(common_local_url('doc', array('title' => 'faq')),
308 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
310 common_menu_item(common_local_url('doc', array('title' => 'source')),
312 common_menu_item(common_local_url('doc', array('title' => 'contact')),
314 common_element_end('ul');
317 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
320 $lattrs['class'] = 'current';
322 common_element_start('li', $lattrs);
323 $attrs['href'] = $url;
325 $attrs['title'] = $title;
327 common_element('a', $attrs, $text);
328 common_element_end('li');
331 function common_input($id, $label, $value=NULL,$instructions=NULL) {
332 common_element_start('p');
333 common_element('label', array('for' => $id), $label);
334 $attrs = array('name' => $id,
336 'class' => 'input_text',
339 $attrs['value'] = htmlspecialchars($value);
341 common_element('input', $attrs);
343 common_element('span', 'input_instructions', $instructions);
345 common_element_end('p');
348 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
350 common_element_start('p');
351 $attrs = array('name' => $id,
352 'type' => 'checkbox',
353 'class' => 'checkbox',
356 $attrs['value'] = htmlspecialchars($value);
359 $attrs['checked'] = 'checked';
361 common_element('input', $attrs);
364 common_element('span', 'checkbox_label', $label);
367 common_element('span', 'input_instructions', $instructions);
369 common_element_end('p');
372 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
373 common_element_start('p');
374 common_element('label', array('for' => $id), $label);
375 common_element_start('select', array('id' => $id, 'name' => $id));
377 common_element('option', array('value' => ''));
379 foreach ($content as $value => $option) {
380 if ($value == $selected) {
381 common_element('option', array('value' => $value, 'selected' => $value), $option);
383 common_element('option', array('value' => $value), $option);
386 common_element_end('select');
388 common_element('span', 'input_instructions', $instructions);
390 common_element_end('p');
392 function common_hidden($id, $value) {
393 common_element('input', array('name' => $id,
399 function common_password($id, $label, $instructions=NULL) {
400 common_element_start('p');
401 common_element('label', array('for' => $id), $label);
402 $attrs = array('name' => $id,
403 'type' => 'password',
404 'class' => 'password',
406 common_element('input', $attrs);
408 common_element('span', 'input_instructions', $instructions);
410 common_element_end('p');
413 function common_submit($id, $label) {
415 common_element_start('p');
416 common_element('input', array('type' => 'submit',
421 common_element_end('p');
424 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
425 common_element_start('p');
426 common_element('label', array('for' => $id), $label);
427 common_element('textarea', array('rows' => 3,
431 ($content) ? $content : '');
433 common_element('span', 'input_instructions', $instructions);
435 common_element_end('p');
438 function common_timezone() {
439 if (common_logged_in()) {
440 $user = common_current_user();
441 if ($user->timezone) {
442 return $user->timezone;
447 return $config['site']['timezone'];
450 function common_language() {
451 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
453 $user_language = FALSE;
455 if (common_logged_in()) {
456 $user = common_current_user();
457 $user_language = $user->language;
460 if ($user_language) {
461 return $user_language;
462 } else if (!empty($httplang)) {
463 $language = client_prefered_language($httplang);
468 return $config['site']['language'];
471 # salted, hashed passwords are stored in the DB
473 function common_munge_password($password, $id) {
474 return md5($password . $id);
477 # check if a username exists and has matching password
478 function common_check_user($nickname, $password) {
479 $user = User::staticGet('nickname', $nickname);
480 if (is_null($user)) {
483 if (0 == strcmp(common_munge_password($password, $user->id),
492 # is the current user logged in?
493 function common_logged_in() {
494 return (!is_null(common_current_user()));
497 function common_have_session() {
498 return (0 != strcmp(session_id(), ''));
501 function common_ensure_session() {
502 if (!common_have_session()) {
507 # Three kinds of arguments:
512 function common_set_user($user) {
513 if (is_null($user) && common_have_session()) {
514 unset($_SESSION['userid']);
516 } else if (is_string($user)) {
518 $user = User::staticGet('nickname', $nickname);
519 } else if (!($user instanceof User)) {
524 common_ensure_session();
525 $_SESSION['userid'] = $user->id;
531 function common_set_cookie($key, $value, $expiration=0) {
532 $path = common_config('site', 'path');
533 $server = common_config('site', 'server');
535 if ($path && ($path != '/')) {
536 $cookiepath = '/' . $path . '/';
540 return setcookie($key,
547 define('REMEMBERME', 'rememberme');
548 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
550 function common_rememberme($user=NULL) {
552 $user = common_current_user();
554 common_debug('No current user to remember', __FILE__);
558 $rm = new Remember_me();
559 $rm->code = common_good_rand(16);
560 $rm->user_id = $user->id;
561 $result = $rm->insert();
563 common_log_db_error($rm, 'INSERT', __FILE__);
564 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
567 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
568 common_set_cookie(REMEMBERME,
569 implode(':', array($rm->user_id, $rm->code)),
570 time() + REMEMBERME_EXPIRY);
574 function common_remembered_user() {
577 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
579 list($id, $code) = explode(':', $packed);
581 $rm = Remember_me::staticGet($code);
582 if ($rm && ($rm->user_id == $id)) {
583 $user = User::staticGet($rm->user_id);
586 $result = $rm->delete();
588 common_log_db_error($rm, 'DELETE', __FILE__);
591 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
592 common_set_user($user->nickname);
593 common_real_login(false);
594 # We issue a new cookie, so they can log in
595 # automatically again after this session
596 common_rememberme($user);
605 # must be called with a valid user!
607 function common_forgetme() {
608 common_set_cookie(REMEMBERME, '', 0);
611 # who is the current user?
612 function common_current_user() {
613 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
614 common_ensure_session();
615 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
617 # note: this should cache
618 $user = User::staticGet($id);
622 # that didn't work; try to remember
623 $user = common_remembered_user();
625 common_debug("Got User " . $user->nickname);
626 common_debug("Faking session on remembered user");
627 $_SESSION['userid'] = $user->id;
632 # Logins that are 'remembered' aren't 'real' -- they're subject to
633 # cookie-stealing. So, we don't let them do certain things. New reg,
634 # OpenID, and password logins _are_ real.
636 function common_real_login($real=true) {
637 common_ensure_session();
638 $_SESSION['real_login'] = $real;
641 function common_is_real_login() {
642 return common_logged_in() && $_SESSION['real_login'];
645 # get canonical version of nickname for comparison
646 function common_canonical_nickname($nickname) {
647 # XXX: UTF-8 canonicalization (like combining chars)
648 return strtolower($nickname);
651 # get canonical version of email for comparison
652 function common_canonical_email($email) {
653 # XXX: canonicalize UTF-8
654 # XXX: lcase the domain part
658 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$_+!*();/?:~-]))');
660 function common_render_content($text, $notice) {
661 $r = htmlspecialchars($text);
663 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
664 $id = $notice->profile_id;
665 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
666 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
667 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
668 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
673 function common_tag_link($tag) {
674 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" class="hashlink">' . $tag . '</a>';
677 function common_at_link($sender_id, $nickname) {
678 $sender = Profile::staticGet($sender_id);
679 $recipient = common_relative_profile($sender, $nickname);
681 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
687 function common_relative_profile($sender, $nickname, $dt=NULL) {
688 # Try to find profiles this profile is subscribed to that have this nickname
689 $recipient = new Profile();
690 # XXX: use a join instead of a subquery
691 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
692 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
693 if ($recipient->find(TRUE)) {
694 # XXX: should probably differentiate between profiles with
695 # the same name by date of most recent update
698 # Try to find profiles that listen to this profile and that have this nickname
699 $recipient = new Profile();
700 # XXX: use a join instead of a subquery
701 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
702 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
703 if ($recipient->find(TRUE)) {
704 # XXX: should probably differentiate between profiles with
705 # the same name by date of most recent update
708 # If this is a local user, try to find a local user with that nickname.
709 $sender = User::staticGet($sender->id);
711 $recipient_user = User::staticGet('nickname', $nickname);
712 if ($recipient_user) {
713 return $recipient_user->getProfile();
716 # Otherwise, no links. @messages from local users to remote users,
717 # or from remote users to other remote users, are just
718 # outside our ability to make intelligent guesses about
722 // where should the avatar go for this user?
724 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
728 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
730 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
734 function common_avatar_path($filename) {
736 return INSTALLDIR . '/avatar/' . $filename;
739 function common_avatar_url($filename) {
740 return common_path('avatar/'.$filename);
743 function common_avatar_display_url($avatar) {
744 $server = common_config('avatar', 'server');
746 return 'http://'.$server.'/'.$avatar->filename;
752 function common_default_avatar($size) {
753 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
754 AVATAR_STREAM_SIZE => 'stream',
755 AVATAR_MINI_SIZE => 'mini');
756 return theme_path('default-avatar-'.$sizenames[$size].'.png');
759 function common_local_url($action, $args=NULL) {
761 if ($config['site']['fancy']) {
762 return common_fancy_url($action, $args);
764 return common_simple_url($action, $args);
768 function common_fancy_url($action, $args=NULL) {
769 switch (strtolower($action)) {
771 if ($args && isset($args['page'])) {
772 return common_path('?page=' . $args['page']);
774 return common_path('');
777 return common_path('rss');
779 return common_path('xrds');
781 return common_path('opensearch');
783 return common_path('doc/'.$args['title']);
789 return common_path('main/'.$action);
790 case 'remotesubscribe':
791 if ($args && $args['nickname']) {
792 return common_path('main/remote?nickname=' . $args['nickname']);
794 return common_path('main/remote');
797 return common_path('main/openid');
800 return common_path('settings/'.$action);
801 case 'profilesettings':
802 return common_path('settings/profile');
803 case 'emailsettings':
804 return common_path('settings/email');
805 case 'openidsettings':
806 return common_path('settings/openid');
808 return common_path('settings/sms');
810 if ($args && $args['replyto']) {
811 return common_path('notice/new?replyto='.$args['replyto']);
813 return common_path('notice/new');
816 return common_path('notice/'.$args['notice']);
818 if ($args && $args['notice']) {
819 return common_path('deletenotice/'.$args['notice']);
821 return common_path('deletenotice/');
825 return common_path($args['nickname'].'/'.$action);
826 case 'subscriptions':
830 if ($args && isset($args['page'])) {
831 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
833 return common_path($args['nickname'].'/'.$action);
836 return common_path($args['nickname'].'/all/rss');
838 return common_path($args['nickname'].'/replies/rss');
840 return common_path($args['nickname'].'/rss');
842 if ($args && isset($args['page'])) {
843 return common_path($args['nickname'].'?page=' . $args['page']);
845 return common_path($args['nickname']);
847 case 'confirmaddress':
848 return common_path('main/confirmaddress/'.$args['code']);
850 return common_path('user/'.$args['id']);
851 case 'recoverpassword':
852 $path = 'main/recoverpassword';
854 $path .= '/' . $args['code'];
856 return common_path($path);
858 return common_path('settings/im');
860 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
862 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
863 case 'noticesearchrss':
864 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
865 case 'avatarbynickname':
866 return common_path($args['nickname'].'/avatar/'.$args['size']);
868 if (isset($args['tag']) && $args['tag']) {
869 $path = 'tag/' . $args['tag'];
874 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
876 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
878 return common_simple_url($action, $args);
882 function common_simple_url($action, $args=NULL) {
884 /* XXX: pretty URLs */
887 foreach ($args as $key => $value) {
888 $extra .= "&${key}=${value}";
891 return common_path("index.php?action=${action}${extra}");
894 function common_path($relative) {
896 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
897 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
900 function common_date_string($dt) {
901 // XXX: do some sexy date formatting
902 // return date(DATE_RFC822, $dt);
907 if ($now < $t) { # that shouldn't happen!
908 return common_exact_date($dt);
909 } else if ($diff < 60) {
910 return _('a few seconds ago');
911 } else if ($diff < 92) {
912 return _('about a minute ago');
913 } else if ($diff < 3300) {
914 return sprintf(_('about %d minutes ago'), round($diff/60));
915 } else if ($diff < 5400) {
916 return _('about an hour ago');
917 } else if ($diff < 22 * 3600) {
918 return sprintf(_('about %d hours ago'), round($diff/3600));
919 } else if ($diff < 37 * 3600) {
920 return _('about a day ago');
921 } else if ($diff < 24 * 24 * 3600) {
922 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
923 } else if ($diff < 46 * 24 * 3600) {
924 return _('about a month ago');
925 } else if ($diff < 330 * 24 * 3600) {
926 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
927 } else if ($diff < 480 * 24 * 3600) {
928 return _('about a year ago');
930 return common_exact_date($dt);
934 function common_exact_date($dt) {
935 $dateStr = date('d F Y H:i:s', strtotime($dt));
936 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
937 $d->setTimezone(new DateTimeZone(common_timezone()));
938 return $d->format(DATE_RFC850);
941 function common_date_w3dtf($dt) {
942 $dateStr = date('d F Y H:i:s', strtotime($dt));
943 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
944 $d->setTimezone(new DateTimeZone(common_timezone()));
945 return $d->format(DATE_W3C);
948 function common_date_rfc2822($dt) {
949 $dateStr = date('d F Y H:i:s', strtotime($dt));
950 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
951 $d->setTimezone(new DateTimeZone(common_timezone()));
952 return $d->format('r');
955 function common_date_iso8601($dt) {
956 $dateStr = date('d F Y H:i:s', strtotime($dt));
957 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
958 $d->setTimezone(new DateTimeZone(common_timezone()));
959 return $d->format('c');
962 function common_redirect($url, $code=307) {
963 static $status = array(301 => "Moved Permanently",
966 307 => "Temporary Redirect");
967 header("Status: ${code} $status[$code]");
968 header("Location: $url");
970 common_start_xml('a',
971 '-//W3C//DTD XHTML 1.0 Strict//EN',
972 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
973 common_element('a', array('href' => $url), $url);
978 function common_save_replies($notice) {
979 # Alternative reply format
981 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
984 # extract all @messages
985 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
986 if (!$cnt && !$tname) {
989 # XXX: is there another way to make an array copy?
990 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
991 $sender = Profile::staticGet($notice->profile_id);
992 # store replied only for first @ (what user/notice what the reply directed,
993 # we assume first @ is it)
994 for ($i=0; $i<count($names); $i++) {
995 $nickname = $names[$i];
996 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1000 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1001 $reply_for = $recipient;
1002 $recipient_notice = $reply_for->getCurrentNotice();
1003 $orig = clone($notice);
1004 $notice->reply_to = $recipient_notice->id;
1005 $notice->update($orig);
1007 $reply = new Reply();
1008 $reply->notice_id = $notice->id;
1009 $reply->profile_id = $recipient->id;
1010 $id = $reply->insert();
1012 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1013 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1014 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1020 function common_broadcast_notice($notice, $remote=false) {
1021 if (common_config('queue', 'enabled')) {
1023 return common_enqueue_notice($notice);
1025 return common_real_broadcast($notice, $remote);
1029 # Stick the notice on the queue
1031 function common_enqueue_notice($notice) {
1032 $qi = new Queue_item();
1033 $qi->notice_id = $notice->id;
1034 $qi->created = $notice->created;
1035 $result = $qi->insert();
1037 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1038 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1041 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1045 function common_dequeue_notice($notice) {
1046 $qi = Queue_Item::staticGet($notice->id);
1048 $result = $qi->delete();
1050 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1051 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1054 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1061 function common_real_broadcast($notice, $remote=false) {
1064 # Make sure we have the OMB stuff
1065 require_once(INSTALLDIR.'/lib/omb.php');
1066 $success = omb_broadcast_remote_subscribers($notice);
1068 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1072 require_once(INSTALLDIR.'/lib/jabber.php');
1073 $success = jabber_broadcast_notice($notice);
1075 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1079 require_once(INSTALLDIR.'/lib/mail.php');
1080 $success = mail_broadcast_notice_sms($notice);
1082 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1085 // XXX: broadcast notices to other IM
1089 function common_broadcast_profile($profile) {
1090 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1091 require_once(INSTALLDIR.'/lib/omb.php');
1092 omb_broadcast_profile($profile);
1093 // XXX: Other broadcasts...?
1097 function common_profile_url($nickname) {
1098 return common_local_url('showstream', array('nickname' => $nickname));
1101 # Don't call if nobody's logged in
1103 function common_notice_form($action=NULL, $content=NULL) {
1104 $user = common_current_user();
1105 assert(!is_null($user));
1106 common_element_start('form', array('id' => 'status_form',
1108 'action' => common_local_url('newnotice')));
1109 common_element_start('p');
1110 common_element('label', array('for' => 'status_textarea',
1111 'id' => 'status_label'),
1112 sprintf(_('What\'s up, %s?'), $user->nickname));
1113 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1114 common_element('textarea', array('id' => 'status_textarea',
1117 'name' => 'status_textarea'),
1118 ($content) ? $content : '');
1120 common_hidden('returnto', $action);
1122 common_element('input', array('id' => 'status_submit',
1123 'name' => 'status_submit',
1125 'value' => _('Send')));
1126 common_element_end('p');
1127 common_element_end('form');
1130 # Should make up a reasonable root URL
1132 function common_root_url() {
1133 return common_path('');
1136 # returns $bytes bytes of random data as a hexadecimal string
1137 # "good" here is a goal and not a guarantee
1139 function common_good_rand($bytes) {
1140 # XXX: use random.org...?
1141 if (file_exists('/dev/urandom')) {
1142 return common_urandom($bytes);
1143 } else { # FIXME: this is probably not good enough
1144 return common_mtrand($bytes);
1148 function common_urandom($bytes) {
1149 $h = fopen('/dev/urandom', 'rb');
1151 $src = fread($h, $bytes);
1154 for ($i = 0; $i < $bytes; $i++) {
1155 $enc .= sprintf("%02x", (ord($src[$i])));
1160 function common_mtrand($bytes) {
1162 for ($i = 0; $i < $bytes; $i++) {
1163 $enc .= sprintf("%02x", mt_rand(0, 255));
1168 function common_set_returnto($url) {
1169 common_ensure_session();
1170 $_SESSION['returnto'] = $url;
1173 function common_get_returnto() {
1174 common_ensure_session();
1175 return $_SESSION['returnto'];
1178 function common_timestamp() {
1179 return date('YmdHis');
1182 function common_ensure_syslog() {
1183 static $initialized = false;
1184 if (!$initialized) {
1186 openlog($config['syslog']['appname'], 0, LOG_USER);
1187 $initialized = true;
1191 function common_log($priority, $msg, $filename=NULL) {
1192 $logfile = common_config('site', 'logfile');
1194 $log = fopen($logfile, "a");
1196 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1197 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1198 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1199 fwrite($log, $output);
1203 common_ensure_syslog();
1204 syslog($priority, $msg);
1208 function common_debug($msg, $filename=NULL) {
1210 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1212 common_log(LOG_DEBUG, $msg);
1216 function common_log_db_error(&$object, $verb, $filename=NULL) {
1217 $objstr = common_log_objstring($object);
1218 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1219 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1222 function common_log_objstring(&$object) {
1223 if (is_null($object)) {
1226 $arr = $object->toArray();
1228 foreach ($arr as $k => $v) {
1229 $fields[] = "$k='$v'";
1231 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1235 function common_valid_http_url($url) {
1236 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1239 function common_valid_tag($tag) {
1240 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1241 return (Validate::email($matches[1]) ||
1242 preg_match('/^([\w-\.]+)$/', $matches[1]));
1247 # Does a little before-after block for next/prev page
1249 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1251 if ($have_before || $have_after) {
1252 common_element_start('div', array('id' => 'pagination'));
1253 common_element_start('ul', array('id' => 'nav_pagination'));
1257 $pargs = array('page' => $page-1);
1258 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1260 common_element_start('li', 'before');
1261 common_element('a', array('href' => common_local_url($action, $newargs)),
1263 common_element_end('li');
1267 $pargs = array('page' => $page+1);
1268 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1269 common_element_start('li', 'after');
1270 common_element('a', array('href' => common_local_url($action, $newargs)),
1272 common_element_end('li');
1275 if ($have_before || $have_after) {
1276 common_element_end('ul');
1277 common_element_end('div');
1281 /* Following functions are copied from MediaWiki GlobalFunctions.php
1282 * and written by Evan Prodromou. */
1284 function common_accept_to_prefs($accept, $def = '*/*') {
1285 # No arg means accept anything (per HTTP spec)
1287 return array($def => 1);
1292 $parts = explode(',', $accept);
1294 foreach($parts as $part) {
1295 # FIXME: doesn't deal with params like 'text/html; level=1'
1296 @list($value, $qpart) = explode(';', $part);
1298 if(!isset($qpart)) {
1300 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1301 $prefs[$value] = $match[1];
1308 function common_mime_type_match($type, $avail) {
1309 if(array_key_exists($type, $avail)) {
1312 $parts = explode('/', $type);
1313 if(array_key_exists($parts[0] . '/*', $avail)) {
1314 return $parts[0] . '/*';
1315 } elseif(array_key_exists('*/*', $avail)) {
1323 function common_negotiate_type($cprefs, $sprefs) {
1326 foreach(array_keys($sprefs) as $type) {
1327 $parts = explode('/', $type);
1328 if($parts[1] != '*') {
1329 $ckey = common_mime_type_match($type, $cprefs);
1331 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1336 foreach(array_keys($cprefs) as $type) {
1337 $parts = explode('/', $type);
1338 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1339 $skey = common_mime_type_match($type, $sprefs);
1341 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1347 $besttype = "text/html";
1349 foreach(array_keys($combine) as $type) {
1350 if($combine[$type] > $bestq) {
1352 $bestq = $combine[$type];
1359 function common_config($main, $sub) {
1361 return $config[$main][$sub];
1364 function common_copy_args($from) {
1366 $strip = get_magic_quotes_gpc();
1367 foreach ($from as $k => $v) {
1368 $to[$k] = ($strip) ? stripslashes($v) : $v;
1373 function common_user_uri(&$user) {
1374 return common_local_url('userbyid', array('id' => $user->id));
1377 function common_notice_uri(&$notice) {
1378 return common_local_url('shownotice',
1379 array('notice' => $notice->id));
1382 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1384 function common_confirmation_code($bits) {
1385 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1386 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1387 $chars = ceil($bits/5);
1389 for ($i = 0; $i < $chars; $i++) {
1390 # XXX: convert to string and back
1391 $num = hexdec(common_good_rand(1));
1392 # XXX: randomness is too precious to throw away almost
1393 # 40% of the bits we get!
1394 $code .= $codechars[$num%32];
1399 # convert markup to HTML
1401 function common_markup_to_html($c) {
1402 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1403 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1404 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1405 return Markdown($c);
1408 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1409 $avatar = $profile->getAvatar($size);
1411 return common_avatar_display_url($avatar);
1413 return common_default_avatar($size);
1417 function common_profile_uri($profile) {
1421 $user = User::staticGet($profile->id);
1426 $remote = Remote_profile::staticGet($profile->id);
1428 return $remote->uri;
1430 # XXX: this is a very bad profile!
1434 function common_canonical_sms($sms) {
1436 preg_replace('/\D/', '', $sms);