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) {
97 # TODO: switch based on $tag
98 $xw->fullEndElement();
101 function common_element($tag, $attrs=NULL, $content=NULL) {
102 common_element_start($tag, $attrs);
105 common_element_end($tag);
108 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
110 $xw = new XMLWriter();
111 $xw->openURI('php://output');
112 $xw->setIndent(true);
113 $xw->startDocument('1.0', 'UTF-8');
115 $xw->writeDTD($doc, $public, $system);
119 function common_end_xml() {
125 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
127 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
130 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
132 # XXX: allow content negotiation for RDF, RSS, or XRDS
134 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
135 common_accept_to_prefs(PAGE_TYPE_PREFS));
138 common_user_error(_t('This page is not available in a media type you accept'), 406);
142 header('Content-Type: '.$type);
144 common_start_xml('html',
145 '-//W3C//DTD XHTML 1.0 Strict//EN',
146 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
148 # FIXME: correct language for interface
150 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
154 common_element_start('head');
155 common_element('title', NULL,
156 $pagetitle . " - " . $config['site']['name']);
157 common_element('link', array('rel' => 'stylesheet',
158 'type' => 'text/css',
159 'href' => theme_path('display.css'),
160 'media' => 'screen, projection, tv'));
161 foreach (array(6,7) as $ver) {
162 if (file_exists(theme_file('ie'.$ver.'.css'))) {
163 # Yes, IE people should be put in jail.
164 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
165 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
169 common_element('script', array('type' => 'text/javascript',
170 'src' => common_path('js/jquery.min.js')),
172 common_element('script', array('type' => 'text/javascript',
173 'src' => common_path('js/util.js')),
178 call_user_func($callable, $data);
180 call_user_func($callable);
183 common_element_end('head');
184 common_element_start('body');
185 common_element_start('div', array('id' => 'wrap'));
186 common_element_start('div', array('id' => 'header'));
188 if ((is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
189 || file_exists(theme_file('logo.png')))
191 common_element_start('a', array('href' => common_local_url('public')));
192 common_element('img', array('src' => ($config['site']['logo']) ?
193 ($config['site']['logo']) : theme_path('logo.png'),
194 'alt' => $config['site']['name'],
196 common_element_end('a');
198 common_element_start('p', array('id' => 'branding'));
199 common_element('a', array('href' => common_local_url('public')),
200 $config['site']['name']);
201 common_element_end('p');
204 common_element('h1', 'pagetitle', $pagetitle);
208 call_user_func($headercall, $data);
210 call_user_func($headercall);
213 common_element_end('div');
214 common_element_start('div', array('id' => 'content'));
217 function common_show_footer() {
219 common_element_end('div'); # content div
221 common_element_start('div', array('id' => 'footer'));
222 common_element_start('div', 'laconica');
223 if (common_config('site', 'broughtby')) {
224 $instr = _t('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
226 $instr = _t('**%%site.name%%** is a microblogging service. ');
228 $instr .= _t('It runs the [Laconica](http://laconi.ca/) ' .
229 'microblogging software, version ' . LACONICA_VERSION . ', ' .
230 'available under the ' .
231 '[GNU Affero General Public License]' .
232 '(http://www.fsf.org/licensing/licenses/agpl-3.0.html).');
233 $output = common_markup_to_html($instr);
235 common_element_end('div');
236 common_element('img', array('id' => 'cc',
237 'src' => $config['license']['image'],
238 'alt' => $config['license']['title']));
239 common_element_start('p');
240 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
241 common_element('a', array('class' => 'license',
243 href => $config['license']['url']),
244 $config['license']['title']);
245 common_text(_t('. Contributors should be attributed by full name or nickname.'));
246 common_element_end('p');
247 common_element_end('div');
248 common_element_end('div');
249 common_element_end('body');
250 common_element_end('html');
254 function common_text($txt) {
259 function common_raw($xml) {
264 function common_nav_menu() {
265 $user = common_current_user();
266 common_element_start('ul', array('id' => 'nav'));
268 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
271 common_menu_item(common_local_url('public'), _t('Public'));
272 common_menu_item(common_local_url('doc', array('title' => 'help')),
275 common_menu_item(common_local_url('profilesettings'),
277 common_menu_item(common_local_url('logout'),
280 common_menu_item(common_local_url('login'), _t('Login'));
281 common_menu_item(common_local_url('register'), _t('Register'));
282 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
284 common_element_end('ul');
287 function common_foot_menu() {
288 common_element_start('ul', array('id' => 'nav_sub'));
289 common_menu_item(common_local_url('doc', array('title' => 'about')),
291 common_menu_item(common_local_url('doc', array('title' => 'faq')),
293 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
295 common_menu_item(common_local_url('doc', array('title' => 'source')),
297 common_menu_item(common_local_url('doc', array('title' => 'contact')),
299 common_element_end('ul');
302 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
305 $lattrs['class'] = 'current';
307 common_element_start('li', $lattrs);
308 $attrs['href'] = $url;
310 $attrs['title'] = $title;
312 common_element('a', $attrs, $text);
313 common_element_end('li');
316 function common_input($id, $label, $value=NULL,$instructions=NULL) {
317 common_element_start('p');
318 common_element('label', array('for' => $id), $label);
319 $attrs = array('name' => $id,
321 'class' => 'input_text',
324 $attrs['value'] = htmlspecialchars($value);
326 common_element('input', $attrs);
328 common_element('span', 'input_instructions', $instructions);
330 common_element_end('p');
333 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
335 common_element_start('p');
336 $attrs = array('name' => $id,
337 'type' => 'checkbox',
338 'class' => 'checkbox',
341 $attrs['value'] = htmlspecialchars($value);
344 $attrs['checked'] = 'checked';
346 common_element('input', $attrs);
349 common_element('span', 'checkbox_label', $label);
352 common_element('span', 'input_instructions', $instructions);
354 common_element_end('p');
357 function common_hidden($id, $value) {
358 common_element('input', array('name' => $id,
364 function common_password($id, $label, $instructions=NULL) {
365 common_element_start('p');
366 common_element('label', array('for' => $id), $label);
367 $attrs = array('name' => $id,
368 'type' => 'password',
369 'class' => 'password',
371 common_element('input', $attrs);
373 common_element('span', 'input_instructions', $instructions);
375 common_element_end('p');
378 function common_submit($id, $label) {
380 common_element_start('p');
381 common_element('input', array('type' => 'submit',
386 common_element_end('p');
389 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
390 common_element_start('p');
391 common_element('label', array('for' => $id), $label);
392 common_element('textarea', array('rows' => 3,
396 ($content) ? $content : '');
398 common_element('span', 'input_instructions', $instructions);
400 common_element_end('p');
403 # salted, hashed passwords are stored in the DB
405 function common_munge_password($password, $id) {
406 return md5($password . $id);
409 # check if a username exists and has matching password
410 function common_check_user($nickname, $password) {
411 $user = User::staticGet('nickname', $nickname);
412 if (is_null($user)) {
415 return (0 == strcmp(common_munge_password($password, $user->id),
420 # is the current user logged in?
421 function common_logged_in() {
422 return (!is_null(common_current_user()));
425 function common_have_session() {
426 return (0 != strcmp(session_id(), ''));
429 function common_ensure_session() {
430 if (!common_have_session()) {
435 function common_set_user($nickname) {
436 if (is_null($nickname) && common_have_session()) {
437 unset($_SESSION['userid']);
440 $user = User::staticGet('nickname', $nickname);
442 common_ensure_session();
443 $_SESSION['userid'] = $user->id;
452 function common_set_cookie($key, $value, $expiration=0) {
453 $path = common_config('site', 'path');
454 $server = common_config('site', 'server');
456 if ($path && ($path != '/')) {
457 $cookiepath = '/' . $path . '/';
461 return setcookie($key,
468 define('REMEMBERME', 'rememberme');
469 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
471 function common_rememberme() {
472 $user = common_current_user();
476 $rm = new Remember_me();
477 $rm->code = common_good_rand(16);
478 $rm->user_id = $user->id;
479 $result = $rm->insert();
481 common_log_db_error($rm, 'INSERT', __FILE__);
484 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
485 common_set_cookie(REMEMBERME,
486 implode(':', array($rm->user_id, $rm->code)),
487 time() + REMEMBERME_EXPIRY);
491 function common_remembered_user() {
494 $packed = $_COOKIE[REMEMBERME];
496 list($id, $code) = explode(':', $packed);
498 $rm = Remember_me::staticGet($code);
499 if ($rm && ($rm->user_id == $id)) {
500 $user = User::staticGet($rm->user_id);
503 $result = $rm->delete();
505 common_log_db_error($rm, 'DELETE', __FILE__);
508 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
509 common_set_user($user->nickname);
510 common_real_login(false);
511 # We issue a new cookie, so they can log in
512 # automatically again after this session
522 # must be called with a valid user!
524 function common_forgetme() {
525 common_set_cookie(REMEMBERME, '', 0);
528 # who is the current user?
529 function common_current_user() {
530 if ($_REQUEST[session_name()]) {
531 common_ensure_session();
532 $id = $_SESSION['userid'];
534 # note: this should cache
535 $user = User::staticGet($id);
539 # that didn't work; try to remember
540 $user = common_remembered_user();
544 # Logins that are 'remembered' aren't 'real' -- they're subject to
545 # cookie-stealing. So, we don't let them do certain things. New reg,
546 # OpenID, and password logins _are_ real.
548 function common_real_login($real=true) {
549 common_ensure_session();
550 $_SESSION['real_login'] = $real;
553 function common_is_real_login() {
554 return common_logged_in() && $_SESSION['real_login'];
557 # get canonical version of nickname for comparison
558 function common_canonical_nickname($nickname) {
559 # XXX: UTF-8 canonicalization (like combining chars)
560 return strtolower($nickname);
563 # get canonical version of email for comparison
564 function common_canonical_email($email) {
565 # XXX: canonicalize UTF-8
566 # XXX: lcase the domain part
570 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$_+!*();/?:~-]))');
572 function common_render_content($text, $notice) {
573 $r = htmlspecialchars($text);
574 $id = $notice->profile_id;
575 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
576 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
582 function common_at_link($sender_id, $nickname) {
583 $sender = Profile::staticGet($sender_id);
584 $recipient = common_relative_profile($sender, $nickname);
586 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
592 function common_relative_profile($sender, $nickname, $dt=NULL) {
593 # Try to find profiles this profile is subscribed to that have this nickname
594 $recipient = new Profile();
595 # XXX: use a join instead of a subquery
596 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
597 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
598 if ($recipient->find(TRUE)) {
599 # XXX: should probably differentiate between profiles with
600 # the same name by date of most recent update
603 # Try to find profiles that listen to this profile and that have this nickname
604 $recipient = new Profile();
605 # XXX: use a join instead of a subquery
606 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
607 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
608 if ($recipient->find(TRUE)) {
609 # XXX: should probably differentiate between profiles with
610 # the same name by date of most recent update
613 # If this is a local user, try to find a local user with that nickname.
614 $sender = User::staticGet($sender->id);
616 $recipient_user = User::staticGet('nickname', $nickname);
617 if ($recipient_user) {
618 return $recipient_user->getProfile();
621 # Otherwise, no links. @messages from local users to remote users,
622 # or from remote users to other remote users, are just
623 # outside our ability to make intelligent guesses about
627 // where should the avatar go for this user?
629 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
633 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
635 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
639 function common_avatar_path($filename) {
641 return INSTALLDIR . '/avatar/' . $filename;
644 function common_avatar_url($filename) {
645 return common_path('avatar/'.$filename);
648 function common_avatar_display_url($avatar) {
649 $server = common_config('avatar', 'server');
651 return 'http://'.$server.'/'.$avatar->filename;
657 function common_default_avatar($size) {
658 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
659 AVATAR_STREAM_SIZE => 'stream',
660 AVATAR_MINI_SIZE => 'mini');
661 return theme_path('default-avatar-'.$sizenames[$size].'.png');
664 function common_local_url($action, $args=NULL) {
666 if ($config['site']['fancy']) {
667 return common_fancy_url($action, $args);
669 return common_simple_url($action, $args);
673 function common_fancy_url($action, $args=NULL) {
674 switch (strtolower($action)) {
676 if ($args && $args['page']) {
677 return common_path('?page=' . $args['page']);
679 return common_path('');
682 return common_path('rss');
684 return common_path('xrds');
686 return common_path('doc/'.$args['title']);
692 return common_path('main/'.$action);
693 case 'remotesubscribe':
694 if ($args && $args['nickname']) {
695 return common_path('main/remote?nickname=' . $args['nickname']);
697 return common_path('main/remote');
700 return common_path('main/openid');
703 return common_path('settings/'.$action);
704 case 'profilesettings':
705 return common_path('settings/profile');
706 case 'openidsettings':
707 return common_path('settings/openid');
709 return common_path('notice/new');
711 return common_path('notice/'.$args['notice']);
714 return common_path($args['nickname'].'/'.$action);
715 case 'subscriptions':
719 if ($args && $args['page']) {
720 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
722 return common_path($args['nickname'].'/'.$action);
725 return common_path($args['nickname'].'/all/rss');
727 return common_path($args['nickname'].'/replies/rss');
729 return common_path($args['nickname'].'/rss');
731 if ($args && $args['page']) {
732 return common_path($args['nickname'].'?page=' . $args['page']);
734 return common_path($args['nickname']);
736 case 'confirmaddress':
737 return common_path('main/confirmaddress/'.$args['code']);
739 return common_path('user/'.$args['id']);
740 case 'recoverpassword':
741 $path = 'main/recoverpassword';
743 $path .= '/' . $args['code'];
745 return common_path($path);
747 return common_path('settings/im');
749 return common_simple_url($action, $args);
753 function common_simple_url($action, $args=NULL) {
755 /* XXX: pretty URLs */
758 foreach ($args as $key => $value) {
759 $extra .= "&${key}=${value}";
762 return common_path("index.php?action=${action}${extra}");
765 function common_path($relative) {
767 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
768 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
771 function common_date_string($dt) {
772 // XXX: do some sexy date formatting
773 // return date(DATE_RFC822, $dt);
778 if ($now < $t) { # that shouldn't happen!
779 return common_exact_date($dt);
780 } else if ($diff < 60) {
781 return _t('a few seconds ago');
782 } else if ($diff < 92) {
783 return _t('about a minute ago');
784 } else if ($diff < 3300) {
785 return _t('about ') . round($diff/60) . _t(' minutes ago');
786 } else if ($diff < 5400) {
787 return _t('about an hour ago');
788 } else if ($diff < 22 * 3600) {
789 return _t('about ') . round($diff/3600) . _t(' hours ago');
790 } else if ($diff < 37 * 3600) {
791 return _t('about a day ago');
792 } else if ($diff < 24 * 24 * 3600) {
793 return _t('about ') . round($diff/(24*3600)) . _t(' days ago');
794 } else if ($diff < 46 * 24 * 3600) {
795 return _t('about a month ago');
796 } else if ($diff < 330 * 24 * 3600) {
797 return _t('about ') . round($diff/(30*24*3600)) . _t(' months ago');
798 } else if ($diff < 480 * 24 * 3600) {
799 return _t('about a year ago');
801 return common_exact_date($dt);
805 function common_exact_date($dt) {
807 return date(DATE_RFC850, $t);
810 function common_date_w3dtf($dt) {
812 return date(DATE_W3C, $t);
815 function common_redirect($url, $code=307) {
816 static $status = array(301 => "Moved Permanently",
819 307 => "Temporary Redirect");
820 header("Status: ${code} $status[$code]");
821 header("Location: $url");
823 common_start_xml('a',
824 '-//W3C//DTD XHTML 1.0 Strict//EN',
825 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
826 common_element('a', array('href' => $url), $url);
830 function common_save_replies($notice) {
831 # extract all @messages
832 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
836 $sender = Profile::staticGet($notice->profile_id);
837 # store replied only for first @ (what user/notice what the reply directed,
838 # we assume first @ is it)
839 for ($i=0; $i<count($match[1]); $i++) {
840 $nickname = $match[1][$i];
841 $recipient = common_relative_profile($sender, $nickname, $notice->created);
846 $reply_for = $recipient;
848 $reply = new Reply();
849 $reply->notice_id = $notice->id;
850 $reply->profile_id = $recipient->id;
852 # $recipient_notice = $reply_for->getCurrentNotice($notice->created);
853 $recipient_notice = $reply_for->getCurrentNotice();
854 $reply->replied_id = $recipient_notice->id;
856 $id = $reply->insert();
858 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
859 common_log(LOG_ERROR, 'DB error inserting reply: ' . $last_error->message);
860 common_server_error('DB error inserting reply: ' . $last_error->message);
866 function common_broadcast_notice($notice, $remote=false) {
867 if (common_config('queue', 'enabled')) {
869 return common_enqueue_notice($notice);
871 return common_real_broadcast($notice, $remote);
875 # Stick the notice on the queue
877 function common_enqueue_notice($notice) {
878 $qi = new Queue_item();
879 $qi->notice_id = $notice->id;
880 $qi->created = $notice->created;
881 $result = $qi->insert();
883 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
884 common_log(LOG_ERROR, 'DB error inserting queue item: ' . $last_error->message);
887 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
891 function common_real_broadcast($notice, $remote=false) {
894 # Make sure we have the OMB stuff
895 require_once(INSTALLDIR.'/lib/omb.php');
896 $success = omb_broadcast_remote_subscribers($notice);
898 common_log(LOG_ERROR, 'Error in OMB broadcast for notice ' . $notice->id);
902 require_once(INSTALLDIR.'/lib/jabber.php');
903 $success = jabber_broadcast_notice($notice);
905 common_log(LOG_ERROR, 'Error in jabber broadcast for notice ' . $notice->id);
908 // XXX: broadcast notices to SMS
909 // XXX: broadcast notices to other IM
913 function common_broadcast_profile($profile) {
914 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
915 require_once(INSTALLDIR.'/lib/omb.php');
916 omb_broadcast_profile($profile);
917 // XXX: Other broadcasts...?
921 function common_profile_url($nickname) {
922 return common_local_url('showstream', array('nickname' => $nickname));
925 # Don't call if nobody's logged in
927 function common_notice_form($action=NULL, $content=NULL) {
928 $user = common_current_user();
929 assert(!is_null($user));
930 common_element_start('form', array('id' => 'status_form',
932 'action' => common_local_url('newnotice')));
933 common_element_start('p');
934 common_element('label', array('for' => 'status_textarea',
935 'id' => 'status_label'),
936 _t('What\'s up, ').$user->nickname.'?');
937 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
938 common_element('textarea', array('id' => 'status_textarea',
941 'name' => 'status_textarea'),
942 ($content) ? $content : '');
944 common_hidden('returnto', $action);
946 common_element('input', array('id' => 'status_submit',
947 'name' => 'status_submit',
949 'value' => _t('Send')));
950 common_element_end('p');
951 common_element_end('form');
954 function common_mint_tag($extra) {
957 'tag:'.$config['tag']['authority'].','.
958 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
961 # Should make up a reasonable root URL
963 function common_root_url() {
964 return common_path('');
967 # returns $bytes bytes of random data as a hexadecimal string
968 # "good" here is a goal and not a guarantee
970 function common_good_rand($bytes) {
971 # XXX: use random.org...?
972 if (file_exists('/dev/urandom')) {
973 return common_urandom($bytes);
974 } else { # FIXME: this is probably not good enough
975 return common_mtrand($bytes);
979 function common_urandom($bytes) {
980 $h = fopen('/dev/urandom', 'rb');
982 $src = fread($h, $bytes);
985 for ($i = 0; $i < $bytes; $i++) {
986 $enc .= sprintf("%02x", (ord($src[$i])));
991 function common_mtrand($bytes) {
993 for ($i = 0; $i < $bytes; $i++) {
994 $enc .= sprintf("%02x", mt_rand(0, 255));
999 function common_set_returnto($url) {
1000 common_ensure_session();
1001 $_SESSION['returnto'] = $url;
1004 function common_get_returnto() {
1005 common_ensure_session();
1006 return $_SESSION['returnto'];
1009 function common_timestamp() {
1010 return date('YmdHis');
1013 // XXX: set up gettext
1019 function common_ensure_syslog() {
1020 static $initialized = false;
1021 if (!$initialized) {
1023 define_syslog_variables();
1024 openlog($config['syslog']['appname'], 0, LOG_USER);
1025 $initialized = true;
1029 function common_log($priority, $msg, $filename=NULL) {
1030 common_ensure_syslog();
1031 syslog($priority, $msg);
1034 function common_debug($msg, $filename=NULL) {
1036 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1038 common_log(LOG_DEBUG, $msg);
1042 function common_log_db_error(&$object, $verb, $filename=NULL) {
1043 $objstr = common_log_objstring($object);
1044 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1045 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1048 function common_log_objstring(&$object) {
1049 if (is_null($object)) {
1052 $arr = $object->toArray();
1054 foreach ($arr as $k => $v) {
1055 $fields[] = "$k='$v'";
1057 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1061 function common_valid_http_url($url) {
1062 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1065 function common_valid_tag($tag) {
1066 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1067 return (Validate::email($matches[1]) ||
1068 preg_match('/^([\w-\.]+)$/', $matches[1]));
1073 # Does a little before-after block for next/prev page
1075 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1077 if ($have_before || $have_after) {
1078 common_element_start('div', array('id' => 'pagination'));
1079 common_element_start('ul', array('id' => 'nav_pagination'));
1083 $pargs = array('page' => $page-1);
1084 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1086 common_element_start('li', 'before');
1087 common_element('a', array('href' => common_local_url($action, $newargs)),
1089 common_element_end('li');
1093 $pargs = array('page' => $page+1);
1094 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1095 common_element_start('li', 'after');
1096 common_element('a', array('href' => common_local_url($action, $newargs)),
1098 common_element_end('li');
1101 if ($have_before || $have_after) {
1102 common_element_end('ul');
1103 common_element_end('div');
1107 /* Following functions are copied from MediaWiki GlobalFunctions.php
1108 * and written by Evan Prodromou. */
1110 function common_accept_to_prefs($accept, $def = '*/*') {
1111 # No arg means accept anything (per HTTP spec)
1113 return array($def => 1);
1118 $parts = explode(',', $accept);
1120 foreach($parts as $part) {
1121 # FIXME: doesn't deal with params like 'text/html; level=1'
1122 @list($value, $qpart) = explode(';', $part);
1124 if(!isset($qpart)) {
1126 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1127 $prefs[$value] = $match[1];
1134 function common_mime_type_match($type, $avail) {
1135 if(array_key_exists($type, $avail)) {
1138 $parts = explode('/', $type);
1139 if(array_key_exists($parts[0] . '/*', $avail)) {
1140 return $parts[0] . '/*';
1141 } elseif(array_key_exists('*/*', $avail)) {
1149 function common_negotiate_type($cprefs, $sprefs) {
1152 foreach(array_keys($sprefs) as $type) {
1153 $parts = explode('/', $type);
1154 if($parts[1] != '*') {
1155 $ckey = common_mime_type_match($type, $cprefs);
1157 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1162 foreach(array_keys($cprefs) as $type) {
1163 $parts = explode('/', $type);
1164 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1165 $skey = common_mime_type_match($type, $sprefs);
1167 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1173 $besttype = "text/html";
1175 foreach(array_keys($combine) as $type) {
1176 if($combine[$type] > $bestq) {
1178 $bestq = $combine[$type];
1185 function common_config($main, $sub) {
1187 return $config[$main][$sub];
1190 function common_copy_args($from) {
1192 $strip = get_magic_quotes_gpc();
1193 foreach ($from as $k => $v) {
1194 $to[$k] = ($strip) ? stripslashes($v) : $v;
1199 function common_user_uri(&$user) {
1200 return common_local_url('userbyid', array('id' => $user->id));
1203 function common_notice_uri(&$notice) {
1204 return common_local_url('shownotice',
1205 array('notice' => $notice->id));
1208 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1210 function common_confirmation_code($bits) {
1211 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1212 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1213 $chars = ceil($bits/5);
1215 for ($i = 0; $i < $chars; $i++) {
1216 # XXX: convert to string and back
1217 $num = hexdec(common_good_rand(1));
1218 # XXX: randomness is too precious to throw away almost
1219 # 40% of the bits we get!
1220 $code .= $codechars[$num%32];
1225 # convert markup to HTML
1227 function common_markup_to_html($c) {
1228 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1229 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1230 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1231 return Markdown($c);