3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
24 function common_server_error($msg, $code=500) {
25 static $status = array(500 => 'Internal Server Error',
26 501 => 'Not Implemented',
28 503 => 'Service Unavailable',
29 504 => 'Gateway Timeout',
30 505 => 'HTTP Version Not Supported');
32 if (!array_key_exists($code, $status)) {
36 $status_string = $status[$code];
38 header('HTTP/1.1 '.$code.' '.$status_string);
39 header('Content-type: text/plain');
47 function common_user_error($msg, $code=400) {
48 static $status = array(400 => 'Bad Request',
49 401 => 'Unauthorized',
50 402 => 'Payment Required',
53 405 => 'Method Not Allowed',
54 406 => 'Not Acceptable',
55 407 => 'Proxy Authentication Required',
56 408 => 'Request Timeout',
59 411 => 'Length Required',
60 412 => 'Precondition Failed',
61 413 => 'Request Entity Too Large',
62 414 => 'Request-URI Too Long',
63 415 => 'Unsupported Media Type',
64 416 => 'Requested Range Not Satisfiable',
65 417 => 'Expectation Failed');
67 if (!array_key_exists($code, $status)) {
71 $status_string = $status[$code];
73 header('HTTP/1.1 '.$code.' '.$status_string);
75 common_show_header('Error');
76 common_element('div', array('class' => 'error'), $msg);
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
85 $xw->startElement($tag);
86 if (is_array($attrs)) {
87 foreach ($attrs as $name => $value) {
88 $xw->writeAttribute($name, $value);
90 } else if (is_string($attrs)) {
91 $xw->writeAttribute('class', $attrs);
95 function common_element_end($tag) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 # XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109 common_element_start($tag, $attrs);
111 if (!is_null($content)) {
114 common_element_end($tag);
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 function common_init_language() {
135 $language = common_language();
136 # So we don't have to make people install the gettext locales
137 putenv('LANGUAGE='.$language);
138 putenv('LANG='.$language);
139 $locale_set = setlocale(LC_ALL, $language . ".utf8",
141 $language . ".utf-8",
142 $language . ".UTF-8",
144 bindtextdomain("laconica", $config['site']['locale_path']);
145 bind_textdomain_codeset("laconica", "UTF-8");
146 textdomain("laconica");
148 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
150 # XXX: allow content negotiation for RDF, RSS, or XRDS
152 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
153 common_accept_to_prefs(PAGE_TYPE_PREFS));
156 common_user_error(_('This page is not available in a media type you accept'), 406);
160 header('Content-Type: '.$type);
162 common_start_xml('html',
163 '-//W3C//DTD XHTML 1.0 Strict//EN',
164 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
166 # FIXME: correct language for interface
168 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
169 'xml:lang' => $language,
170 'lang' => $language));
172 common_element_start('head');
173 common_element('title', NULL,
174 $pagetitle . " - " . $config['site']['name']);
175 common_element('link', array('rel' => 'stylesheet',
176 'type' => 'text/css',
177 'href' => theme_path('display.css'),
178 'media' => 'screen, projection, tv'));
179 foreach (array(6,7) as $ver) {
180 if (file_exists(theme_file('ie'.$ver.'.css'))) {
181 # Yes, IE people should be put in jail.
182 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
183 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
187 common_element('script', array('type' => 'text/javascript',
188 'src' => common_path('js/jquery.min.js')),
190 common_element('script', array('type' => 'text/javascript',
191 'src' => common_path('js/util.js')),
193 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
194 'href' => common_local_url('opensearch', array('type' => 'people')),
195 'title' => common_config('site', 'name').' People Search'));
197 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
198 'href' => common_local_url('opensearch', array('type' => 'notice')),
199 'title' => common_config('site', 'name').' Notice Search'));
203 call_user_func($callable, $data);
205 call_user_func($callable);
208 common_element_end('head');
209 common_element_start('body');
210 common_element_start('div', array('id' => 'wrap'));
211 common_element_start('div', array('id' => 'header'));
213 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
214 || file_exists(theme_file('logo.png')))
216 common_element_start('a', array('href' => common_local_url('public')));
217 common_element('img', array('src' => isset($config['site']['logo']) ?
218 ($config['site']['logo']) : theme_path('logo.png'),
219 'alt' => $config['site']['name'],
221 common_element_end('a');
223 common_element_start('p', array('id' => 'branding'));
224 common_element('a', array('href' => common_local_url('public')),
225 $config['site']['name']);
226 common_element_end('p');
229 common_element('h1', 'pagetitle', $pagetitle);
233 call_user_func($headercall, $data);
235 call_user_func($headercall);
238 common_element_end('div');
239 common_element_start('div', array('id' => 'content'));
242 function common_show_footer() {
244 common_element_end('div'); # content div
246 common_element_start('div', array('id' => 'footer'));
247 common_element_start('div', 'laconica');
248 if (common_config('site', 'broughtby')) {
249 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
251 $instr = _('**%%site.name%%** is a microblogging service. ');
253 $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);
254 $output = common_markup_to_html($instr);
256 common_element_end('div');
257 common_element('img', array('id' => 'cc',
258 'src' => $config['license']['image'],
259 'alt' => $config['license']['title']));
260 common_element_start('p');
261 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
262 common_element('a', array('class' => 'license',
264 'href' => $config['license']['url']),
265 $config['license']['title']);
266 common_text(_('. Contributors should be attributed by full name or nickname.'));
267 common_element_end('p');
268 common_element_end('div');
269 common_element_end('div');
270 common_element_end('body');
271 common_element_end('html');
275 function common_text($txt) {
280 function common_raw($xml) {
285 function common_nav_menu() {
286 $user = common_current_user();
287 common_element_start('ul', array('id' => 'nav'));
289 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
292 common_menu_item(common_local_url('peoplesearch'), _('Search'));
293 common_menu_item(common_local_url('tags'), _('Tags'));
295 common_menu_item(common_local_url('profilesettings'),
297 common_menu_item(common_local_url('logout'),
300 common_menu_item(common_local_url('login'), _('Login'));
301 if (!common_config('site', 'closed')) {
302 common_menu_item(common_local_url('register'), _('Register'));
304 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
306 common_element_end('ul');
309 function common_foot_menu() {
310 common_element_start('ul', array('id' => 'nav_sub'));
311 common_menu_item(common_local_url('doc', array('title' => 'help')),
313 common_menu_item(common_local_url('doc', array('title' => 'about')),
315 common_menu_item(common_local_url('doc', array('title' => 'faq')),
317 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
319 common_menu_item(common_local_url('doc', array('title' => 'source')),
321 common_menu_item(common_local_url('doc', array('title' => 'contact')),
323 common_element_end('ul');
326 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
329 $lattrs['class'] = 'current';
331 common_element_start('li', $lattrs);
332 $attrs['href'] = $url;
334 $attrs['title'] = $title;
336 common_element('a', $attrs, $text);
337 common_element_end('li');
340 function common_input($id, $label, $value=NULL,$instructions=NULL) {
341 common_element_start('p');
342 common_element('label', array('for' => $id), $label);
343 $attrs = array('name' => $id,
345 'class' => 'input_text',
348 $attrs['value'] = htmlspecialchars($value);
350 common_element('input', $attrs);
352 common_element('span', 'input_instructions', $instructions);
354 common_element_end('p');
357 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
359 common_element_start('p');
360 $attrs = array('name' => $id,
361 'type' => 'checkbox',
362 'class' => 'checkbox',
365 $attrs['value'] = htmlspecialchars($value);
368 $attrs['checked'] = 'checked';
370 common_element('input', $attrs);
373 common_element('span', 'checkbox_label', $label);
376 common_element('span', 'input_instructions', $instructions);
378 common_element_end('p');
381 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
382 common_element_start('p');
383 common_element('label', array('for' => $id), $label);
384 common_element_start('select', array('id' => $id, 'name' => $id));
386 common_element('option', array('value' => ''));
388 foreach ($content as $value => $option) {
389 if ($value == $selected) {
390 common_element('option', array('value' => $value, 'selected' => $value), $option);
392 common_element('option', array('value' => $value), $option);
395 common_element_end('select');
397 common_element('span', 'input_instructions', $instructions);
399 common_element_end('p');
401 function common_hidden($id, $value) {
402 common_element('input', array('name' => $id,
408 function common_password($id, $label, $instructions=NULL) {
409 common_element_start('p');
410 common_element('label', array('for' => $id), $label);
411 $attrs = array('name' => $id,
412 'type' => 'password',
413 'class' => 'password',
415 common_element('input', $attrs);
417 common_element('span', 'input_instructions', $instructions);
419 common_element_end('p');
422 function common_submit($id, $label) {
424 common_element_start('p');
425 common_element('input', array('type' => 'submit',
430 common_element_end('p');
433 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
434 common_element_start('p');
435 common_element('label', array('for' => $id), $label);
436 common_element('textarea', array('rows' => 3,
440 ($content) ? $content : '');
442 common_element('span', 'input_instructions', $instructions);
444 common_element_end('p');
447 function common_timezone() {
448 if (common_logged_in()) {
449 $user = common_current_user();
450 if ($user->timezone) {
451 return $user->timezone;
456 return $config['site']['timezone'];
459 function common_language() {
460 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
462 $user_language = FALSE;
464 if (common_logged_in()) {
465 $user = common_current_user();
466 $user_language = $user->language;
469 if ($user_language) {
470 return $user_language;
471 } else if (!empty($httplang)) {
472 $language = client_prefered_language($httplang);
477 return $config['site']['language'];
480 # salted, hashed passwords are stored in the DB
482 function common_munge_password($password, $id) {
483 return md5($password . $id);
486 # check if a username exists and has matching password
487 function common_check_user($nickname, $password) {
488 $user = User::staticGet('nickname', $nickname);
489 if (is_null($user)) {
492 if (0 == strcmp(common_munge_password($password, $user->id),
501 # is the current user logged in?
502 function common_logged_in() {
503 return (!is_null(common_current_user()));
506 function common_have_session() {
507 return (0 != strcmp(session_id(), ''));
510 function common_ensure_session() {
511 if (!common_have_session()) {
516 # Three kinds of arguments:
521 function common_set_user($user) {
522 if (is_null($user) && common_have_session()) {
523 unset($_SESSION['userid']);
525 } else if (is_string($user)) {
527 $user = User::staticGet('nickname', $nickname);
528 } else if (!($user instanceof User)) {
533 common_ensure_session();
534 $_SESSION['userid'] = $user->id;
540 function common_set_cookie($key, $value, $expiration=0) {
541 $path = common_config('site', 'path');
542 $server = common_config('site', 'server');
544 if ($path && ($path != '/')) {
545 $cookiepath = '/' . $path . '/';
549 return setcookie($key,
556 define('REMEMBERME', 'rememberme');
557 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
559 function common_rememberme($user=NULL) {
561 $user = common_current_user();
563 common_debug('No current user to remember', __FILE__);
567 $rm = new Remember_me();
568 $rm->code = common_good_rand(16);
569 $rm->user_id = $user->id;
570 $result = $rm->insert();
572 common_log_db_error($rm, 'INSERT', __FILE__);
573 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
576 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
577 common_set_cookie(REMEMBERME,
578 implode(':', array($rm->user_id, $rm->code)),
579 time() + REMEMBERME_EXPIRY);
583 function common_remembered_user() {
586 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
588 list($id, $code) = explode(':', $packed);
590 $rm = Remember_me::staticGet($code);
591 if ($rm && ($rm->user_id == $id)) {
592 $user = User::staticGet($rm->user_id);
595 $result = $rm->delete();
597 common_log_db_error($rm, 'DELETE', __FILE__);
600 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
601 common_set_user($user->nickname);
602 common_real_login(false);
603 # We issue a new cookie, so they can log in
604 # automatically again after this session
605 common_rememberme($user);
614 # must be called with a valid user!
616 function common_forgetme() {
617 common_set_cookie(REMEMBERME, '', 0);
620 # who is the current user?
621 function common_current_user() {
622 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
623 common_ensure_session();
624 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
626 # note: this should cache
627 $user = User::staticGet($id);
631 # that didn't work; try to remember
632 $user = common_remembered_user();
634 common_debug("Got User " . $user->nickname);
635 common_debug("Faking session on remembered user");
636 $_SESSION['userid'] = $user->id;
641 # Logins that are 'remembered' aren't 'real' -- they're subject to
642 # cookie-stealing. So, we don't let them do certain things. New reg,
643 # OpenID, and password logins _are_ real.
645 function common_real_login($real=true) {
646 common_ensure_session();
647 $_SESSION['real_login'] = $real;
650 function common_is_real_login() {
651 return common_logged_in() && $_SESSION['real_login'];
654 # get canonical version of nickname for comparison
655 function common_canonical_nickname($nickname) {
656 # XXX: UTF-8 canonicalization (like combining chars)
657 return strtolower($nickname);
660 # get canonical version of email for comparison
661 function common_canonical_email($email) {
662 # XXX: canonicalize UTF-8
663 # XXX: lcase the domain part
667 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$_+!*();/?:~-]))');
669 function common_render_content($text, $notice) {
670 $r = htmlspecialchars($text);
672 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
673 $id = $notice->profile_id;
674 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
675 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
676 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
677 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
682 function common_tag_link($tag) {
683 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
686 function common_at_link($sender_id, $nickname) {
687 $sender = Profile::staticGet($sender_id);
688 $recipient = common_relative_profile($sender, $nickname);
690 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
696 function common_relative_profile($sender, $nickname, $dt=NULL) {
697 # Try to find profiles this profile is subscribed to that have this nickname
698 $recipient = new Profile();
699 # XXX: use a join instead of a subquery
700 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
701 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
702 if ($recipient->find(TRUE)) {
703 # XXX: should probably differentiate between profiles with
704 # the same name by date of most recent update
707 # Try to find profiles that listen to this profile and that have this nickname
708 $recipient = new Profile();
709 # XXX: use a join instead of a subquery
710 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
711 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
712 if ($recipient->find(TRUE)) {
713 # XXX: should probably differentiate between profiles with
714 # the same name by date of most recent update
717 # If this is a local user, try to find a local user with that nickname.
718 $sender = User::staticGet($sender->id);
720 $recipient_user = User::staticGet('nickname', $nickname);
721 if ($recipient_user) {
722 return $recipient_user->getProfile();
725 # Otherwise, no links. @messages from local users to remote users,
726 # or from remote users to other remote users, are just
727 # outside our ability to make intelligent guesses about
731 // where should the avatar go for this user?
733 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
737 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
739 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
743 function common_avatar_path($filename) {
745 return INSTALLDIR . '/avatar/' . $filename;
748 function common_avatar_url($filename) {
749 return common_path('avatar/'.$filename);
752 function common_avatar_display_url($avatar) {
753 $server = common_config('avatar', 'server');
755 return 'http://'.$server.'/'.$avatar->filename;
761 function common_default_avatar($size) {
762 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
763 AVATAR_STREAM_SIZE => 'stream',
764 AVATAR_MINI_SIZE => 'mini');
765 return theme_path('default-avatar-'.$sizenames[$size].'.png');
768 function common_local_url($action, $args=NULL) {
770 if ($config['site']['fancy']) {
771 return common_fancy_url($action, $args);
773 return common_simple_url($action, $args);
777 function common_fancy_url($action, $args=NULL) {
778 switch (strtolower($action)) {
780 if ($args && isset($args['page'])) {
781 return common_path('?page=' . $args['page']);
783 return common_path('');
786 return common_path('rss');
788 return common_path('xrds');
790 if ($args && $args['type']) {
791 return common_path('opensearch/'.$args['type']);
793 return common_path('opensearch/people');
796 return common_path('doc/'.$args['title']);
802 return common_path('main/'.$action);
803 case 'remotesubscribe':
804 if ($args && $args['nickname']) {
805 return common_path('main/remote?nickname=' . $args['nickname']);
807 return common_path('main/remote');
810 return common_path('main/openid');
813 return common_path('settings/'.$action);
814 case 'profilesettings':
815 return common_path('settings/profile');
816 case 'emailsettings':
817 return common_path('settings/email');
818 case 'openidsettings':
819 return common_path('settings/openid');
821 return common_path('settings/sms');
823 if ($args && $args['replyto']) {
824 return common_path('notice/new?replyto='.$args['replyto']);
826 return common_path('notice/new');
829 return common_path('notice/'.$args['notice']);
831 if ($args && $args['notice']) {
832 return common_path('notice/delete/'.$args['notice']);
834 return common_path('notice/delete');
838 return common_path($args['nickname'].'/'.$action);
839 case 'subscriptions':
843 if ($args && isset($args['page'])) {
844 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
846 return common_path($args['nickname'].'/'.$action);
849 return common_path($args['nickname'].'/all/rss');
851 return common_path($args['nickname'].'/replies/rss');
853 return common_path($args['nickname'].'/rss');
855 if ($args && isset($args['page'])) {
856 return common_path($args['nickname'].'?page=' . $args['page']);
858 return common_path($args['nickname']);
860 case 'confirmaddress':
861 return common_path('main/confirmaddress/'.$args['code']);
863 return common_path('user/'.$args['id']);
864 case 'recoverpassword':
865 $path = 'main/recoverpassword';
867 $path .= '/' . $args['code'];
869 return common_path($path);
871 return common_path('settings/im');
873 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
875 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
876 case 'noticesearchrss':
877 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
878 case 'avatarbynickname':
879 return common_path($args['nickname'].'/avatar/'.$args['size']);
881 if (isset($args['tag']) && $args['tag']) {
882 $path = 'tag/' . $args['tag'];
887 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
889 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
891 return common_simple_url($action, $args);
895 function common_simple_url($action, $args=NULL) {
897 /* XXX: pretty URLs */
900 foreach ($args as $key => $value) {
901 $extra .= "&${key}=${value}";
904 return common_path("index.php?action=${action}${extra}");
907 function common_path($relative) {
909 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
910 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
913 function common_date_string($dt) {
914 // XXX: do some sexy date formatting
915 // return date(DATE_RFC822, $dt);
920 if ($now < $t) { # that shouldn't happen!
921 return common_exact_date($dt);
922 } else if ($diff < 60) {
923 return _('a few seconds ago');
924 } else if ($diff < 92) {
925 return _('about a minute ago');
926 } else if ($diff < 3300) {
927 return sprintf(_('about %d minutes ago'), round($diff/60));
928 } else if ($diff < 5400) {
929 return _('about an hour ago');
930 } else if ($diff < 22 * 3600) {
931 return sprintf(_('about %d hours ago'), round($diff/3600));
932 } else if ($diff < 37 * 3600) {
933 return _('about a day ago');
934 } else if ($diff < 24 * 24 * 3600) {
935 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
936 } else if ($diff < 46 * 24 * 3600) {
937 return _('about a month ago');
938 } else if ($diff < 330 * 24 * 3600) {
939 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
940 } else if ($diff < 480 * 24 * 3600) {
941 return _('about a year ago');
943 return common_exact_date($dt);
947 function common_exact_date($dt) {
952 $_utc = new DateTimeZone('UTC');
953 $_siteTz = new DateTimeZone(common_timezone());
956 $dateStr = date('d F Y H:i:s', strtotime($dt));
957 $d = new DateTime($dateStr, $_utc);
958 $d->setTimezone($_siteTz);
959 return $d->format(DATE_RFC850);
962 function common_date_w3dtf($dt) {
963 $dateStr = date('d F Y H:i:s', strtotime($dt));
964 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
965 $d->setTimezone(new DateTimeZone(common_timezone()));
966 return $d->format(DATE_W3C);
969 function common_date_rfc2822($dt) {
970 $dateStr = date('d F Y H:i:s', strtotime($dt));
971 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
972 $d->setTimezone(new DateTimeZone(common_timezone()));
973 return $d->format('r');
976 function common_date_iso8601($dt) {
977 $dateStr = date('d F Y H:i:s', strtotime($dt));
978 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
979 $d->setTimezone(new DateTimeZone(common_timezone()));
980 return $d->format('c');
983 function common_redirect($url, $code=307) {
984 static $status = array(301 => "Moved Permanently",
987 307 => "Temporary Redirect");
988 header("Status: ${code} $status[$code]");
989 header("Location: $url");
991 common_start_xml('a',
992 '-//W3C//DTD XHTML 1.0 Strict//EN',
993 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
994 common_element('a', array('href' => $url), $url);
999 function common_save_replies($notice) {
1000 # Alternative reply format
1002 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1005 # extract all @messages
1006 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1007 if (!$cnt && !$tname) {
1010 # XXX: is there another way to make an array copy?
1011 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1012 $sender = Profile::staticGet($notice->profile_id);
1013 # store replied only for first @ (what user/notice what the reply directed,
1014 # we assume first @ is it)
1015 for ($i=0; $i<count($names); $i++) {
1016 $nickname = $names[$i];
1017 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1021 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
1022 $reply_for = $recipient;
1023 $recipient_notice = $reply_for->getCurrentNotice();
1024 if ($recipient_notice) {
1025 $orig = clone($notice);
1026 $notice->reply_to = $recipient_notice->id;
1027 $notice->update($orig);
1030 $reply = new Reply();
1031 $reply->notice_id = $notice->id;
1032 $reply->profile_id = $recipient->id;
1033 $id = $reply->insert();
1035 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1036 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1037 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1043 function common_broadcast_notice($notice, $remote=false) {
1044 if (common_config('queue', 'enabled')) {
1046 return common_enqueue_notice($notice);
1048 return common_real_broadcast($notice, $remote);
1052 # Stick the notice on the queue
1054 function common_enqueue_notice($notice) {
1055 $qi = new Queue_item();
1056 $qi->notice_id = $notice->id;
1057 $qi->created = $notice->created;
1058 $result = $qi->insert();
1060 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1061 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1064 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1068 function common_dequeue_notice($notice) {
1069 $qi = Queue_item::staticGet($notice->id);
1071 $result = $qi->delete();
1073 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1074 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1077 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1084 function common_real_broadcast($notice, $remote=false) {
1087 # Make sure we have the OMB stuff
1088 require_once(INSTALLDIR.'/lib/omb.php');
1089 $success = omb_broadcast_remote_subscribers($notice);
1091 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1095 require_once(INSTALLDIR.'/lib/jabber.php');
1096 $success = jabber_broadcast_notice($notice);
1098 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1102 require_once(INSTALLDIR.'/lib/mail.php');
1103 $success = mail_broadcast_notice_sms($notice);
1105 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1108 // XXX: broadcast notices to other IM
1112 function common_broadcast_profile($profile) {
1113 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1114 require_once(INSTALLDIR.'/lib/omb.php');
1115 omb_broadcast_profile($profile);
1116 // XXX: Other broadcasts...?
1120 function common_profile_url($nickname) {
1121 return common_local_url('showstream', array('nickname' => $nickname));
1124 # Don't call if nobody's logged in
1126 function common_notice_form($action=NULL, $content=NULL) {
1127 $user = common_current_user();
1128 assert(!is_null($user));
1129 common_element_start('form', array('id' => 'status_form',
1131 'action' => common_local_url('newnotice')));
1132 common_element_start('p');
1133 common_element('label', array('for' => 'status_textarea',
1134 'id' => 'status_label'),
1135 sprintf(_('What\'s up, %s?'), $user->nickname));
1136 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1137 common_element('textarea', array('id' => 'status_textarea',
1140 'name' => 'status_textarea'),
1141 ($content) ? $content : '');
1143 common_hidden('returnto', $action);
1145 common_element('input', array('id' => 'status_submit',
1146 'name' => 'status_submit',
1148 'value' => _('Send')));
1149 common_element_end('p');
1150 common_element_end('form');
1153 # Should make up a reasonable root URL
1155 function common_root_url() {
1156 return common_path('');
1159 # returns $bytes bytes of random data as a hexadecimal string
1160 # "good" here is a goal and not a guarantee
1162 function common_good_rand($bytes) {
1163 # XXX: use random.org...?
1164 if (file_exists('/dev/urandom')) {
1165 return common_urandom($bytes);
1166 } else { # FIXME: this is probably not good enough
1167 return common_mtrand($bytes);
1171 function common_urandom($bytes) {
1172 $h = fopen('/dev/urandom', 'rb');
1174 $src = fread($h, $bytes);
1177 for ($i = 0; $i < $bytes; $i++) {
1178 $enc .= sprintf("%02x", (ord($src[$i])));
1183 function common_mtrand($bytes) {
1185 for ($i = 0; $i < $bytes; $i++) {
1186 $enc .= sprintf("%02x", mt_rand(0, 255));
1191 function common_set_returnto($url) {
1192 common_ensure_session();
1193 $_SESSION['returnto'] = $url;
1196 function common_get_returnto() {
1197 common_ensure_session();
1198 return $_SESSION['returnto'];
1201 function common_timestamp() {
1202 return date('YmdHis');
1205 function common_ensure_syslog() {
1206 static $initialized = false;
1207 if (!$initialized) {
1209 openlog($config['syslog']['appname'], 0, LOG_USER);
1210 $initialized = true;
1214 function common_log($priority, $msg, $filename=NULL) {
1215 $logfile = common_config('site', 'logfile');
1217 $log = fopen($logfile, "a");
1219 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1220 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1221 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1222 fwrite($log, $output);
1226 common_ensure_syslog();
1227 syslog($priority, $msg);
1231 function common_debug($msg, $filename=NULL) {
1233 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1235 common_log(LOG_DEBUG, $msg);
1239 function common_log_db_error(&$object, $verb, $filename=NULL) {
1240 $objstr = common_log_objstring($object);
1241 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1242 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1245 function common_log_objstring(&$object) {
1246 if (is_null($object)) {
1249 $arr = $object->toArray();
1251 foreach ($arr as $k => $v) {
1252 $fields[] = "$k='$v'";
1254 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1258 function common_valid_http_url($url) {
1259 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1262 function common_valid_tag($tag) {
1263 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1264 return (Validate::email($matches[1]) ||
1265 preg_match('/^([\w-\.]+)$/', $matches[1]));
1270 # Does a little before-after block for next/prev page
1272 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1274 if ($have_before || $have_after) {
1275 common_element_start('div', array('id' => 'pagination'));
1276 common_element_start('ul', array('id' => 'nav_pagination'));
1280 $pargs = array('page' => $page-1);
1281 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1283 common_element_start('li', 'before');
1284 common_element('a', array('href' => common_local_url($action, $newargs)),
1286 common_element_end('li');
1290 $pargs = array('page' => $page+1);
1291 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1292 common_element_start('li', 'after');
1293 common_element('a', array('href' => common_local_url($action, $newargs)),
1295 common_element_end('li');
1298 if ($have_before || $have_after) {
1299 common_element_end('ul');
1300 common_element_end('div');
1304 /* Following functions are copied from MediaWiki GlobalFunctions.php
1305 * and written by Evan Prodromou. */
1307 function common_accept_to_prefs($accept, $def = '*/*') {
1308 # No arg means accept anything (per HTTP spec)
1310 return array($def => 1);
1315 $parts = explode(',', $accept);
1317 foreach($parts as $part) {
1318 # FIXME: doesn't deal with params like 'text/html; level=1'
1319 @list($value, $qpart) = explode(';', $part);
1321 if(!isset($qpart)) {
1323 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1324 $prefs[$value] = $match[1];
1331 function common_mime_type_match($type, $avail) {
1332 if(array_key_exists($type, $avail)) {
1335 $parts = explode('/', $type);
1336 if(array_key_exists($parts[0] . '/*', $avail)) {
1337 return $parts[0] . '/*';
1338 } elseif(array_key_exists('*/*', $avail)) {
1346 function common_negotiate_type($cprefs, $sprefs) {
1349 foreach(array_keys($sprefs) as $type) {
1350 $parts = explode('/', $type);
1351 if($parts[1] != '*') {
1352 $ckey = common_mime_type_match($type, $cprefs);
1354 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1359 foreach(array_keys($cprefs) as $type) {
1360 $parts = explode('/', $type);
1361 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1362 $skey = common_mime_type_match($type, $sprefs);
1364 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1370 $besttype = "text/html";
1372 foreach(array_keys($combine) as $type) {
1373 if($combine[$type] > $bestq) {
1375 $bestq = $combine[$type];
1382 function common_config($main, $sub) {
1384 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1387 function common_copy_args($from) {
1389 $strip = get_magic_quotes_gpc();
1390 foreach ($from as $k => $v) {
1391 $to[$k] = ($strip) ? stripslashes($v) : $v;
1396 function common_user_uri(&$user) {
1397 return common_local_url('userbyid', array('id' => $user->id));
1400 function common_notice_uri(&$notice) {
1401 return common_local_url('shownotice',
1402 array('notice' => $notice->id));
1405 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1407 function common_confirmation_code($bits) {
1408 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1409 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1410 $chars = ceil($bits/5);
1412 for ($i = 0; $i < $chars; $i++) {
1413 # XXX: convert to string and back
1414 $num = hexdec(common_good_rand(1));
1415 # XXX: randomness is too precious to throw away almost
1416 # 40% of the bits we get!
1417 $code .= $codechars[$num%32];
1422 # convert markup to HTML
1424 function common_markup_to_html($c) {
1425 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1426 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1427 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1428 return Markdown($c);
1431 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1432 $avatar = $profile->getAvatar($size);
1434 return common_avatar_display_url($avatar);
1436 return common_default_avatar($size);
1440 function common_profile_uri($profile) {
1444 $user = User::staticGet($profile->id);
1449 $remote = Remote_profile::staticGet($profile->id);
1451 return $remote->uri;
1453 # XXX: this is a very bad profile!
1457 function common_canonical_sms($sms) {
1459 preg_replace('/\D/', '', $sms);