3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
24 function common_server_error($msg, $code=500) {
25 static $status = array(500 => 'Internal Server Error',
26 501 => 'Not Implemented',
28 503 => 'Service Unavailable',
29 504 => 'Gateway Timeout',
30 505 => 'HTTP Version Not Supported');
32 if (!array_key_exists($code, $status)) {
36 $status_string = $status[$code];
38 header('HTTP/1.1 '.$code.' '.$status_string);
39 header('Content-type: text/plain');
47 function common_user_error($msg, $code=400) {
48 static $status = array(400 => 'Bad Request',
49 401 => 'Unauthorized',
50 402 => 'Payment Required',
53 405 => 'Method Not Allowed',
54 406 => 'Not Acceptable',
55 407 => 'Proxy Authentication Required',
56 408 => 'Request Timeout',
59 411 => 'Length Required',
60 412 => 'Precondition Failed',
61 413 => 'Request Entity Too Large',
62 414 => 'Request-URI Too Long',
63 415 => 'Unsupported Media Type',
64 416 => 'Requested Range Not Satisfiable',
65 417 => 'Expectation Failed');
67 if (!array_key_exists($code, $status)) {
71 $status_string = $status[$code];
73 header('HTTP/1.1 '.$code.' '.$status_string);
75 common_show_header('Error');
76 common_element('div', array('class' => 'error'), $msg);
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
85 $xw->startElement($tag);
86 if (is_array($attrs)) {
87 foreach ($attrs as $name => $value) {
88 $xw->writeAttribute($name, $value);
90 } else if (is_string($attrs)) {
91 $xw->writeAttribute('class', $attrs);
95 function common_element_end($tag) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 # XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109 common_element_start($tag, $attrs);
111 if (!is_null($content)) {
114 common_element_end($tag);
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 function common_init_language() {
135 mb_internal_encoding('UTF-8');
136 $language = common_language();
137 # So we don't have to make people install the gettext locales
138 putenv('LANGUAGE='.$language);
139 putenv('LANG='.$language);
140 $locale_set = setlocale(LC_ALL, $language . ".utf8",
142 $language . ".utf-8",
143 $language . ".UTF-8",
145 bindtextdomain("laconica", common_config('site','locale_path'));
146 bind_textdomain_codeset("laconica", "UTF-8");
147 textdomain("laconica");
148 setlocale(LC_CTYPE, 'C');
150 common_log(LOG_INFO,'Language requested:'.$language.' - locale could not be set:',__FILE__);
154 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
156 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
162 common_element_start('head');
163 common_element('title', NULL,
164 $pagetitle . " - " . $config['site']['name']);
165 common_element('link', array('rel' => 'stylesheet',
166 'type' => 'text/css',
167 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
168 'media' => 'screen, projection, tv'));
169 foreach (array(6,7) as $ver) {
170 if (file_exists(theme_file('ie'.$ver.'.css'))) {
171 # Yes, IE people should be put in jail.
172 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
173 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
177 common_element('script', array('type' => 'text/javascript',
178 'src' => common_path('js/jquery.min.js')),
180 common_element('script', array('type' => 'text/javascript',
181 'src' => common_path('js/jquery.form.js')),
183 common_element('script', array('type' => 'text/javascript',
184 'src' => common_path('js/xbImportNode.js')),
186 common_element('script', array('type' => 'text/javascript',
187 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
189 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
190 'href' => common_local_url('opensearch', array('type' => 'people')),
191 'title' => common_config('site', 'name').' People Search'));
193 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
194 'href' => common_local_url('opensearch', array('type' => 'notice')),
195 'title' => common_config('site', 'name').' Notice Search'));
199 call_user_func($callable, $data);
201 call_user_func($callable);
204 common_element_end('head');
205 common_element_start('body');
206 common_element_start('div', array('id' => 'wrap'));
207 common_element_start('div', array('id' => 'header'));
209 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
210 || file_exists(theme_file('logo.png')))
212 common_element_start('a', array('href' => common_local_url('public')));
213 common_element('img', array('src' => isset($config['site']['logo']) ?
214 ($config['site']['logo']) : theme_path('logo.png'),
215 'alt' => $config['site']['name'],
217 common_element_end('a');
219 common_element_start('p', array('id' => 'branding'));
220 common_element('a', array('href' => common_local_url('public')),
221 $config['site']['name']);
222 common_element_end('p');
225 common_element('h1', 'pagetitle', $pagetitle);
229 call_user_func($headercall, $data);
231 call_user_func($headercall);
234 common_element_end('div');
235 common_element_start('div', array('id' => 'content'));
238 function common_start_html($type=NULL) {
241 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
243 # XXX: allow content negotiation for RDF, RSS, or XRDS
245 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
246 common_accept_to_prefs(PAGE_TYPE_PREFS));
249 common_user_error(_('This page is not available in a media type you accept'), 406);
254 header('Content-Type: '.$type);
256 common_start_xml('html',
257 '-//W3C//DTD XHTML 1.0 Strict//EN',
258 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
260 # FIXME: correct language for interface
262 $language = common_language();
264 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
265 'xml:lang' => $language,
266 'lang' => $language));
269 function common_show_footer() {
271 common_element_end('div'); # content div
273 common_element_start('div', array('id' => 'footer'));
274 common_element_start('div', 'laconica');
275 if (common_config('site', 'broughtby')) {
276 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
278 $instr = _('**%%site.name%%** is a microblogging service. ');
280 $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);
281 $output = common_markup_to_html($instr);
283 common_element_end('div');
284 common_element('img', array('id' => 'cc',
285 'src' => $config['license']['image'],
286 'alt' => $config['license']['title']));
287 common_element_start('p');
288 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
289 common_element('a', array('class' => 'license',
291 'href' => $config['license']['url']),
292 $config['license']['title']);
293 common_text(_('. Contributors should be attributed by full name or nickname.'));
294 common_element_end('p');
295 common_element_end('div');
296 common_element_end('div');
297 common_element_end('body');
298 common_element_end('html');
302 function common_text($txt) {
307 function common_raw($xml) {
312 function common_nav_menu() {
313 $user = common_current_user();
314 common_element_start('ul', array('id' => 'nav'));
316 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
319 common_menu_item(common_local_url('peoplesearch'), _('Search'));
320 common_menu_item(common_local_url('tags'), _('Tags'));
322 common_menu_item(common_local_url('profilesettings'),
324 common_menu_item(common_local_url('invite'),
326 common_menu_item(common_local_url('logout'),
329 common_menu_item(common_local_url('login'), _('Login'));
330 if (!common_config('site', 'closed')) {
331 common_menu_item(common_local_url('register'), _('Register'));
333 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
335 common_element_end('ul');
338 function common_foot_menu() {
339 common_element_start('ul', array('id' => 'nav_sub'));
340 common_menu_item(common_local_url('doc', array('title' => 'help')),
342 common_menu_item(common_local_url('doc', array('title' => 'about')),
344 common_menu_item(common_local_url('doc', array('title' => 'faq')),
346 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
348 common_menu_item(common_local_url('doc', array('title' => 'source')),
350 common_menu_item(common_local_url('doc', array('title' => 'contact')),
352 common_element_end('ul');
355 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
358 $lattrs['class'] = 'current';
360 common_element_start('li', $lattrs);
361 $attrs['href'] = $url;
363 $attrs['title'] = $title;
365 common_element('a', $attrs, $text);
366 common_element_end('li');
369 function common_input($id, $label, $value=NULL,$instructions=NULL) {
370 common_element_start('p');
371 common_element('label', array('for' => $id), $label);
372 $attrs = array('name' => $id,
374 'class' => 'input_text',
377 $attrs['value'] = htmlspecialchars($value);
379 common_element('input', $attrs);
381 common_element('span', 'input_instructions', $instructions);
383 common_element_end('p');
386 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false)
388 common_element_start('p');
389 $attrs = array('name' => $id,
390 'type' => 'checkbox',
391 'class' => 'checkbox',
394 $attrs['value'] = htmlspecialchars($value);
397 $attrs['checked'] = 'checked';
400 $attrs['disabled'] = 'true';
402 common_element('input', $attrs);
405 common_element('span', 'checkbox_label', $label);
408 common_element('span', 'input_instructions', $instructions);
410 common_element_end('p');
413 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
414 common_element_start('p');
415 common_element('label', array('for' => $id), $label);
416 common_element_start('select', array('id' => $id, 'name' => $id));
418 common_element('option', array('value' => ''));
420 foreach ($content as $value => $option) {
421 if ($value == $selected) {
422 common_element('option', array('value' => $value, 'selected' => $value), $option);
424 common_element('option', array('value' => $value), $option);
427 common_element_end('select');
429 common_element('span', 'input_instructions', $instructions);
431 common_element_end('p');
433 function common_hidden($id, $value) {
434 common_element('input', array('name' => $id,
440 function common_password($id, $label, $instructions=NULL) {
441 common_element_start('p');
442 common_element('label', array('for' => $id), $label);
443 $attrs = array('name' => $id,
444 'type' => 'password',
445 'class' => 'password',
447 common_element('input', $attrs);
449 common_element('span', 'input_instructions', $instructions);
451 common_element_end('p');
454 function common_submit($id, $label, $cls='submit') {
456 common_element_start('p');
457 common_element('input', array('type' => 'submit',
462 common_element_end('p');
465 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
466 common_element_start('p');
467 common_element('label', array('for' => $id), $label);
468 common_element('textarea', array('rows' => 3,
472 ($content) ? $content : '');
474 common_element('span', 'input_instructions', $instructions);
476 common_element_end('p');
479 function common_timezone() {
480 if (common_logged_in()) {
481 $user = common_current_user();
482 if ($user->timezone) {
483 return $user->timezone;
488 return $config['site']['timezone'];
491 function common_language() {
493 // If there is a user logged in and they've set a language preference
494 // then return that one...
495 if (common_logged_in()) {
496 $user = common_current_user();
497 $user_language = $user->language;
499 return $user_language;
502 // Otherwise, find the best match for the languages requested by the
504 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
505 if (!empty($httplang)) {
506 $language = client_prefered_language($httplang);
511 // Finally, if none of the above worked, use the site's default...
512 return common_config('site', 'language');
514 # salted, hashed passwords are stored in the DB
516 function common_munge_password($password, $id) {
517 return md5($password . $id);
520 # check if a username exists and has matching password
521 function common_check_user($nickname, $password) {
522 # NEVER allow blank passwords, even if they match the DB
523 if (mb_strlen($password) == 0) {
526 $user = User::staticGet('nickname', $nickname);
527 if (is_null($user)) {
530 if (0 == strcmp(common_munge_password($password, $user->id),
539 # is the current user logged in?
540 function common_logged_in() {
541 return (!is_null(common_current_user()));
544 function common_have_session() {
545 return (0 != strcmp(session_id(), ''));
548 function common_ensure_session() {
549 if (!common_have_session()) {
554 # Three kinds of arguments:
559 function common_set_user($user) {
560 if (is_null($user) && common_have_session()) {
561 unset($_SESSION['userid']);
563 } else if (is_string($user)) {
565 $user = User::staticGet('nickname', $nickname);
566 } else if (!($user instanceof User)) {
571 common_ensure_session();
572 $_SESSION['userid'] = $user->id;
578 function common_set_cookie($key, $value, $expiration=0) {
579 $path = common_config('site', 'path');
580 $server = common_config('site', 'server');
582 if ($path && ($path != '/')) {
583 $cookiepath = '/' . $path . '/';
587 return setcookie($key,
594 define('REMEMBERME', 'rememberme');
595 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
597 function common_rememberme($user=NULL) {
599 $user = common_current_user();
601 common_debug('No current user to remember', __FILE__);
605 $rm = new Remember_me();
606 $rm->code = common_good_rand(16);
607 $rm->user_id = $user->id;
608 $result = $rm->insert();
610 common_log_db_error($rm, 'INSERT', __FILE__);
611 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
614 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
615 common_set_cookie(REMEMBERME,
616 implode(':', array($rm->user_id, $rm->code)),
617 time() + REMEMBERME_EXPIRY);
621 function common_remembered_user() {
624 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
626 list($id, $code) = explode(':', $packed);
628 $rm = Remember_me::staticGet($code);
629 if ($rm && ($rm->user_id == $id)) {
630 $user = User::staticGet($rm->user_id);
633 $result = $rm->delete();
635 common_log_db_error($rm, 'DELETE', __FILE__);
638 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
639 common_set_user($user->nickname);
640 common_real_login(false);
641 # We issue a new cookie, so they can log in
642 # automatically again after this session
643 common_rememberme($user);
652 # must be called with a valid user!
654 function common_forgetme() {
655 common_set_cookie(REMEMBERME, '', 0);
658 # who is the current user?
659 function common_current_user() {
660 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
661 common_ensure_session();
662 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
664 # note: this should cache
665 $user = User::staticGet($id);
669 # that didn't work; try to remember
670 $user = common_remembered_user();
672 common_debug("Got User " . $user->nickname);
673 common_debug("Faking session on remembered user");
674 $_SESSION['userid'] = $user->id;
679 # Logins that are 'remembered' aren't 'real' -- they're subject to
680 # cookie-stealing. So, we don't let them do certain things. New reg,
681 # OpenID, and password logins _are_ real.
683 function common_real_login($real=true) {
684 common_ensure_session();
685 $_SESSION['real_login'] = $real;
688 function common_is_real_login() {
689 return common_logged_in() && $_SESSION['real_login'];
692 # get canonical version of nickname for comparison
693 function common_canonical_nickname($nickname) {
694 # XXX: UTF-8 canonicalization (like combining chars)
695 return strtolower($nickname);
698 # get canonical version of email for comparison
699 function common_canonical_email($email) {
700 # XXX: canonicalize UTF-8
701 # XXX: lcase the domain part
705 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$_+!*();/?:~-]))');
707 function common_render_content($text, $notice) {
708 $r = common_render_text($text);
709 $id = $notice->profile_id;
710 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
711 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
715 function common_render_text($text) {
716 $r = htmlspecialchars($text);
718 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
719 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
720 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
725 function common_render_uri_thingy($matches) {
729 # Some heuristics for extracting URIs from surrounding punctuation
730 # Strip from trailing text...
731 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
733 $trailer = $matches[2];
737 ']' => '[', # technically disallowed in URIs, but used in Java docs
738 ')' => '(', # far too frequent in Wikipedia and MSDN
740 $final = substr($uri, -1, 1);
741 if (isset($pairs[$final])) {
742 $openers = substr_count($uri, $pairs[$final]);
743 $closers = substr_count($uri, $final);
744 if ($closers > $openers) {
745 // Assume the paren was opened outside the URI
746 $uri = substr($uri, 0, -1);
747 $trailer = $final . $trailer;
750 if ($longurl = common_longurl($uri)) {
751 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
752 $title = " title='$longurl'";
756 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
759 function common_longurl($uri) {
760 $uri_e = urlencode($uri);
761 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
762 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
763 return stripslashes($longurl['long_url']);
766 function common_shorten_links($text) {
767 // \s = not a horizontal whitespace character (since PHP 5.2.4)
768 // RYM this should prevent * preceded URLs from being processed but it its a char
769 // $r = preg_replace('@[^*](https?://[^)\]>\s]+)@e', "common_shorten_link('\\1')", $r);
770 return preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
773 function common_shorten_link($long_url) {
775 $user = common_current_user();
777 $curlh = curl_init();
778 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
779 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
780 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
782 switch($user->urlshorteningservice) {
784 $short_url_service = new LilUrl;
785 $short_url = $short_url_service->shorten($long_url);
789 $short_url_service = new TightUrl;
790 $short_url = $short_url_service->shorten($long_url);
794 $short_url_service = new PtitUrl;
795 $short_url = $short_url_service->shorten($long_url);
799 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($long_url));
800 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
804 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($long_url));
805 $short_url = curl_exec($curlh);
808 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($long_url));
809 $short_url = curl_exec($curlh);
812 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($long_url));
813 $short_url = curl_exec($curlh);
816 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($long_url));
817 $short_url = curl_exec($curlh);
831 function common_xml_safe_str($str) {
832 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
834 // Replace control, formatting, and surrogate characters with '*', ala Twitter
835 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
838 function common_tag_link($tag) {
839 $canonical = common_canonical_tag($tag);
840 $url = common_local_url('tag', array('tag' => $canonical));
841 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
844 function common_canonical_tag($tag) {
845 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
848 function common_at_link($sender_id, $nickname) {
849 $sender = Profile::staticGet($sender_id);
850 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
852 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
858 function common_relative_profile($sender, $nickname, $dt=NULL) {
859 # Try to find profiles this profile is subscribed to that have this nickname
860 $recipient = new Profile();
861 # XXX: use a join instead of a subquery
862 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
863 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
864 if ($recipient->find(TRUE)) {
865 # XXX: should probably differentiate between profiles with
866 # the same name by date of most recent update
869 # Try to find profiles that listen to this profile and that have this nickname
870 $recipient = new Profile();
871 # XXX: use a join instead of a subquery
872 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
873 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
874 if ($recipient->find(TRUE)) {
875 # XXX: should probably differentiate between profiles with
876 # the same name by date of most recent update
879 # If this is a local user, try to find a local user with that nickname.
880 $sender = User::staticGet($sender->id);
882 $recipient_user = User::staticGet('nickname', $nickname);
883 if ($recipient_user) {
884 return $recipient_user->getProfile();
887 # Otherwise, no links. @messages from local users to remote users,
888 # or from remote users to other remote users, are just
889 # outside our ability to make intelligent guesses about
893 // where should the avatar go for this user?
895 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
899 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
901 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
905 function common_avatar_path($filename) {
907 return INSTALLDIR . '/avatar/' . $filename;
910 function common_avatar_url($filename) {
911 return common_path('avatar/'.$filename);
914 function common_avatar_display_url($avatar) {
915 $server = common_config('avatar', 'server');
917 return 'http://'.$server.'/'.$avatar->filename;
923 function common_default_avatar($size) {
924 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
925 AVATAR_STREAM_SIZE => 'stream',
926 AVATAR_MINI_SIZE => 'mini');
927 return theme_path('default-avatar-'.$sizenames[$size].'.png');
930 function common_local_url($action, $args=NULL, $fragment=NULL) {
932 if (common_config('site','fancy')) {
933 $url = common_fancy_url($action, $args);
935 $url = common_simple_url($action, $args);
937 if (!is_null($fragment)) {
938 $url .= '#'.$fragment;
943 function common_fancy_url($action, $args=NULL) {
944 switch (strtolower($action)) {
946 if ($args && isset($args['page'])) {
947 return common_path('?page=' . $args['page']);
949 return common_path('');
952 return common_path('rss');
954 return common_path('xrds');
956 if ($args && $args['type']) {
957 return common_path('opensearch/'.$args['type']);
959 return common_path('opensearch/people');
962 return common_path('doc/'.$args['title']);
968 return common_path('main/'.$action);
970 if ($args && $args['code']) {
971 return common_path('main/register/'.$args['code']);
973 return common_path('main/register');
975 case 'remotesubscribe':
976 if ($args && $args['nickname']) {
977 return common_path('main/remote?nickname=' . $args['nickname']);
979 return common_path('main/remote');
982 return common_path('main/openid');
983 case 'profilesettings':
984 return common_path('settings/profile');
985 case 'emailsettings':
986 return common_path('settings/email');
987 case 'openidsettings':
988 return common_path('settings/openid');
990 return common_path('settings/sms');
991 case 'twittersettings':
992 return common_path('settings/twitter');
993 case 'othersettings':
994 return common_path('settings/other');
996 if ($args && $args['replyto']) {
997 return common_path('notice/new?replyto='.$args['replyto']);
999 return common_path('notice/new');
1002 return common_path('notice/'.$args['notice']);
1003 case 'deletenotice':
1004 if ($args && $args['notice']) {
1005 return common_path('notice/delete/'.$args['notice']);
1007 return common_path('notice/delete');
1011 return common_path($args['nickname'].'/'.$action);
1012 case 'subscriptions':
1018 if ($args && isset($args['page'])) {
1019 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1021 return common_path($args['nickname'].'/'.$action);
1024 return common_path($args['nickname'].'/all/rss');
1026 return common_path($args['nickname'].'/replies/rss');
1028 return common_path($args['nickname'].'/rss');
1030 if ($args && isset($args['page'])) {
1031 return common_path($args['nickname'].'?page=' . $args['page']);
1033 return common_path($args['nickname']);
1036 case 'usertimeline':
1037 return common_path("api/statuses/user_timeline/".$args['nickname'].".atom");
1038 case 'confirmaddress':
1039 return common_path('main/confirmaddress/'.$args['code']);
1041 return common_path('user/'.$args['id']);
1042 case 'recoverpassword':
1043 $path = 'main/recoverpassword';
1044 if ($args['code']) {
1045 $path .= '/' . $args['code'];
1047 return common_path($path);
1049 return common_path('settings/im');
1050 case 'peoplesearch':
1051 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1052 case 'noticesearch':
1053 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1054 case 'noticesearchrss':
1055 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1056 case 'avatarbynickname':
1057 return common_path($args['nickname'].'/avatar/'.$args['size']);
1059 if (isset($args['tag']) && $args['tag']) {
1060 $path = 'tag/' . $args['tag'];
1061 unset($args['tag']);
1065 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1067 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1069 return common_path('main/favor');
1071 return common_path('main/disfavor');
1072 case 'showfavorites':
1073 if ($args && isset($args['page'])) {
1074 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1076 return common_path($args['nickname'].'/favorites');
1078 case 'favoritesrss':
1079 return common_path($args['nickname'].'/favorites/rss');
1081 return common_path('message/' . $args['message']);
1083 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1085 # XXX: do fancy URLs for all the API methods
1086 switch (strtolower($args['apiaction'])) {
1088 switch (strtolower($args['method'])) {
1089 case 'user_timeline.rss':
1090 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1091 case 'user_timeline.atom':
1092 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1093 case 'user_timeline.rss':
1094 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1095 case 'user_timeline.atom':
1096 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1097 default: return common_simple_url($action, $args);
1099 default: return common_simple_url($action, $args);
1102 if ($args && isset($args['seconds'])) {
1103 return common_path('main/sup?seconds='.$args['seconds']);
1105 return common_path('main/sup');
1108 return common_simple_url($action, $args);
1112 function common_simple_url($action, $args=NULL) {
1114 /* XXX: pretty URLs */
1117 foreach ($args as $key => $value) {
1118 $extra .= "&${key}=${value}";
1121 return common_path("index.php?action=${action}${extra}");
1124 function common_path($relative) {
1126 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1127 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1130 function common_date_string($dt) {
1131 // XXX: do some sexy date formatting
1132 // return date(DATE_RFC822, $dt);
1133 $t = strtotime($dt);
1137 if ($now < $t) { # that shouldn't happen!
1138 return common_exact_date($dt);
1139 } else if ($diff < 60) {
1140 return _('a few seconds ago');
1141 } else if ($diff < 92) {
1142 return _('about a minute ago');
1143 } else if ($diff < 3300) {
1144 return sprintf(_('about %d minutes ago'), round($diff/60));
1145 } else if ($diff < 5400) {
1146 return _('about an hour ago');
1147 } else if ($diff < 22 * 3600) {
1148 return sprintf(_('about %d hours ago'), round($diff/3600));
1149 } else if ($diff < 37 * 3600) {
1150 return _('about a day ago');
1151 } else if ($diff < 24 * 24 * 3600) {
1152 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1153 } else if ($diff < 46 * 24 * 3600) {
1154 return _('about a month ago');
1155 } else if ($diff < 330 * 24 * 3600) {
1156 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1157 } else if ($diff < 480 * 24 * 3600) {
1158 return _('about a year ago');
1160 return common_exact_date($dt);
1164 function common_exact_date($dt) {
1169 $_utc = new DateTimeZone('UTC');
1170 $_siteTz = new DateTimeZone(common_timezone());
1173 $dateStr = date('d F Y H:i:s', strtotime($dt));
1174 $d = new DateTime($dateStr, $_utc);
1175 $d->setTimezone($_siteTz);
1176 return $d->format(DATE_RFC850);
1179 function common_date_w3dtf($dt) {
1180 $dateStr = date('d F Y H:i:s', strtotime($dt));
1181 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1182 $d->setTimezone(new DateTimeZone(common_timezone()));
1183 return $d->format(DATE_W3C);
1186 function common_date_rfc2822($dt) {
1187 $dateStr = date('d F Y H:i:s', strtotime($dt));
1188 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1189 $d->setTimezone(new DateTimeZone(common_timezone()));
1190 return $d->format('r');
1193 function common_date_iso8601($dt) {
1194 $dateStr = date('d F Y H:i:s', strtotime($dt));
1195 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1196 $d->setTimezone(new DateTimeZone(common_timezone()));
1197 return $d->format('c');
1200 function common_sql_now() {
1201 return strftime('%Y-%m-%d %H:%M:%S', time());
1204 function common_redirect($url, $code=307) {
1205 static $status = array(301 => "Moved Permanently",
1208 307 => "Temporary Redirect");
1209 header("Status: ${code} $status[$code]");
1210 header("Location: $url");
1212 common_start_xml('a',
1213 '-//W3C//DTD XHTML 1.0 Strict//EN',
1214 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1215 common_element('a', array('href' => $url), $url);
1220 function common_save_replies($notice) {
1221 # Alternative reply format
1223 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1226 # extract all @messages
1227 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1228 if (!$cnt && !$tname) {
1231 # XXX: is there another way to make an array copy?
1232 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1233 $sender = Profile::staticGet($notice->profile_id);
1234 # store replied only for first @ (what user/notice what the reply directed,
1235 # we assume first @ is it)
1236 for ($i=0; $i<count($names); $i++) {
1237 $nickname = $names[$i];
1238 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1242 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1243 $reply_for = $recipient;
1244 $recipient_notice = $reply_for->getCurrentNotice();
1245 if ($recipient_notice) {
1246 $orig = clone($notice);
1247 $notice->reply_to = $recipient_notice->id;
1248 $notice->update($orig);
1251 $reply = new Reply();
1252 $reply->notice_id = $notice->id;
1253 $reply->profile_id = $recipient->id;
1254 $id = $reply->insert();
1256 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1257 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1258 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1264 function common_broadcast_notice($notice, $remote=false) {
1266 // Check to see if notice should go to Twitter
1267 $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1268 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1270 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1272 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1273 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1275 $result = common_twitter_broadcast($notice, $flink);
1278 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1283 if (common_config('queue', 'enabled')) {
1285 return common_enqueue_notice($notice);
1287 return common_real_broadcast($notice, $remote);
1291 function common_twitter_broadcast($notice, $flink) {
1294 $fuser = $flink->getForeignUser();
1295 $twitter_user = $fuser->nickname;
1296 $twitter_password = $flink->credentials;
1297 $uri = 'http://www.twitter.com/statuses/update.json';
1299 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1300 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1303 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1304 CURLOPT_POST => true,
1305 CURLOPT_POSTFIELDS => array(
1306 'status' => $statustxt,
1307 'source' => $config['integration']['source']
1309 CURLOPT_RETURNTRANSFER => true,
1310 CURLOPT_FAILONERROR => true,
1311 CURLOPT_HEADER => false,
1312 CURLOPT_FOLLOWLOCATION => true,
1313 CURLOPT_USERAGENT => "Laconica",
1314 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1315 CURLOPT_TIMEOUT => 120
1318 $ch = curl_init($uri);
1319 curl_setopt_array($ch, $options);
1320 $data = curl_exec($ch);
1321 $errmsg = curl_error($ch);
1324 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1332 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1337 // Twitter should return a status
1338 $status = json_decode($data);
1341 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1349 # Stick the notice on the queue
1351 function common_enqueue_notice($notice) {
1352 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1353 $qi = new Queue_item();
1354 $qi->notice_id = $notice->id;
1355 $qi->transport = $transport;
1356 $qi->created = $notice->created;
1357 $result = $qi->insert();
1359 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1360 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1363 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1368 function common_dequeue_notice($notice) {
1369 $qi = Queue_item::staticGet($notice->id);
1371 $result = $qi->delete();
1373 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1374 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1377 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1384 function common_real_broadcast($notice, $remote=false) {
1387 # Make sure we have the OMB stuff
1388 require_once(INSTALLDIR.'/lib/omb.php');
1389 $success = omb_broadcast_remote_subscribers($notice);
1391 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1395 require_once(INSTALLDIR.'/lib/jabber.php');
1396 $success = jabber_broadcast_notice($notice);
1398 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1402 require_once(INSTALLDIR.'/lib/mail.php');
1403 $success = mail_broadcast_notice_sms($notice);
1405 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1409 $success = jabber_public_notice($notice);
1411 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1414 // XXX: broadcast notices to other IM
1418 function common_broadcast_profile($profile) {
1419 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1420 require_once(INSTALLDIR.'/lib/omb.php');
1421 omb_broadcast_profile($profile);
1422 // XXX: Other broadcasts...?
1426 function common_profile_url($nickname) {
1427 return common_local_url('showstream', array('nickname' => $nickname));
1430 # Don't call if nobody's logged in
1432 function common_notice_form($action=NULL, $content=NULL) {
1433 $user = common_current_user();
1434 assert(!is_null($user));
1435 common_element_start('form', array('id' => 'status_form',
1437 'action' => common_local_url('newnotice')));
1438 common_element_start('p');
1439 common_element('label', array('for' => 'status_textarea',
1440 'id' => 'status_label'),
1441 sprintf(_('What\'s up, %s?'), $user->nickname));
1442 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1443 common_element('textarea', array('id' => 'status_textarea',
1446 'name' => 'status_textarea'),
1447 ($content) ? $content : '');
1448 common_hidden('token', common_session_token());
1450 common_hidden('returnto', $action);
1453 common_hidden('inreplyto', 'false');
1454 common_element('input', array('id' => 'status_submit',
1455 'name' => 'status_submit',
1457 'value' => _('Send')));
1458 common_element_end('p');
1459 common_element_end('form');
1462 # Should make up a reasonable root URL
1464 function common_root_url() {
1465 return common_path('');
1468 # returns $bytes bytes of random data as a hexadecimal string
1469 # "good" here is a goal and not a guarantee
1471 function common_good_rand($bytes) {
1472 # XXX: use random.org...?
1473 if (file_exists('/dev/urandom')) {
1474 return common_urandom($bytes);
1475 } else { # FIXME: this is probably not good enough
1476 return common_mtrand($bytes);
1480 function common_urandom($bytes) {
1481 $h = fopen('/dev/urandom', 'rb');
1483 $src = fread($h, $bytes);
1486 for ($i = 0; $i < $bytes; $i++) {
1487 $enc .= sprintf("%02x", (ord($src[$i])));
1492 function common_mtrand($bytes) {
1494 for ($i = 0; $i < $bytes; $i++) {
1495 $enc .= sprintf("%02x", mt_rand(0, 255));
1500 function common_set_returnto($url) {
1501 common_ensure_session();
1502 $_SESSION['returnto'] = $url;
1505 function common_get_returnto() {
1506 common_ensure_session();
1507 return $_SESSION['returnto'];
1510 function common_timestamp() {
1511 return date('YmdHis');
1514 function common_ensure_syslog() {
1515 static $initialized = false;
1516 if (!$initialized) {
1518 openlog($config['syslog']['appname'], 0, LOG_USER);
1519 $initialized = true;
1523 function common_log($priority, $msg, $filename=NULL) {
1524 $logfile = common_config('site', 'logfile');
1526 $log = fopen($logfile, "a");
1528 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1529 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1530 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1531 fwrite($log, $output);
1535 common_ensure_syslog();
1536 syslog($priority, $msg);
1540 function common_debug($msg, $filename=NULL) {
1542 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1544 common_log(LOG_DEBUG, $msg);
1548 function common_log_db_error(&$object, $verb, $filename=NULL) {
1549 $objstr = common_log_objstring($object);
1550 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1551 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1554 function common_log_objstring(&$object) {
1555 if (is_null($object)) {
1558 $arr = $object->toArray();
1560 foreach ($arr as $k => $v) {
1561 $fields[] = "$k='$v'";
1563 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1567 function common_valid_http_url($url) {
1568 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1571 function common_valid_tag($tag) {
1572 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1573 return (Validate::email($matches[1]) ||
1574 preg_match('/^([\w-\.]+)$/', $matches[1]));
1579 # Does a little before-after block for next/prev page
1581 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1583 if ($have_before || $have_after) {
1584 common_element_start('div', array('id' => 'pagination'));
1585 common_element_start('ul', array('id' => 'nav_pagination'));
1589 $pargs = array('page' => $page-1);
1590 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1592 common_element_start('li', 'before');
1593 common_element('a', array('href' => common_local_url($action, $newargs)),
1595 common_element_end('li');
1599 $pargs = array('page' => $page+1);
1600 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1601 common_element_start('li', 'after');
1602 common_element('a', array('href' => common_local_url($action, $newargs)),
1604 common_element_end('li');
1607 if ($have_before || $have_after) {
1608 common_element_end('ul');
1609 common_element_end('div');
1613 /* Following functions are copied from MediaWiki GlobalFunctions.php
1614 * and written by Evan Prodromou. */
1616 function common_accept_to_prefs($accept, $def = '*/*') {
1617 # No arg means accept anything (per HTTP spec)
1619 return array($def => 1);
1624 $parts = explode(',', $accept);
1626 foreach($parts as $part) {
1627 # FIXME: doesn't deal with params like 'text/html; level=1'
1628 @list($value, $qpart) = explode(';', $part);
1630 if(!isset($qpart)) {
1632 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1633 $prefs[$value] = $match[1];
1640 function common_mime_type_match($type, $avail) {
1641 if(array_key_exists($type, $avail)) {
1644 $parts = explode('/', $type);
1645 if(array_key_exists($parts[0] . '/*', $avail)) {
1646 return $parts[0] . '/*';
1647 } elseif(array_key_exists('*/*', $avail)) {
1655 function common_negotiate_type($cprefs, $sprefs) {
1658 foreach(array_keys($sprefs) as $type) {
1659 $parts = explode('/', $type);
1660 if($parts[1] != '*') {
1661 $ckey = common_mime_type_match($type, $cprefs);
1663 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1668 foreach(array_keys($cprefs) as $type) {
1669 $parts = explode('/', $type);
1670 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1671 $skey = common_mime_type_match($type, $sprefs);
1673 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1679 $besttype = "text/html";
1681 foreach(array_keys($combine) as $type) {
1682 if($combine[$type] > $bestq) {
1684 $bestq = $combine[$type];
1691 function common_config($main, $sub) {
1693 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1696 function common_copy_args($from) {
1698 $strip = get_magic_quotes_gpc();
1699 foreach ($from as $k => $v) {
1700 $to[$k] = ($strip) ? stripslashes($v) : $v;
1705 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1706 // This is used before handing a request off to OAuthRequest::from_request.
1707 function common_remove_magic_from_request() {
1708 if(get_magic_quotes_gpc()) {
1709 $_POST=array_map('stripslashes',$_POST);
1710 $_GET=array_map('stripslashes',$_GET);
1714 function common_user_uri(&$user) {
1715 return common_local_url('userbyid', array('id' => $user->id));
1718 function common_notice_uri(&$notice) {
1719 return common_local_url('shownotice',
1720 array('notice' => $notice->id));
1723 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1725 function common_confirmation_code($bits) {
1726 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1727 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1728 $chars = ceil($bits/5);
1730 for ($i = 0; $i < $chars; $i++) {
1731 # XXX: convert to string and back
1732 $num = hexdec(common_good_rand(1));
1733 # XXX: randomness is too precious to throw away almost
1734 # 40% of the bits we get!
1735 $code .= $codechars[$num%32];
1740 # convert markup to HTML
1742 function common_markup_to_html($c) {
1743 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1744 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1745 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1746 return Markdown($c);
1749 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1750 $avatar = $profile->getAvatar($size);
1752 return common_avatar_display_url($avatar);
1754 return common_default_avatar($size);
1758 function common_profile_uri($profile) {
1762 $user = User::staticGet($profile->id);
1767 $remote = Remote_profile::staticGet($profile->id);
1769 return $remote->uri;
1771 # XXX: this is a very bad profile!
1775 function common_canonical_sms($sms) {
1777 preg_replace('/\D/', '', $sms);
1781 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1784 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1788 case E_USER_WARNING:
1789 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1793 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1797 # FIXME: show error page if we're on the Web
1798 /* Don't execute PHP internal error handler */
1802 function common_session_token() {
1803 common_ensure_session();
1804 if (!array_key_exists('token', $_SESSION)) {
1805 $_SESSION['token'] = common_good_rand(64);
1807 return $_SESSION['token'];
1810 function common_disfavor_form($notice) {
1811 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1813 'class' => 'disfavor',
1814 'action' => common_local_url('disfavor')));
1816 common_element('input', array('type' => 'hidden',
1817 'name' => 'token-'. $notice->id,
1818 'id' => 'token-'. $notice->id,
1820 'value' => common_session_token()));
1822 common_element('input', array('type' => 'hidden',
1824 'id' => 'notice-n'. $notice->id,
1825 'class' => 'notice',
1826 'value' => $notice->id));
1828 common_element('input', array('type' => 'submit',
1829 'id' => 'disfavor-submit-' . $notice->id,
1830 'name' => 'disfavor-submit-' . $notice->id,
1831 'class' => 'disfavor',
1832 'value' => 'Disfavor favorite',
1833 'title' => 'Remove this message from favorites'));
1834 common_element_end('form');
1837 function common_favor_form($notice) {
1838 common_element_start('form', array('id' => 'favor-' . $notice->id,
1841 'action' => common_local_url('favor')));
1843 common_element('input', array('type' => 'hidden',
1844 'name' => 'token-'. $notice->id,
1845 'id' => 'token-'. $notice->id,
1847 'value' => common_session_token()));
1849 common_element('input', array('type' => 'hidden',
1851 'id' => 'notice-n'. $notice->id,
1852 'class' => 'notice',
1853 'value' => $notice->id));
1855 common_element('input', array('type' => 'submit',
1856 'id' => 'favor-submit-' . $notice->id,
1857 'name' => 'favor-submit-' . $notice->id,
1859 'value' => 'Add to favorites',
1860 'title' => 'Add this message to favorites'));
1861 common_element_end('form');
1864 function common_cache_key($extra) {
1865 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1868 function common_keyize($str) {
1869 $str = strtolower($str);
1870 $str = preg_replace('/\s/', '_', $str);
1874 function common_message_form($content, $user, $to) {
1876 common_element_start('form', array('id' => 'message_form',
1878 'action' => common_local_url('newmessage')));
1880 $mutual_users = $user->mutuallySubscribedUsers();
1884 while ($mutual_users->fetch()) {
1885 if ($mutual_users->id != $user->id) {
1886 $mutual[$mutual_users->id] = $mutual_users->nickname;
1890 $mutual_users->free();
1891 unset($mutual_users);
1893 common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
1895 common_element_start('p');
1897 common_element('textarea', array('id' => 'message_content',
1900 'name' => 'content'),
1901 ($content) ? $content : '');
1903 common_element('input', array('id' => 'message_send',
1904 'name' => 'message_send',
1906 'value' => _('Send')));
1908 common_hidden('token', common_session_token());
1910 common_element_end('p');
1911 common_element_end('form');
1914 function common_memcache() {
1915 static $cache = NULL;
1916 if (!common_config('memcached', 'enabled')) {
1920 $cache = new Memcache();
1921 $servers = common_config('memcached', 'server');
1922 if (is_array($servers)) {
1923 foreach($servers as $server) {
1924 $cache->addServer($server);
1927 $cache->addServer($servers);