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/util.js?version='.LACONICA_VERSION)),
186 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
187 'href' => common_local_url('opensearch', array('type' => 'people')),
188 'title' => common_config('site', 'name').' People Search'));
190 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
191 'href' => common_local_url('opensearch', array('type' => 'notice')),
192 'title' => common_config('site', 'name').' Notice Search'));
196 call_user_func($callable, $data);
198 call_user_func($callable);
201 common_element_end('head');
202 common_element_start('body');
203 common_element_start('div', array('id' => 'wrap'));
204 common_element_start('div', array('id' => 'header'));
206 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
207 || file_exists(theme_file('logo.png')))
209 common_element_start('a', array('href' => common_local_url('public')));
210 common_element('img', array('src' => isset($config['site']['logo']) ?
211 ($config['site']['logo']) : theme_path('logo.png'),
212 'alt' => $config['site']['name'],
214 common_element_end('a');
216 common_element_start('p', array('id' => 'branding'));
217 common_element('a', array('href' => common_local_url('public')),
218 $config['site']['name']);
219 common_element_end('p');
222 common_element('h1', 'pagetitle', $pagetitle);
226 call_user_func($headercall, $data);
228 call_user_func($headercall);
231 common_element_end('div');
232 common_element_start('div', array('id' => 'content'));
235 function common_start_html($type=NULL) {
238 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
240 # XXX: allow content negotiation for RDF, RSS, or XRDS
242 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
243 common_accept_to_prefs(PAGE_TYPE_PREFS));
246 common_user_error(_('This page is not available in a media type you accept'), 406);
251 header('Content-Type: '.$type);
253 common_start_xml('html',
254 '-//W3C//DTD XHTML 1.0 Strict//EN',
255 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
257 # FIXME: correct language for interface
259 $language = common_language();
261 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
262 'xml:lang' => $language,
263 'lang' => $language));
266 function common_show_footer() {
268 common_element_end('div'); # content div
270 common_element_start('div', array('id' => 'footer'));
271 common_element_start('div', 'laconica');
272 if (common_config('site', 'broughtby')) {
273 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
275 $instr = _('**%%site.name%%** is a microblogging service. ');
277 $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);
278 $output = common_markup_to_html($instr);
280 common_element_end('div');
281 common_element('img', array('id' => 'cc',
282 'src' => $config['license']['image'],
283 'alt' => $config['license']['title']));
284 common_element_start('p');
285 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
286 common_element('a', array('class' => 'license',
288 'href' => $config['license']['url']),
289 $config['license']['title']);
290 common_text(_('. Contributors should be attributed by full name or nickname.'));
291 common_element_end('p');
292 common_element_end('div');
293 common_element_end('div');
294 common_element_end('body');
295 common_element_end('html');
299 function common_text($txt) {
304 function common_raw($xml) {
309 function common_nav_menu() {
310 $user = common_current_user();
311 common_element_start('ul', array('id' => 'nav'));
313 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
316 common_menu_item(common_local_url('peoplesearch'), _('Search'));
317 common_menu_item(common_local_url('tags'), _('Tags'));
319 common_menu_item(common_local_url('profilesettings'),
321 common_menu_item(common_local_url('invite'),
323 common_menu_item(common_local_url('logout'),
326 common_menu_item(common_local_url('login'), _('Login'));
327 if (!common_config('site', 'closed')) {
328 common_menu_item(common_local_url('register'), _('Register'));
330 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
332 common_element_end('ul');
335 function common_foot_menu() {
336 common_element_start('ul', array('id' => 'nav_sub'));
337 common_menu_item(common_local_url('doc', array('title' => 'help')),
339 common_menu_item(common_local_url('doc', array('title' => 'about')),
341 common_menu_item(common_local_url('doc', array('title' => 'faq')),
343 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
345 common_menu_item(common_local_url('doc', array('title' => 'source')),
347 common_menu_item(common_local_url('doc', array('title' => 'contact')),
349 common_element_end('ul');
352 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
355 $lattrs['class'] = 'current';
357 common_element_start('li', $lattrs);
358 $attrs['href'] = $url;
360 $attrs['title'] = $title;
362 common_element('a', $attrs, $text);
363 common_element_end('li');
366 function common_input($id, $label, $value=NULL,$instructions=NULL) {
367 common_element_start('p');
368 common_element('label', array('for' => $id), $label);
369 $attrs = array('name' => $id,
371 'class' => 'input_text',
374 $attrs['value'] = htmlspecialchars($value);
376 common_element('input', $attrs);
378 common_element('span', 'input_instructions', $instructions);
380 common_element_end('p');
383 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false)
385 common_element_start('p');
386 $attrs = array('name' => $id,
387 'type' => 'checkbox',
388 'class' => 'checkbox',
391 $attrs['value'] = htmlspecialchars($value);
394 $attrs['checked'] = 'checked';
397 $attrs['disabled'] = 'true';
399 common_element('input', $attrs);
402 common_element('span', 'checkbox_label', $label);
405 common_element('span', 'input_instructions', $instructions);
407 common_element_end('p');
410 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
411 common_element_start('p');
412 common_element('label', array('for' => $id), $label);
413 common_element_start('select', array('id' => $id, 'name' => $id));
415 common_element('option', array('value' => ''));
417 foreach ($content as $value => $option) {
418 if ($value == $selected) {
419 common_element('option', array('value' => $value, 'selected' => $value), $option);
421 common_element('option', array('value' => $value), $option);
424 common_element_end('select');
426 common_element('span', 'input_instructions', $instructions);
428 common_element_end('p');
430 function common_hidden($id, $value) {
431 common_element('input', array('name' => $id,
437 function common_password($id, $label, $instructions=NULL) {
438 common_element_start('p');
439 common_element('label', array('for' => $id), $label);
440 $attrs = array('name' => $id,
441 'type' => 'password',
442 'class' => 'password',
444 common_element('input', $attrs);
446 common_element('span', 'input_instructions', $instructions);
448 common_element_end('p');
451 function common_submit($id, $label, $cls='submit') {
453 common_element_start('p');
454 common_element('input', array('type' => 'submit',
459 common_element_end('p');
462 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
463 common_element_start('p');
464 common_element('label', array('for' => $id), $label);
465 common_element('textarea', array('rows' => 3,
469 ($content) ? $content : '');
471 common_element('span', 'input_instructions', $instructions);
473 common_element_end('p');
476 function common_timezone() {
477 if (common_logged_in()) {
478 $user = common_current_user();
479 if ($user->timezone) {
480 return $user->timezone;
485 return $config['site']['timezone'];
488 function common_language() {
490 // If there is a user logged in and they've set a language preference
491 // then return that one...
492 if (common_logged_in()) {
493 $user = common_current_user();
494 $user_language = $user->language;
496 return $user_language;
499 // Otherwise, find the best match for the languages requested by the
501 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
502 if (!empty($httplang)) {
503 $language = client_prefered_language($httplang);
508 // Finally, if none of the above worked, use the site's default...
509 return common_config('site', 'language');
511 # salted, hashed passwords are stored in the DB
513 function common_munge_password($password, $id) {
514 return md5($password . $id);
517 # check if a username exists and has matching password
518 function common_check_user($nickname, $password) {
519 # NEVER allow blank passwords, even if they match the DB
520 if (mb_strlen($password) == 0) {
523 $user = User::staticGet('nickname', $nickname);
524 if (is_null($user)) {
527 if (0 == strcmp(common_munge_password($password, $user->id),
536 # is the current user logged in?
537 function common_logged_in() {
538 return (!is_null(common_current_user()));
541 function common_have_session() {
542 return (0 != strcmp(session_id(), ''));
545 function common_ensure_session() {
546 if (!common_have_session()) {
551 # Three kinds of arguments:
556 function common_set_user($user) {
557 if (is_null($user) && common_have_session()) {
558 unset($_SESSION['userid']);
560 } else if (is_string($user)) {
562 $user = User::staticGet('nickname', $nickname);
563 } else if (!($user instanceof User)) {
568 common_ensure_session();
569 $_SESSION['userid'] = $user->id;
575 function common_set_cookie($key, $value, $expiration=0) {
576 $path = common_config('site', 'path');
577 $server = common_config('site', 'server');
579 if ($path && ($path != '/')) {
580 $cookiepath = '/' . $path . '/';
584 return setcookie($key,
591 define('REMEMBERME', 'rememberme');
592 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
594 function common_rememberme($user=NULL) {
596 $user = common_current_user();
598 common_debug('No current user to remember', __FILE__);
602 $rm = new Remember_me();
603 $rm->code = common_good_rand(16);
604 $rm->user_id = $user->id;
605 $result = $rm->insert();
607 common_log_db_error($rm, 'INSERT', __FILE__);
608 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
611 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
612 common_set_cookie(REMEMBERME,
613 implode(':', array($rm->user_id, $rm->code)),
614 time() + REMEMBERME_EXPIRY);
618 function common_remembered_user() {
621 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
623 list($id, $code) = explode(':', $packed);
625 $rm = Remember_me::staticGet($code);
626 if ($rm && ($rm->user_id == $id)) {
627 $user = User::staticGet($rm->user_id);
630 $result = $rm->delete();
632 common_log_db_error($rm, 'DELETE', __FILE__);
635 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
636 common_set_user($user->nickname);
637 common_real_login(false);
638 # We issue a new cookie, so they can log in
639 # automatically again after this session
640 common_rememberme($user);
649 # must be called with a valid user!
651 function common_forgetme() {
652 common_set_cookie(REMEMBERME, '', 0);
655 # who is the current user?
656 function common_current_user() {
657 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
658 common_ensure_session();
659 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
661 # note: this should cache
662 $user = User::staticGet($id);
666 # that didn't work; try to remember
667 $user = common_remembered_user();
669 common_debug("Got User " . $user->nickname);
670 common_debug("Faking session on remembered user");
671 $_SESSION['userid'] = $user->id;
676 # Logins that are 'remembered' aren't 'real' -- they're subject to
677 # cookie-stealing. So, we don't let them do certain things. New reg,
678 # OpenID, and password logins _are_ real.
680 function common_real_login($real=true) {
681 common_ensure_session();
682 $_SESSION['real_login'] = $real;
685 function common_is_real_login() {
686 return common_logged_in() && $_SESSION['real_login'];
689 # get canonical version of nickname for comparison
690 function common_canonical_nickname($nickname) {
691 # XXX: UTF-8 canonicalization (like combining chars)
692 return strtolower($nickname);
695 # get canonical version of email for comparison
696 function common_canonical_email($email) {
697 # XXX: canonicalize UTF-8
698 # XXX: lcase the domain part
702 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$_+!*();/?:~-]))');
704 function common_render_content($text, $notice) {
705 $r = common_render_text($text);
706 $id = $notice->profile_id;
707 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
708 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
712 function common_render_text($text) {
713 $r = htmlspecialchars($text);
715 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
716 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
717 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
722 function common_render_uri_thingy($matches) {
726 # Some heuristics for extracting URIs from surrounding punctuation
727 # Strip from trailing text...
728 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
730 $trailer = $matches[2];
734 ']' => '[', # technically disallowed in URIs, but used in Java docs
735 ')' => '(', # far too frequent in Wikipedia and MSDN
737 $final = substr($uri, -1, 1);
738 if (isset($pairs[$final])) {
739 $openers = substr_count($uri, $pairs[$final]);
740 $closers = substr_count($uri, $final);
741 if ($closers > $openers) {
742 // Assume the paren was opened outside the URI
743 $uri = substr($uri, 0, -1);
744 $trailer = $final . $trailer;
747 if ($longurl = common_longurl($uri)) {
748 $longurl = htmlentities($longurl, ENT_QUOTES, 'UTF-8');
749 $title = " title='$longurl'";
753 return '<a href="' . $uri . '"' . $title . ' class="extlink">' . $uri . '</a>' . $trailer;
756 function common_longurl($uri) {
757 $uri_e = urlencode($uri);
758 $longurl = unserialize(file_get_contents("http://api.longurl.org/v1/expand?format=php&url=$uri_e"));
759 if (empty($longurl['long_url']) || $uri === $longurl['long_url']) return false;
760 return stripslashes($longurl['long_url']);
763 function common_shorten_links($text) {
764 // \s = not a horizontal whitespace character (since PHP 5.2.4)
765 // RYM this should prevent * preceded URLs from being processed but it its a char
766 // $r = preg_replace('@[^*](https?://[^)\]>\s]+)@e', "common_shorten_link('\\1')", $r);
767 return preg_replace('@https?://[^)\]>\s]+@e', "common_shorten_link('\\0')", $text);
770 function common_shorten_link($long_url) {
772 $user = common_current_user();
774 $curlh = curl_init();
775 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
776 curl_setopt($curlh, CURLOPT_USERAGENT, 'Laconica');
777 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
779 switch($user->urlshorteningservice) {
781 $short_url_service = new LilUrl;
782 $short_url = $short_url_service->shorten($long_url);
786 $short_url_service = new TightUrl;
787 $short_url = $short_url_service->shorten($long_url);
791 $short_url_service = new PtitUrl;
792 $short_url = $short_url_service->shorten($long_url);
796 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($long_url));
797 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
801 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($long_url));
802 $short_url = curl_exec($curlh);
805 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($long_url));
806 $short_url = curl_exec($curlh);
809 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($long_url));
810 $short_url = curl_exec($curlh);
813 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($long_url));
814 $short_url = curl_exec($curlh);
828 function common_xml_safe_str($str) {
829 $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
831 // Replace control, formatting, and surrogate characters with '*', ala Twitter
832 return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
835 function common_tag_link($tag) {
836 $canonical = common_canonical_tag($tag);
837 $url = common_local_url('tag', array('tag' => $canonical));
838 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
841 function common_canonical_tag($tag) {
842 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
845 function common_at_link($sender_id, $nickname) {
846 $sender = Profile::staticGet($sender_id);
847 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
849 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
855 function common_relative_profile($sender, $nickname, $dt=NULL) {
856 # Try to find profiles this profile is subscribed to that have this nickname
857 $recipient = new Profile();
858 # XXX: use a join instead of a subquery
859 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
860 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
861 if ($recipient->find(TRUE)) {
862 # XXX: should probably differentiate between profiles with
863 # the same name by date of most recent update
866 # Try to find profiles that listen to this profile and that have this nickname
867 $recipient = new Profile();
868 # XXX: use a join instead of a subquery
869 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
870 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
871 if ($recipient->find(TRUE)) {
872 # XXX: should probably differentiate between profiles with
873 # the same name by date of most recent update
876 # If this is a local user, try to find a local user with that nickname.
877 $sender = User::staticGet($sender->id);
879 $recipient_user = User::staticGet('nickname', $nickname);
880 if ($recipient_user) {
881 return $recipient_user->getProfile();
884 # Otherwise, no links. @messages from local users to remote users,
885 # or from remote users to other remote users, are just
886 # outside our ability to make intelligent guesses about
890 // where should the avatar go for this user?
892 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
896 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
898 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
902 function common_avatar_path($filename) {
904 return INSTALLDIR . '/avatar/' . $filename;
907 function common_avatar_url($filename) {
908 return common_path('avatar/'.$filename);
911 function common_avatar_display_url($avatar) {
912 $server = common_config('avatar', 'server');
914 return 'http://'.$server.'/'.$avatar->filename;
920 function common_default_avatar($size) {
921 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
922 AVATAR_STREAM_SIZE => 'stream',
923 AVATAR_MINI_SIZE => 'mini');
924 return theme_path('default-avatar-'.$sizenames[$size].'.png');
927 function common_local_url($action, $args=NULL, $fragment=NULL) {
929 if (common_config('site','fancy')) {
930 $url = common_fancy_url($action, $args);
932 $url = common_simple_url($action, $args);
934 if (!is_null($fragment)) {
935 $url .= '#'.$fragment;
940 function common_fancy_url($action, $args=NULL) {
941 switch (strtolower($action)) {
943 if ($args && isset($args['page'])) {
944 return common_path('?page=' . $args['page']);
946 return common_path('');
949 return common_path('rss');
951 return common_path('xrds');
953 if ($args && $args['type']) {
954 return common_path('opensearch/'.$args['type']);
956 return common_path('opensearch/people');
959 return common_path('doc/'.$args['title']);
965 return common_path('main/'.$action);
967 if ($args && $args['code']) {
968 return common_path('main/register/'.$args['code']);
970 return common_path('main/register');
972 case 'remotesubscribe':
973 if ($args && $args['nickname']) {
974 return common_path('main/remote?nickname=' . $args['nickname']);
976 return common_path('main/remote');
979 return common_path('main/openid');
980 case 'profilesettings':
981 return common_path('settings/profile');
982 case 'emailsettings':
983 return common_path('settings/email');
984 case 'openidsettings':
985 return common_path('settings/openid');
987 return common_path('settings/sms');
988 case 'twittersettings':
989 return common_path('settings/twitter');
990 case 'othersettings':
991 return common_path('settings/other');
993 if ($args && $args['replyto']) {
994 return common_path('notice/new?replyto='.$args['replyto']);
996 return common_path('notice/new');
999 return common_path('notice/'.$args['notice']);
1000 case 'deletenotice':
1001 if ($args && $args['notice']) {
1002 return common_path('notice/delete/'.$args['notice']);
1004 return common_path('notice/delete');
1008 return common_path($args['nickname'].'/'.$action);
1009 case 'subscriptions':
1015 if ($args && isset($args['page'])) {
1016 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
1018 return common_path($args['nickname'].'/'.$action);
1021 return common_path($args['nickname'].'/all/rss');
1023 return common_path($args['nickname'].'/replies/rss');
1025 return common_path($args['nickname'].'/rss');
1027 if ($args && isset($args['page'])) {
1028 return common_path($args['nickname'].'?page=' . $args['page']);
1030 return common_path($args['nickname']);
1032 case 'confirmaddress':
1033 return common_path('main/confirmaddress/'.$args['code']);
1035 return common_path('user/'.$args['id']);
1036 case 'recoverpassword':
1037 $path = 'main/recoverpassword';
1038 if ($args['code']) {
1039 $path .= '/' . $args['code'];
1041 return common_path($path);
1043 return common_path('settings/im');
1044 case 'peoplesearch':
1045 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
1046 case 'noticesearch':
1047 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
1048 case 'noticesearchrss':
1049 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
1050 case 'avatarbynickname':
1051 return common_path($args['nickname'].'/avatar/'.$args['size']);
1053 if (isset($args['tag']) && $args['tag']) {
1054 $path = 'tag/' . $args['tag'];
1055 unset($args['tag']);
1059 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
1061 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
1063 return common_path('main/favor');
1065 return common_path('main/disfavor');
1066 case 'showfavorites':
1067 if ($args && isset($args['page'])) {
1068 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
1070 return common_path($args['nickname'].'/favorites');
1072 case 'favoritesrss':
1073 return common_path($args['nickname'].'/favorites/rss');
1075 return common_path('message/' . $args['message']);
1077 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
1079 # XXX: do fancy URLs for all the API methods
1080 switch (strtolower($args['apiaction'])) {
1082 switch (strtolower($args['method'])) {
1083 case 'user_timeline.rss':
1084 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1085 case 'user_timeline.atom':
1086 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1087 case 'user_timeline.rss':
1088 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1089 case 'user_timeline.atom':
1090 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1091 default: return common_simple_url($action, $args);
1093 default: return common_simple_url($action, $args);
1096 if ($args && isset($args['seconds'])) {
1097 return common_path('main/sup?seconds='.$args['seconds']);
1099 return common_path('main/sup');
1102 return common_simple_url($action, $args);
1106 function common_simple_url($action, $args=NULL) {
1108 /* XXX: pretty URLs */
1111 foreach ($args as $key => $value) {
1112 $extra .= "&${key}=${value}";
1115 return common_path("index.php?action=${action}${extra}");
1118 function common_path($relative) {
1120 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1121 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1124 function common_date_string($dt) {
1125 // XXX: do some sexy date formatting
1126 // return date(DATE_RFC822, $dt);
1127 $t = strtotime($dt);
1131 if ($now < $t) { # that shouldn't happen!
1132 return common_exact_date($dt);
1133 } else if ($diff < 60) {
1134 return _('a few seconds ago');
1135 } else if ($diff < 92) {
1136 return _('about a minute ago');
1137 } else if ($diff < 3300) {
1138 return sprintf(_('about %d minutes ago'), round($diff/60));
1139 } else if ($diff < 5400) {
1140 return _('about an hour ago');
1141 } else if ($diff < 22 * 3600) {
1142 return sprintf(_('about %d hours ago'), round($diff/3600));
1143 } else if ($diff < 37 * 3600) {
1144 return _('about a day ago');
1145 } else if ($diff < 24 * 24 * 3600) {
1146 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1147 } else if ($diff < 46 * 24 * 3600) {
1148 return _('about a month ago');
1149 } else if ($diff < 330 * 24 * 3600) {
1150 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1151 } else if ($diff < 480 * 24 * 3600) {
1152 return _('about a year ago');
1154 return common_exact_date($dt);
1158 function common_exact_date($dt) {
1163 $_utc = new DateTimeZone('UTC');
1164 $_siteTz = new DateTimeZone(common_timezone());
1167 $dateStr = date('d F Y H:i:s', strtotime($dt));
1168 $d = new DateTime($dateStr, $_utc);
1169 $d->setTimezone($_siteTz);
1170 return $d->format(DATE_RFC850);
1173 function common_date_w3dtf($dt) {
1174 $dateStr = date('d F Y H:i:s', strtotime($dt));
1175 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1176 $d->setTimezone(new DateTimeZone(common_timezone()));
1177 return $d->format(DATE_W3C);
1180 function common_date_rfc2822($dt) {
1181 $dateStr = date('d F Y H:i:s', strtotime($dt));
1182 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1183 $d->setTimezone(new DateTimeZone(common_timezone()));
1184 return $d->format('r');
1187 function common_date_iso8601($dt) {
1188 $dateStr = date('d F Y H:i:s', strtotime($dt));
1189 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1190 $d->setTimezone(new DateTimeZone(common_timezone()));
1191 return $d->format('c');
1194 function common_sql_now() {
1195 return strftime('%Y-%m-%d %H:%M:%S', time());
1198 function common_redirect($url, $code=307) {
1199 static $status = array(301 => "Moved Permanently",
1202 307 => "Temporary Redirect");
1203 header("Status: ${code} $status[$code]");
1204 header("Location: $url");
1206 common_start_xml('a',
1207 '-//W3C//DTD XHTML 1.0 Strict//EN',
1208 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1209 common_element('a', array('href' => $url), $url);
1214 function common_save_replies($notice) {
1215 # Alternative reply format
1217 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1220 # extract all @messages
1221 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1222 if (!$cnt && !$tname) {
1225 # XXX: is there another way to make an array copy?
1226 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1227 $sender = Profile::staticGet($notice->profile_id);
1228 # store replied only for first @ (what user/notice what the reply directed,
1229 # we assume first @ is it)
1230 for ($i=0; $i<count($names); $i++) {
1231 $nickname = $names[$i];
1232 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1236 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1237 $reply_for = $recipient;
1238 $recipient_notice = $reply_for->getCurrentNotice();
1239 if ($recipient_notice) {
1240 $orig = clone($notice);
1241 $notice->reply_to = $recipient_notice->id;
1242 $notice->update($orig);
1245 $reply = new Reply();
1246 $reply->notice_id = $notice->id;
1247 $reply->profile_id = $recipient->id;
1248 $id = $reply->insert();
1250 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1251 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1252 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1258 function common_broadcast_notice($notice, $remote=false) {
1260 // Check to see if notice should go to Twitter
1261 $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1262 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1264 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1266 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1267 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1269 $result = common_twitter_broadcast($notice, $flink);
1272 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1277 if (common_config('queue', 'enabled')) {
1279 return common_enqueue_notice($notice);
1281 return common_real_broadcast($notice, $remote);
1285 function common_twitter_broadcast($notice, $flink) {
1288 $fuser = $flink->getForeignUser();
1289 $twitter_user = $fuser->nickname;
1290 $twitter_password = $flink->credentials;
1291 $uri = 'http://www.twitter.com/statuses/update.json';
1293 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1294 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1297 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1298 CURLOPT_POST => true,
1299 CURLOPT_POSTFIELDS => array(
1300 'status' => $statustxt,
1301 'source' => $config['integration']['source']
1303 CURLOPT_RETURNTRANSFER => true,
1304 CURLOPT_FAILONERROR => true,
1305 CURLOPT_HEADER => false,
1306 CURLOPT_FOLLOWLOCATION => true,
1307 CURLOPT_USERAGENT => "Laconica",
1308 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1309 CURLOPT_TIMEOUT => 120
1312 $ch = curl_init($uri);
1313 curl_setopt_array($ch, $options);
1314 $data = curl_exec($ch);
1315 $errmsg = curl_error($ch);
1318 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1326 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1331 // Twitter should return a status
1332 $status = json_decode($data);
1335 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1343 # Stick the notice on the queue
1345 function common_enqueue_notice($notice) {
1346 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1347 $qi = new Queue_item();
1348 $qi->notice_id = $notice->id;
1349 $qi->transport = $transport;
1350 $qi->created = $notice->created;
1351 $result = $qi->insert();
1353 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1354 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1357 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1362 function common_dequeue_notice($notice) {
1363 $qi = Queue_item::staticGet($notice->id);
1365 $result = $qi->delete();
1367 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1368 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1371 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1378 function common_real_broadcast($notice, $remote=false) {
1381 # Make sure we have the OMB stuff
1382 require_once(INSTALLDIR.'/lib/omb.php');
1383 $success = omb_broadcast_remote_subscribers($notice);
1385 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1389 require_once(INSTALLDIR.'/lib/jabber.php');
1390 $success = jabber_broadcast_notice($notice);
1392 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1396 require_once(INSTALLDIR.'/lib/mail.php');
1397 $success = mail_broadcast_notice_sms($notice);
1399 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1403 $success = jabber_public_notice($notice);
1405 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1408 // XXX: broadcast notices to other IM
1412 function common_broadcast_profile($profile) {
1413 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1414 require_once(INSTALLDIR.'/lib/omb.php');
1415 omb_broadcast_profile($profile);
1416 // XXX: Other broadcasts...?
1420 function common_profile_url($nickname) {
1421 return common_local_url('showstream', array('nickname' => $nickname));
1424 # Don't call if nobody's logged in
1426 function common_notice_form($action=NULL, $content=NULL) {
1427 $user = common_current_user();
1428 assert(!is_null($user));
1429 common_element_start('form', array('id' => 'status_form',
1431 'action' => common_local_url('newnotice')));
1432 common_element_start('p');
1433 common_element('label', array('for' => 'status_textarea',
1434 'id' => 'status_label'),
1435 sprintf(_('What\'s up, %s?'), $user->nickname));
1436 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1437 common_element('textarea', array('id' => 'status_textarea',
1440 'name' => 'status_textarea'),
1441 ($content) ? $content : '');
1442 common_hidden('token', common_session_token());
1444 common_hidden('returnto', $action);
1447 common_hidden('inreplyto', 'false');
1448 common_element('input', array('id' => 'status_submit',
1449 'name' => 'status_submit',
1451 'value' => _('Send')));
1452 common_element_end('p');
1453 common_element_end('form');
1456 # Should make up a reasonable root URL
1458 function common_root_url() {
1459 return common_path('');
1462 # returns $bytes bytes of random data as a hexadecimal string
1463 # "good" here is a goal and not a guarantee
1465 function common_good_rand($bytes) {
1466 # XXX: use random.org...?
1467 if (file_exists('/dev/urandom')) {
1468 return common_urandom($bytes);
1469 } else { # FIXME: this is probably not good enough
1470 return common_mtrand($bytes);
1474 function common_urandom($bytes) {
1475 $h = fopen('/dev/urandom', 'rb');
1477 $src = fread($h, $bytes);
1480 for ($i = 0; $i < $bytes; $i++) {
1481 $enc .= sprintf("%02x", (ord($src[$i])));
1486 function common_mtrand($bytes) {
1488 for ($i = 0; $i < $bytes; $i++) {
1489 $enc .= sprintf("%02x", mt_rand(0, 255));
1494 function common_set_returnto($url) {
1495 common_ensure_session();
1496 $_SESSION['returnto'] = $url;
1499 function common_get_returnto() {
1500 common_ensure_session();
1501 return $_SESSION['returnto'];
1504 function common_timestamp() {
1505 return date('YmdHis');
1508 function common_ensure_syslog() {
1509 static $initialized = false;
1510 if (!$initialized) {
1512 openlog($config['syslog']['appname'], 0, LOG_USER);
1513 $initialized = true;
1517 function common_log($priority, $msg, $filename=NULL) {
1518 $logfile = common_config('site', 'logfile');
1520 $log = fopen($logfile, "a");
1522 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1523 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1524 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1525 fwrite($log, $output);
1529 common_ensure_syslog();
1530 syslog($priority, $msg);
1534 function common_debug($msg, $filename=NULL) {
1536 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1538 common_log(LOG_DEBUG, $msg);
1542 function common_log_db_error(&$object, $verb, $filename=NULL) {
1543 $objstr = common_log_objstring($object);
1544 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1545 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1548 function common_log_objstring(&$object) {
1549 if (is_null($object)) {
1552 $arr = $object->toArray();
1554 foreach ($arr as $k => $v) {
1555 $fields[] = "$k='$v'";
1557 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1561 function common_valid_http_url($url) {
1562 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1565 function common_valid_tag($tag) {
1566 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1567 return (Validate::email($matches[1]) ||
1568 preg_match('/^([\w-\.]+)$/', $matches[1]));
1573 # Does a little before-after block for next/prev page
1575 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1577 if ($have_before || $have_after) {
1578 common_element_start('div', array('id' => 'pagination'));
1579 common_element_start('ul', array('id' => 'nav_pagination'));
1583 $pargs = array('page' => $page-1);
1584 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1586 common_element_start('li', 'before');
1587 common_element('a', array('href' => common_local_url($action, $newargs)),
1589 common_element_end('li');
1593 $pargs = array('page' => $page+1);
1594 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1595 common_element_start('li', 'after');
1596 common_element('a', array('href' => common_local_url($action, $newargs)),
1598 common_element_end('li');
1601 if ($have_before || $have_after) {
1602 common_element_end('ul');
1603 common_element_end('div');
1607 /* Following functions are copied from MediaWiki GlobalFunctions.php
1608 * and written by Evan Prodromou. */
1610 function common_accept_to_prefs($accept, $def = '*/*') {
1611 # No arg means accept anything (per HTTP spec)
1613 return array($def => 1);
1618 $parts = explode(',', $accept);
1620 foreach($parts as $part) {
1621 # FIXME: doesn't deal with params like 'text/html; level=1'
1622 @list($value, $qpart) = explode(';', $part);
1624 if(!isset($qpart)) {
1626 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1627 $prefs[$value] = $match[1];
1634 function common_mime_type_match($type, $avail) {
1635 if(array_key_exists($type, $avail)) {
1638 $parts = explode('/', $type);
1639 if(array_key_exists($parts[0] . '/*', $avail)) {
1640 return $parts[0] . '/*';
1641 } elseif(array_key_exists('*/*', $avail)) {
1649 function common_negotiate_type($cprefs, $sprefs) {
1652 foreach(array_keys($sprefs) as $type) {
1653 $parts = explode('/', $type);
1654 if($parts[1] != '*') {
1655 $ckey = common_mime_type_match($type, $cprefs);
1657 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1662 foreach(array_keys($cprefs) as $type) {
1663 $parts = explode('/', $type);
1664 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1665 $skey = common_mime_type_match($type, $sprefs);
1667 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1673 $besttype = "text/html";
1675 foreach(array_keys($combine) as $type) {
1676 if($combine[$type] > $bestq) {
1678 $bestq = $combine[$type];
1685 function common_config($main, $sub) {
1687 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1690 function common_copy_args($from) {
1692 $strip = get_magic_quotes_gpc();
1693 foreach ($from as $k => $v) {
1694 $to[$k] = ($strip) ? stripslashes($v) : $v;
1699 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1700 // This is used before handing a request off to OAuthRequest::from_request.
1701 function common_remove_magic_from_request() {
1702 if(get_magic_quotes_gpc()) {
1703 $_POST=array_map('stripslashes',$_POST);
1704 $_GET=array_map('stripslashes',$_GET);
1708 function common_user_uri(&$user) {
1709 return common_local_url('userbyid', array('id' => $user->id));
1712 function common_notice_uri(&$notice) {
1713 return common_local_url('shownotice',
1714 array('notice' => $notice->id));
1717 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1719 function common_confirmation_code($bits) {
1720 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1721 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1722 $chars = ceil($bits/5);
1724 for ($i = 0; $i < $chars; $i++) {
1725 # XXX: convert to string and back
1726 $num = hexdec(common_good_rand(1));
1727 # XXX: randomness is too precious to throw away almost
1728 # 40% of the bits we get!
1729 $code .= $codechars[$num%32];
1734 # convert markup to HTML
1736 function common_markup_to_html($c) {
1737 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1738 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1739 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1740 return Markdown($c);
1743 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1744 $avatar = $profile->getAvatar($size);
1746 return common_avatar_display_url($avatar);
1748 return common_default_avatar($size);
1752 function common_profile_uri($profile) {
1756 $user = User::staticGet($profile->id);
1761 $remote = Remote_profile::staticGet($profile->id);
1763 return $remote->uri;
1765 # XXX: this is a very bad profile!
1769 function common_canonical_sms($sms) {
1771 preg_replace('/\D/', '', $sms);
1775 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1778 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1782 case E_USER_WARNING:
1783 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1787 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1791 # FIXME: show error page if we're on the Web
1792 /* Don't execute PHP internal error handler */
1796 function common_session_token() {
1797 common_ensure_session();
1798 if (!array_key_exists('token', $_SESSION)) {
1799 $_SESSION['token'] = common_good_rand(64);
1801 return $_SESSION['token'];
1804 function common_disfavor_form($notice) {
1805 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1807 'class' => 'disfavor',
1808 'action' => common_local_url('disfavor')));
1809 common_hidden('token', common_session_token());
1810 common_hidden('notice', $notice->id);
1811 common_element('input', array('type' => 'submit',
1812 'id' => 'disfavor-submit-' . $notice->id,
1813 'name' => 'disfavor-submit-' . $notice->id,
1814 'class' => 'disfavor',
1816 common_element_end('form');
1819 function common_favor_form($notice) {
1820 common_element_start('form', array('id' => 'favor-' . $notice->id,
1823 'action' => common_local_url('favor')));
1824 common_hidden('token', common_session_token());
1825 common_hidden('notice', $notice->id);
1826 common_element('input', array('type' => 'submit',
1827 'id' => 'favor-submit-' . $notice->id,
1828 'name' => 'favor-submit-' . $notice->id,
1831 common_element_end('form');
1834 function common_cache_key($extra) {
1835 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1838 function common_keyize($str) {
1839 $str = strtolower($str);
1840 $str = preg_replace('/\s/', '_', $str);
1844 function common_message_form($content, $user, $to) {
1846 common_element_start('form', array('id' => 'message_form',
1848 'action' => common_local_url('newmessage')));
1850 $mutual_users = $user->mutuallySubscribedUsers();
1854 while ($mutual_users->fetch()) {
1855 if ($mutual_users->id != $user->id) {
1856 $mutual[$mutual_users->id] = $mutual_users->nickname;
1860 $mutual_users->free();
1861 unset($mutual_users);
1863 common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
1865 common_element_start('p');
1867 common_element('textarea', array('id' => 'message_content',
1870 'name' => 'content'),
1871 ($content) ? $content : '');
1873 common_element('input', array('id' => 'message_send',
1874 'name' => 'message_send',
1876 'value' => _('Send')));
1878 common_hidden('token', common_session_token());
1880 common_element_end('p');
1881 common_element_end('form');
1884 function common_memcache() {
1885 static $cache = NULL;
1886 if (!common_config('memcached', 'enabled')) {
1890 $cache = new Memcache();
1891 $servers = common_config('memcached', 'server');
1892 if (is_array($servers)) {
1893 foreach($servers as $server) {
1894 $cache->addServer($server);
1897 $cache->addServer($servers);