3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
24 function common_server_error($msg, $code=500) {
25 static $status = array(500 => 'Internal Server Error',
26 501 => 'Not Implemented',
28 503 => 'Service Unavailable',
29 504 => 'Gateway Timeout',
30 505 => 'HTTP Version Not Supported');
32 if (!array_key_exists($code, $status)) {
36 $status_string = $status[$code];
38 header('HTTP/1.1 '.$code.' '.$status_string);
39 header('Content-type: text/plain');
47 function common_user_error($msg, $code=400) {
48 static $status = array(400 => 'Bad Request',
49 401 => 'Unauthorized',
50 402 => 'Payment Required',
53 405 => 'Method Not Allowed',
54 406 => 'Not Acceptable',
55 407 => 'Proxy Authentication Required',
56 408 => 'Request Timeout',
59 411 => 'Length Required',
60 412 => 'Precondition Failed',
61 413 => 'Request Entity Too Large',
62 414 => 'Request-URI Too Long',
63 415 => 'Unsupported Media Type',
64 416 => 'Requested Range Not Satisfiable',
65 417 => 'Expectation Failed');
67 if (!array_key_exists($code, $status)) {
71 $status_string = $status[$code];
73 header('HTTP/1.1 '.$code.' '.$status_string);
75 common_show_header('Error');
76 common_element('div', array('class' => 'error'), $msg);
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
85 $xw->startElement($tag);
86 if (is_array($attrs)) {
87 foreach ($attrs as $name => $value) {
88 $xw->writeAttribute($name, $value);
90 } else if (is_string($attrs)) {
91 $xw->writeAttribute('class', $attrs);
95 function common_element_end($tag) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 # XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109 common_element_start($tag, $attrs);
111 if (!is_null($content)) {
114 common_element_end($tag);
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
136 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
139 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
140 $language = common_language();
141 setlocale(LC_ALL, $language);
142 bindtextdomain("laconica", $config['site']['locale_path']);
143 textdomain("laconica");
145 # XXX: allow content negotiation for RDF, RSS, or XRDS
147 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
148 common_accept_to_prefs(PAGE_TYPE_PREFS));
151 common_user_error(_('This page is not available in a media type you accept'), 406);
155 header('Content-Type: '.$type);
157 common_start_xml('html',
158 '-//W3C//DTD XHTML 1.0 Strict//EN',
159 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
161 # FIXME: correct language for interface
163 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
164 'xml:lang' => $language,
165 'lang' => $language));
167 common_element_start('head');
168 common_element('title', NULL,
169 $pagetitle . " - " . $config['site']['name']);
170 common_element('link', array('rel' => 'stylesheet',
171 'type' => 'text/css',
172 'href' => theme_path('display.css'),
173 'media' => 'screen, projection, tv'));
174 foreach (array(6,7) as $ver) {
175 if (file_exists(theme_file('ie'.$ver.'.css'))) {
176 # Yes, IE people should be put in jail.
177 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
178 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
182 common_element('script', array('type' => 'text/javascript',
183 'src' => common_path('js/jquery.min.js')),
185 common_element('script', array('type' => 'text/javascript',
186 'src' => common_path('js/util.js')),
188 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
189 'href' => common_local_url('opensearch'), 'title' => common_config('site', 'name').' Search'));
193 call_user_func($callable, $data);
195 call_user_func($callable);
198 common_element_end('head');
199 common_element_start('body');
200 common_element_start('div', array('id' => 'wrap'));
201 common_element_start('div', array('id' => 'header'));
203 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
204 || file_exists(theme_file('logo.png')))
206 common_element_start('a', array('href' => common_local_url('public')));
207 common_element('img', array('src' => isset($config['site']['logo']) ?
208 ($config['site']['logo']) : theme_path('logo.png'),
209 'alt' => $config['site']['name'],
211 common_element_end('a');
213 common_element_start('p', array('id' => 'branding'));
214 common_element('a', array('href' => common_local_url('public')),
215 $config['site']['name']);
216 common_element_end('p');
219 common_element('h1', 'pagetitle', $pagetitle);
223 call_user_func($headercall, $data);
225 call_user_func($headercall);
228 common_element_end('div');
229 common_element_start('div', array('id' => 'content'));
232 function common_show_footer() {
234 common_element_end('div'); # content div
236 common_element_start('div', array('id' => 'footer'));
237 common_element_start('div', 'laconica');
238 if (common_config('site', 'broughtby')) {
239 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
241 $instr = _('**%%site.name%%** is a microblogging service. ');
243 $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION);
244 $output = common_markup_to_html($instr);
246 common_element_end('div');
247 common_element('img', array('id' => 'cc',
248 'src' => $config['license']['image'],
249 'alt' => $config['license']['title']));
250 common_element_start('p');
251 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
252 common_element('a', array('class' => 'license',
254 'href' => $config['license']['url']),
255 $config['license']['title']);
256 common_text(_('. Contributors should be attributed by full name or nickname.'));
257 common_element_end('p');
258 common_element_end('div');
259 common_element_end('div');
260 common_element_end('body');
261 common_element_end('html');
265 function common_text($txt) {
270 function common_raw($xml) {
275 function common_nav_menu() {
276 $user = common_current_user();
277 common_element_start('ul', array('id' => 'nav'));
279 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
282 common_menu_item(common_local_url('public'), _('Public'));
283 common_menu_item(common_local_url('peoplesearch'), _('Search'));
284 common_menu_item(common_local_url('tags'), _('Tags'));
285 common_menu_item(common_local_url('doc', array('title' => 'help')),
288 common_menu_item(common_local_url('profilesettings'),
290 common_menu_item(common_local_url('logout'),
293 common_menu_item(common_local_url('login'), _('Login'));
294 if (!common_config('site', 'closed')) {
295 common_menu_item(common_local_url('register'), _('Register'));
297 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
299 common_element_end('ul');
302 function common_foot_menu() {
303 common_element_start('ul', array('id' => 'nav_sub'));
304 common_menu_item(common_local_url('doc', array('title' => 'about')),
306 common_menu_item(common_local_url('doc', array('title' => 'faq')),
308 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
310 common_menu_item(common_local_url('doc', array('title' => 'source')),
312 common_menu_item(common_local_url('doc', array('title' => 'contact')),
314 common_element_end('ul');
317 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
320 $lattrs['class'] = 'current';
322 common_element_start('li', $lattrs);
323 $attrs['href'] = $url;
325 $attrs['title'] = $title;
327 common_element('a', $attrs, $text);
328 common_element_end('li');
331 function common_input($id, $label, $value=NULL,$instructions=NULL) {
332 common_element_start('p');
333 common_element('label', array('for' => $id), $label);
334 $attrs = array('name' => $id,
336 'class' => 'input_text',
339 $attrs['value'] = htmlspecialchars($value);
341 common_element('input', $attrs);
343 common_element('span', 'input_instructions', $instructions);
345 common_element_end('p');
348 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
350 common_element_start('p');
351 $attrs = array('name' => $id,
352 'type' => 'checkbox',
353 'class' => 'checkbox',
356 $attrs['value'] = htmlspecialchars($value);
359 $attrs['checked'] = 'checked';
361 common_element('input', $attrs);
364 common_element('span', 'checkbox_label', $label);
367 common_element('span', 'input_instructions', $instructions);
369 common_element_end('p');
372 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
373 common_element_start('p');
374 common_element('label', array('for' => $id), $label);
375 common_element_start('select', array('id' => $id, 'name' => $id));
377 common_element('option', array('value' => ''));
379 foreach ($content as $value => $option) {
380 if ($value == $selected) {
381 common_element('option', array('value' => $value, 'selected' => $value), $option);
383 common_element('option', array('value' => $value), $option);
386 common_element_end('select');
388 common_element('span', 'input_instructions', $instructions);
390 common_element_end('p');
392 function common_hidden($id, $value) {
393 common_element('input', array('name' => $id,
399 function common_password($id, $label, $instructions=NULL) {
400 common_element_start('p');
401 common_element('label', array('for' => $id), $label);
402 $attrs = array('name' => $id,
403 'type' => 'password',
404 'class' => 'password',
406 common_element('input', $attrs);
408 common_element('span', 'input_instructions', $instructions);
410 common_element_end('p');
413 function common_submit($id, $label) {
415 common_element_start('p');
416 common_element('input', array('type' => 'submit',
421 common_element_end('p');
424 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
425 common_element_start('p');
426 common_element('label', array('for' => $id), $label);
427 common_element('textarea', array('rows' => 3,
431 ($content) ? $content : '');
433 common_element('span', 'input_instructions', $instructions);
435 common_element_end('p');
438 function common_language() {
439 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
441 $user_language = FALSE;
443 if (common_logged_in()) {
444 $user = common_current_user();
445 $user_language = $user->language;
448 if ($user_language) {
449 return $user_language;
450 } else if (!empty($httplang)) {
451 $language = client_prefered_language($httplang);
456 return $config['site']['language'];
459 # salted, hashed passwords are stored in the DB
461 function common_munge_password($password, $id) {
462 return md5($password . $id);
465 # check if a username exists and has matching password
466 function common_check_user($nickname, $password) {
467 $user = User::staticGet('nickname', $nickname);
468 if (is_null($user)) {
471 if (0 == strcmp(common_munge_password($password, $user->id),
480 # is the current user logged in?
481 function common_logged_in() {
482 return (!is_null(common_current_user()));
485 function common_have_session() {
486 return (0 != strcmp(session_id(), ''));
489 function common_ensure_session() {
490 if (!common_have_session()) {
495 # Three kinds of arguments:
500 function common_set_user($user) {
501 if (is_null($user) && common_have_session()) {
502 unset($_SESSION['userid']);
504 } else if (is_string($user)) {
506 $user = User::staticGet('nickname', $nickname);
507 } else if (!($user instanceof User)) {
512 common_ensure_session();
513 $_SESSION['userid'] = $user->id;
519 function common_set_cookie($key, $value, $expiration=0) {
520 $path = common_config('site', 'path');
521 $server = common_config('site', 'server');
523 if ($path && ($path != '/')) {
524 $cookiepath = '/' . $path . '/';
528 return setcookie($key,
535 define('REMEMBERME', 'rememberme');
536 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
538 function common_rememberme($user=NULL) {
540 $user = common_current_user();
542 common_debug('No current user to remember', __FILE__);
546 $rm = new Remember_me();
547 $rm->code = common_good_rand(16);
548 $rm->user_id = $user->id;
549 $result = $rm->insert();
551 common_log_db_error($rm, 'INSERT', __FILE__);
552 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
555 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
556 common_set_cookie(REMEMBERME,
557 implode(':', array($rm->user_id, $rm->code)),
558 time() + REMEMBERME_EXPIRY);
562 function common_remembered_user() {
565 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
567 list($id, $code) = explode(':', $packed);
569 $rm = Remember_me::staticGet($code);
570 if ($rm && ($rm->user_id == $id)) {
571 $user = User::staticGet($rm->user_id);
574 $result = $rm->delete();
576 common_log_db_error($rm, 'DELETE', __FILE__);
579 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
580 common_set_user($user->nickname);
581 common_real_login(false);
582 # We issue a new cookie, so they can log in
583 # automatically again after this session
584 common_rememberme($user);
593 # must be called with a valid user!
595 function common_forgetme() {
596 common_set_cookie(REMEMBERME, '', 0);
599 # who is the current user?
600 function common_current_user() {
601 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
602 common_ensure_session();
603 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
605 # note: this should cache
606 $user = User::staticGet($id);
610 # that didn't work; try to remember
611 $user = common_remembered_user();
613 common_debug("Got User " . $user->nickname);
614 common_debug("Faking session on remembered user");
615 $_SESSION['userid'] = $user->id;
620 # Logins that are 'remembered' aren't 'real' -- they're subject to
621 # cookie-stealing. So, we don't let them do certain things. New reg,
622 # OpenID, and password logins _are_ real.
624 function common_real_login($real=true) {
625 common_ensure_session();
626 $_SESSION['real_login'] = $real;
629 function common_is_real_login() {
630 return common_logged_in() && $_SESSION['real_login'];
633 # get canonical version of nickname for comparison
634 function common_canonical_nickname($nickname) {
635 # XXX: UTF-8 canonicalization (like combining chars)
636 return strtolower($nickname);
639 # get canonical version of email for comparison
640 function common_canonical_email($email) {
641 # XXX: canonicalize UTF-8
642 # XXX: lcase the domain part
646 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$_+!*();/?:~-]))');
648 function common_render_content($text, $notice) {
649 $r = htmlspecialchars($text);
651 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
652 $id = $notice->profile_id;
653 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
654 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
655 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
656 $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
661 function common_tag_link($tag) {
662 return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" class="hashlink">' . $tag . '</a>';
665 function common_at_link($sender_id, $nickname) {
666 $sender = Profile::staticGet($sender_id);
667 $recipient = common_relative_profile($sender, $nickname);
669 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
675 function common_relative_profile($sender, $nickname, $dt=NULL) {
676 # Try to find profiles this profile is subscribed to that have this nickname
677 $recipient = new Profile();
678 # XXX: use a join instead of a subquery
679 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
680 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
681 if ($recipient->find(TRUE)) {
682 # XXX: should probably differentiate between profiles with
683 # the same name by date of most recent update
686 # Try to find profiles that listen to this profile and that have this nickname
687 $recipient = new Profile();
688 # XXX: use a join instead of a subquery
689 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
690 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
691 if ($recipient->find(TRUE)) {
692 # XXX: should probably differentiate between profiles with
693 # the same name by date of most recent update
696 # If this is a local user, try to find a local user with that nickname.
697 $sender = User::staticGet($sender->id);
699 $recipient_user = User::staticGet('nickname', $nickname);
700 if ($recipient_user) {
701 return $recipient_user->getProfile();
704 # Otherwise, no links. @messages from local users to remote users,
705 # or from remote users to other remote users, are just
706 # outside our ability to make intelligent guesses about
710 // where should the avatar go for this user?
712 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
716 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
718 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
722 function common_avatar_path($filename) {
724 return INSTALLDIR . '/avatar/' . $filename;
727 function common_avatar_url($filename) {
728 return common_path('avatar/'.$filename);
731 function common_avatar_display_url($avatar) {
732 $server = common_config('avatar', 'server');
734 return 'http://'.$server.'/'.$avatar->filename;
740 function common_default_avatar($size) {
741 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
742 AVATAR_STREAM_SIZE => 'stream',
743 AVATAR_MINI_SIZE => 'mini');
744 return theme_path('default-avatar-'.$sizenames[$size].'.png');
747 function common_local_url($action, $args=NULL) {
749 if ($config['site']['fancy']) {
750 return common_fancy_url($action, $args);
752 return common_simple_url($action, $args);
756 function common_fancy_url($action, $args=NULL) {
757 switch (strtolower($action)) {
759 if ($args && isset($args['page'])) {
760 return common_path('?page=' . $args['page']);
762 return common_path('');
765 return common_path('rss');
767 return common_path('xrds');
769 return common_path('opensearch');
771 return common_path('doc/'.$args['title']);
777 return common_path('main/'.$action);
778 case 'remotesubscribe':
779 if ($args && $args['nickname']) {
780 return common_path('main/remote?nickname=' . $args['nickname']);
782 return common_path('main/remote');
785 return common_path('main/openid');
788 return common_path('settings/'.$action);
789 case 'profilesettings':
790 return common_path('settings/profile');
791 case 'emailsettings':
792 return common_path('settings/email');
793 case 'openidsettings':
794 return common_path('settings/openid');
796 return common_path('settings/sms');
798 if ($args && $args['replyto']) {
799 return common_path('notice/new?replyto='.$args['replyto']);
801 return common_path('notice/new');
804 return common_path('notice/'.$args['notice']);
806 if ($args && $args['notice']) {
807 return common_path('deletenotice/'.$args['notice']);
809 return common_path('deletenotice/');
813 return common_path($args['nickname'].'/'.$action);
814 case 'subscriptions':
818 if ($args && isset($args['page'])) {
819 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
821 return common_path($args['nickname'].'/'.$action);
824 return common_path($args['nickname'].'/all/rss');
826 return common_path($args['nickname'].'/replies/rss');
828 return common_path($args['nickname'].'/rss');
830 if ($args && isset($args['page'])) {
831 return common_path($args['nickname'].'?page=' . $args['page']);
833 return common_path($args['nickname']);
835 case 'confirmaddress':
836 return common_path('main/confirmaddress/'.$args['code']);
838 return common_path('user/'.$args['id']);
839 case 'recoverpassword':
840 $path = 'main/recoverpassword';
842 $path .= '/' . $args['code'];
844 return common_path($path);
846 return common_path('settings/im');
848 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
850 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
851 case 'noticesearchrss':
852 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
853 case 'avatarbynickname':
854 return common_path($args['nickname'].'/avatar/'.$args['size']);
856 if (isset($args['tag']) && $args['tag']) {
857 $path = 'tag/' . $args['tag'];
862 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
864 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
866 return common_simple_url($action, $args);
870 function common_simple_url($action, $args=NULL) {
872 /* XXX: pretty URLs */
875 foreach ($args as $key => $value) {
876 $extra .= "&${key}=${value}";
879 return common_path("index.php?action=${action}${extra}");
882 function common_path($relative) {
884 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
885 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
888 function common_date_string($dt) {
889 // XXX: do some sexy date formatting
890 // return date(DATE_RFC822, $dt);
895 if ($now < $t) { # that shouldn't happen!
896 return common_exact_date($dt);
897 } else if ($diff < 60) {
898 return _('a few seconds ago');
899 } else if ($diff < 92) {
900 return _('about a minute ago');
901 } else if ($diff < 3300) {
902 return sprintf(_('about %d minutes ago'), round($diff/60));
903 } else if ($diff < 5400) {
904 return _('about an hour ago');
905 } else if ($diff < 22 * 3600) {
906 return sprintf(_('about %d hours ago'), round($diff/3600));
907 } else if ($diff < 37 * 3600) {
908 return _('about a day ago');
909 } else if ($diff < 24 * 24 * 3600) {
910 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
911 } else if ($diff < 46 * 24 * 3600) {
912 return _('about a month ago');
913 } else if ($diff < 330 * 24 * 3600) {
914 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
915 } else if ($diff < 480 * 24 * 3600) {
916 return _('about a year ago');
918 return common_exact_date($dt);
922 function common_exact_date($dt) {
924 return date(DATE_RFC850, $t);
927 function common_date_w3dtf($dt) {
929 return date(DATE_W3C, $t);
932 function common_date_rfc2822($dt) {
934 return date("r", $t);
937 function common_date_iso8601($dt) {
939 return date("c", $t);
942 function common_redirect($url, $code=307) {
943 static $status = array(301 => "Moved Permanently",
946 307 => "Temporary Redirect");
947 header("Status: ${code} $status[$code]");
948 header("Location: $url");
950 common_start_xml('a',
951 '-//W3C//DTD XHTML 1.0 Strict//EN',
952 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
953 common_element('a', array('href' => $url), $url);
958 function common_save_replies($notice) {
959 # Alternative reply format
961 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
964 # extract all @messages
965 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
966 if (!$cnt && !$tname) {
969 # XXX: is there another way to make an array copy?
970 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
971 $sender = Profile::staticGet($notice->profile_id);
972 # store replied only for first @ (what user/notice what the reply directed,
973 # we assume first @ is it)
974 for ($i=0; $i<count($names); $i++) {
975 $nickname = $names[$i];
976 $recipient = common_relative_profile($sender, $nickname, $notice->created);
980 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
981 $reply_for = $recipient;
982 $recipient_notice = $reply_for->getCurrentNotice();
983 $orig = clone($notice);
984 $notice->reply_to = $recipient_notice->id;
985 $notice->update($orig);
987 $reply = new Reply();
988 $reply->notice_id = $notice->id;
989 $reply->profile_id = $recipient->id;
990 $id = $reply->insert();
992 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
993 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
994 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1000 function common_broadcast_notice($notice, $remote=false) {
1001 if (common_config('queue', 'enabled')) {
1003 return common_enqueue_notice($notice);
1005 return common_real_broadcast($notice, $remote);
1009 # Stick the notice on the queue
1011 function common_enqueue_notice($notice) {
1012 $qi = new Queue_item();
1013 $qi->notice_id = $notice->id;
1014 $qi->created = $notice->created;
1015 $result = $qi->insert();
1017 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1018 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1021 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
1025 function common_dequeue_notice($notice) {
1026 $qi = Queue_Item::staticGet($notice->id);
1028 $result = $qi->delete();
1030 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1031 common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
1034 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1041 function common_real_broadcast($notice, $remote=false) {
1044 # Make sure we have the OMB stuff
1045 require_once(INSTALLDIR.'/lib/omb.php');
1046 $success = omb_broadcast_remote_subscribers($notice);
1048 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1052 require_once(INSTALLDIR.'/lib/jabber.php');
1053 $success = jabber_broadcast_notice($notice);
1055 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1059 require_once(INSTALLDIR.'/lib/mail.php');
1060 $success = mail_broadcast_notice_sms($notice);
1062 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1065 // XXX: broadcast notices to other IM
1069 function common_broadcast_profile($profile) {
1070 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1071 require_once(INSTALLDIR.'/lib/omb.php');
1072 omb_broadcast_profile($profile);
1073 // XXX: Other broadcasts...?
1077 function common_profile_url($nickname) {
1078 return common_local_url('showstream', array('nickname' => $nickname));
1081 # Don't call if nobody's logged in
1083 function common_notice_form($action=NULL, $content=NULL) {
1084 $user = common_current_user();
1085 assert(!is_null($user));
1086 common_element_start('form', array('id' => 'status_form',
1088 'action' => common_local_url('newnotice')));
1089 common_element_start('p');
1090 common_element('label', array('for' => 'status_textarea',
1091 'id' => 'status_label'),
1092 sprintf(_('What\'s up, %s?'), $user->nickname));
1093 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1094 common_element('textarea', array('id' => 'status_textarea',
1097 'name' => 'status_textarea'),
1098 ($content) ? $content : '');
1100 common_hidden('returnto', $action);
1102 common_element('input', array('id' => 'status_submit',
1103 'name' => 'status_submit',
1105 'value' => _('Send')));
1106 common_element_end('p');
1107 common_element_end('form');
1110 # Should make up a reasonable root URL
1112 function common_root_url() {
1113 return common_path('');
1116 # returns $bytes bytes of random data as a hexadecimal string
1117 # "good" here is a goal and not a guarantee
1119 function common_good_rand($bytes) {
1120 # XXX: use random.org...?
1121 if (file_exists('/dev/urandom')) {
1122 return common_urandom($bytes);
1123 } else { # FIXME: this is probably not good enough
1124 return common_mtrand($bytes);
1128 function common_urandom($bytes) {
1129 $h = fopen('/dev/urandom', 'rb');
1131 $src = fread($h, $bytes);
1134 for ($i = 0; $i < $bytes; $i++) {
1135 $enc .= sprintf("%02x", (ord($src[$i])));
1140 function common_mtrand($bytes) {
1142 for ($i = 0; $i < $bytes; $i++) {
1143 $enc .= sprintf("%02x", mt_rand(0, 255));
1148 function common_set_returnto($url) {
1149 common_ensure_session();
1150 $_SESSION['returnto'] = $url;
1153 function common_get_returnto() {
1154 common_ensure_session();
1155 return $_SESSION['returnto'];
1158 function common_timestamp() {
1159 return date('YmdHis');
1162 function common_ensure_syslog() {
1163 static $initialized = false;
1164 if (!$initialized) {
1166 openlog($config['syslog']['appname'], 0, LOG_USER);
1167 $initialized = true;
1171 function common_log($priority, $msg, $filename=NULL) {
1172 $logfile = common_config('site', 'logfile');
1174 $log = fopen($logfile, "a");
1176 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1177 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1178 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1179 fwrite($log, $output);
1183 common_ensure_syslog();
1184 syslog($priority, $msg);
1188 function common_debug($msg, $filename=NULL) {
1190 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1192 common_log(LOG_DEBUG, $msg);
1196 function common_log_db_error(&$object, $verb, $filename=NULL) {
1197 $objstr = common_log_objstring($object);
1198 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1199 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1202 function common_log_objstring(&$object) {
1203 if (is_null($object)) {
1206 $arr = $object->toArray();
1208 foreach ($arr as $k => $v) {
1209 $fields[] = "$k='$v'";
1211 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1215 function common_valid_http_url($url) {
1216 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1219 function common_valid_tag($tag) {
1220 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1221 return (Validate::email($matches[1]) ||
1222 preg_match('/^([\w-\.]+)$/', $matches[1]));
1227 # Does a little before-after block for next/prev page
1229 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1231 if ($have_before || $have_after) {
1232 common_element_start('div', array('id' => 'pagination'));
1233 common_element_start('ul', array('id' => 'nav_pagination'));
1237 $pargs = array('page' => $page-1);
1238 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1240 common_element_start('li', 'before');
1241 common_element('a', array('href' => common_local_url($action, $newargs)),
1243 common_element_end('li');
1247 $pargs = array('page' => $page+1);
1248 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1249 common_element_start('li', 'after');
1250 common_element('a', array('href' => common_local_url($action, $newargs)),
1252 common_element_end('li');
1255 if ($have_before || $have_after) {
1256 common_element_end('ul');
1257 common_element_end('div');
1261 /* Following functions are copied from MediaWiki GlobalFunctions.php
1262 * and written by Evan Prodromou. */
1264 function common_accept_to_prefs($accept, $def = '*/*') {
1265 # No arg means accept anything (per HTTP spec)
1267 return array($def => 1);
1272 $parts = explode(',', $accept);
1274 foreach($parts as $part) {
1275 # FIXME: doesn't deal with params like 'text/html; level=1'
1276 @list($value, $qpart) = explode(';', $part);
1278 if(!isset($qpart)) {
1280 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1281 $prefs[$value] = $match[1];
1288 function common_mime_type_match($type, $avail) {
1289 if(array_key_exists($type, $avail)) {
1292 $parts = explode('/', $type);
1293 if(array_key_exists($parts[0] . '/*', $avail)) {
1294 return $parts[0] . '/*';
1295 } elseif(array_key_exists('*/*', $avail)) {
1303 function common_negotiate_type($cprefs, $sprefs) {
1306 foreach(array_keys($sprefs) as $type) {
1307 $parts = explode('/', $type);
1308 if($parts[1] != '*') {
1309 $ckey = common_mime_type_match($type, $cprefs);
1311 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1316 foreach(array_keys($cprefs) as $type) {
1317 $parts = explode('/', $type);
1318 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1319 $skey = common_mime_type_match($type, $sprefs);
1321 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1327 $besttype = "text/html";
1329 foreach(array_keys($combine) as $type) {
1330 if($combine[$type] > $bestq) {
1332 $bestq = $combine[$type];
1339 function common_config($main, $sub) {
1341 return $config[$main][$sub];
1344 function common_copy_args($from) {
1346 $strip = get_magic_quotes_gpc();
1347 foreach ($from as $k => $v) {
1348 $to[$k] = ($strip) ? stripslashes($v) : $v;
1353 function common_user_uri(&$user) {
1354 return common_local_url('userbyid', array('id' => $user->id));
1357 function common_notice_uri(&$notice) {
1358 return common_local_url('shownotice',
1359 array('notice' => $notice->id));
1362 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1364 function common_confirmation_code($bits) {
1365 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1366 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1367 $chars = ceil($bits/5);
1369 for ($i = 0; $i < $chars; $i++) {
1370 # XXX: convert to string and back
1371 $num = hexdec(common_good_rand(1));
1372 # XXX: randomness is too precious to throw away almost
1373 # 40% of the bits we get!
1374 $code .= $codechars[$num%32];
1379 # convert markup to HTML
1381 function common_markup_to_html($c) {
1382 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1383 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1384 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1385 return Markdown($c);
1388 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1389 $avatar = $profile->getAvatar($size);
1391 return common_avatar_display_url($avatar);
1393 return common_default_avatar($size);
1397 function common_profile_uri($profile) {
1401 $user = User::staticGet($profile->id);
1406 $remote = Remote_profile::staticGet($profile->id);
1408 return $remote->uri;
1410 # XXX: this is a very bad profile!
1414 function common_canonical_sms($sms) {
1416 preg_replace('/\D/', '', $sms);