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 setlocale(LC_ALL, $language);
141 bindtextdomain("laconica", $config['site']['locale_path']);
142 textdomain("laconica");
144 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
146 # XXX: allow content negotiation for RDF, RSS, or XRDS
148 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
149 common_accept_to_prefs(PAGE_TYPE_PREFS));
152 common_user_error(_('This page is not available in a media type you accept'), 406);
156 header('Content-Type: '.$type);
158 common_start_xml('html',
159 '-//W3C//DTD XHTML 1.0 Strict//EN',
160 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
162 # FIXME: correct language for interface
164 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
165 'xml:lang' => $language,
166 'lang' => $language));
168 common_element_start('head');
169 common_element('title', NULL,
170 $pagetitle . " - " . $config['site']['name']);
171 common_element('link', array('rel' => 'stylesheet',
172 'type' => 'text/css',
173 'href' => theme_path('display.css'),
174 'media' => 'screen, projection, tv'));
175 foreach (array(6,7) as $ver) {
176 if (file_exists(theme_file('ie'.$ver.'.css'))) {
177 # Yes, IE people should be put in jail.
178 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
179 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
183 common_element('script', array('type' => 'text/javascript',
184 'src' => common_path('js/jquery.min.js')),
186 common_element('script', array('type' => 'text/javascript',
187 'src' => common_path('js/util.js')),
189 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
190 'href' => common_local_url('opensearch', array('type' => 'people')),
191 'title' => common_config('site', 'name').' People Search'));
193 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
194 'href' => common_local_url('opensearch', array('type' => 'notice')),
195 'title' => common_config('site', 'name').' Notice Search'));
199 call_user_func($callable, $data);
201 call_user_func($callable);
204 common_element_end('head');
205 common_element_start('body');
206 common_element_start('div', array('id' => 'wrap'));
207 common_element_start('div', array('id' => 'header'));
209 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
210 || file_exists(theme_file('logo.png')))
212 common_element_start('a', array('href' => common_local_url('public')));
213 common_element('img', array('src' => isset($config['site']['logo']) ?
214 ($config['site']['logo']) : theme_path('logo.png'),
215 'alt' => $config['site']['name'],
217 common_element_end('a');
219 common_element_start('p', array('id' => 'branding'));
220 common_element('a', array('href' => common_local_url('public')),
221 $config['site']['name']);
222 common_element_end('p');
225 common_element('h1', 'pagetitle', $pagetitle);
229 call_user_func($headercall, $data);
231 call_user_func($headercall);
234 common_element_end('div');
235 common_element_start('div', array('id' => 'content'));
238 function common_show_footer() {
240 common_element_end('div'); # content div
242 common_element_start('div', array('id' => 'footer'));
243 common_element_start('div', 'laconica');
244 if (common_config('site', 'broughtby')) {
245 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
247 $instr = _('**%%site.name%%** is a microblogging service. ');
249 $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);
250 $output = common_markup_to_html($instr);
252 common_element_end('div');
253 common_element('img', array('id' => 'cc',
254 'src' => $config['license']['image'],
255 'alt' => $config['license']['title']));
256 common_element_start('p');
257 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
258 common_element('a', array('class' => 'license',
260 'href' => $config['license']['url']),
261 $config['license']['title']);
262 common_text(_('. Contributors should be attributed by full name or nickname.'));
263 common_element_end('p');
264 common_element_end('div');
265 common_element_end('div');
266 common_element_end('body');
267 common_element_end('html');
271 function common_text($txt) {
276 function common_raw($xml) {
281 function common_nav_menu() {
282 $user = common_current_user();
283 common_element_start('ul', array('id' => 'nav'));
285 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
288 common_menu_item(common_local_url('public'), _('Public'));
289 common_menu_item(common_local_url('peoplesearch'), _('Search'));
290 common_menu_item(common_local_url('tags'), _('Tags'));
291 common_menu_item(common_local_url('doc', array('title' => 'help')),
294 common_menu_item(common_local_url('profilesettings'),
296 common_menu_item(common_local_url('logout'),
299 common_menu_item(common_local_url('login'), _('Login'));
300 if (!common_config('site', 'closed')) {
301 common_menu_item(common_local_url('register'), _('Register'));
303 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
305 common_element_end('ul');
308 function common_foot_menu() {
309 common_element_start('ul', array('id' => 'nav_sub'));
310 common_menu_item(common_local_url('doc', array('title' => 'about')),
312 common_menu_item(common_local_url('doc', array('title' => 'faq')),
314 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
316 common_menu_item(common_local_url('doc', array('title' => 'source')),
318 common_menu_item(common_local_url('doc', array('title' => 'contact')),
320 common_element_end('ul');
323 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
326 $lattrs['class'] = 'current';
328 common_element_start('li', $lattrs);
329 $attrs['href'] = $url;
331 $attrs['title'] = $title;
333 common_element('a', $attrs, $text);
334 common_element_end('li');
337 function common_input($id, $label, $value=NULL,$instructions=NULL) {
338 common_element_start('p');
339 common_element('label', array('for' => $id), $label);
340 $attrs = array('name' => $id,
342 'class' => 'input_text',
345 $attrs['value'] = htmlspecialchars($value);
347 common_element('input', $attrs);
349 common_element('span', 'input_instructions', $instructions);
351 common_element_end('p');
354 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
356 common_element_start('p');
357 $attrs = array('name' => $id,
358 'type' => 'checkbox',
359 'class' => 'checkbox',
362 $attrs['value'] = htmlspecialchars($value);
365 $attrs['checked'] = 'checked';
367 common_element('input', $attrs);
370 common_element('span', 'checkbox_label', $label);
373 common_element('span', 'input_instructions', $instructions);
375 common_element_end('p');
378 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
379 common_element_start('p');
380 common_element('label', array('for' => $id), $label);
381 common_element_start('select', array('id' => $id, 'name' => $id));
383 common_element('option', array('value' => ''));
385 foreach ($content as $value => $option) {
386 if ($value == $selected) {
387 common_element('option', array('value' => $value, 'selected' => $value), $option);
389 common_element('option', array('value' => $value), $option);
392 common_element_end('select');
394 common_element('span', 'input_instructions', $instructions);
396 common_element_end('p');
398 function common_hidden($id, $value) {
399 common_element('input', array('name' => $id,
405 function common_password($id, $label, $instructions=NULL) {
406 common_element_start('p');
407 common_element('label', array('for' => $id), $label);
408 $attrs = array('name' => $id,
409 'type' => 'password',
410 'class' => 'password',
412 common_element('input', $attrs);
414 common_element('span', 'input_instructions', $instructions);
416 common_element_end('p');
419 function common_submit($id, $label) {
421 common_element_start('p');
422 common_element('input', array('type' => 'submit',
427 common_element_end('p');
430 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
431 common_element_start('p');
432 common_element('label', array('for' => $id), $label);
433 common_element('textarea', array('rows' => 3,
437 ($content) ? $content : '');
439 common_element('span', 'input_instructions', $instructions);
441 common_element_end('p');
444 function common_timezone() {
445 if (common_logged_in()) {
446 $user = common_current_user();
447 if ($user->timezone) {
448 return $user->timezone;
453 return $config['site']['timezone'];
456 function common_language() {
457 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
459 $user_language = FALSE;
461 if (common_logged_in()) {
462 $user = common_current_user();
463 $user_language = $user->language;
466 if ($user_language) {
467 return $user_language;
468 } else if (!empty($httplang)) {
469 $language = client_prefered_language($httplang);
474 return $config['site']['language'];
477 # salted, hashed passwords are stored in the DB
479 function common_munge_password($password, $id) {
480 return md5($password . $id);
483 # check if a username exists and has matching password
484 function common_check_user($nickname, $password) {
485 $user = User::staticGet('nickname', $nickname);
486 if (is_null($user)) {
489 if (0 == strcmp(common_munge_password($password, $user->id),
498 # is the current user logged in?
499 function common_logged_in() {
500 return (!is_null(common_current_user()));
503 function common_have_session() {
504 return (0 != strcmp(session_id(), ''));
507 function common_ensure_session() {
508 if (!common_have_session()) {
513 # Three kinds of arguments:
518 function common_set_user($user) {
519 if (is_null($user) && common_have_session()) {
520 unset($_SESSION['userid']);
522 } else if (is_string($user)) {
524 $user = User::staticGet('nickname', $nickname);
525 } else if (!($user instanceof User)) {
530 common_ensure_session();
531 $_SESSION['userid'] = $user->id;
537 function common_set_cookie($key, $value, $expiration=0) {
538 $path = common_config('site', 'path');
539 $server = common_config('site', 'server');
541 if ($path && ($path != '/')) {
542 $cookiepath = '/' . $path . '/';
546 return setcookie($key,
553 define('REMEMBERME', 'rememberme');
554 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
556 function common_rememberme($user=NULL) {
558 $user = common_current_user();
560 common_debug('No current user to remember', __FILE__);
564 $rm = new Remember_me();
565 $rm->code = common_good_rand(16);
566 $rm->user_id = $user->id;
567 $result = $rm->insert();
569 common_log_db_error($rm, 'INSERT', __FILE__);
570 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
573 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
574 common_set_cookie(REMEMBERME,
575 implode(':', array($rm->user_id, $rm->code)),
576 time() + REMEMBERME_EXPIRY);
580 function common_remembered_user() {
583 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
585 list($id, $code) = explode(':', $packed);
587 $rm = Remember_me::staticGet($code);
588 if ($rm && ($rm->user_id == $id)) {
589 $user = User::staticGet($rm->user_id);
592 $result = $rm->delete();
594 common_log_db_error($rm, 'DELETE', __FILE__);
597 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
598 common_set_user($user->nickname);
599 common_real_login(false);
600 # We issue a new cookie, so they can log in
601 # automatically again after this session
602 common_rememberme($user);
611 # must be called with a valid user!
613 function common_forgetme() {
614 common_set_cookie(REMEMBERME, '', 0);
617 # who is the current user?
618 function common_current_user() {
619 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
620 common_ensure_session();
621 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
623 # note: this should cache
624 $user = User::staticGet($id);
628 # that didn't work; try to remember
629 $user = common_remembered_user();
631 common_debug("Got User " . $user->nickname);
632 common_debug("Faking session on remembered user");
633 $_SESSION['userid'] = $user->id;
638 # Logins that are 'remembered' aren't 'real' -- they're subject to
639 # cookie-stealing. So, we don't let them do certain things. New reg,
640 # OpenID, and password logins _are_ real.
642 function common_real_login($real=true) {
643 common_ensure_session();
644 $_SESSION['real_login'] = $real;
647 function common_is_real_login() {
648 return common_logged_in() && $_SESSION['real_login'];
651 # get canonical version of nickname for comparison
652 function common_canonical_nickname($nickname) {
653 # XXX: UTF-8 canonicalization (like combining chars)
654 return strtolower($nickname);
657 # get canonical version of email for comparison
658 function common_canonical_email($email) {
659 # XXX: canonicalize UTF-8
660 # XXX: lcase the domain part
664 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$_+!*();/?:~-]))');
666 function common_render_content($text, $notice) {
667 $r = htmlspecialchars($text);
669 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
670 $id = $notice->profile_id;
671 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
672 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
673 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
674 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
679 function common_tag_link($tag) {
680 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
683 function common_at_link($sender_id, $nickname) {
684 $sender = Profile::staticGet($sender_id);
685 $recipient = common_relative_profile($sender, $nickname);
687 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
693 function common_relative_profile($sender, $nickname, $dt=NULL) {
694 # Try to find profiles this profile is subscribed to that have this nickname
695 $recipient = new Profile();
696 # XXX: use a join instead of a subquery
697 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
698 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
699 if ($recipient->find(TRUE)) {
700 # XXX: should probably differentiate between profiles with
701 # the same name by date of most recent update
704 # Try to find profiles that listen to this profile and that have this nickname
705 $recipient = new Profile();
706 # XXX: use a join instead of a subquery
707 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = 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 # If this is a local user, try to find a local user with that nickname.
715 $sender = User::staticGet($sender->id);
717 $recipient_user = User::staticGet('nickname', $nickname);
718 if ($recipient_user) {
719 return $recipient_user->getProfile();
722 # Otherwise, no links. @messages from local users to remote users,
723 # or from remote users to other remote users, are just
724 # outside our ability to make intelligent guesses about
728 // where should the avatar go for this user?
730 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
734 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
736 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
740 function common_avatar_path($filename) {
742 return INSTALLDIR . '/avatar/' . $filename;
745 function common_avatar_url($filename) {
746 return common_path('avatar/'.$filename);
749 function common_avatar_display_url($avatar) {
750 $server = common_config('avatar', 'server');
752 return 'http://'.$server.'/'.$avatar->filename;
758 function common_default_avatar($size) {
759 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
760 AVATAR_STREAM_SIZE => 'stream',
761 AVATAR_MINI_SIZE => 'mini');
762 return theme_path('default-avatar-'.$sizenames[$size].'.png');
765 function common_local_url($action, $args=NULL) {
767 if ($config['site']['fancy']) {
768 return common_fancy_url($action, $args);
770 return common_simple_url($action, $args);
774 function common_fancy_url($action, $args=NULL) {
775 switch (strtolower($action)) {
777 if ($args && isset($args['page'])) {
778 return common_path('?page=' . $args['page']);
780 return common_path('');
783 return common_path('rss');
785 return common_path('xrds');
787 if ($args && $args['type']) {
788 return common_path('opensearch/'.$args['type']);
790 return common_path('opensearch/people');
793 return common_path('doc/'.$args['title']);
799 return common_path('main/'.$action);
800 case 'remotesubscribe':
801 if ($args && $args['nickname']) {
802 return common_path('main/remote?nickname=' . $args['nickname']);
804 return common_path('main/remote');
807 return common_path('main/openid');
810 return common_path('settings/'.$action);
811 case 'profilesettings':
812 return common_path('settings/profile');
813 case 'emailsettings':
814 return common_path('settings/email');
815 case 'openidsettings':
816 return common_path('settings/openid');
818 return common_path('settings/sms');
820 if ($args && $args['replyto']) {
821 return common_path('notice/new?replyto='.$args['replyto']);
823 return common_path('notice/new');
826 return common_path('notice/'.$args['notice']);
828 if ($args && $args['notice']) {
829 return common_path('notice/delete/'.$args['notice']);
831 return common_path('notice/delete');
835 return common_path($args['nickname'].'/'.$action);
836 case 'subscriptions':
840 if ($args && isset($args['page'])) {
841 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
843 return common_path($args['nickname'].'/'.$action);
846 return common_path($args['nickname'].'/all/rss');
848 return common_path($args['nickname'].'/replies/rss');
850 return common_path($args['nickname'].'/rss');
852 if ($args && isset($args['page'])) {
853 return common_path($args['nickname'].'?page=' . $args['page']);
855 return common_path($args['nickname']);
857 case 'confirmaddress':
858 return common_path('main/confirmaddress/'.$args['code']);
860 return common_path('user/'.$args['id']);
861 case 'recoverpassword':
862 $path = 'main/recoverpassword';
864 $path .= '/' . $args['code'];
866 return common_path($path);
868 return common_path('settings/im');
870 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
872 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
873 case 'noticesearchrss':
874 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
875 case 'avatarbynickname':
876 return common_path($args['nickname'].'/avatar/'.$args['size']);
878 if (isset($args['tag']) && $args['tag']) {
879 $path = 'tag/' . $args['tag'];
884 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
886 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
888 return common_simple_url($action, $args);
892 function common_simple_url($action, $args=NULL) {
894 /* XXX: pretty URLs */
897 foreach ($args as $key => $value) {
898 $extra .= "&${key}=${value}";
901 return common_path("index.php?action=${action}${extra}");
904 function common_path($relative) {
906 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
907 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
910 function common_date_string($dt) {
911 // XXX: do some sexy date formatting
912 // return date(DATE_RFC822, $dt);
917 if ($now < $t) { # that shouldn't happen!
918 return common_exact_date($dt);
919 } else if ($diff < 60) {
920 return _('a few seconds ago');
921 } else if ($diff < 92) {
922 return _('about a minute ago');
923 } else if ($diff < 3300) {
924 return sprintf(_('about %d minutes ago'), round($diff/60));
925 } else if ($diff < 5400) {
926 return _('about an hour ago');
927 } else if ($diff < 22 * 3600) {
928 return sprintf(_('about %d hours ago'), round($diff/3600));
929 } else if ($diff < 37 * 3600) {
930 return _('about a day ago');
931 } else if ($diff < 24 * 24 * 3600) {
932 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
933 } else if ($diff < 46 * 24 * 3600) {
934 return _('about a month ago');
935 } else if ($diff < 330 * 24 * 3600) {
936 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
937 } else if ($diff < 480 * 24 * 3600) {
938 return _('about a year ago');
940 return common_exact_date($dt);
944 function common_exact_date($dt) {
949 $_utc = new DateTimeZone('UTC');
950 $_siteTz = new DateTimeZone(common_timezone());
953 $dateStr = date('d F Y H:i:s', strtotime($dt));
954 $d = new DateTime($dateStr, $_utc);
955 $d->setTimezone($_siteTz);
956 return $d->format(DATE_RFC850);
959 function common_date_w3dtf($dt) {
960 $dateStr = date('d F Y H:i:s', strtotime($dt));
961 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
962 $d->setTimezone(new DateTimeZone(common_timezone()));
963 return $d->format(DATE_W3C);
966 function common_date_rfc2822($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('r');
973 function common_date_iso8601($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('c');
980 function common_redirect($url, $code=307) {
981 static $status = array(301 => "Moved Permanently",
984 307 => "Temporary Redirect");
985 header("Status: ${code} $status[$code]");
986 header("Location: $url");
988 common_start_xml('a',
989 '-//W3C//DTD XHTML 1.0 Strict//EN',
990 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
991 common_element('a', array('href' => $url), $url);
996 function common_save_replies($notice) {
997 # Alternative reply format
999 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1002 # extract all @messages
1003 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1004 if (!$cnt && !$tname) {
1007 # XXX: is there another way to make an array copy?
1008 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1009 $sender = Profile::staticGet($notice->profile_id);
1010 # store replied only for first @ (what user/notice what the reply directed,
1011 # we assume first @ is it)
1012 for ($i=0; $i<count($names); $i++) {
1013 $nickname = $names[$i];
1014 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1018 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1019 $reply_for = $recipient;
1020 $recipient_notice = $reply_for->getCurrentNotice();
1021 if ($recipient_notice) {
1022 $orig = clone($notice);
1023 $notice->reply_to = $recipient_notice->id;
1024 $notice->update($orig);
1027 $reply = new Reply();
1028 $reply->notice_id = $notice->id;
1029 $reply->profile_id = $recipient->id;
1030 $id = $reply->insert();
1032 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1033 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1034 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1040 function common_broadcast_notice($notice, $remote=false) {
1041 if (common_config('queue', 'enabled')) {
1043 return common_enqueue_notice($notice);
1045 return common_real_broadcast($notice, $remote);
1049 # Stick the notice on the queue
1051 function common_enqueue_notice($notice) {
1052 $qi = new Queue_item();
1053 $qi->notice_id = $notice->id;
1054 $qi->created = $notice->created;
1055 $result = $qi->insert();
1057 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1058 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1061 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1065 function common_dequeue_notice($notice) {
1066 $qi = Queue_item::staticGet($notice->id);
1068 $result = $qi->delete();
1070 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1071 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1074 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1081 function common_real_broadcast($notice, $remote=false) {
1084 # Make sure we have the OMB stuff
1085 require_once(INSTALLDIR.'/lib/omb.php');
1086 $success = omb_broadcast_remote_subscribers($notice);
1088 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1092 require_once(INSTALLDIR.'/lib/jabber.php');
1093 $success = jabber_broadcast_notice($notice);
1095 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1099 require_once(INSTALLDIR.'/lib/mail.php');
1100 $success = mail_broadcast_notice_sms($notice);
1102 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1105 // XXX: broadcast notices to other IM
1109 function common_broadcast_profile($profile) {
1110 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1111 require_once(INSTALLDIR.'/lib/omb.php');
1112 omb_broadcast_profile($profile);
1113 // XXX: Other broadcasts...?
1117 function common_profile_url($nickname) {
1118 return common_local_url('showstream', array('nickname' => $nickname));
1121 # Don't call if nobody's logged in
1123 function common_notice_form($action=NULL, $content=NULL) {
1124 $user = common_current_user();
1125 assert(!is_null($user));
1126 common_element_start('form', array('id' => 'status_form',
1128 'action' => common_local_url('newnotice')));
1129 common_element_start('p');
1130 common_element('label', array('for' => 'status_textarea',
1131 'id' => 'status_label'),
1132 sprintf(_('What\'s up, %s?'), $user->nickname));
1133 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1134 common_element('textarea', array('id' => 'status_textarea',
1137 'name' => 'status_textarea'),
1138 ($content) ? $content : '');
1140 common_hidden('returnto', $action);
1142 common_element('input', array('id' => 'status_submit',
1143 'name' => 'status_submit',
1145 'value' => _('Send')));
1146 common_element_end('p');
1147 common_element_end('form');
1150 # Should make up a reasonable root URL
1152 function common_root_url() {
1153 return common_path('');
1156 # returns $bytes bytes of random data as a hexadecimal string
1157 # "good" here is a goal and not a guarantee
1159 function common_good_rand($bytes) {
1160 # XXX: use random.org...?
1161 if (file_exists('/dev/urandom')) {
1162 return common_urandom($bytes);
1163 } else { # FIXME: this is probably not good enough
1164 return common_mtrand($bytes);
1168 function common_urandom($bytes) {
1169 $h = fopen('/dev/urandom', 'rb');
1171 $src = fread($h, $bytes);
1174 for ($i = 0; $i < $bytes; $i++) {
1175 $enc .= sprintf("%02x", (ord($src[$i])));
1180 function common_mtrand($bytes) {
1182 for ($i = 0; $i < $bytes; $i++) {
1183 $enc .= sprintf("%02x", mt_rand(0, 255));
1188 function common_set_returnto($url) {
1189 common_ensure_session();
1190 $_SESSION['returnto'] = $url;
1193 function common_get_returnto() {
1194 common_ensure_session();
1195 return $_SESSION['returnto'];
1198 function common_timestamp() {
1199 return date('YmdHis');
1202 function common_ensure_syslog() {
1203 static $initialized = false;
1204 if (!$initialized) {
1206 openlog($config['syslog']['appname'], 0, LOG_USER);
1207 $initialized = true;
1211 function common_log($priority, $msg, $filename=NULL) {
1212 $logfile = common_config('site', 'logfile');
1214 $log = fopen($logfile, "a");
1216 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1217 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1218 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1219 fwrite($log, $output);
1223 common_ensure_syslog();
1224 syslog($priority, $msg);
1228 function common_debug($msg, $filename=NULL) {
1230 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1232 common_log(LOG_DEBUG, $msg);
1236 function common_log_db_error(&$object, $verb, $filename=NULL) {
1237 $objstr = common_log_objstring($object);
1238 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1239 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1242 function common_log_objstring(&$object) {
1243 if (is_null($object)) {
1246 $arr = $object->toArray();
1248 foreach ($arr as $k => $v) {
1249 $fields[] = "$k='$v'";
1251 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1255 function common_valid_http_url($url) {
1256 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1259 function common_valid_tag($tag) {
1260 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1261 return (Validate::email($matches[1]) ||
1262 preg_match('/^([\w-\.]+)$/', $matches[1]));
1267 # Does a little before-after block for next/prev page
1269 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1271 if ($have_before || $have_after) {
1272 common_element_start('div', array('id' => 'pagination'));
1273 common_element_start('ul', array('id' => 'nav_pagination'));
1277 $pargs = array('page' => $page-1);
1278 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1280 common_element_start('li', 'before');
1281 common_element('a', array('href' => common_local_url($action, $newargs)),
1283 common_element_end('li');
1287 $pargs = array('page' => $page+1);
1288 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1289 common_element_start('li', 'after');
1290 common_element('a', array('href' => common_local_url($action, $newargs)),
1292 common_element_end('li');
1295 if ($have_before || $have_after) {
1296 common_element_end('ul');
1297 common_element_end('div');
1301 /* Following functions are copied from MediaWiki GlobalFunctions.php
1302 * and written by Evan Prodromou. */
1304 function common_accept_to_prefs($accept, $def = '*/*') {
1305 # No arg means accept anything (per HTTP spec)
1307 return array($def => 1);
1312 $parts = explode(',', $accept);
1314 foreach($parts as $part) {
1315 # FIXME: doesn't deal with params like 'text/html; level=1'
1316 @list($value, $qpart) = explode(';', $part);
1318 if(!isset($qpart)) {
1320 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1321 $prefs[$value] = $match[1];
1328 function common_mime_type_match($type, $avail) {
1329 if(array_key_exists($type, $avail)) {
1332 $parts = explode('/', $type);
1333 if(array_key_exists($parts[0] . '/*', $avail)) {
1334 return $parts[0] . '/*';
1335 } elseif(array_key_exists('*/*', $avail)) {
1343 function common_negotiate_type($cprefs, $sprefs) {
1346 foreach(array_keys($sprefs) as $type) {
1347 $parts = explode('/', $type);
1348 if($parts[1] != '*') {
1349 $ckey = common_mime_type_match($type, $cprefs);
1351 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1356 foreach(array_keys($cprefs) as $type) {
1357 $parts = explode('/', $type);
1358 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1359 $skey = common_mime_type_match($type, $sprefs);
1361 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1367 $besttype = "text/html";
1369 foreach(array_keys($combine) as $type) {
1370 if($combine[$type] > $bestq) {
1372 $bestq = $combine[$type];
1379 function common_config($main, $sub) {
1381 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1384 function common_copy_args($from) {
1386 $strip = get_magic_quotes_gpc();
1387 foreach ($from as $k => $v) {
1388 $to[$k] = ($strip) ? stripslashes($v) : $v;
1393 function common_user_uri(&$user) {
1394 return common_local_url('userbyid', array('id' => $user->id));
1397 function common_notice_uri(&$notice) {
1398 return common_local_url('shownotice',
1399 array('notice' => $notice->id));
1402 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1404 function common_confirmation_code($bits) {
1405 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1406 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1407 $chars = ceil($bits/5);
1409 for ($i = 0; $i < $chars; $i++) {
1410 # XXX: convert to string and back
1411 $num = hexdec(common_good_rand(1));
1412 # XXX: randomness is too precious to throw away almost
1413 # 40% of the bits we get!
1414 $code .= $codechars[$num%32];
1419 # convert markup to HTML
1421 function common_markup_to_html($c) {
1422 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1423 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1424 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1425 return Markdown($c);
1428 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1429 $avatar = $profile->getAvatar($size);
1431 return common_avatar_display_url($avatar);
1433 return common_default_avatar($size);
1437 function common_profile_uri($profile) {
1441 $user = User::staticGet($profile->id);
1446 $remote = Remote_profile::staticGet($profile->id);
1448 return $remote->uri;
1450 # XXX: this is a very bad profile!
1454 function common_canonical_sms($sms) {
1456 preg_replace('/\D/', '', $sms);