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', array('type' => 'people')),
190 'title' => common_config('site', 'name').' People Search'));
192 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
193 'href' => common_local_url('opensearch', array('type' => 'notice')),
194 'title' => common_config('site', 'name').' Notice Search'));
198 call_user_func($callable, $data);
200 call_user_func($callable);
203 common_element_end('head');
204 common_element_start('body');
205 common_element_start('div', array('id' => 'wrap'));
206 common_element_start('div', array('id' => 'header'));
208 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
209 || file_exists(theme_file('logo.png')))
211 common_element_start('a', array('href' => common_local_url('public')));
212 common_element('img', array('src' => isset($config['site']['logo']) ?
213 ($config['site']['logo']) : theme_path('logo.png'),
214 'alt' => $config['site']['name'],
216 common_element_end('a');
218 common_element_start('p', array('id' => 'branding'));
219 common_element('a', array('href' => common_local_url('public')),
220 $config['site']['name']);
221 common_element_end('p');
224 common_element('h1', 'pagetitle', $pagetitle);
228 call_user_func($headercall, $data);
230 call_user_func($headercall);
233 common_element_end('div');
234 common_element_start('div', array('id' => 'content'));
237 function common_show_footer() {
239 common_element_end('div'); # content div
241 common_element_start('div', array('id' => 'footer'));
242 common_element_start('div', 'laconica');
243 if (common_config('site', 'broughtby')) {
244 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
246 $instr = _('**%%site.name%%** is a microblogging service. ');
248 $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);
249 $output = common_markup_to_html($instr);
251 common_element_end('div');
252 common_element('img', array('id' => 'cc',
253 'src' => $config['license']['image'],
254 'alt' => $config['license']['title']));
255 common_element_start('p');
256 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
257 common_element('a', array('class' => 'license',
259 'href' => $config['license']['url']),
260 $config['license']['title']);
261 common_text(_('. Contributors should be attributed by full name or nickname.'));
262 common_element_end('p');
263 common_element_end('div');
264 common_element_end('div');
265 common_element_end('body');
266 common_element_end('html');
270 function common_text($txt) {
275 function common_raw($xml) {
280 function common_nav_menu() {
281 $user = common_current_user();
282 common_element_start('ul', array('id' => 'nav'));
284 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
287 common_menu_item(common_local_url('public'), _('Public'));
288 common_menu_item(common_local_url('peoplesearch'), _('Search'));
289 common_menu_item(common_local_url('tags'), _('Tags'));
290 common_menu_item(common_local_url('doc', array('title' => 'help')),
293 common_menu_item(common_local_url('profilesettings'),
295 common_menu_item(common_local_url('logout'),
298 common_menu_item(common_local_url('login'), _('Login'));
299 if (!common_config('site', 'closed')) {
300 common_menu_item(common_local_url('register'), _('Register'));
302 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
304 common_element_end('ul');
307 function common_foot_menu() {
308 common_element_start('ul', array('id' => 'nav_sub'));
309 common_menu_item(common_local_url('doc', array('title' => 'about')),
311 common_menu_item(common_local_url('doc', array('title' => 'faq')),
313 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
315 common_menu_item(common_local_url('doc', array('title' => 'source')),
317 common_menu_item(common_local_url('doc', array('title' => 'contact')),
319 common_element_end('ul');
322 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
325 $lattrs['class'] = 'current';
327 common_element_start('li', $lattrs);
328 $attrs['href'] = $url;
330 $attrs['title'] = $title;
332 common_element('a', $attrs, $text);
333 common_element_end('li');
336 function common_input($id, $label, $value=NULL,$instructions=NULL) {
337 common_element_start('p');
338 common_element('label', array('for' => $id), $label);
339 $attrs = array('name' => $id,
341 'class' => 'input_text',
344 $attrs['value'] = htmlspecialchars($value);
346 common_element('input', $attrs);
348 common_element('span', 'input_instructions', $instructions);
350 common_element_end('p');
353 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
355 common_element_start('p');
356 $attrs = array('name' => $id,
357 'type' => 'checkbox',
358 'class' => 'checkbox',
361 $attrs['value'] = htmlspecialchars($value);
364 $attrs['checked'] = 'checked';
366 common_element('input', $attrs);
369 common_element('span', 'checkbox_label', $label);
372 common_element('span', 'input_instructions', $instructions);
374 common_element_end('p');
377 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
378 common_element_start('p');
379 common_element('label', array('for' => $id), $label);
380 common_element_start('select', array('id' => $id, 'name' => $id));
382 common_element('option', array('value' => ''));
384 foreach ($content as $value => $option) {
385 if ($value == $selected) {
386 common_element('option', array('value' => $value, 'selected' => $value), $option);
388 common_element('option', array('value' => $value), $option);
391 common_element_end('select');
393 common_element('span', 'input_instructions', $instructions);
395 common_element_end('p');
397 function common_hidden($id, $value) {
398 common_element('input', array('name' => $id,
404 function common_password($id, $label, $instructions=NULL) {
405 common_element_start('p');
406 common_element('label', array('for' => $id), $label);
407 $attrs = array('name' => $id,
408 'type' => 'password',
409 'class' => 'password',
411 common_element('input', $attrs);
413 common_element('span', 'input_instructions', $instructions);
415 common_element_end('p');
418 function common_submit($id, $label) {
420 common_element_start('p');
421 common_element('input', array('type' => 'submit',
426 common_element_end('p');
429 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
430 common_element_start('p');
431 common_element('label', array('for' => $id), $label);
432 common_element('textarea', array('rows' => 3,
436 ($content) ? $content : '');
438 common_element('span', 'input_instructions', $instructions);
440 common_element_end('p');
443 function common_timezone() {
444 if (common_logged_in()) {
445 $user = common_current_user();
446 if ($user->timezone) {
447 return $user->timezone;
452 return $config['site']['timezone'];
455 function common_language() {
456 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
458 $user_language = FALSE;
460 if (common_logged_in()) {
461 $user = common_current_user();
462 $user_language = $user->language;
465 if ($user_language) {
466 return $user_language;
467 } else if (!empty($httplang)) {
468 $language = client_prefered_language($httplang);
473 return $config['site']['language'];
476 # salted, hashed passwords are stored in the DB
478 function common_munge_password($password, $id) {
479 return md5($password . $id);
482 # check if a username exists and has matching password
483 function common_check_user($nickname, $password) {
484 $user = User::staticGet('nickname', $nickname);
485 if (is_null($user)) {
488 if (0 == strcmp(common_munge_password($password, $user->id),
497 # is the current user logged in?
498 function common_logged_in() {
499 return (!is_null(common_current_user()));
502 function common_have_session() {
503 return (0 != strcmp(session_id(), ''));
506 function common_ensure_session() {
507 if (!common_have_session()) {
512 # Three kinds of arguments:
517 function common_set_user($user) {
518 if (is_null($user) && common_have_session()) {
519 unset($_SESSION['userid']);
521 } else if (is_string($user)) {
523 $user = User::staticGet('nickname', $nickname);
524 } else if (!($user instanceof User)) {
529 common_ensure_session();
530 $_SESSION['userid'] = $user->id;
536 function common_set_cookie($key, $value, $expiration=0) {
537 $path = common_config('site', 'path');
538 $server = common_config('site', 'server');
540 if ($path && ($path != '/')) {
541 $cookiepath = '/' . $path . '/';
545 return setcookie($key,
552 define('REMEMBERME', 'rememberme');
553 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
555 function common_rememberme($user=NULL) {
557 $user = common_current_user();
559 common_debug('No current user to remember', __FILE__);
563 $rm = new Remember_me();
564 $rm->code = common_good_rand(16);
565 $rm->user_id = $user->id;
566 $result = $rm->insert();
568 common_log_db_error($rm, 'INSERT', __FILE__);
569 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
572 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
573 common_set_cookie(REMEMBERME,
574 implode(':', array($rm->user_id, $rm->code)),
575 time() + REMEMBERME_EXPIRY);
579 function common_remembered_user() {
582 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
584 list($id, $code) = explode(':', $packed);
586 $rm = Remember_me::staticGet($code);
587 if ($rm && ($rm->user_id == $id)) {
588 $user = User::staticGet($rm->user_id);
591 $result = $rm->delete();
593 common_log_db_error($rm, 'DELETE', __FILE__);
596 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
597 common_set_user($user->nickname);
598 common_real_login(false);
599 # We issue a new cookie, so they can log in
600 # automatically again after this session
601 common_rememberme($user);
610 # must be called with a valid user!
612 function common_forgetme() {
613 common_set_cookie(REMEMBERME, '', 0);
616 # who is the current user?
617 function common_current_user() {
618 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
619 common_ensure_session();
620 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
622 # note: this should cache
623 $user = User::staticGet($id);
627 # that didn't work; try to remember
628 $user = common_remembered_user();
630 common_debug("Got User " . $user->nickname);
631 common_debug("Faking session on remembered user");
632 $_SESSION['userid'] = $user->id;
637 # Logins that are 'remembered' aren't 'real' -- they're subject to
638 # cookie-stealing. So, we don't let them do certain things. New reg,
639 # OpenID, and password logins _are_ real.
641 function common_real_login($real=true) {
642 common_ensure_session();
643 $_SESSION['real_login'] = $real;
646 function common_is_real_login() {
647 return common_logged_in() && $_SESSION['real_login'];
650 # get canonical version of nickname for comparison
651 function common_canonical_nickname($nickname) {
652 # XXX: UTF-8 canonicalization (like combining chars)
653 return strtolower($nickname);
656 # get canonical version of email for comparison
657 function common_canonical_email($email) {
658 # XXX: canonicalize UTF-8
659 # XXX: lcase the domain part
663 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$_+!*();/?:~-]))');
665 function common_render_content($text, $notice) {
666 $r = htmlspecialchars($text);
668 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
669 $id = $notice->profile_id;
670 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
671 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
672 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
673 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
678 function common_tag_link($tag) {
679 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" class="hashlink">' . $tag . '</a>';
682 function common_at_link($sender_id, $nickname) {
683 $sender = Profile::staticGet($sender_id);
684 $recipient = common_relative_profile($sender, $nickname);
686 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
692 function common_relative_profile($sender, $nickname, $dt=NULL) {
693 # Try to find profiles this profile is subscribed to that have this nickname
694 $recipient = new Profile();
695 # XXX: use a join instead of a subquery
696 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
697 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
698 if ($recipient->find(TRUE)) {
699 # XXX: should probably differentiate between profiles with
700 # the same name by date of most recent update
703 # Try to find profiles that listen to this profile and that have this nickname
704 $recipient = new Profile();
705 # XXX: use a join instead of a subquery
706 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
707 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
708 if ($recipient->find(TRUE)) {
709 # XXX: should probably differentiate between profiles with
710 # the same name by date of most recent update
713 # If this is a local user, try to find a local user with that nickname.
714 $sender = User::staticGet($sender->id);
716 $recipient_user = User::staticGet('nickname', $nickname);
717 if ($recipient_user) {
718 return $recipient_user->getProfile();
721 # Otherwise, no links. @messages from local users to remote users,
722 # or from remote users to other remote users, are just
723 # outside our ability to make intelligent guesses about
727 // where should the avatar go for this user?
729 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
733 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
735 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
739 function common_avatar_path($filename) {
741 return INSTALLDIR . '/avatar/' . $filename;
744 function common_avatar_url($filename) {
745 return common_path('avatar/'.$filename);
748 function common_avatar_display_url($avatar) {
749 $server = common_config('avatar', 'server');
751 return 'http://'.$server.'/'.$avatar->filename;
757 function common_default_avatar($size) {
758 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
759 AVATAR_STREAM_SIZE => 'stream',
760 AVATAR_MINI_SIZE => 'mini');
761 return theme_path('default-avatar-'.$sizenames[$size].'.png');
764 function common_local_url($action, $args=NULL) {
766 if ($config['site']['fancy']) {
767 return common_fancy_url($action, $args);
769 return common_simple_url($action, $args);
773 function common_fancy_url($action, $args=NULL) {
774 switch (strtolower($action)) {
776 if ($args && isset($args['page'])) {
777 return common_path('?page=' . $args['page']);
779 return common_path('');
782 return common_path('rss');
784 return common_path('xrds');
786 if ($args && $args['type']) {
787 return common_path('opensearch/'.$args['type']);
789 return common_path('opensearch/people');
792 return common_path('doc/'.$args['title']);
798 return common_path('main/'.$action);
799 case 'remotesubscribe':
800 if ($args && $args['nickname']) {
801 return common_path('main/remote?nickname=' . $args['nickname']);
803 return common_path('main/remote');
806 return common_path('main/openid');
809 return common_path('settings/'.$action);
810 case 'profilesettings':
811 return common_path('settings/profile');
812 case 'emailsettings':
813 return common_path('settings/email');
814 case 'openidsettings':
815 return common_path('settings/openid');
817 return common_path('settings/sms');
819 if ($args && $args['replyto']) {
820 return common_path('notice/new?replyto='.$args['replyto']);
822 return common_path('notice/new');
825 return common_path('notice/'.$args['notice']);
827 if ($args && $args['notice']) {
828 return common_path('deletenotice/'.$args['notice']);
830 return common_path('deletenotice/');
834 return common_path($args['nickname'].'/'.$action);
835 case 'subscriptions':
839 if ($args && isset($args['page'])) {
840 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
842 return common_path($args['nickname'].'/'.$action);
845 return common_path($args['nickname'].'/all/rss');
847 return common_path($args['nickname'].'/replies/rss');
849 return common_path($args['nickname'].'/rss');
851 if ($args && isset($args['page'])) {
852 return common_path($args['nickname'].'?page=' . $args['page']);
854 return common_path($args['nickname']);
856 case 'confirmaddress':
857 return common_path('main/confirmaddress/'.$args['code']);
859 return common_path('user/'.$args['id']);
860 case 'recoverpassword':
861 $path = 'main/recoverpassword';
863 $path .= '/' . $args['code'];
865 return common_path($path);
867 return common_path('settings/im');
869 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
871 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
872 case 'noticesearchrss':
873 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
874 case 'avatarbynickname':
875 return common_path($args['nickname'].'/avatar/'.$args['size']);
877 if (isset($args['tag']) && $args['tag']) {
878 $path = 'tag/' . $args['tag'];
883 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
885 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
887 return common_simple_url($action, $args);
891 function common_simple_url($action, $args=NULL) {
893 /* XXX: pretty URLs */
896 foreach ($args as $key => $value) {
897 $extra .= "&${key}=${value}";
900 return common_path("index.php?action=${action}${extra}");
903 function common_path($relative) {
905 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
906 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
909 function common_date_string($dt) {
910 // XXX: do some sexy date formatting
911 // return date(DATE_RFC822, $dt);
916 if ($now < $t) { # that shouldn't happen!
917 return common_exact_date($dt);
918 } else if ($diff < 60) {
919 return _('a few seconds ago');
920 } else if ($diff < 92) {
921 return _('about a minute ago');
922 } else if ($diff < 3300) {
923 return sprintf(_('about %d minutes ago'), round($diff/60));
924 } else if ($diff < 5400) {
925 return _('about an hour ago');
926 } else if ($diff < 22 * 3600) {
927 return sprintf(_('about %d hours ago'), round($diff/3600));
928 } else if ($diff < 37 * 3600) {
929 return _('about a day ago');
930 } else if ($diff < 24 * 24 * 3600) {
931 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
932 } else if ($diff < 46 * 24 * 3600) {
933 return _('about a month ago');
934 } else if ($diff < 330 * 24 * 3600) {
935 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
936 } else if ($diff < 480 * 24 * 3600) {
937 return _('about a year ago');
939 return common_exact_date($dt);
943 function common_exact_date($dt) {
948 $_utc = new DateTimeZone('UTC');
949 $_siteTz = new DateTimeZone(common_timezone());
952 $dateStr = date('d F Y H:i:s', strtotime($dt));
953 $d = new DateTime($dateStr, $_utc);
954 $d->setTimezone($_siteTz);
955 return $d->format(DATE_RFC850);
958 function common_date_w3dtf($dt) {
959 $dateStr = date('d F Y H:i:s', strtotime($dt));
960 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
961 $d->setTimezone(new DateTimeZone(common_timezone()));
962 return $d->format(DATE_W3C);
965 function common_date_rfc2822($dt) {
966 $dateStr = date('d F Y H:i:s', strtotime($dt));
967 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
968 $d->setTimezone(new DateTimeZone(common_timezone()));
969 return $d->format('r');
972 function common_date_iso8601($dt) {
973 $dateStr = date('d F Y H:i:s', strtotime($dt));
974 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
975 $d->setTimezone(new DateTimeZone(common_timezone()));
976 return $d->format('c');
979 function common_redirect($url, $code=307) {
980 static $status = array(301 => "Moved Permanently",
983 307 => "Temporary Redirect");
984 header("Status: ${code} $status[$code]");
985 header("Location: $url");
987 common_start_xml('a',
988 '-//W3C//DTD XHTML 1.0 Strict//EN',
989 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
990 common_element('a', array('href' => $url), $url);
995 function common_save_replies($notice) {
996 # Alternative reply format
998 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1001 # extract all @messages
1002 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1003 if (!$cnt && !$tname) {
1006 # XXX: is there another way to make an array copy?
1007 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1008 $sender = Profile::staticGet($notice->profile_id);
1009 # store replied only for first @ (what user/notice what the reply directed,
1010 # we assume first @ is it)
1011 for ($i=0; $i<count($names); $i++) {
1012 $nickname = $names[$i];
1013 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1017 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1018 $reply_for = $recipient;
1019 $recipient_notice = $reply_for->getCurrentNotice();
1020 if ($recipient_notice) {
1021 $orig = clone($notice);
1022 $notice->reply_to = $recipient_notice->id;
1023 $notice->update($orig);
1026 $reply = new Reply();
1027 $reply->notice_id = $notice->id;
1028 $reply->profile_id = $recipient->id;
1029 $id = $reply->insert();
1031 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1032 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1033 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1039 function common_broadcast_notice($notice, $remote=false) {
1040 if (common_config('queue', 'enabled')) {
1042 return common_enqueue_notice($notice);
1044 return common_real_broadcast($notice, $remote);
1048 # Stick the notice on the queue
1050 function common_enqueue_notice($notice) {
1051 $qi = new Queue_item();
1052 $qi->notice_id = $notice->id;
1053 $qi->created = $notice->created;
1054 $result = $qi->insert();
1056 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1057 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1060 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1064 function common_dequeue_notice($notice) {
1065 $qi = Queue_item::staticGet($notice->id);
1067 $result = $qi->delete();
1069 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1070 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1073 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1080 function common_real_broadcast($notice, $remote=false) {
1083 # Make sure we have the OMB stuff
1084 require_once(INSTALLDIR.'/lib/omb.php');
1085 $success = omb_broadcast_remote_subscribers($notice);
1087 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1091 require_once(INSTALLDIR.'/lib/jabber.php');
1092 $success = jabber_broadcast_notice($notice);
1094 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1098 require_once(INSTALLDIR.'/lib/mail.php');
1099 $success = mail_broadcast_notice_sms($notice);
1101 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1104 // XXX: broadcast notices to other IM
1108 function common_broadcast_profile($profile) {
1109 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1110 require_once(INSTALLDIR.'/lib/omb.php');
1111 omb_broadcast_profile($profile);
1112 // XXX: Other broadcasts...?
1116 function common_profile_url($nickname) {
1117 return common_local_url('showstream', array('nickname' => $nickname));
1120 # Don't call if nobody's logged in
1122 function common_notice_form($action=NULL, $content=NULL) {
1123 $user = common_current_user();
1124 assert(!is_null($user));
1125 common_element_start('form', array('id' => 'status_form',
1127 'action' => common_local_url('newnotice')));
1128 common_element_start('p');
1129 common_element('label', array('for' => 'status_textarea',
1130 'id' => 'status_label'),
1131 sprintf(_('What\'s up, %s?'), $user->nickname));
1132 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1133 common_element('textarea', array('id' => 'status_textarea',
1136 'name' => 'status_textarea'),
1137 ($content) ? $content : '');
1139 common_hidden('returnto', $action);
1141 common_element('input', array('id' => 'status_submit',
1142 'name' => 'status_submit',
1144 'value' => _('Send')));
1145 common_element_end('p');
1146 common_element_end('form');
1149 # Should make up a reasonable root URL
1151 function common_root_url() {
1152 return common_path('');
1155 # returns $bytes bytes of random data as a hexadecimal string
1156 # "good" here is a goal and not a guarantee
1158 function common_good_rand($bytes) {
1159 # XXX: use random.org...?
1160 if (file_exists('/dev/urandom')) {
1161 return common_urandom($bytes);
1162 } else { # FIXME: this is probably not good enough
1163 return common_mtrand($bytes);
1167 function common_urandom($bytes) {
1168 $h = fopen('/dev/urandom', 'rb');
1170 $src = fread($h, $bytes);
1173 for ($i = 0; $i < $bytes; $i++) {
1174 $enc .= sprintf("%02x", (ord($src[$i])));
1179 function common_mtrand($bytes) {
1181 for ($i = 0; $i < $bytes; $i++) {
1182 $enc .= sprintf("%02x", mt_rand(0, 255));
1187 function common_set_returnto($url) {
1188 common_ensure_session();
1189 $_SESSION['returnto'] = $url;
1192 function common_get_returnto() {
1193 common_ensure_session();
1194 return $_SESSION['returnto'];
1197 function common_timestamp() {
1198 return date('YmdHis');
1201 function common_ensure_syslog() {
1202 static $initialized = false;
1203 if (!$initialized) {
1205 openlog($config['syslog']['appname'], 0, LOG_USER);
1206 $initialized = true;
1210 function common_log($priority, $msg, $filename=NULL) {
1211 $logfile = common_config('site', 'logfile');
1213 $log = fopen($logfile, "a");
1215 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1216 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1217 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1218 fwrite($log, $output);
1222 common_ensure_syslog();
1223 syslog($priority, $msg);
1227 function common_debug($msg, $filename=NULL) {
1229 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1231 common_log(LOG_DEBUG, $msg);
1235 function common_log_db_error(&$object, $verb, $filename=NULL) {
1236 $objstr = common_log_objstring($object);
1237 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1238 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1241 function common_log_objstring(&$object) {
1242 if (is_null($object)) {
1245 $arr = $object->toArray();
1247 foreach ($arr as $k => $v) {
1248 $fields[] = "$k='$v'";
1250 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1254 function common_valid_http_url($url) {
1255 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1258 function common_valid_tag($tag) {
1259 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1260 return (Validate::email($matches[1]) ||
1261 preg_match('/^([\w-\.]+)$/', $matches[1]));
1266 # Does a little before-after block for next/prev page
1268 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1270 if ($have_before || $have_after) {
1271 common_element_start('div', array('id' => 'pagination'));
1272 common_element_start('ul', array('id' => 'nav_pagination'));
1276 $pargs = array('page' => $page-1);
1277 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1279 common_element_start('li', 'before');
1280 common_element('a', array('href' => common_local_url($action, $newargs)),
1282 common_element_end('li');
1286 $pargs = array('page' => $page+1);
1287 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1288 common_element_start('li', 'after');
1289 common_element('a', array('href' => common_local_url($action, $newargs)),
1291 common_element_end('li');
1294 if ($have_before || $have_after) {
1295 common_element_end('ul');
1296 common_element_end('div');
1300 /* Following functions are copied from MediaWiki GlobalFunctions.php
1301 * and written by Evan Prodromou. */
1303 function common_accept_to_prefs($accept, $def = '*/*') {
1304 # No arg means accept anything (per HTTP spec)
1306 return array($def => 1);
1311 $parts = explode(',', $accept);
1313 foreach($parts as $part) {
1314 # FIXME: doesn't deal with params like 'text/html; level=1'
1315 @list($value, $qpart) = explode(';', $part);
1317 if(!isset($qpart)) {
1319 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1320 $prefs[$value] = $match[1];
1327 function common_mime_type_match($type, $avail) {
1328 if(array_key_exists($type, $avail)) {
1331 $parts = explode('/', $type);
1332 if(array_key_exists($parts[0] . '/*', $avail)) {
1333 return $parts[0] . '/*';
1334 } elseif(array_key_exists('*/*', $avail)) {
1342 function common_negotiate_type($cprefs, $sprefs) {
1345 foreach(array_keys($sprefs) as $type) {
1346 $parts = explode('/', $type);
1347 if($parts[1] != '*') {
1348 $ckey = common_mime_type_match($type, $cprefs);
1350 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1355 foreach(array_keys($cprefs) as $type) {
1356 $parts = explode('/', $type);
1357 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1358 $skey = common_mime_type_match($type, $sprefs);
1360 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1366 $besttype = "text/html";
1368 foreach(array_keys($combine) as $type) {
1369 if($combine[$type] > $bestq) {
1371 $bestq = $combine[$type];
1378 function common_config($main, $sub) {
1380 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1383 function common_copy_args($from) {
1385 $strip = get_magic_quotes_gpc();
1386 foreach ($from as $k => $v) {
1387 $to[$k] = ($strip) ? stripslashes($v) : $v;
1392 function common_user_uri(&$user) {
1393 return common_local_url('userbyid', array('id' => $user->id));
1396 function common_notice_uri(&$notice) {
1397 return common_local_url('shownotice',
1398 array('notice' => $notice->id));
1401 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1403 function common_confirmation_code($bits) {
1404 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1405 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1406 $chars = ceil($bits/5);
1408 for ($i = 0; $i < $chars; $i++) {
1409 # XXX: convert to string and back
1410 $num = hexdec(common_good_rand(1));
1411 # XXX: randomness is too precious to throw away almost
1412 # 40% of the bits we get!
1413 $code .= $codechars[$num%32];
1418 # convert markup to HTML
1420 function common_markup_to_html($c) {
1421 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1422 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1423 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1424 return Markdown($c);
1427 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1428 $avatar = $profile->getAvatar($size);
1430 return common_avatar_display_url($avatar);
1432 return common_default_avatar($size);
1436 function common_profile_uri($profile) {
1440 $user = User::staticGet($profile->id);
1445 $remote = Remote_profile::staticGet($profile->id);
1447 return $remote->uri;
1449 # XXX: this is a very bad profile!
1453 function common_canonical_sms($sms) {
1455 preg_replace('/\D/', '', $sms);