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;
141 # XXX: allow content negotiation for RDF, RSS, or XRDS
143 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
144 common_accept_to_prefs(PAGE_TYPE_PREFS));
147 common_user_error(_('This page is not available in a media type you accept'), 406);
151 header('Content-Type: '.$type);
153 common_start_xml('html',
154 '-//W3C//DTD XHTML 1.0 Strict//EN',
155 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
157 # FIXME: correct language for interface
159 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
163 common_element_start('head');
164 common_element('title', NULL,
165 $pagetitle . " - " . $config['site']['name']);
166 common_element('link', array('rel' => 'stylesheet',
167 'type' => 'text/css',
168 'href' => theme_path('display.css'),
169 'media' => 'screen, projection, tv'));
170 foreach (array(6,7) as $ver) {
171 if (file_exists(theme_file('ie'.$ver.'.css'))) {
172 # Yes, IE people should be put in jail.
173 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
174 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
178 common_element('script', array('type' => 'text/javascript',
179 'src' => common_path('js/jquery.min.js')),
181 common_element('script', array('type' => 'text/javascript',
182 'src' => common_path('js/util.js')),
187 call_user_func($callable, $data);
189 call_user_func($callable);
192 common_element_end('head');
193 common_element_start('body');
194 common_element_start('div', array('id' => 'wrap'));
195 common_element_start('div', array('id' => 'header'));
197 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
198 || file_exists(theme_file('logo.png')))
200 common_element_start('a', array('href' => common_local_url('public')));
201 common_element('img', array('src' => isset($config['site']['logo']) ?
202 ($config['site']['logo']) : theme_path('logo.png'),
203 'alt' => $config['site']['name'],
205 common_element_end('a');
207 common_element_start('p', array('id' => 'branding'));
208 common_element('a', array('href' => common_local_url('public')),
209 $config['site']['name']);
210 common_element_end('p');
213 common_element('h1', 'pagetitle', $pagetitle);
217 call_user_func($headercall, $data);
219 call_user_func($headercall);
222 common_element_end('div');
223 common_element_start('div', array('id' => 'content'));
226 function common_show_footer() {
228 common_element_end('div'); # content div
230 common_element_start('div', array('id' => 'footer'));
231 common_element_start('div', 'laconica');
232 if (common_config('site', 'broughtby')) {
233 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
235 $instr = _('**%%site.name%%** is a microblogging service. ');
237 $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);
238 $output = common_markup_to_html($instr);
240 common_element_end('div');
241 common_element('img', array('id' => 'cc',
242 'src' => $config['license']['image'],
243 'alt' => $config['license']['title']));
244 common_element_start('p');
245 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
246 common_element('a', array('class' => 'license',
248 'href' => $config['license']['url']),
249 $config['license']['title']);
250 common_text(_('. Contributors should be attributed by full name or nickname.'));
251 common_element_end('p');
252 common_element_end('div');
253 common_element_end('div');
254 common_element_end('body');
255 common_element_end('html');
259 function common_text($txt) {
264 function common_raw($xml) {
269 function common_nav_menu() {
270 $user = common_current_user();
271 common_element_start('ul', array('id' => 'nav'));
273 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
276 common_menu_item(common_local_url('public'), _('Public'));
277 common_menu_item(common_local_url('peoplesearch'), _('Search'));
278 common_menu_item(common_local_url('doc', array('title' => 'help')),
281 common_menu_item(common_local_url('profilesettings'),
283 common_menu_item(common_local_url('logout'),
286 common_menu_item(common_local_url('login'), _('Login'));
287 common_menu_item(common_local_url('register'), _('Register'));
288 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
290 common_element_end('ul');
293 function common_foot_menu() {
294 common_element_start('ul', array('id' => 'nav_sub'));
295 common_menu_item(common_local_url('doc', array('title' => 'about')),
297 common_menu_item(common_local_url('doc', array('title' => 'faq')),
299 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
301 common_menu_item(common_local_url('doc', array('title' => 'source')),
303 common_menu_item(common_local_url('doc', array('title' => 'contact')),
305 common_element_end('ul');
308 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
311 $lattrs['class'] = 'current';
313 common_element_start('li', $lattrs);
314 $attrs['href'] = $url;
316 $attrs['title'] = $title;
318 common_element('a', $attrs, $text);
319 common_element_end('li');
322 function common_input($id, $label, $value=NULL,$instructions=NULL) {
323 common_element_start('p');
324 common_element('label', array('for' => $id), $label);
325 $attrs = array('name' => $id,
327 'class' => 'input_text',
330 $attrs['value'] = htmlspecialchars($value);
332 common_element('input', $attrs);
334 common_element('span', 'input_instructions', $instructions);
336 common_element_end('p');
339 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
341 common_element_start('p');
342 $attrs = array('name' => $id,
343 'type' => 'checkbox',
344 'class' => 'checkbox',
347 $attrs['value'] = htmlspecialchars($value);
350 $attrs['checked'] = 'checked';
352 common_element('input', $attrs);
355 common_element('span', 'checkbox_label', $label);
358 common_element('span', 'input_instructions', $instructions);
360 common_element_end('p');
363 function common_hidden($id, $value) {
364 common_element('input', array('name' => $id,
370 function common_password($id, $label, $instructions=NULL) {
371 common_element_start('p');
372 common_element('label', array('for' => $id), $label);
373 $attrs = array('name' => $id,
374 'type' => 'password',
375 'class' => 'password',
377 common_element('input', $attrs);
379 common_element('span', 'input_instructions', $instructions);
381 common_element_end('p');
384 function common_submit($id, $label) {
386 common_element_start('p');
387 common_element('input', array('type' => 'submit',
392 common_element_end('p');
395 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
396 common_element_start('p');
397 common_element('label', array('for' => $id), $label);
398 common_element('textarea', array('rows' => 3,
402 ($content) ? $content : '');
404 common_element('span', 'input_instructions', $instructions);
406 common_element_end('p');
409 # salted, hashed passwords are stored in the DB
411 function common_munge_password($password, $id) {
412 return md5($password . $id);
415 # check if a username exists and has matching password
416 function common_check_user($nickname, $password) {
417 $user = User::staticGet('nickname', $nickname);
418 if (is_null($user)) {
421 if (0 == strcmp(common_munge_password($password, $user->id),
430 # is the current user logged in?
431 function common_logged_in() {
432 return (!is_null(common_current_user()));
435 function common_have_session() {
436 return (0 != strcmp(session_id(), ''));
439 function common_ensure_session() {
440 if (!common_have_session()) {
445 # Three kinds of arguments:
450 function common_set_user($user) {
451 if (is_null($user) && common_have_session()) {
452 unset($_SESSION['userid']);
454 } else if (is_string($user)) {
456 $user = User::staticGet('nickname', $nickname);
457 } else if (!($user instanceof User)) {
462 common_ensure_session();
463 $_SESSION['userid'] = $user->id;
469 function common_set_cookie($key, $value, $expiration=0) {
470 $path = common_config('site', 'path');
471 $server = common_config('site', 'server');
473 if ($path && ($path != '/')) {
474 $cookiepath = '/' . $path . '/';
478 return setcookie($key,
485 define('REMEMBERME', 'rememberme');
486 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
488 function common_rememberme($user=NULL) {
490 $user = common_current_user();
492 common_debug('No current user to remember', __FILE__);
496 $rm = new Remember_me();
497 $rm->code = common_good_rand(16);
498 $rm->user_id = $user->id;
499 $result = $rm->insert();
501 common_log_db_error($rm, 'INSERT', __FILE__);
502 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
505 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
506 common_set_cookie(REMEMBERME,
507 implode(':', array($rm->user_id, $rm->code)),
508 time() + REMEMBERME_EXPIRY);
512 function common_remembered_user() {
515 $packed = $_COOKIE[REMEMBERME];
517 list($id, $code) = explode(':', $packed);
519 $rm = Remember_me::staticGet($code);
520 if ($rm && ($rm->user_id == $id)) {
521 $user = User::staticGet($rm->user_id);
524 $result = $rm->delete();
526 common_log_db_error($rm, 'DELETE', __FILE__);
529 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
530 common_set_user($user->nickname);
531 common_real_login(false);
532 # We issue a new cookie, so they can log in
533 # automatically again after this session
534 common_rememberme($user);
543 # must be called with a valid user!
545 function common_forgetme() {
546 common_set_cookie(REMEMBERME, '', 0);
549 # who is the current user?
550 function common_current_user() {
551 if ($_REQUEST[session_name()] || $_SESSION && $_SESSION['userid']) {
552 common_ensure_session();
553 $id = $_SESSION['userid'];
555 # note: this should cache
556 $user = User::staticGet($id);
560 # that didn't work; try to remember
561 $user = common_remembered_user();
562 common_debug("Got User " . $user->nickname);
564 common_debug("Faking session on remembered user");
565 $_SESSION['userid'] = $user->id;
570 # Logins that are 'remembered' aren't 'real' -- they're subject to
571 # cookie-stealing. So, we don't let them do certain things. New reg,
572 # OpenID, and password logins _are_ real.
574 function common_real_login($real=true) {
575 common_ensure_session();
576 $_SESSION['real_login'] = $real;
579 function common_is_real_login() {
580 return common_logged_in() && $_SESSION['real_login'];
583 # get canonical version of nickname for comparison
584 function common_canonical_nickname($nickname) {
585 # XXX: UTF-8 canonicalization (like combining chars)
586 return strtolower($nickname);
589 # get canonical version of email for comparison
590 function common_canonical_email($email) {
591 # XXX: canonicalize UTF-8
592 # XXX: lcase the domain part
596 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$_+!*();/?:~-]))');
598 function common_render_content($text, $notice) {
599 $r = htmlspecialchars($text);
600 $id = $notice->profile_id;
601 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
602 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
603 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
609 function common_at_link($sender_id, $nickname) {
610 $sender = Profile::staticGet($sender_id);
611 $recipient = common_relative_profile($sender, $nickname);
613 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
619 function common_relative_profile($sender, $nickname, $dt=NULL) {
620 # Try to find profiles this profile is subscribed to that have this nickname
621 $recipient = new Profile();
622 # XXX: use a join instead of a subquery
623 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
624 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
625 if ($recipient->find(TRUE)) {
626 # XXX: should probably differentiate between profiles with
627 # the same name by date of most recent update
630 # Try to find profiles that listen to this profile and that have this nickname
631 $recipient = new Profile();
632 # XXX: use a join instead of a subquery
633 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
634 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
635 if ($recipient->find(TRUE)) {
636 # XXX: should probably differentiate between profiles with
637 # the same name by date of most recent update
640 # If this is a local user, try to find a local user with that nickname.
641 $sender = User::staticGet($sender->id);
643 $recipient_user = User::staticGet('nickname', $nickname);
644 if ($recipient_user) {
645 return $recipient_user->getProfile();
648 # Otherwise, no links. @messages from local users to remote users,
649 # or from remote users to other remote users, are just
650 # outside our ability to make intelligent guesses about
654 // where should the avatar go for this user?
656 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
660 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
662 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
666 function common_avatar_path($filename) {
668 return INSTALLDIR . '/avatar/' . $filename;
671 function common_avatar_url($filename) {
672 return common_path('avatar/'.$filename);
675 function common_avatar_display_url($avatar) {
676 $server = common_config('avatar', 'server');
678 return 'http://'.$server.'/'.$avatar->filename;
684 function common_default_avatar($size) {
685 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
686 AVATAR_STREAM_SIZE => 'stream',
687 AVATAR_MINI_SIZE => 'mini');
688 return theme_path('default-avatar-'.$sizenames[$size].'.png');
691 function common_local_url($action, $args=NULL) {
693 if ($config['site']['fancy']) {
694 return common_fancy_url($action, $args);
696 return common_simple_url($action, $args);
700 function common_fancy_url($action, $args=NULL) {
701 switch (strtolower($action)) {
703 if ($args && isset($args['page'])) {
704 return common_path('?page=' . $args['page']);
706 return common_path('');
709 return common_path('rss');
711 return common_path('xrds');
713 return common_path('doc/'.$args['title']);
719 return common_path('main/'.$action);
720 case 'remotesubscribe':
721 if ($args && $args['nickname']) {
722 return common_path('main/remote?nickname=' . $args['nickname']);
724 return common_path('main/remote');
727 return common_path('main/openid');
730 return common_path('settings/'.$action);
731 case 'profilesettings':
732 return common_path('settings/profile');
733 case 'emailsettings':
734 return common_path('settings/email');
735 case 'openidsettings':
736 return common_path('settings/openid');
738 return common_path('settings/sms');
740 if ($args && $args['replyto']) {
741 return common_path('notice/new?replyto='.$args['replyto']);
743 return common_path('notice/new');
746 return common_path('notice/'.$args['notice']);
749 return common_path($args['nickname'].'/'.$action);
750 case 'subscriptions':
754 if ($args && isset($args['page'])) {
755 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
757 return common_path($args['nickname'].'/'.$action);
760 return common_path($args['nickname'].'/all/rss');
762 return common_path($args['nickname'].'/replies/rss');
764 return common_path($args['nickname'].'/rss');
766 if ($args && isset($args['page'])) {
767 return common_path($args['nickname'].'?page=' . $args['page']);
769 return common_path($args['nickname']);
771 case 'confirmaddress':
772 return common_path('main/confirmaddress/'.$args['code']);
774 return common_path('user/'.$args['id']);
775 case 'recoverpassword':
776 $path = 'main/recoverpassword';
778 $path .= '/' . $args['code'];
780 return common_path($path);
782 return common_path('settings/im');
784 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
786 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
787 case 'noticesearchrss':
788 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
789 case 'avatarbynickname':
790 return common_path($args['nickname'].'/avatar/'.$args['size']);
792 return common_simple_url($action, $args);
796 function common_simple_url($action, $args=NULL) {
798 /* XXX: pretty URLs */
801 foreach ($args as $key => $value) {
802 $extra .= "&${key}=${value}";
805 return common_path("index.php?action=${action}${extra}");
808 function common_path($relative) {
810 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
811 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
814 function common_date_string($dt) {
815 // XXX: do some sexy date formatting
816 // return date(DATE_RFC822, $dt);
821 if ($now < $t) { # that shouldn't happen!
822 return common_exact_date($dt);
823 } else if ($diff < 60) {
824 return _('a few seconds ago');
825 } else if ($diff < 92) {
826 return _('about a minute ago');
827 } else if ($diff < 3300) {
828 return sprintf(_('about %d minutes ago'), round($diff/60));
829 } else if ($diff < 5400) {
830 return _('about an hour ago');
831 } else if ($diff < 22 * 3600) {
832 return sprintf(_('about %d hours ago'), round($diff/3600));
833 } else if ($diff < 37 * 3600) {
834 return _('about a day ago');
835 } else if ($diff < 24 * 24 * 3600) {
836 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
837 } else if ($diff < 46 * 24 * 3600) {
838 return _('about a month ago');
839 } else if ($diff < 330 * 24 * 3600) {
840 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
841 } else if ($diff < 480 * 24 * 3600) {
842 return _('about a year ago');
844 return common_exact_date($dt);
848 function common_exact_date($dt) {
850 return date(DATE_RFC850, $t);
853 function common_date_w3dtf($dt) {
855 return date(DATE_W3C, $t);
858 function common_date_rfc2822($dt) {
860 return date("r", $t);
863 function common_date_iso8601($dt) {
865 return date("c", $t);
868 function common_redirect($url, $code=307) {
869 static $status = array(301 => "Moved Permanently",
872 307 => "Temporary Redirect");
873 header("Status: ${code} $status[$code]");
874 header("Location: $url");
876 common_start_xml('a',
877 '-//W3C//DTD XHTML 1.0 Strict//EN',
878 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
879 common_element('a', array('href' => $url), $url);
884 function common_save_replies($notice) {
885 # Alternative reply format
887 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
890 # extract all @messages
891 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
892 if (!$cnt && !$tname) {
895 # XXX: is there another way to make an array copy?
896 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
897 $sender = Profile::staticGet($notice->profile_id);
898 # store replied only for first @ (what user/notice what the reply directed,
899 # we assume first @ is it)
900 for ($i=0; $i<count($names); $i++) {
901 $nickname = $names[$i];
902 $recipient = common_relative_profile($sender, $nickname, $notice->created);
906 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
907 $reply_for = $recipient;
908 $recipient_notice = $reply_for->getCurrentNotice();
909 $orig = clone($notice);
910 $notice->reply_to = $recipient_notice->id;
911 $notice->update($orig);
913 $reply = new Reply();
914 $reply->notice_id = $notice->id;
915 $reply->profile_id = $recipient->id;
916 $id = $reply->insert();
918 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
919 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
920 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
926 function common_broadcast_notice($notice, $remote=false) {
927 if (common_config('queue', 'enabled')) {
929 return common_enqueue_notice($notice);
931 return common_real_broadcast($notice, $remote);
935 # Stick the notice on the queue
937 function common_enqueue_notice($notice) {
938 $qi = new Queue_item();
939 $qi->notice_id = $notice->id;
940 $qi->created = $notice->created;
941 $result = $qi->insert();
943 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
944 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
947 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
951 function common_real_broadcast($notice, $remote=false) {
954 # Make sure we have the OMB stuff
955 require_once(INSTALLDIR.'/lib/omb.php');
956 $success = omb_broadcast_remote_subscribers($notice);
958 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
962 require_once(INSTALLDIR.'/lib/jabber.php');
963 $success = jabber_broadcast_notice($notice);
965 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
969 require_once(INSTALLDIR.'/lib/mail.php');
970 $success = mail_broadcast_notice_sms($notice);
972 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
975 // XXX: broadcast notices to other IM
979 function common_broadcast_profile($profile) {
980 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
981 require_once(INSTALLDIR.'/lib/omb.php');
982 omb_broadcast_profile($profile);
983 // XXX: Other broadcasts...?
987 function common_profile_url($nickname) {
988 return common_local_url('showstream', array('nickname' => $nickname));
991 # Don't call if nobody's logged in
993 function common_notice_form($action=NULL, $content=NULL) {
994 $user = common_current_user();
995 assert(!is_null($user));
996 common_element_start('form', array('id' => 'status_form',
998 'action' => common_local_url('newnotice')));
999 common_element_start('p');
1000 common_element('label', array('for' => 'status_textarea',
1001 'id' => 'status_label'),
1002 sprintf(_('What\'s up, %s?'), $user->nickname));
1003 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1004 common_element('textarea', array('id' => 'status_textarea',
1007 'name' => 'status_textarea'),
1008 ($content) ? $content : '');
1010 common_hidden('returnto', $action);
1012 common_element('input', array('id' => 'status_submit',
1013 'name' => 'status_submit',
1015 'value' => _('Send')));
1016 common_element_end('p');
1017 common_element_end('form');
1020 # Should make up a reasonable root URL
1022 function common_root_url() {
1023 return common_path('');
1026 # returns $bytes bytes of random data as a hexadecimal string
1027 # "good" here is a goal and not a guarantee
1029 function common_good_rand($bytes) {
1030 # XXX: use random.org...?
1031 if (file_exists('/dev/urandom')) {
1032 return common_urandom($bytes);
1033 } else { # FIXME: this is probably not good enough
1034 return common_mtrand($bytes);
1038 function common_urandom($bytes) {
1039 $h = fopen('/dev/urandom', 'rb');
1041 $src = fread($h, $bytes);
1044 for ($i = 0; $i < $bytes; $i++) {
1045 $enc .= sprintf("%02x", (ord($src[$i])));
1050 function common_mtrand($bytes) {
1052 for ($i = 0; $i < $bytes; $i++) {
1053 $enc .= sprintf("%02x", mt_rand(0, 255));
1058 function common_set_returnto($url) {
1059 common_ensure_session();
1060 $_SESSION['returnto'] = $url;
1063 function common_get_returnto() {
1064 common_ensure_session();
1065 return $_SESSION['returnto'];
1068 function common_timestamp() {
1069 return date('YmdHis');
1072 function common_ensure_syslog() {
1073 static $initialized = false;
1074 if (!$initialized) {
1076 openlog($config['syslog']['appname'], 0, LOG_USER);
1077 $initialized = true;
1081 function common_log($priority, $msg, $filename=NULL) {
1082 $logfile = common_config('site', 'logfile');
1084 $log = fopen($logfile, "a");
1086 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1087 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1088 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1089 fwrite($log, $output);
1093 common_ensure_syslog();
1094 syslog($priority, $msg);
1098 function common_debug($msg, $filename=NULL) {
1100 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1102 common_log(LOG_DEBUG, $msg);
1106 function common_log_db_error(&$object, $verb, $filename=NULL) {
1107 $objstr = common_log_objstring($object);
1108 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1109 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1112 function common_log_objstring(&$object) {
1113 if (is_null($object)) {
1116 $arr = $object->toArray();
1118 foreach ($arr as $k => $v) {
1119 $fields[] = "$k='$v'";
1121 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1125 function common_valid_http_url($url) {
1126 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1129 function common_valid_tag($tag) {
1130 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1131 return (Validate::email($matches[1]) ||
1132 preg_match('/^([\w-\.]+)$/', $matches[1]));
1137 # Does a little before-after block for next/prev page
1139 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1141 if ($have_before || $have_after) {
1142 common_element_start('div', array('id' => 'pagination'));
1143 common_element_start('ul', array('id' => 'nav_pagination'));
1147 $pargs = array('page' => $page-1);
1148 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1150 common_element_start('li', 'before');
1151 common_element('a', array('href' => common_local_url($action, $newargs)),
1153 common_element_end('li');
1157 $pargs = array('page' => $page+1);
1158 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1159 common_element_start('li', 'after');
1160 common_element('a', array('href' => common_local_url($action, $newargs)),
1162 common_element_end('li');
1165 if ($have_before || $have_after) {
1166 common_element_end('ul');
1167 common_element_end('div');
1171 /* Following functions are copied from MediaWiki GlobalFunctions.php
1172 * and written by Evan Prodromou. */
1174 function common_accept_to_prefs($accept, $def = '*/*') {
1175 # No arg means accept anything (per HTTP spec)
1177 return array($def => 1);
1182 $parts = explode(',', $accept);
1184 foreach($parts as $part) {
1185 # FIXME: doesn't deal with params like 'text/html; level=1'
1186 @list($value, $qpart) = explode(';', $part);
1188 if(!isset($qpart)) {
1190 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1191 $prefs[$value] = $match[1];
1198 function common_mime_type_match($type, $avail) {
1199 if(array_key_exists($type, $avail)) {
1202 $parts = explode('/', $type);
1203 if(array_key_exists($parts[0] . '/*', $avail)) {
1204 return $parts[0] . '/*';
1205 } elseif(array_key_exists('*/*', $avail)) {
1213 function common_negotiate_type($cprefs, $sprefs) {
1216 foreach(array_keys($sprefs) as $type) {
1217 $parts = explode('/', $type);
1218 if($parts[1] != '*') {
1219 $ckey = common_mime_type_match($type, $cprefs);
1221 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1226 foreach(array_keys($cprefs) as $type) {
1227 $parts = explode('/', $type);
1228 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1229 $skey = common_mime_type_match($type, $sprefs);
1231 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1237 $besttype = "text/html";
1239 foreach(array_keys($combine) as $type) {
1240 if($combine[$type] > $bestq) {
1242 $bestq = $combine[$type];
1249 function common_config($main, $sub) {
1251 return $config[$main][$sub];
1254 function common_copy_args($from) {
1256 $strip = get_magic_quotes_gpc();
1257 foreach ($from as $k => $v) {
1258 $to[$k] = ($strip) ? stripslashes($v) : $v;
1263 function common_user_uri(&$user) {
1264 return common_local_url('userbyid', array('id' => $user->id));
1267 function common_notice_uri(&$notice) {
1268 return common_local_url('shownotice',
1269 array('notice' => $notice->id));
1272 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1274 function common_confirmation_code($bits) {
1275 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1276 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1277 $chars = ceil($bits/5);
1279 for ($i = 0; $i < $chars; $i++) {
1280 # XXX: convert to string and back
1281 $num = hexdec(common_good_rand(1));
1282 # XXX: randomness is too precious to throw away almost
1283 # 40% of the bits we get!
1284 $code .= $codechars[$num%32];
1289 # convert markup to HTML
1291 function common_markup_to_html($c) {
1292 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1293 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1294 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1295 return Markdown($c);
1298 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1299 $avatar = $profile->getAvatar($size);
1301 return common_avatar_display_url($avatar);
1303 return common_default_avatar($size);
1307 function common_profile_uri($profile) {
1311 $user = User::staticGet($profile->id);
1316 $remote = Remote_profile::staticGet($profile->id);
1318 return $remote->uri;
1320 # XXX: this is a very bad profile!
1324 function common_canonical_sms($sms) {
1326 preg_replace('/\D/', '', $sms);