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) {
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101 common_element_start($tag, $attrs);
106 common_element_end($tag);
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
111 $xw = new XMLWriter();
112 $xw->openURI('php://output');
113 $xw->setIndent(true);
114 $xw->startDocument('1.0', 'UTF-8');
116 $xw->writeDTD($doc, $public, $system);
120 function common_end_xml() {
126 define('PAGE_TYPE_PREFS', 'application/xhtml+xml,text/html;q=0.7,application/xml;q=0.3,text/xml;q=0.2');
128 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
131 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
133 # XXX: allow content negotiation for RDF, RSS, or XRDS
135 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
136 common_accept_to_prefs(PAGE_TYPE_PREFS));
139 common_user_error(_t('This page is not available in a media type you accept'), 406);
143 header('Content-Type: '.$type);
145 common_start_xml('html',
146 '-//W3C//DTD XHTML 1.0 Strict//EN',
147 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
149 # FIXME: correct language for interface
151 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
155 common_element_start('head');
156 common_element('title', NULL,
157 $pagetitle . " - " . $config['site']['name']);
158 common_element('link', array('rel' => 'stylesheet',
159 'type' => 'text/css',
160 'href' => theme_path('display.css'),
161 'media' => 'screen, projection, tv'));
162 foreach (array(6,7) as $ver) {
163 if (file_exists(theme_file('ie'.$ver.'.css'))) {
164 # Yes, IE people should be put in jail.
165 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
166 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
170 common_element('script', array('type' => 'text/javascript',
171 'src' => common_path('js/jquery.min.js')),
176 call_user_func($callable, $data);
178 call_user_func($callable);
181 common_element_end('head');
182 common_element_start('body');
183 common_element_start('div', array('id' => 'wrap'));
184 common_element_start('div', array('id' => 'header'));
186 if ((is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
187 || file_exists(theme_file('logo.png')))
189 common_element_start('a', array('href' => common_local_url('public')));
190 common_element('img', array('src' => ($config['site']['logo']) ?
191 ($config['site']['logo']) : theme_path('logo.png'),
192 'alt' => $config['site']['name'],
194 common_element_end('a');
196 common_element_start('p', array('id' => 'branding'));
197 common_element('a', array('href' => common_local_url('public')),
198 $config['site']['name']);
199 common_element_end('p');
202 common_element('h1', 'pagetitle', $pagetitle);
206 call_user_func($headercall, $data);
208 call_user_func($headercall);
211 common_element_end('div');
212 common_element_start('div', array('id' => 'content'));
215 function common_show_footer() {
217 common_element_end('div'); # content div
219 common_element_start('div', array('id' => 'footer'));
220 common_element_start('p', 'laconica');
221 if (common_config('site', 'broughtby')) {
222 $instr = _t('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
224 $instr = _t('**%%site.name%%** is a microblogging service. ');
226 $instr .= _t('It runs the [Laconica](http://laconi.ca/) ' .
227 'microblogging software, version ' . LACONICA_VERSION . ', ' .
228 'available under the ' .
229 '[GNU Affero General Public License]' .
230 '(http://www.fsf.org/licensing/licenses/agpl-3.0.html).');
231 $output = common_markup_to_html($instr);
233 common_element_end('p');
234 common_element('img', array('id' => 'cc',
235 'src' => $config['license']['image'],
236 'alt' => $config['license']['title']));
237 common_element_start('p');
238 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
239 common_element('a', array('class' => 'license',
241 href => $config['license']['url']),
242 $config['license']['title']);
243 common_text(_t('. Contributors should be attributed by full name or nickname.'));
244 common_element_end('p');
245 common_element_end('div');
246 common_element_end('div');
247 common_element_end('body');
248 common_element_end('html');
252 function common_text($txt) {
257 function common_raw($xml) {
262 function common_nav_menu() {
263 $user = common_current_user();
264 common_element_start('ul', array('id' => 'nav'));
266 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
269 common_menu_item(common_local_url('public'), _t('Public'));
270 common_menu_item(common_local_url('doc', array('title' => 'help')),
273 common_menu_item(common_local_url('profilesettings'),
275 common_menu_item(common_local_url('logout'),
278 common_menu_item(common_local_url('login'), _t('Login'));
279 common_menu_item(common_local_url('register'), _t('Register'));
280 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
282 common_element_end('ul');
285 function common_foot_menu() {
286 common_element_start('ul', array('id' => 'nav_sub'));
287 common_menu_item(common_local_url('doc', array('title' => 'about')),
289 common_menu_item(common_local_url('doc', array('title' => 'faq')),
291 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
293 common_menu_item(common_local_url('doc', array('title' => 'source')),
295 common_menu_item(common_local_url('doc', array('title' => 'contact')),
297 common_element_end('ul');
300 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
303 $lattrs['class'] = 'current';
305 common_element_start('li', $lattrs);
306 $attrs['href'] = $url;
308 $attrs['title'] = $title;
310 common_element('a', $attrs, $text);
311 common_element_end('li');
314 function common_input($id, $label, $value=NULL,$instructions=NULL) {
315 common_element_start('p');
316 common_element('label', array('for' => $id), $label);
317 $attrs = array('name' => $id,
319 'class' => 'input_text',
322 $attrs['value'] = htmlspecialchars($value);
324 common_element('input', $attrs);
326 common_element('span', 'input_instructions', $instructions);
328 common_element_end('p');
331 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
333 common_element_start('p');
334 $attrs = array('name' => $id,
335 'type' => 'checkbox',
336 'class' => 'checkbox',
339 $attrs['value'] = htmlspecialchars($value);
342 $attrs['checked'] = 'checked';
344 common_element('input', $attrs);
347 common_element('span', 'checkbox_label', $label);
350 common_element('span', 'input_instructions', $instructions);
352 common_element_end('p');
355 function common_hidden($id, $value) {
356 common_element('input', array('name' => $id,
362 function common_password($id, $label, $instructions=NULL) {
363 common_element_start('p');
364 common_element('label', array('for' => $id), $label);
365 $attrs = array('name' => $id,
366 'type' => 'password',
367 'class' => 'password',
369 common_element('input', $attrs);
371 common_element('span', 'input_instructions', $instructions);
373 common_element_end('p');
376 function common_submit($id, $label) {
378 common_element_start('p');
379 common_element('input', array('type' => 'submit',
384 common_element_end('p');
387 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
388 common_element_start('p');
389 common_element('label', array('for' => $id), $label);
390 common_element('textarea', array('rows' => 3,
394 ($content) ? $content : ' ');
396 common_element('span', 'input_instructions', $instructions);
398 common_element_end('p');
401 # salted, hashed passwords are stored in the DB
403 function common_munge_password($password, $id) {
404 return md5($password . $id);
407 # check if a username exists and has matching password
408 function common_check_user($nickname, $password) {
409 $user = User::staticGet('nickname', $nickname);
410 if (is_null($user)) {
413 return (0 == strcmp(common_munge_password($password, $user->id),
418 # is the current user logged in?
419 function common_logged_in() {
420 return (!is_null(common_current_user()));
423 function common_have_session() {
424 return (0 != strcmp(session_id(), ''));
427 function common_ensure_session() {
428 if (!common_have_session()) {
433 function common_set_user($nickname) {
434 if (is_null($nickname) && common_have_session()) {
435 unset($_SESSION['userid']);
438 $user = User::staticGet('nickname', $nickname);
440 common_ensure_session();
441 $_SESSION['userid'] = $user->id;
450 function common_set_cookie($key, $value, $expiration=0) {
451 $path = common_config('site', 'path');
452 $server = common_config('site', 'server');
454 if ($path && ($path != '/')) {
455 $cookiepath = '/' . $path . '/';
459 return setcookie($key,
466 define('REMEMBERME', 'rememberme');
467 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
469 function common_rememberme() {
470 $user = common_current_user();
474 $rm = new Remember_me();
475 $rm->code = common_good_rand(16);
476 $rm->user_id = $user->id;
477 $result = $rm->insert();
479 common_log_db_error($rm, 'INSERT', __FILE__);
482 common_set_cookie(REMEMBERME,
483 implode(':', array($rm->user_id, $rm->code)),
484 time() + REMEMBERME_EXPIRY);
487 function common_remembered_user() {
490 $packed = $_COOKIE[REMEMBERME];
492 list($id, $code) = explode(':', $packed);
494 $rm = Remember_me::staticGet($code);
495 if ($rm && ($rm->user_id == $id)) {
496 $user = User::staticGet($rm->user_id);
499 $result = $rm->delete();
501 common_log_db_error($rm, 'DELETE', __FILE__);
504 common_set_user($user->nickname);
505 common_real_login(false);
506 # We issue a new cookie, so they can log in
507 # automatically again after this session
517 # must be called with a valid user!
519 function common_forgetme() {
520 common_set_cookie(REMEMBERME, '', 0);
523 # who is the current user?
524 function common_current_user() {
525 if ($_REQUEST[session_name()]) {
526 common_ensure_session();
527 $id = $_SESSION['userid'];
529 # note: this should cache
530 $user = User::staticGet($id);
534 # that didn't work; try to remember
535 $user = common_remembered_user();
539 # Logins that are 'remembered' aren't 'real' -- they're subject to
540 # cookie-stealing. So, we don't let them do certain things. New reg,
541 # OpenID, and password logins _are_ real.
543 function common_real_login($real=true) {
544 common_ensure_session();
545 $_SESSION['real_login'] = $real;
548 function common_is_real_login() {
549 return common_logged_in() && $_SESSION['real_login'];
552 # get canonical version of nickname for comparison
553 function common_canonical_nickname($nickname) {
554 # XXX: UTF-8 canonicalization (like combining chars)
555 return strtolower($nickname);
558 # get canonical version of email for comparison
559 function common_canonical_email($email) {
560 # XXX: canonicalize UTF-8
561 # XXX: lcase the domain part
565 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$_+!*();/?:~-]))');
567 function common_render_content($text, $notice) {
568 $r = htmlspecialchars($text);
569 $id = $notice->profile_id;
570 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
571 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
577 function common_at_link($sender_id, $nickname) {
578 # Try to find profiles this profile is subscribed to that have this nickname
579 $recipient = new Profile();
580 # XXX: chokety and bad
581 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
582 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
583 if ($recipient->find(TRUE)) {
584 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
586 # Try to find profiles that listen to this profile and that have this nickname
587 $recipient = new Profile();
588 # XXX: chokety and bad
589 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
590 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
591 if ($recipient->find(TRUE)) {
592 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
594 # If this is a local user, try to find a local user with that nickname.
595 $sender = User::staticGet($sender_id);
597 $recipient_user = User::staticGet('nickname', $nickname);
598 if ($recipient_user) {
599 return '<a href="'.htmlspecialchars(common_profile_url($nickname)).'" class="atlink usertouser">'.$nickname.'</a>';
602 # Otherwise, no links. @messages from local users to remote users,
603 # or from remote users to other remote users, are just
604 # outside our ability to make intelligent guesses about
608 // where should the avatar go for this user?
610 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
614 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
616 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
620 function common_avatar_path($filename) {
622 return INSTALLDIR . '/avatar/' . $filename;
625 function common_avatar_url($filename) {
626 return common_path('avatar/'.$filename);
629 function common_default_avatar($size) {
630 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
631 AVATAR_STREAM_SIZE => 'stream',
632 AVATAR_MINI_SIZE => 'mini');
633 return theme_path('default-avatar-'.$sizenames[$size].'.png');
636 function common_local_url($action, $args=NULL) {
638 if ($config['site']['fancy']) {
639 return common_fancy_url($action, $args);
641 return common_simple_url($action, $args);
645 function common_fancy_url($action, $args=NULL) {
646 switch (strtolower($action)) {
648 if ($args && $args['page']) {
649 return common_path('?page=' . $args['page']);
651 return common_path('');
654 return common_path('rss');
656 return common_path('xrds');
658 return common_path('doc/'.$args['title']);
664 return common_path('main/'.$action);
665 case 'remotesubscribe':
666 if ($args && $args['nickname']) {
667 return common_path('main/remote?nickname=' . $args['nickname']);
669 return common_path('main/remote');
672 return common_path('main/openid');
675 return common_path('settings/'.$action);
676 case 'profilesettings':
677 return common_path('settings/profile');
678 case 'openidsettings':
679 return common_path('settings/openid');
681 return common_path('notice/new');
683 return common_path('notice/'.$args['notice']);
686 return common_path($args['nickname'].'/'.$action);
687 case 'subscriptions':
690 if ($args && $args['page']) {
691 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
693 return common_path($args['nickname'].'/'.$action);
696 return common_path($args['nickname'].'/all/rss');
698 return common_path($args['nickname'].'/rss');
700 if ($args && $args['page']) {
701 return common_path($args['nickname'].'?page=' . $args['page']);
703 return common_path($args['nickname']);
705 case 'confirmaddress':
706 return common_path('main/confirmaddress/'.$args['code']);
708 return common_path('user/'.$args['id']);
709 case 'recoverpassword':
710 $path = 'main/recoverpassword';
712 $path .= '/' . $args['code'];
714 return common_path($path);
716 return common_path('settings/im');
718 return common_simple_url($action, $args);
722 function common_simple_url($action, $args=NULL) {
724 /* XXX: pretty URLs */
727 foreach ($args as $key => $value) {
728 $extra .= "&${key}=${value}";
731 return common_path("index.php?action=${action}${extra}");
734 function common_path($relative) {
736 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
737 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
740 function common_date_string($dt) {
741 // XXX: do some sexy date formatting
742 // return date(DATE_RFC822, $dt);
747 if ($now < $t) { # that shouldn't happen!
748 return common_exact_date($dt);
749 } else if ($diff < 60) {
750 return _t('a few seconds ago');
751 } else if ($diff < 92) {
752 return _t('about a minute ago');
753 } else if ($diff < 3300) {
754 return _t('about ') . round($diff/60) . _t(' minutes ago');
755 } else if ($diff < 5400) {
756 return _t('about an hour ago');
757 } else if ($diff < 22 * 3600) {
758 return _t('about ') . round($diff/3600) . _t(' hours ago');
759 } else if ($diff < 37 * 3600) {
760 return _t('about a day ago');
761 } else if ($diff < 24 * 24 * 3600) {
762 return _t('about ') . round($diff/(24*3600)) . _t(' days ago');
763 } else if ($diff < 46 * 24 * 3600) {
764 return _t('about a month ago');
765 } else if ($diff < 330 * 24 * 3600) {
766 return _t('about ') . round($diff/(30*24*3600)) . _t(' months ago');
767 } else if ($diff < 480 * 24 * 3600) {
768 return _t('about a year ago');
770 return common_exact_date($dt);
774 function common_exact_date($dt) {
776 return date(DATE_RFC850, $t);
779 function common_date_w3dtf($dt) {
781 return date(DATE_W3C, $t);
784 function common_redirect($url, $code=307) {
785 static $status = array(301 => "Moved Permanently",
788 307 => "Temporary Redirect");
789 header("Status: ${code} $status[$code]");
790 header("Location: $url");
792 common_start_xml('a',
793 '-//W3C//DTD XHTML 1.0 Strict//EN',
794 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
795 common_element('a', array('href' => $url), $url);
799 function common_broadcast_notice($notice, $remote=false) {
800 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
802 # Make sure we have the OMB stuff
803 require_once(INSTALLDIR.'/lib/omb.php');
804 omb_broadcast_remote_subscribers($notice);
806 require_once(INSTALLDIR.'/lib/jabber.php');
807 jabber_broadcast_notice($notice);
808 // XXX: broadcast notices to SMS
809 // XXX: broadcast notices to other IM
813 function common_broadcast_profile($profile) {
814 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
815 require_once(INSTALLDIR.'/lib/omb.php');
816 omb_broadcast_profile($profile);
817 // XXX: Other broadcasts...?
821 function common_profile_url($nickname) {
822 return common_local_url('showstream', array('nickname' => $nickname));
825 # Don't call if nobody's logged in
827 function common_notice_form($action=NULL, $content=NULL) {
828 $user = common_current_user();
829 assert(!is_null($user));
830 common_element_start('form', array('id' => 'status_form',
832 'action' => common_local_url('newnotice')));
833 common_element_start('p');
834 common_element('label', array('for' => 'status_update',
835 'id' => 'status_label'),
836 _t('What\'s up, ').$user->nickname.'?');
837 common_element('textarea', array('id' => 'status_textarea',
838 'name' => 'status_textarea'),
839 ($content) ? $content : ' ');
841 common_hidden('returnto', $action);
843 common_element('input', array('id' => 'status_submit',
844 'name' => 'status_submit',
846 'value' => _t('Send')));
847 common_element_end('p');
848 common_element_end('form');
851 function common_mint_tag($extra) {
854 'tag:'.$config['tag']['authority'].','.
855 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
858 # Should make up a reasonable root URL
860 function common_root_url() {
861 return common_path('');
864 # returns $bytes bytes of random data as a hexadecimal string
865 # "good" here is a goal and not a guarantee
867 function common_good_rand($bytes) {
868 # XXX: use random.org...?
869 if (file_exists('/dev/urandom')) {
870 return common_urandom($bytes);
871 } else { # FIXME: this is probably not good enough
872 return common_mtrand($bytes);
876 function common_urandom($bytes) {
877 $h = fopen('/dev/urandom', 'rb');
879 $src = fread($h, $bytes);
882 for ($i = 0; $i < $bytes; $i++) {
883 $enc .= sprintf("%02x", (ord($src[$i])));
888 function common_mtrand($bytes) {
890 for ($i = 0; $i < $bytes; $i++) {
891 $enc .= sprintf("%02x", mt_rand(0, 255));
896 function common_set_returnto($url) {
897 common_ensure_session();
898 $_SESSION['returnto'] = $url;
901 function common_get_returnto() {
902 common_ensure_session();
903 return $_SESSION['returnto'];
906 function common_timestamp() {
907 return date('YmdHis');
910 // XXX: set up gettext
916 function common_ensure_syslog() {
917 static $initialized = false;
920 define_syslog_variables();
921 openlog($config['syslog']['appname'], 0, LOG_USER);
926 function common_log($priority, $msg, $filename=NULL) {
927 common_ensure_syslog();
928 syslog($priority, $msg);
931 function common_debug($msg, $filename=NULL) {
933 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
935 common_log(LOG_DEBUG, $msg);
939 function common_log_db_error(&$object, $verb, $filename=NULL) {
940 $objstr = common_log_objstring($object);
941 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
942 common_log(LOG_ERROR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
945 function common_log_objstring(&$object) {
946 if (is_null($object)) {
949 $arr = $object->toArray();
951 foreach ($arr as $k => $v) {
952 $fields[] = "$k='$v'";
954 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
958 function common_valid_http_url($url) {
959 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
962 function common_valid_tag($tag) {
963 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
964 return (Validate::email($matches[1]) ||
965 preg_match('/^([\w-\.]+)$/', $matches[1]));
970 # Does a little before-after block for next/prev page
972 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
974 if ($have_before || $have_after) {
975 common_element_start('div', array('id' => 'pagination'));
976 common_element_start('ul', array('id' => 'nav_pagination'));
980 $pargs = array('page' => $page-1);
981 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
983 common_element_start('li', 'before');
984 common_element('a', array('href' => common_local_url($action, $newargs)),
986 common_element_end('li');
990 $pargs = array('page' => $page+1);
991 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
992 common_element_start('li', 'after');
993 common_element('a', array('href' => common_local_url($action, $newargs)),
995 common_element_end('li');
998 if ($have_before || $have_after) {
999 common_element_end('ul');
1000 common_element_end('div');
1004 /* Following functions are copied from MediaWiki GlobalFunctions.php
1005 * and written by Evan Prodromou. */
1007 function common_accept_to_prefs($accept, $def = '*/*') {
1008 # No arg means accept anything (per HTTP spec)
1010 return array($def => 1);
1015 $parts = explode(',', $accept);
1017 foreach($parts as $part) {
1018 # FIXME: doesn't deal with params like 'text/html; level=1'
1019 @list($value, $qpart) = explode(';', $part);
1021 if(!isset($qpart)) {
1023 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1024 $prefs[$value] = $match[1];
1031 function common_mime_type_match($type, $avail) {
1032 if(array_key_exists($type, $avail)) {
1035 $parts = explode('/', $type);
1036 if(array_key_exists($parts[0] . '/*', $avail)) {
1037 return $parts[0] . '/*';
1038 } elseif(array_key_exists('*/*', $avail)) {
1046 function common_negotiate_type($cprefs, $sprefs) {
1049 foreach(array_keys($sprefs) as $type) {
1050 $parts = explode('/', $type);
1051 if($parts[1] != '*') {
1052 $ckey = common_mime_type_match($type, $cprefs);
1054 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1059 foreach(array_keys($cprefs) as $type) {
1060 $parts = explode('/', $type);
1061 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1062 $skey = common_mime_type_match($type, $sprefs);
1064 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1070 $besttype = "text/html";
1072 foreach(array_keys($combine) as $type) {
1073 if($combine[$type] > $bestq) {
1075 $bestq = $combine[$type];
1082 function common_config($main, $sub) {
1084 return $config[$main][$sub];
1087 function common_copy_args($from) {
1089 $strip = get_magic_quotes_gpc();
1090 foreach ($from as $k => $v) {
1091 $to[$k] = ($strip) ? stripslashes($v) : $v;
1096 function common_user_uri(&$user) {
1097 return common_local_url('userbyid', array('id' => $user->id));
1100 function common_notice_uri(&$notice) {
1101 return common_local_url('shownotice',
1102 array('notice' => $notice->id));
1105 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1107 function common_confirmation_code($bits) {
1108 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1109 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1110 $chars = ceil($bits/5);
1112 for ($i = 0; $i < $chars; $i++) {
1113 # XXX: convert to string and back
1114 $num = hexdec(common_good_rand(1));
1115 # XXX: randomness is too precious to throw away almost
1116 # 40% of the bits we get!
1117 $code .= $codechars[$num%32];
1122 # convert markup to HTML
1124 function common_markup_to_html($c) {
1125 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1126 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1127 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1128 return Markdown($c);