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);
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 # XXX: Refactor w/common_user_error() ?
227 function common_show_basic_auth_error() {
228 header('HTTP/1.1 401 Unauthorized');
229 header('Content-type: text/plain');
230 print("Could not authenticate you."); # exactly what Twitter says - no \n
234 function common_show_footer() {
236 common_element_end('div'); # content div
238 common_element_start('div', array('id' => 'footer'));
239 common_element_start('div', 'laconica');
240 if (common_config('site', 'broughtby')) {
241 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
243 $instr = _('**%%site.name%%** is a microblogging service. ');
245 $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);
246 $output = common_markup_to_html($instr);
248 common_element_end('div');
249 common_element('img', array('id' => 'cc',
250 'src' => $config['license']['image'],
251 'alt' => $config['license']['title']));
252 common_element_start('p');
253 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
254 common_element('a', array('class' => 'license',
256 'href' => $config['license']['url']),
257 $config['license']['title']);
258 common_text(_('. Contributors should be attributed by full name or nickname.'));
259 common_element_end('p');
260 common_element_end('div');
261 common_element_end('div');
262 common_element_end('body');
263 common_element_end('html');
267 function common_text($txt) {
272 function common_raw($xml) {
277 function common_nav_menu() {
278 $user = common_current_user();
279 common_element_start('ul', array('id' => 'nav'));
281 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
284 common_menu_item(common_local_url('public'), _('Public'));
285 common_menu_item(common_local_url('peoplesearch'), _('Search'));
286 common_menu_item(common_local_url('doc', array('title' => 'help')),
289 common_menu_item(common_local_url('profilesettings'),
291 common_menu_item(common_local_url('logout'),
294 common_menu_item(common_local_url('login'), _('Login'));
295 common_menu_item(common_local_url('register'), _('Register'));
296 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
298 common_element_end('ul');
301 function common_foot_menu() {
302 common_element_start('ul', array('id' => 'nav_sub'));
303 common_menu_item(common_local_url('doc', array('title' => 'about')),
305 common_menu_item(common_local_url('doc', array('title' => 'faq')),
307 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
309 common_menu_item(common_local_url('doc', array('title' => 'source')),
311 common_menu_item(common_local_url('doc', array('title' => 'contact')),
313 common_element_end('ul');
316 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
319 $lattrs['class'] = 'current';
321 common_element_start('li', $lattrs);
322 $attrs['href'] = $url;
324 $attrs['title'] = $title;
326 common_element('a', $attrs, $text);
327 common_element_end('li');
330 function common_input($id, $label, $value=NULL,$instructions=NULL) {
331 common_element_start('p');
332 common_element('label', array('for' => $id), $label);
333 $attrs = array('name' => $id,
335 'class' => 'input_text',
338 $attrs['value'] = htmlspecialchars($value);
340 common_element('input', $attrs);
342 common_element('span', 'input_instructions', $instructions);
344 common_element_end('p');
347 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
349 common_element_start('p');
350 $attrs = array('name' => $id,
351 'type' => 'checkbox',
352 'class' => 'checkbox',
355 $attrs['value'] = htmlspecialchars($value);
358 $attrs['checked'] = 'checked';
360 common_element('input', $attrs);
363 common_element('span', 'checkbox_label', $label);
366 common_element('span', 'input_instructions', $instructions);
368 common_element_end('p');
371 function common_hidden($id, $value) {
372 common_element('input', array('name' => $id,
378 function common_password($id, $label, $instructions=NULL) {
379 common_element_start('p');
380 common_element('label', array('for' => $id), $label);
381 $attrs = array('name' => $id,
382 'type' => 'password',
383 'class' => 'password',
385 common_element('input', $attrs);
387 common_element('span', 'input_instructions', $instructions);
389 common_element_end('p');
392 function common_submit($id, $label) {
394 common_element_start('p');
395 common_element('input', array('type' => 'submit',
400 common_element_end('p');
403 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
404 common_element_start('p');
405 common_element('label', array('for' => $id), $label);
406 common_element('textarea', array('rows' => 3,
410 ($content) ? $content : '');
412 common_element('span', 'input_instructions', $instructions);
414 common_element_end('p');
417 # salted, hashed passwords are stored in the DB
419 function common_munge_password($password, $id) {
420 return md5($password . $id);
423 # check if a username exists and has matching password
424 function common_check_user($nickname, $password) {
425 $user = User::staticGet('nickname', $nickname);
426 if (is_null($user)) {
429 if (0 == strcmp(common_munge_password($password, $user->id),
438 # is the current user logged in?
439 function common_logged_in() {
440 return (!is_null(common_current_user()));
443 function common_have_session() {
444 return (0 != strcmp(session_id(), ''));
447 function common_ensure_session() {
448 if (!common_have_session()) {
453 # Three kinds of arguments:
458 function common_set_user($user) {
459 if (is_null($user) && common_have_session()) {
460 unset($_SESSION['userid']);
462 } else if (is_string($user)) {
464 $user = User::staticGet('nickname', $nickname);
465 } else if (!($user instanceof User)) {
470 common_ensure_session();
471 $_SESSION['userid'] = $user->id;
477 function common_set_cookie($key, $value, $expiration=0) {
478 $path = common_config('site', 'path');
479 $server = common_config('site', 'server');
481 if ($path && ($path != '/')) {
482 $cookiepath = '/' . $path . '/';
486 return setcookie($key,
493 define('REMEMBERME', 'rememberme');
494 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
496 function common_rememberme($user=NULL) {
498 $user = common_current_user();
500 common_debug('No current user to remember', __FILE__);
504 $rm = new Remember_me();
505 $rm->code = common_good_rand(16);
506 $rm->user_id = $user->id;
507 $result = $rm->insert();
509 common_log_db_error($rm, 'INSERT', __FILE__);
510 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
513 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
514 common_set_cookie(REMEMBERME,
515 implode(':', array($rm->user_id, $rm->code)),
516 time() + REMEMBERME_EXPIRY);
520 function common_remembered_user() {
523 $packed = $_COOKIE[REMEMBERME];
525 list($id, $code) = explode(':', $packed);
527 $rm = Remember_me::staticGet($code);
528 if ($rm && ($rm->user_id == $id)) {
529 $user = User::staticGet($rm->user_id);
532 $result = $rm->delete();
534 common_log_db_error($rm, 'DELETE', __FILE__);
537 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
538 common_set_user($user->nickname);
539 common_real_login(false);
540 # We issue a new cookie, so they can log in
541 # automatically again after this session
542 common_rememberme($user);
551 # must be called with a valid user!
553 function common_forgetme() {
554 common_set_cookie(REMEMBERME, '', 0);
557 # who is the current user?
558 function common_current_user() {
559 if ($_REQUEST[session_name()] || $_SESSION && $_SESSION['userid']) {
560 common_ensure_session();
561 $id = $_SESSION['userid'];
563 # note: this should cache
564 $user = User::staticGet($id);
568 # that didn't work; try to remember
569 $user = common_remembered_user();
570 common_debug("Got User " . $user->nickname);
572 common_debug("Faking session on remembered user");
573 $_SESSION['userid'] = $user->id;
578 # Logins that are 'remembered' aren't 'real' -- they're subject to
579 # cookie-stealing. So, we don't let them do certain things. New reg,
580 # OpenID, and password logins _are_ real.
582 function common_real_login($real=true) {
583 common_ensure_session();
584 $_SESSION['real_login'] = $real;
587 function common_is_real_login() {
588 return common_logged_in() && $_SESSION['real_login'];
591 # get canonical version of nickname for comparison
592 function common_canonical_nickname($nickname) {
593 # XXX: UTF-8 canonicalization (like combining chars)
594 return strtolower($nickname);
597 # get canonical version of email for comparison
598 function common_canonical_email($email) {
599 # XXX: canonicalize UTF-8
600 # XXX: lcase the domain part
604 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$_+!*();/?:~-]))');
606 function common_render_content($text, $notice) {
607 $r = htmlspecialchars($text);
608 $id = $notice->profile_id;
609 $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
610 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
611 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
617 function common_at_link($sender_id, $nickname) {
618 $sender = Profile::staticGet($sender_id);
619 $recipient = common_relative_profile($sender, $nickname);
621 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
627 function common_relative_profile($sender, $nickname, $dt=NULL) {
628 # Try to find profiles this profile is subscribed to that have this nickname
629 $recipient = new Profile();
630 # XXX: use a join instead of a subquery
631 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
632 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
633 if ($recipient->find(TRUE)) {
634 # XXX: should probably differentiate between profiles with
635 # the same name by date of most recent update
638 # Try to find profiles that listen to this profile and that have this nickname
639 $recipient = new Profile();
640 # XXX: use a join instead of a subquery
641 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
642 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
643 if ($recipient->find(TRUE)) {
644 # XXX: should probably differentiate between profiles with
645 # the same name by date of most recent update
648 # If this is a local user, try to find a local user with that nickname.
649 $sender = User::staticGet($sender->id);
651 $recipient_user = User::staticGet('nickname', $nickname);
652 if ($recipient_user) {
653 return $recipient_user->getProfile();
656 # Otherwise, no links. @messages from local users to remote users,
657 # or from remote users to other remote users, are just
658 # outside our ability to make intelligent guesses about
662 // where should the avatar go for this user?
664 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
668 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
670 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
674 function common_avatar_path($filename) {
676 return INSTALLDIR . '/avatar/' . $filename;
679 function common_avatar_url($filename) {
680 return common_path('avatar/'.$filename);
683 function common_avatar_display_url($avatar) {
684 $server = common_config('avatar', 'server');
686 return 'http://'.$server.'/'.$avatar->filename;
692 function common_default_avatar($size) {
693 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
694 AVATAR_STREAM_SIZE => 'stream',
695 AVATAR_MINI_SIZE => 'mini');
696 return theme_path('default-avatar-'.$sizenames[$size].'.png');
699 function common_local_url($action, $args=NULL) {
701 if ($config['site']['fancy']) {
702 return common_fancy_url($action, $args);
704 return common_simple_url($action, $args);
708 function common_fancy_url($action, $args=NULL) {
709 switch (strtolower($action)) {
711 if ($args && isset($args['page'])) {
712 return common_path('?page=' . $args['page']);
714 return common_path('');
717 return common_path('rss');
719 return common_path('xrds');
721 return common_path('doc/'.$args['title']);
727 return common_path('main/'.$action);
728 case 'remotesubscribe':
729 if ($args && $args['nickname']) {
730 return common_path('main/remote?nickname=' . $args['nickname']);
732 return common_path('main/remote');
735 return common_path('main/openid');
738 return common_path('settings/'.$action);
739 case 'profilesettings':
740 return common_path('settings/profile');
741 case 'emailsettings':
742 return common_path('settings/email');
743 case 'openidsettings':
744 return common_path('settings/openid');
746 return common_path('settings/sms');
748 if ($args && $args['replyto']) {
749 return common_path('notice/new?replyto='.$args['replyto']);
751 return common_path('notice/new');
754 return common_path('notice/'.$args['notice']);
757 return common_path($args['nickname'].'/'.$action);
758 case 'subscriptions':
762 if ($args && isset($args['page'])) {
763 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
765 return common_path($args['nickname'].'/'.$action);
768 return common_path($args['nickname'].'/all/rss');
770 return common_path($args['nickname'].'/replies/rss');
772 return common_path($args['nickname'].'/rss');
774 if ($args && isset($args['page'])) {
775 return common_path($args['nickname'].'?page=' . $args['page']);
777 return common_path($args['nickname']);
779 case 'confirmaddress':
780 return common_path('main/confirmaddress/'.$args['code']);
782 return common_path('user/'.$args['id']);
783 case 'recoverpassword':
784 $path = 'main/recoverpassword';
786 $path .= '/' . $args['code'];
788 return common_path($path);
790 return common_path('settings/im');
792 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
794 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
795 case 'noticesearchrss':
796 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
797 case 'avatarbynickname':
798 return common_path($args['nickname'].'/avatar/'.$args['size']);
800 return common_simple_url($action, $args);
804 function common_simple_url($action, $args=NULL) {
806 /* XXX: pretty URLs */
809 foreach ($args as $key => $value) {
810 $extra .= "&${key}=${value}";
813 return common_path("index.php?action=${action}${extra}");
816 function common_path($relative) {
818 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
819 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
822 function common_date_string($dt) {
823 // XXX: do some sexy date formatting
824 // return date(DATE_RFC822, $dt);
829 if ($now < $t) { # that shouldn't happen!
830 return common_exact_date($dt);
831 } else if ($diff < 60) {
832 return _('a few seconds ago');
833 } else if ($diff < 92) {
834 return _('about a minute ago');
835 } else if ($diff < 3300) {
836 return sprintf(_('about %d minutes ago'), round($diff/60));
837 } else if ($diff < 5400) {
838 return _('about an hour ago');
839 } else if ($diff < 22 * 3600) {
840 return sprintf(_('about %d hours ago'), round($diff/3600));
841 } else if ($diff < 37 * 3600) {
842 return _('about a day ago');
843 } else if ($diff < 24 * 24 * 3600) {
844 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
845 } else if ($diff < 46 * 24 * 3600) {
846 return _('about a month ago');
847 } else if ($diff < 330 * 24 * 3600) {
848 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
849 } else if ($diff < 480 * 24 * 3600) {
850 return _('about a year ago');
852 return common_exact_date($dt);
856 function common_exact_date($dt) {
858 return date(DATE_RFC850, $t);
861 function common_date_w3dtf($dt) {
863 return date(DATE_W3C, $t);
866 function common_date_rfc2822($dt) {
868 return date("r", $t);
871 function common_date_iso8601($dt) {
873 return date("c", $t);
876 function common_redirect($url, $code=307) {
877 static $status = array(301 => "Moved Permanently",
880 307 => "Temporary Redirect");
881 header("Status: ${code} $status[$code]");
882 header("Location: $url");
884 common_start_xml('a',
885 '-//W3C//DTD XHTML 1.0 Strict//EN',
886 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
887 common_element('a', array('href' => $url), $url);
892 function common_save_replies($notice) {
893 # Alternative reply format
895 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
898 # extract all @messages
899 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
900 if (!$cnt && !$tname) {
903 # XXX: is there another way to make an array copy?
904 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
905 $sender = Profile::staticGet($notice->profile_id);
906 # store replied only for first @ (what user/notice what the reply directed,
907 # we assume first @ is it)
908 for ($i=0; $i<count($names); $i++) {
909 $nickname = $names[$i];
910 $recipient = common_relative_profile($sender, $nickname, $notice->created);
914 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
915 $reply_for = $recipient;
916 $recipient_notice = $reply_for->getCurrentNotice();
917 $orig = clone($notice);
918 $notice->reply_to = $recipient_notice->id;
919 $notice->update($orig);
921 $reply = new Reply();
922 $reply->notice_id = $notice->id;
923 $reply->profile_id = $recipient->id;
924 $id = $reply->insert();
926 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
927 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
928 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
934 function common_broadcast_notice($notice, $remote=false) {
935 if (common_config('queue', 'enabled')) {
937 return common_enqueue_notice($notice);
939 return common_real_broadcast($notice, $remote);
943 # Stick the notice on the queue
945 function common_enqueue_notice($notice) {
946 $qi = new Queue_item();
947 $qi->notice_id = $notice->id;
948 $qi->created = $notice->created;
949 $result = $qi->insert();
951 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
952 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
955 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
959 function common_real_broadcast($notice, $remote=false) {
962 # Make sure we have the OMB stuff
963 require_once(INSTALLDIR.'/lib/omb.php');
964 $success = omb_broadcast_remote_subscribers($notice);
966 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
970 require_once(INSTALLDIR.'/lib/jabber.php');
971 $success = jabber_broadcast_notice($notice);
973 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
977 require_once(INSTALLDIR.'/lib/mail.php');
978 $success = mail_broadcast_notice_sms($notice);
980 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
983 // XXX: broadcast notices to other IM
987 function common_broadcast_profile($profile) {
988 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
989 require_once(INSTALLDIR.'/lib/omb.php');
990 omb_broadcast_profile($profile);
991 // XXX: Other broadcasts...?
995 function common_profile_url($nickname) {
996 return common_local_url('showstream', array('nickname' => $nickname));
999 # Don't call if nobody's logged in
1001 function common_notice_form($action=NULL, $content=NULL) {
1002 $user = common_current_user();
1003 assert(!is_null($user));
1004 common_element_start('form', array('id' => 'status_form',
1006 'action' => common_local_url('newnotice')));
1007 common_element_start('p');
1008 common_element('label', array('for' => 'status_textarea',
1009 'id' => 'status_label'),
1010 sprintf(_('What\'s up, %s?'), $user->nickname));
1011 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1012 common_element('textarea', array('id' => 'status_textarea',
1015 'name' => 'status_textarea'),
1016 ($content) ? $content : '');
1018 common_hidden('returnto', $action);
1020 common_element('input', array('id' => 'status_submit',
1021 'name' => 'status_submit',
1023 'value' => _('Send')));
1024 common_element_end('p');
1025 common_element_end('form');
1028 # Should make up a reasonable root URL
1030 function common_root_url() {
1031 return common_path('');
1034 # returns $bytes bytes of random data as a hexadecimal string
1035 # "good" here is a goal and not a guarantee
1037 function common_good_rand($bytes) {
1038 # XXX: use random.org...?
1039 if (file_exists('/dev/urandom')) {
1040 return common_urandom($bytes);
1041 } else { # FIXME: this is probably not good enough
1042 return common_mtrand($bytes);
1046 function common_urandom($bytes) {
1047 $h = fopen('/dev/urandom', 'rb');
1049 $src = fread($h, $bytes);
1052 for ($i = 0; $i < $bytes; $i++) {
1053 $enc .= sprintf("%02x", (ord($src[$i])));
1058 function common_mtrand($bytes) {
1060 for ($i = 0; $i < $bytes; $i++) {
1061 $enc .= sprintf("%02x", mt_rand(0, 255));
1066 function common_set_returnto($url) {
1067 common_ensure_session();
1068 $_SESSION['returnto'] = $url;
1071 function common_get_returnto() {
1072 common_ensure_session();
1073 return $_SESSION['returnto'];
1076 function common_timestamp() {
1077 return date('YmdHis');
1080 function common_ensure_syslog() {
1081 static $initialized = false;
1082 if (!$initialized) {
1084 openlog($config['syslog']['appname'], 0, LOG_USER);
1085 $initialized = true;
1089 function common_log($priority, $msg, $filename=NULL) {
1090 $logfile = common_config('site', 'logfile');
1092 $log = fopen($logfile, "a");
1094 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1095 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1096 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1097 fwrite($log, $output);
1101 common_ensure_syslog();
1102 syslog($priority, $msg);
1106 function common_debug($msg, $filename=NULL) {
1108 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1110 common_log(LOG_DEBUG, $msg);
1114 function common_log_db_error(&$object, $verb, $filename=NULL) {
1115 $objstr = common_log_objstring($object);
1116 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1117 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1120 function common_log_objstring(&$object) {
1121 if (is_null($object)) {
1124 $arr = $object->toArray();
1126 foreach ($arr as $k => $v) {
1127 $fields[] = "$k='$v'";
1129 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1133 function common_valid_http_url($url) {
1134 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1137 function common_valid_tag($tag) {
1138 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1139 return (Validate::email($matches[1]) ||
1140 preg_match('/^([\w-\.]+)$/', $matches[1]));
1145 # Does a little before-after block for next/prev page
1147 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1149 if ($have_before || $have_after) {
1150 common_element_start('div', array('id' => 'pagination'));
1151 common_element_start('ul', array('id' => 'nav_pagination'));
1155 $pargs = array('page' => $page-1);
1156 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1158 common_element_start('li', 'before');
1159 common_element('a', array('href' => common_local_url($action, $newargs)),
1161 common_element_end('li');
1165 $pargs = array('page' => $page+1);
1166 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1167 common_element_start('li', 'after');
1168 common_element('a', array('href' => common_local_url($action, $newargs)),
1170 common_element_end('li');
1173 if ($have_before || $have_after) {
1174 common_element_end('ul');
1175 common_element_end('div');
1179 /* Following functions are copied from MediaWiki GlobalFunctions.php
1180 * and written by Evan Prodromou. */
1182 function common_accept_to_prefs($accept, $def = '*/*') {
1183 # No arg means accept anything (per HTTP spec)
1185 return array($def => 1);
1190 $parts = explode(',', $accept);
1192 foreach($parts as $part) {
1193 # FIXME: doesn't deal with params like 'text/html; level=1'
1194 @list($value, $qpart) = explode(';', $part);
1196 if(!isset($qpart)) {
1198 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1199 $prefs[$value] = $match[1];
1206 function common_mime_type_match($type, $avail) {
1207 if(array_key_exists($type, $avail)) {
1210 $parts = explode('/', $type);
1211 if(array_key_exists($parts[0] . '/*', $avail)) {
1212 return $parts[0] . '/*';
1213 } elseif(array_key_exists('*/*', $avail)) {
1221 function common_negotiate_type($cprefs, $sprefs) {
1224 foreach(array_keys($sprefs) as $type) {
1225 $parts = explode('/', $type);
1226 if($parts[1] != '*') {
1227 $ckey = common_mime_type_match($type, $cprefs);
1229 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1234 foreach(array_keys($cprefs) as $type) {
1235 $parts = explode('/', $type);
1236 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1237 $skey = common_mime_type_match($type, $sprefs);
1239 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1245 $besttype = "text/html";
1247 foreach(array_keys($combine) as $type) {
1248 if($combine[$type] > $bestq) {
1250 $bestq = $combine[$type];
1257 function common_config($main, $sub) {
1259 return $config[$main][$sub];
1262 function common_copy_args($from) {
1264 $strip = get_magic_quotes_gpc();
1265 foreach ($from as $k => $v) {
1266 $to[$k] = ($strip) ? stripslashes($v) : $v;
1271 function common_user_uri(&$user) {
1272 return common_local_url('userbyid', array('id' => $user->id));
1275 function common_notice_uri(&$notice) {
1276 return common_local_url('shownotice',
1277 array('notice' => $notice->id));
1280 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1282 function common_confirmation_code($bits) {
1283 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1284 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1285 $chars = ceil($bits/5);
1287 for ($i = 0; $i < $chars; $i++) {
1288 # XXX: convert to string and back
1289 $num = hexdec(common_good_rand(1));
1290 # XXX: randomness is too precious to throw away almost
1291 # 40% of the bits we get!
1292 $code .= $codechars[$num%32];
1297 # convert markup to HTML
1299 function common_markup_to_html($c) {
1300 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1301 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1302 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1303 return Markdown($c);
1306 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1307 $avatar = $profile->getAvatar($size);
1309 return common_avatar_display_url($avatar);
1311 return common_default_avatar($size);
1315 function common_profile_uri($profile) {
1319 $user = User::staticGet($profile->id);
1324 $remote = Remote_profile::staticGet($profile->id);
1326 return $remote->uri;
1328 # XXX: this is a very bad profile!
1332 function common_canonical_sms($sms) {
1334 preg_replace('/\D/', '', $sms);