]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
add a script to populate notice inboxes
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
21
22 # Show a server error
23
24 function common_server_error($msg, $code=500) {
25         static $status = array(500 => 'Internal Server Error',
26                                                    501 => 'Not Implemented',
27                                                    502 => 'Bad Gateway',
28                                                    503 => 'Service Unavailable',
29                                                    504 => 'Gateway Timeout',
30                                                    505 => 'HTTP Version Not Supported');
31
32         if (!array_key_exists($code, $status)) {
33                 $code = 500;
34         }
35
36         $status_string = $status[$code];
37
38         header('HTTP/1.1 '.$code.' '.$status_string);
39         header('Content-type: text/plain');
40
41         print $msg;
42         print "\n";
43         exit();
44 }
45
46 # Show a user error
47 function common_user_error($msg, $code=400) {
48         static $status = array(400 => 'Bad Request',
49                                                    401 => 'Unauthorized',
50                                                    402 => 'Payment Required',
51                                                    403 => 'Forbidden',
52                                                    404 => 'Not Found',
53                                                    405 => 'Method Not Allowed',
54                                                    406 => 'Not Acceptable',
55                                                    407 => 'Proxy Authentication Required',
56                                                    408 => 'Request Timeout',
57                                                    409 => 'Conflict',
58                                                    410 => 'Gone',
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');
66
67         if (!array_key_exists($code, $status)) {
68                 $code = 400;
69         }
70
71         $status_string = $status[$code];
72
73         header('HTTP/1.1 '.$code.' '.$status_string);
74
75         common_show_header('Error');
76         common_element('div', array('class' => 'error'), $msg);
77         common_show_footer();
78 }
79
80 $xw = null;
81
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
84         global $xw;
85         $xw->startElement($tag);
86         if (is_array($attrs)) {
87                 foreach ($attrs as $name => $value) {
88                         $xw->writeAttribute($name, $value);
89                 }
90         } else if (is_string($attrs)) {
91                 $xw->writeAttribute('class', $attrs);
92         }
93 }
94
95 function common_element_end($tag) {
96         static $empty_tag = array('base', 'meta', 'link', 'hr',
97                                                           'br', 'param', 'img', 'area',
98                                                           'input', 'col');
99         global $xw;
100         # XXX: check namespace
101         if (in_array($tag, $empty_tag)) {
102                 $xw->endElement();
103         } else {
104                 $xw->fullEndElement();
105         }
106 }
107
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109         common_element_start($tag, $attrs);
110         global $xw;
111         if (!is_null($content)) {
112                 $xw->text($content);
113         }
114         common_element_end($tag);
115 }
116
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
118         global $xw;
119         $xw = new XMLWriter();
120         $xw->openURI('php://output');
121         $xw->setIndent(true);
122         $xw->startDocument('1.0', 'UTF-8');
123         if ($doc) {
124                 $xw->writeDTD($doc, $public, $system);
125         }
126 }
127
128 function common_end_xml() {
129         global $xw;
130         $xw->endDocument();
131         $xw->flush();
132 }
133
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",
141                                                         $language . ".UTF8",
142                                                         $language . ".utf-8",
143                                                         $language . ".UTF-8",
144                                                         $language);
145         bindtextdomain("laconica", common_config('site','locale_path'));
146         bind_textdomain_codeset("laconica", "UTF-8");
147         textdomain("laconica");
148         setlocale(LC_CTYPE, 'C');
149         common_log(LOG_INFO,'Language requested:'.$language.' Locale set:'.$locale_set,__FILE__);
150 }
151
152 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
153
154 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
155         
156         global $config, $xw;
157
158         common_start_html();
159         
160         common_element_start('head');
161         common_element('title', NULL,
162                                    $pagetitle . " - " . $config['site']['name']);
163         common_element('link', array('rel' => 'stylesheet',
164                                                                  'type' => 'text/css',
165                                                                  'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
166                                                                  'media' => 'screen, projection, tv'));
167         foreach (array(6,7) as $ver) {
168                 if (file_exists(theme_file('ie'.$ver.'.css'))) {
169                         # Yes, IE people should be put in jail.
170                         $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
171                                                           'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
172                 }
173         }
174
175         common_element('script', array('type' => 'text/javascript',
176                                                                    'src' => common_path('js/jquery.min.js')),
177                                    ' ');
178         common_element('script', array('type' => 'text/javascript',
179                                                                    'src' => common_path('js/jquery.form.js')),
180                                    ' ');
181         common_element('script', array('type' => 'text/javascript',
182                                                                    'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
183                                    ' ');
184         common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
185                                         'href' =>  common_local_url('opensearch', array('type' => 'people')),
186                                         'title' => common_config('site', 'name').' People Search'));
187
188         common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
189                                         'href' =>  common_local_url('opensearch', array('type' => 'notice')),
190                                         'title' => common_config('site', 'name').' Notice Search'));
191
192         if ($callable) {
193                 if ($data) {
194                         call_user_func($callable, $data);
195                 } else {
196                         call_user_func($callable);
197                 }
198         }
199         common_element_end('head');
200         common_element_start('body');
201         common_element_start('div', array('id' => 'wrap'));
202         common_element_start('div', array('id' => 'header'));
203         common_nav_menu();
204         if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
205                 || file_exists(theme_file('logo.png')))
206         {
207                 common_element_start('a', array('href' => common_local_url('public')));
208                 common_element('img', array('src' => isset($config['site']['logo']) ?
209                                                                         ($config['site']['logo']) : theme_path('logo.png'),
210                                                                         'alt' => $config['site']['name'],
211                                                                         'id' => 'logo'));
212                 common_element_end('a');
213         } else {
214                 common_element_start('p', array('id' => 'branding'));
215                 common_element('a', array('href' => common_local_url('public')),
216                                            $config['site']['name']);
217                 common_element_end('p');
218         }
219
220         common_element('h1', 'pagetitle', $pagetitle);
221
222         if ($headercall) {
223                 if ($data) {
224                         call_user_func($headercall, $data);
225                 } else {
226                         call_user_func($headercall);
227                 }
228         }
229         common_element_end('div');
230         common_element_start('div', array('id' => 'content'));
231 }
232
233 function common_start_html($type=NULL) {
234         
235         if (!$type) {
236                 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
237                 
238                 # XXX: allow content negotiation for RDF, RSS, or XRDS
239                 
240                 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
241                                                                           common_accept_to_prefs(PAGE_TYPE_PREFS));
242                 
243                 if (!$type) {
244                         common_user_error(_('This page is not available in a media type you accept'), 406);
245                         exit(0);
246                 }
247         }
248         
249         header('Content-Type: '.$type);
250
251         common_start_xml('html',
252                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
253                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
254
255         # FIXME: correct language for interface
256
257         $language = common_language();
258
259         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
260                                                                            'xml:lang' => $language,
261                                                                            'lang' => $language));
262 }
263
264 function common_show_footer() {
265         global $xw, $config;
266         common_element_end('div'); # content div
267         common_foot_menu();
268         common_element_start('div', array('id' => 'footer'));
269         common_element_start('div', 'laconica');
270         if (common_config('site', 'broughtby')) {
271                 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
272         } else {
273                 $instr = _('**%%site.name%%** is a microblogging service. ');
274         }
275         $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);
276     $output = common_markup_to_html($instr);
277     common_raw($output);
278         common_element_end('div');
279         common_element('img', array('id' => 'cc',
280                                                                 'src' => $config['license']['image'],
281                                                                 'alt' => $config['license']['title']));
282         common_element_start('p');
283         common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
284         common_element('a', array('class' => 'license',
285                                                           'rel' => 'license',
286                                                           'href' => $config['license']['url']),
287                                    $config['license']['title']);
288         common_text(_('. Contributors should be attributed by full name or nickname.'));
289         common_element_end('p');
290         common_element_end('div');
291         common_element_end('div');
292         common_element_end('body');
293         common_element_end('html');
294         common_end_xml();
295 }
296
297 function common_text($txt) {
298         global $xw;
299         $xw->text($txt);
300 }
301
302 function common_raw($xml) {
303         global $xw;
304         $xw->writeRaw($xml);
305 }
306
307 function common_nav_menu() {
308         $user = common_current_user();
309         common_element_start('ul', array('id' => 'nav'));
310         if ($user) {
311                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
312                                                  _('Home'));
313         }
314         common_menu_item(common_local_url('peoplesearch'), _('Search'));
315         common_menu_item(common_local_url('tags'), _('Tags'));
316         if ($user) {
317                 common_menu_item(common_local_url('profilesettings'),
318                                                  _('Settings'));
319                 common_menu_item(common_local_url('invite'),
320                                                  _('Invite'));
321                 common_menu_item(common_local_url('logout'),
322                                                  _('Logout'));
323         } else {
324                 common_menu_item(common_local_url('login'), _('Login'));
325                 if (!common_config('site', 'closed')) {
326                         common_menu_item(common_local_url('register'), _('Register'));
327                 }
328                 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
329         }
330         common_element_end('ul');
331 }
332
333 function common_foot_menu() {
334         common_element_start('ul', array('id' => 'nav_sub'));
335         common_menu_item(common_local_url('doc', array('title' => 'help')),
336                                          _('Help'));
337         common_menu_item(common_local_url('doc', array('title' => 'about')),
338                                          _('About'));
339         common_menu_item(common_local_url('doc', array('title' => 'faq')),
340                                          _('FAQ'));
341         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
342                                          _('Privacy'));
343         common_menu_item(common_local_url('doc', array('title' => 'source')),
344                                          _('Source'));
345         common_menu_item(common_local_url('doc', array('title' => 'contact')),
346                                          _('Contact'));
347         common_element_end('ul');
348 }
349
350 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
351         $lattrs = array();
352         if ($is_selected) {
353                 $lattrs['class'] = 'current';
354         }
355         common_element_start('li', $lattrs);
356         $attrs['href'] = $url;
357         if ($title) {
358                 $attrs['title'] = $title;
359         }
360         common_element('a', $attrs, $text);
361         common_element_end('li');
362 }
363
364 function common_input($id, $label, $value=NULL,$instructions=NULL) {
365         common_element_start('p');
366         common_element('label', array('for' => $id), $label);
367         $attrs = array('name' => $id,
368                                    'type' => 'text',
369                                    'class' => 'input_text',
370                                    'id' => $id);
371         if ($value) {
372                 $attrs['value'] = htmlspecialchars($value);
373         }
374         common_element('input', $attrs);
375         if ($instructions) {
376                 common_element('span', 'input_instructions', $instructions);
377         }
378         common_element_end('p');
379 }
380
381 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false)
382 {
383         common_element_start('p');
384         $attrs = array('name' => $id,
385                                    'type' => 'checkbox',
386                                    'class' => 'checkbox',
387                                    'id' => $id);
388         if ($value) {
389                 $attrs['value'] = htmlspecialchars($value);
390         }
391         if ($checked) {
392                 $attrs['checked'] = 'checked';
393         }
394         if ($disabled) {
395                 $attrs['disabled'] = 'true';
396         }
397         common_element('input', $attrs);
398         # XXX: use a <label>
399         common_text(' ');
400         common_element('span', 'checkbox_label', $label);
401         common_text(' ');
402         if ($instructions) {
403                 common_element('span', 'input_instructions', $instructions);
404         }
405         common_element_end('p');
406 }
407
408 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
409         common_element_start('p');
410         common_element('label', array('for' => $id), $label);
411         common_element_start('select', array('id' => $id, 'name' => $id));
412         if ($blank_select) {
413                 common_element('option', array('value' => ''));
414         }
415         foreach ($content as $value => $option) {
416                 if ($value == $selected) {
417                         common_element('option', array('value' => $value, 'selected' => $value), $option);
418                 } else {
419                         common_element('option', array('value' => $value), $option);
420                 }
421         }
422         common_element_end('select');
423         if ($instructions) {
424                 common_element('span', 'input_instructions', $instructions);
425         }
426         common_element_end('p');
427 }
428 function common_hidden($id, $value) {
429         common_element('input', array('name' => $id,
430                                                                   'type' => 'hidden',
431                                                                   'id' => $id,
432                                                                   'value' => $value));
433 }
434
435 function common_password($id, $label, $instructions=NULL) {
436         common_element_start('p');
437         common_element('label', array('for' => $id), $label);
438         $attrs = array('name' => $id,
439                                    'type' => 'password',
440                                    'class' => 'password',
441                                    'id' => $id);
442         common_element('input', $attrs);
443         if ($instructions) {
444                 common_element('span', 'input_instructions', $instructions);
445         }
446         common_element_end('p');
447 }
448
449 function common_submit($id, $label, $cls='submit') {
450         global $xw;
451         common_element_start('p');
452         common_element('input', array('type' => 'submit',
453                                                                   'id' => $id,
454                                                                   'name' => $id,
455                                                                   'class' => $cls,
456                                                                   'value' => $label));
457         common_element_end('p');
458 }
459
460 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
461         common_element_start('p');
462         common_element('label', array('for' => $id), $label);
463         common_element('textarea', array('rows' => 3,
464                                                                          'cols' => 40,
465                                                                          'name' => $id,
466                                                                          'id' => $id),
467                                    ($content) ? $content : '');
468         if ($instructions) {
469                 common_element('span', 'input_instructions', $instructions);
470         }
471         common_element_end('p');
472 }
473
474 function common_timezone() {
475         if (common_logged_in()) {
476                 $user = common_current_user();
477                 if ($user->timezone) {
478                         return $user->timezone;
479                 }
480         }
481
482         global $config;
483         return $config['site']['timezone'];
484 }
485
486 function common_language() {
487
488         // If there is a user logged in and they've set a language preference
489         // then return that one...
490         if (common_logged_in()) {
491                 $user = common_current_user();
492                 $user_language = $user->language;
493                 if ($user_language)
494                         return $user_language;
495         }
496
497         // Otherwise, find the best match for the languages requested by the
498         // user's browser...
499         $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
500         if (!empty($httplang)) {
501                 $language = client_prefered_language($httplang);
502                 if ($language)
503                         return $language;
504         }
505
506         // Finally, if none of the above worked, use the site's default...
507         return common_config('site', 'language');
508 }
509 # salted, hashed passwords are stored in the DB
510
511 function common_munge_password($password, $id) {
512         return md5($password . $id);
513 }
514
515 # check if a username exists and has matching password
516 function common_check_user($nickname, $password) {
517         # NEVER allow blank passwords, even if they match the DB
518         if (mb_strlen($password) == 0) {
519                 return false;
520         }
521         $user = User::staticGet('nickname', $nickname);
522         if (is_null($user)) {
523                 return false;
524         } else {
525                 if (0 == strcmp(common_munge_password($password, $user->id),
526                                                 $user->password)) {
527                         return $user;
528                 } else {
529                         return false;
530                 }
531         }
532 }
533
534 # is the current user logged in?
535 function common_logged_in() {
536         return (!is_null(common_current_user()));
537 }
538
539 function common_have_session() {
540         return (0 != strcmp(session_id(), ''));
541 }
542
543 function common_ensure_session() {
544         if (!common_have_session()) {
545                 @session_start();
546         }
547 }
548
549 # Three kinds of arguments:
550 # 1) a user object
551 # 2) a nickname
552 # 3) NULL to clear
553
554 function common_set_user($user) {
555         if (is_null($user) && common_have_session()) {
556                 unset($_SESSION['userid']);
557                 return true;
558         } else if (is_string($user)) {
559                 $nickname = $user;
560                 $user = User::staticGet('nickname', $nickname);
561         } else if (!($user instanceof User)) {
562                 return false;
563         }
564
565         if ($user) {
566                 common_ensure_session();
567                 $_SESSION['userid'] = $user->id;
568                 return $user;
569         }
570         return false;
571 }
572
573 function common_set_cookie($key, $value, $expiration=0) {
574         $path = common_config('site', 'path');
575         $server = common_config('site', 'server');
576
577         if ($path && ($path != '/')) {
578                 $cookiepath = '/' . $path . '/';
579         } else {
580                 $cookiepath = '/';
581         }
582         return setcookie($key,
583                          $value,
584                                  $expiration,
585                                          $cookiepath,
586                                      $server);
587 }
588
589 define('REMEMBERME', 'rememberme');
590 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
591
592 function common_rememberme($user=NULL) {
593         if (!$user) {
594                 $user = common_current_user();
595                 if (!$user) {
596                         common_debug('No current user to remember', __FILE__);
597                         return false;
598                 }
599         }
600         $rm = new Remember_me();
601         $rm->code = common_good_rand(16);
602         $rm->user_id = $user->id;
603         $result = $rm->insert();
604         if (!$result) {
605                 common_log_db_error($rm, 'INSERT', __FILE__);
606                 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
607                 return false;
608         }
609         common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
610         common_set_cookie(REMEMBERME,
611                                           implode(':', array($rm->user_id, $rm->code)),
612                                           time() + REMEMBERME_EXPIRY);
613         return true;
614 }
615
616 function common_remembered_user() {
617         $user = NULL;
618         # Try to remember
619         $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
620         if ($packed) {
621                 list($id, $code) = explode(':', $packed);
622                 if ($id && $code) {
623                         $rm = Remember_me::staticGet($code);
624                         if ($rm && ($rm->user_id == $id)) {
625                                 $user = User::staticGet($rm->user_id);
626                                 if ($user) {
627                                         # successful!
628                                         $result = $rm->delete();
629                                         if (!$result) {
630                                                 common_log_db_error($rm, 'DELETE', __FILE__);
631                                                 $user = NULL;
632                                         } else {
633                                                 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
634                                                 common_set_user($user->nickname);
635                                                 common_real_login(false);
636                                                 # We issue a new cookie, so they can log in
637                                                 # automatically again after this session
638                                                 common_rememberme($user);
639                                         }
640                                 }
641                         }
642                 }
643         }
644         return $user;
645 }
646
647 # must be called with a valid user!
648
649 function common_forgetme() {
650         common_set_cookie(REMEMBERME, '', 0);
651 }
652
653 # who is the current user?
654 function common_current_user() {
655         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
656                 common_ensure_session();
657                 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
658                 if ($id) {
659                         # note: this should cache
660                         $user = User::staticGet($id);
661                         return $user;
662                 }
663         }
664         # that didn't work; try to remember
665         $user = common_remembered_user();
666         if ($user) {
667                 common_debug("Got User " . $user->nickname);
668             common_debug("Faking session on remembered user");
669             $_SESSION['userid'] = $user->id;
670         }
671         return $user;
672 }
673
674 # Logins that are 'remembered' aren't 'real' -- they're subject to
675 # cookie-stealing. So, we don't let them do certain things. New reg,
676 # OpenID, and password logins _are_ real.
677
678 function common_real_login($real=true) {
679         common_ensure_session();
680         $_SESSION['real_login'] = $real;
681 }
682
683 function common_is_real_login() {
684         return common_logged_in() && $_SESSION['real_login'];
685 }
686
687 # get canonical version of nickname for comparison
688 function common_canonical_nickname($nickname) {
689         # XXX: UTF-8 canonicalization (like combining chars)
690         return strtolower($nickname);
691 }
692
693 # get canonical version of email for comparison
694 function common_canonical_email($email) {
695         # XXX: canonicalize UTF-8
696         # XXX: lcase the domain part
697         return $email;
698 }
699
700 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$_+!*();/?:~-]))');
701
702 function common_render_content($text, $notice) {
703         $r = common_render_text($text);
704         $id = $notice->profile_id;
705         $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
706         $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
707         return $r;
708 }
709
710 function common_render_text($text) {
711         $r = htmlspecialchars($text);
712
713         $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
714         $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
715         $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
716         # XXX: machine tags
717         return $r;
718 }
719
720 function common_render_uri_thingy($matches) {
721         $uri = $matches[0];
722         $trailer = '';
723
724         # Some heuristics for extracting URIs from surrounding punctuation
725         # Strip from trailing text...
726         if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
727                 $uri = $matches[1];
728                 $trailer = $matches[2];
729         }
730
731         $pairs = array(
732                 ']' => '[', # technically disallowed in URIs, but used in Java docs
733                 ')' => '(', # far too frequent in Wikipedia and MSDN
734         );
735         $final = substr($uri, -1, 1);
736         if (isset($pairs[$final])) {
737                 $openers = substr_count($uri, $pairs[$final]);
738                 $closers = substr_count($uri, $final);
739                 if ($closers > $openers) {
740                         // Assume the paren was opened outside the URI
741                         $uri = substr($uri, 0, -1);
742                         $trailer = $final . $trailer;
743                 }
744         }
745         return '<a href="' . $uri . '" class="extlink">' . $uri . '</a>' . $trailer;
746 }
747
748 function common_xml_safe_str($str) {
749         $xmlStr = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str), ENT_NOQUOTES, 'UTF-8');
750         
751         // Replace control, formatting, and surrogate characters with '*', ala Twitter
752         return preg_replace('/[\p{Cc}\p{Cf}\p{Cs}]/u', '*', $str);
753 }
754
755 function common_tag_link($tag) {
756         $canonical = common_canonical_tag($tag);
757         $url = common_local_url('tag', array('tag' => $canonical));
758         return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
759 }
760
761 function common_canonical_tag($tag) {  
762         return strtolower(str_replace(array('-', '_', '.'), '', $tag));
763 }
764
765 function common_at_link($sender_id, $nickname) {
766         $sender = Profile::staticGet($sender_id);
767         $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
768         if ($recipient) {
769                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
770         } else {
771                 return $nickname;
772         }
773 }
774
775 function common_relative_profile($sender, $nickname, $dt=NULL) {
776         # Try to find profiles this profile is subscribed to that have this nickname
777         $recipient = new Profile();
778         # XXX: use a join instead of a subquery
779         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
780         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
781         if ($recipient->find(TRUE)) {
782                 # XXX: should probably differentiate between profiles with
783                 # the same name by date of most recent update
784                 return $recipient;
785         }
786         # Try to find profiles that listen to this profile and that have this nickname
787         $recipient = new Profile();
788         # XXX: use a join instead of a subquery
789         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
790         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
791         if ($recipient->find(TRUE)) {
792                 # XXX: should probably differentiate between profiles with
793                 # the same name by date of most recent update
794                 return $recipient;
795         }
796         # If this is a local user, try to find a local user with that nickname.
797         $sender = User::staticGet($sender->id);
798         if ($sender) {
799                 $recipient_user = User::staticGet('nickname', $nickname);
800                 if ($recipient_user) {
801                         return $recipient_user->getProfile();
802                 }
803         }
804         # Otherwise, no links. @messages from local users to remote users,
805         # or from remote users to other remote users, are just
806         # outside our ability to make intelligent guesses about
807         return NULL;
808 }
809
810 // where should the avatar go for this user?
811
812 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
813         global $config;
814
815         if ($size) {
816                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
817         } else {
818                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
819         }
820 }
821
822 function common_avatar_path($filename) {
823         global $config;
824         return INSTALLDIR . '/avatar/' . $filename;
825 }
826
827 function common_avatar_url($filename) {
828         return common_path('avatar/'.$filename);
829 }
830
831 function common_avatar_display_url($avatar) {
832         $server = common_config('avatar', 'server');
833         if ($server) {
834                 return 'http://'.$server.'/'.$avatar->filename;
835         } else {
836                 return $avatar->url;
837         }
838 }
839
840 function common_default_avatar($size) {
841         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
842                                                           AVATAR_STREAM_SIZE => 'stream',
843                                                           AVATAR_MINI_SIZE => 'mini');
844         return theme_path('default-avatar-'.$sizenames[$size].'.png');
845 }
846
847 function common_local_url($action, $args=NULL, $fragment=NULL) {
848         $url = NULL;
849         if (common_config('site','fancy')) {
850                 $url = common_fancy_url($action, $args);
851         } else {
852                 $url = common_simple_url($action, $args);
853         }
854         if (!is_null($fragment)) {
855                 $url .= '#'.$fragment;
856         }
857         return $url;
858 }
859
860 function common_fancy_url($action, $args=NULL) {
861         switch (strtolower($action)) {
862          case 'public':
863                 if ($args && isset($args['page'])) {
864                         return common_path('?page=' . $args['page']);
865                 } else {
866                         return common_path('');
867                 }
868          case 'publicrss':
869                 return common_path('rss');
870          case 'publicxrds':
871                 return common_path('xrds');
872          case 'opensearch':
873                 if ($args && $args['type']) {
874                         return common_path('opensearch/'.$args['type']);
875                 } else {
876                         return common_path('opensearch/people');
877                 }
878          case 'doc':
879                 return common_path('doc/'.$args['title']);
880          case 'login':
881          case 'logout':
882          case 'subscribe':
883          case 'unsubscribe':
884          case 'invite':
885                 return common_path('main/'.$action);
886          case 'register':
887                 if ($args && $args['code']) {
888                         return common_path('main/register/'.$args['code']);
889                 } else {
890                         return common_path('main/register');
891                 }
892          case 'remotesubscribe':
893                 if ($args && $args['nickname']) {
894                         return common_path('main/remote?nickname=' . $args['nickname']);
895                 } else {
896                         return common_path('main/remote');
897                 }
898          case 'openidlogin':
899                 return common_path('main/openid');
900          case 'profilesettings':
901                 return common_path('settings/profile');
902          case 'emailsettings':
903                 return common_path('settings/email');
904          case 'openidsettings':
905                 return common_path('settings/openid');
906          case 'smssettings':
907                 return common_path('settings/sms');
908          case 'twittersettings':
909                 return common_path('settings/twitter');
910          case 'newnotice':
911                 if ($args && $args['replyto']) {
912                         return common_path('notice/new?replyto='.$args['replyto']);
913                 } else {
914                         return common_path('notice/new');
915                 }
916          case 'shownotice':
917                 return common_path('notice/'.$args['notice']);
918          case 'deletenotice':
919                 if ($args && $args['notice']) {
920                         return common_path('notice/delete/'.$args['notice']);
921                 } else {
922                         return common_path('notice/delete');
923                 }
924          case 'xrds':
925          case 'foaf':
926                 return common_path($args['nickname'].'/'.$action);
927          case 'subscriptions':
928          case 'subscribers':
929          case 'all':
930          case 'replies':
931          case 'inbox':
932          case 'outbox':
933                 if ($args && isset($args['page'])) {
934                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
935                 } else {
936                         return common_path($args['nickname'].'/'.$action);
937                 }
938          case 'allrss':
939                 return common_path($args['nickname'].'/all/rss');
940          case 'repliesrss':
941                 return common_path($args['nickname'].'/replies/rss');
942          case 'userrss':
943                 return common_path($args['nickname'].'/rss');
944          case 'showstream':
945                 if ($args && isset($args['page'])) {
946                         return common_path($args['nickname'].'?page=' . $args['page']);
947                 } else {
948                         return common_path($args['nickname']);
949                 }
950          case 'confirmaddress':
951                 return common_path('main/confirmaddress/'.$args['code']);
952          case 'userbyid':
953                 return common_path('user/'.$args['id']);
954          case 'recoverpassword':
955             $path = 'main/recoverpassword';
956             if ($args['code']) {
957                 $path .= '/' . $args['code'];
958                 }
959             return common_path($path);
960          case 'imsettings':
961                 return common_path('settings/im');
962          case 'peoplesearch':
963                 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
964          case 'noticesearch':
965                 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
966          case 'noticesearchrss':
967                 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
968          case 'avatarbynickname':
969                 return common_path($args['nickname'].'/avatar/'.$args['size']);
970          case 'tag':
971             if (isset($args['tag']) && $args['tag']) {
972                         $path = 'tag/' . $args['tag'];
973                         unset($args['tag']);
974                 } else {
975                         $path = 'tags';
976                 }
977                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
978          case 'tags':
979                 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
980          case 'favor':
981                 return common_path('main/favor');
982          case 'disfavor':
983                 return common_path('main/disfavor');
984          case 'showfavorites':
985                 if ($args && isset($args['page'])) {
986                         return common_path($args['nickname'].'/favorites?page=' . $args['page']);
987                 } else {
988                         return common_path($args['nickname'].'/favorites');
989                 }
990          case 'favoritesrss':
991                 return common_path($args['nickname'].'/favorites/rss');
992          case 'showmessage':
993                 return common_path('message/' . $args['message']);
994          case 'newmessage':
995                 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
996          case 'api':
997                 # XXX: do fancy URLs for all the API methods
998                 switch (strtolower($args['apiaction'])) {
999                  case 'statuses':
1000                         switch (strtolower($args['method'])) {
1001                          case 'user_timeline.rss':
1002                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1003                          case 'user_timeline.atom':                             
1004                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1005                          case 'user_timeline.rss':
1006                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1007                          case 'user_timeline.atom':                             
1008                                 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1009                          default: return common_simple_url($action, $args);
1010                         }
1011                  default: return common_simple_url($action, $args);
1012                 }
1013          case 'sup':
1014                 if ($args && isset($args['seconds'])) {
1015                         return common_path('main/sup?seconds='.$args['seconds']);                       
1016                 } else {
1017                         return common_path('main/sup');
1018                 }
1019          default:
1020                 return common_simple_url($action, $args);
1021         }
1022 }
1023
1024 function common_simple_url($action, $args=NULL) {
1025         global $config;
1026         /* XXX: pretty URLs */
1027         $extra = '';
1028         if ($args) {
1029                 foreach ($args as $key => $value) {
1030                         $extra .= "&${key}=${value}";
1031                 }
1032         }
1033         return common_path("index.php?action=${action}${extra}");
1034 }
1035
1036 function common_path($relative) {
1037         global $config;
1038         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1039         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1040 }
1041
1042 function common_date_string($dt) {
1043         // XXX: do some sexy date formatting
1044         // return date(DATE_RFC822, $dt);
1045         $t = strtotime($dt);
1046         $now = time();
1047         $diff = $now - $t;
1048
1049         if ($now < $t) { # that shouldn't happen!
1050                 return common_exact_date($dt);
1051         } else if ($diff < 60) {
1052                 return _('a few seconds ago');
1053         } else if ($diff < 92) {
1054                 return _('about a minute ago');
1055         } else if ($diff < 3300) {
1056                 return sprintf(_('about %d minutes ago'), round($diff/60));
1057         } else if ($diff < 5400) {
1058                 return _('about an hour ago');
1059         } else if ($diff < 22 * 3600) {
1060                 return sprintf(_('about %d hours ago'), round($diff/3600));
1061         } else if ($diff < 37 * 3600) {
1062                 return _('about a day ago');
1063         } else if ($diff < 24 * 24 * 3600) {
1064                 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1065         } else if ($diff < 46 * 24 * 3600) {
1066                 return _('about a month ago');
1067         } else if ($diff < 330 * 24 * 3600) {
1068                 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1069         } else if ($diff < 480 * 24 * 3600) {
1070                 return _('about a year ago');
1071         } else {
1072                 return common_exact_date($dt);
1073         }
1074 }
1075
1076 function common_exact_date($dt) {
1077     static $_utc;
1078     static $_siteTz;
1079
1080     if (!$_utc) {
1081         $_utc = new DateTimeZone('UTC');
1082         $_siteTz = new DateTimeZone(common_timezone());
1083     }
1084
1085         $dateStr = date('d F Y H:i:s', strtotime($dt));
1086         $d = new DateTime($dateStr, $_utc);
1087         $d->setTimezone($_siteTz);
1088         return $d->format(DATE_RFC850);
1089 }
1090
1091 function common_date_w3dtf($dt) {
1092         $dateStr = date('d F Y H:i:s', strtotime($dt));
1093         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1094         $d->setTimezone(new DateTimeZone(common_timezone()));
1095         return $d->format(DATE_W3C);
1096 }
1097
1098 function common_date_rfc2822($dt) {
1099         $dateStr = date('d F Y H:i:s', strtotime($dt));
1100         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1101         $d->setTimezone(new DateTimeZone(common_timezone()));
1102         return $d->format('r');
1103 }
1104
1105 function common_date_iso8601($dt) {
1106         $dateStr = date('d F Y H:i:s', strtotime($dt));
1107         $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1108         $d->setTimezone(new DateTimeZone(common_timezone()));
1109         return $d->format('c');
1110 }
1111
1112 function common_sql_now() {
1113         return strftime('%Y-%m-%d %H:%M:%S', time());
1114 }
1115
1116 function common_redirect($url, $code=307) {
1117         static $status = array(301 => "Moved Permanently",
1118                                                    302 => "Found",
1119                                                    303 => "See Other",
1120                                                    307 => "Temporary Redirect");
1121         header("Status: ${code} $status[$code]");
1122         header("Location: $url");
1123
1124         common_start_xml('a',
1125                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
1126                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1127         common_element('a', array('href' => $url), $url);
1128         common_end_xml();
1129     exit;
1130 }
1131
1132 function common_save_replies($notice) {
1133         # Alternative reply format
1134         $tname = false;
1135         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1136                 $tname = $match[1];
1137         }
1138         # extract all @messages
1139         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1140         if (!$cnt && !$tname) {
1141                 return true;
1142         }
1143         # XXX: is there another way to make an array copy?
1144         $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1145         $sender = Profile::staticGet($notice->profile_id);
1146         # store replied only for first @ (what user/notice what the reply directed,
1147         # we assume first @ is it)
1148         for ($i=0; $i<count($names); $i++) {
1149                 $nickname = $names[$i];
1150                 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1151                 if (!$recipient) {
1152                         continue;
1153                 }
1154                 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1155                         $reply_for = $recipient;
1156                         $recipient_notice = $reply_for->getCurrentNotice();
1157                         if ($recipient_notice) {
1158                                 $orig = clone($notice);
1159                                 $notice->reply_to = $recipient_notice->id;
1160                                 $notice->update($orig);
1161                         }
1162                 }
1163                 $reply = new Reply();
1164                 $reply->notice_id = $notice->id;
1165                 $reply->profile_id = $recipient->id;
1166                 $id = $reply->insert();
1167                 if (!$id) {
1168                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1169                         common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1170                         common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1171                         return;
1172                 }
1173         }
1174 }
1175
1176 function common_broadcast_notice($notice, $remote=false) {
1177
1178         // Check to see if notice should go to Twitter
1179         $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1180         if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1181
1182                 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1183
1184                 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1185                         (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1186
1187                         $result = common_twitter_broadcast($notice, $flink);
1188
1189                         if (!$result) {
1190                                 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1191                         }
1192                 }
1193         }
1194
1195         if (common_config('queue', 'enabled')) {
1196                 # Do it later!
1197                 return common_enqueue_notice($notice);
1198         } else {
1199                 return common_real_broadcast($notice, $remote);
1200         }
1201 }
1202
1203 function common_twitter_broadcast($notice, $flink) {
1204         global $config;
1205         $success = true;
1206         $fuser = $flink->getForeignUser();
1207         $twitter_user = $fuser->nickname;
1208         $twitter_password = $flink->credentials;
1209         $uri = 'http://www.twitter.com/statuses/update.json';
1210
1211         // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1212         $statustxt = preg_replace('/^@/', ' @', $notice->content);
1213
1214         $options = array(
1215                 CURLOPT_USERPWD                 => "$twitter_user:$twitter_password",
1216                 CURLOPT_POST                    => true,
1217                 CURLOPT_POSTFIELDS              => array(
1218                                                                         'status'        => $statustxt,
1219                                                                         'source'        => $config['integration']['source']
1220                                                                         ),
1221                 CURLOPT_RETURNTRANSFER  => true,
1222                 CURLOPT_FAILONERROR             => true,
1223                 CURLOPT_HEADER                  => false,
1224                 CURLOPT_FOLLOWLOCATION  => true,
1225                 CURLOPT_USERAGENT               => "Laconica",
1226                 CURLOPT_CONNECTTIMEOUT  => 120,  // XXX: Scary!!!! How long should this be?
1227                 CURLOPT_TIMEOUT                 => 120
1228         );
1229
1230         $ch = curl_init($uri);
1231     curl_setopt_array($ch, $options);
1232     $data = curl_exec($ch);
1233     $errmsg = curl_error($ch);
1234
1235         if ($errmsg) {
1236                 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1237                         __FILE__);
1238                 $success = false;
1239         }
1240
1241         curl_close($ch);
1242
1243         if (!$data) {
1244                 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1245                         __FILE__);
1246                 $success = false;
1247         }
1248
1249         // Twitter should return a status
1250         $status = json_decode($data);
1251
1252         if (!$status->id) {
1253                 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1254                         __FILE__);
1255                 $success = false;
1256         }
1257
1258         return $success;
1259 }
1260
1261 # Stick the notice on the queue
1262
1263 function common_enqueue_notice($notice) {
1264         foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1265                 $qi = new Queue_item();
1266                 $qi->notice_id = $notice->id;
1267                 $qi->transport = $transport;
1268                 $qi->created = $notice->created;
1269         $result = $qi->insert();
1270                 if (!$result) {
1271                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1272                         common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1273                         return false;
1274                 }
1275                 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1276         }
1277         return $result;
1278 }
1279
1280 function common_dequeue_notice($notice) {
1281         $qi = Queue_item::staticGet($notice->id);
1282         if ($qi) {
1283                 $result = $qi->delete();
1284                 if (!$result) {
1285                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1286                     common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1287                     return false;
1288                 }
1289                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1290                 return $result;
1291         } else {
1292             return false;
1293         }
1294 }
1295
1296 function common_real_broadcast($notice, $remote=false) {
1297         $success = true;
1298         if (!$remote) {
1299                 # Make sure we have the OMB stuff
1300                 require_once(INSTALLDIR.'/lib/omb.php');
1301                 $success = omb_broadcast_remote_subscribers($notice);
1302                 if (!$success) {
1303                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1304                 }
1305         }
1306         if ($success) {
1307                 require_once(INSTALLDIR.'/lib/jabber.php');
1308                 $success = jabber_broadcast_notice($notice);
1309                 if (!$success) {
1310                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1311                 }
1312         }
1313         if ($success) {
1314                 require_once(INSTALLDIR.'/lib/mail.php');
1315                 $success = mail_broadcast_notice_sms($notice);
1316                 if (!$success) {
1317                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1318                 }
1319         }
1320         if ($success) {
1321                 $success = jabber_public_notice($notice);
1322                 if (!$success) {
1323                         common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1324                 }
1325         }
1326         // XXX: broadcast notices to other IM
1327         return $success;
1328 }
1329
1330 function common_broadcast_profile($profile) {
1331         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1332         require_once(INSTALLDIR.'/lib/omb.php');
1333         omb_broadcast_profile($profile);
1334         // XXX: Other broadcasts...?
1335         return true;
1336 }
1337
1338 function common_profile_url($nickname) {
1339         return common_local_url('showstream', array('nickname' => $nickname));
1340 }
1341
1342 # Don't call if nobody's logged in
1343
1344 function common_notice_form($action=NULL, $content=NULL) {
1345         $user = common_current_user();
1346         assert(!is_null($user));
1347         common_element_start('form', array('id' => 'status_form',
1348                                                                            'method' => 'post',
1349                                                                            'action' => common_local_url('newnotice')));
1350         common_element_start('p');
1351         common_element('label', array('for' => 'status_textarea',
1352                                                                   'id' => 'status_label'),
1353                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1354         common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1355         common_element('textarea', array('id' => 'status_textarea',
1356                                                                          'cols' => 60,
1357                                                                          'rows' => 3,
1358                                                                          'name' => 'status_textarea'),
1359                                    ($content) ? $content : '');
1360         if ($action) {
1361                 common_hidden('returnto', $action);
1362         }
1363         # set by JavaScript
1364         common_hidden('inreplyto', 'false');
1365         common_element('input', array('id' => 'status_submit',
1366                                                                   'name' => 'status_submit',
1367                                                                   'type' => 'submit',
1368                                                                   'value' => _('Send')));
1369         common_element_end('p');
1370         common_element_end('form');
1371 }
1372
1373 # Should make up a reasonable root URL
1374
1375 function common_root_url() {
1376         return common_path('');
1377 }
1378
1379 # returns $bytes bytes of random data as a hexadecimal string
1380 # "good" here is a goal and not a guarantee
1381
1382 function common_good_rand($bytes) {
1383         # XXX: use random.org...?
1384         if (file_exists('/dev/urandom')) {
1385                 return common_urandom($bytes);
1386         } else { # FIXME: this is probably not good enough
1387                 return common_mtrand($bytes);
1388         }
1389 }
1390
1391 function common_urandom($bytes) {
1392         $h = fopen('/dev/urandom', 'rb');
1393         # should not block
1394         $src = fread($h, $bytes);
1395         fclose($h);
1396         $enc = '';
1397         for ($i = 0; $i < $bytes; $i++) {
1398                 $enc .= sprintf("%02x", (ord($src[$i])));
1399         }
1400         return $enc;
1401 }
1402
1403 function common_mtrand($bytes) {
1404         $enc = '';
1405         for ($i = 0; $i < $bytes; $i++) {
1406                 $enc .= sprintf("%02x", mt_rand(0, 255));
1407         }
1408         return $enc;
1409 }
1410
1411 function common_set_returnto($url) {
1412         common_ensure_session();
1413         $_SESSION['returnto'] = $url;
1414 }
1415
1416 function common_get_returnto() {
1417         common_ensure_session();
1418         return $_SESSION['returnto'];
1419 }
1420
1421 function common_timestamp() {
1422         return date('YmdHis');
1423 }
1424
1425 function common_ensure_syslog() {
1426         static $initialized = false;
1427         if (!$initialized) {
1428                 global $config;
1429                 openlog($config['syslog']['appname'], 0, LOG_USER);
1430                 $initialized = true;
1431         }
1432 }
1433
1434 function common_log($priority, $msg, $filename=NULL) {
1435         $logfile = common_config('site', 'logfile');
1436         if ($logfile) {
1437                 $log = fopen($logfile, "a");
1438                 if ($log) {
1439                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1440                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1441                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1442                         fwrite($log, $output);
1443                         fclose($log);
1444                 }
1445         } else {
1446                 common_ensure_syslog();
1447                 syslog($priority, $msg);
1448         }
1449 }
1450
1451 function common_debug($msg, $filename=NULL) {
1452         if ($filename) {
1453                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1454         } else {
1455                 common_log(LOG_DEBUG, $msg);
1456         }
1457 }
1458
1459 function common_log_db_error(&$object, $verb, $filename=NULL) {
1460         $objstr = common_log_objstring($object);
1461         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1462         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1463 }
1464
1465 function common_log_objstring(&$object) {
1466         if (is_null($object)) {
1467                 return "NULL";
1468         }
1469         $arr = $object->toArray();
1470         $fields = array();
1471         foreach ($arr as $k => $v) {
1472                 $fields[] = "$k='$v'";
1473         }
1474         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1475         return $objstring;
1476 }
1477
1478 function common_valid_http_url($url) {
1479         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1480 }
1481
1482 function common_valid_tag($tag) {
1483         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1484                 return (Validate::email($matches[1]) ||
1485                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1486         }
1487         return false;
1488 }
1489
1490 # Does a little before-after block for next/prev page
1491
1492 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1493
1494         if ($have_before || $have_after) {
1495                 common_element_start('div', array('id' => 'pagination'));
1496                 common_element_start('ul', array('id' => 'nav_pagination'));
1497         }
1498
1499         if ($have_before) {
1500                 $pargs = array('page' => $page-1);
1501                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1502
1503                 common_element_start('li', 'before');
1504                 common_element('a', array('href' => common_local_url($action, $newargs)),
1505                                            _('« After'));
1506                 common_element_end('li');
1507         }
1508
1509         if ($have_after) {
1510                 $pargs = array('page' => $page+1);
1511                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1512                 common_element_start('li', 'after');
1513                 common_element('a', array('href' => common_local_url($action, $newargs)),
1514                                                    _('Before »'));
1515                 common_element_end('li');
1516         }
1517
1518         if ($have_before || $have_after) {
1519                 common_element_end('ul');
1520                 common_element_end('div');
1521         }
1522 }
1523
1524 /* Following functions are copied from MediaWiki GlobalFunctions.php
1525  * and written by Evan Prodromou. */
1526
1527 function common_accept_to_prefs($accept, $def = '*/*') {
1528         # No arg means accept anything (per HTTP spec)
1529         if(!$accept) {
1530                 return array($def => 1);
1531         }
1532
1533         $prefs = array();
1534
1535         $parts = explode(',', $accept);
1536
1537         foreach($parts as $part) {
1538                 # FIXME: doesn't deal with params like 'text/html; level=1'
1539                 @list($value, $qpart) = explode(';', $part);
1540                 $match = array();
1541                 if(!isset($qpart)) {
1542                         $prefs[$value] = 1;
1543                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1544                         $prefs[$value] = $match[1];
1545                 }
1546         }
1547
1548         return $prefs;
1549 }
1550
1551 function common_mime_type_match($type, $avail) {
1552         if(array_key_exists($type, $avail)) {
1553                 return $type;
1554         } else {
1555                 $parts = explode('/', $type);
1556                 if(array_key_exists($parts[0] . '/*', $avail)) {
1557                         return $parts[0] . '/*';
1558                 } elseif(array_key_exists('*/*', $avail)) {
1559                         return '*/*';
1560                 } else {
1561                         return NULL;
1562                 }
1563         }
1564 }
1565
1566 function common_negotiate_type($cprefs, $sprefs) {
1567         $combine = array();
1568
1569         foreach(array_keys($sprefs) as $type) {
1570                 $parts = explode('/', $type);
1571                 if($parts[1] != '*') {
1572                         $ckey = common_mime_type_match($type, $cprefs);
1573                         if($ckey) {
1574                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1575                         }
1576                 }
1577         }
1578
1579         foreach(array_keys($cprefs) as $type) {
1580                 $parts = explode('/', $type);
1581                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1582                         $skey = common_mime_type_match($type, $sprefs);
1583                         if($skey) {
1584                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1585                         }
1586                 }
1587         }
1588
1589         $bestq = 0;
1590         $besttype = "text/html";
1591
1592         foreach(array_keys($combine) as $type) {
1593                 if($combine[$type] > $bestq) {
1594                         $besttype = $type;
1595                         $bestq = $combine[$type];
1596                 }
1597         }
1598
1599         return $besttype;
1600 }
1601
1602 function common_config($main, $sub) {
1603         global $config;
1604         return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1605 }
1606
1607 function common_copy_args($from) {
1608         $to = array();
1609         $strip = get_magic_quotes_gpc();
1610         foreach ($from as $k => $v) {
1611                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1612         }
1613         return $to;
1614 }
1615
1616 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1617 // This is used before handing a request off to OAuthRequest::from_request.
1618 function common_remove_magic_from_request() {
1619         if(get_magic_quotes_gpc()) {
1620                 $_POST=array_map('stripslashes',$_POST);
1621                 $_GET=array_map('stripslashes',$_GET);
1622         }
1623 }
1624
1625 function common_user_uri(&$user) {
1626         return common_local_url('userbyid', array('id' => $user->id));
1627 }
1628
1629 function common_notice_uri(&$notice) {
1630         return common_local_url('shownotice',
1631                 array('notice' => $notice->id));
1632 }
1633
1634 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1635
1636 function common_confirmation_code($bits) {
1637         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1638         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1639         $chars = ceil($bits/5);
1640         $code = '';
1641         for ($i = 0; $i < $chars; $i++) {
1642                 # XXX: convert to string and back
1643                 $num = hexdec(common_good_rand(1));
1644                 # XXX: randomness is too precious to throw away almost
1645                 # 40% of the bits we get!
1646                 $code .= $codechars[$num%32];
1647         }
1648         return $code;
1649 }
1650
1651 # convert markup to HTML
1652
1653 function common_markup_to_html($c) {
1654         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1655         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1656         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1657         return Markdown($c);
1658 }
1659
1660 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1661         $avatar = $profile->getAvatar($size);
1662         if ($avatar) {
1663                 return common_avatar_display_url($avatar);
1664         } else {
1665                 return common_default_avatar($size);
1666         }
1667 }
1668
1669 function common_profile_uri($profile) {
1670         if (!$profile) {
1671                 return NULL;
1672         }
1673         $user = User::staticGet($profile->id);
1674         if ($user) {
1675                 return $user->uri;
1676         }
1677
1678         $remote = Remote_profile::staticGet($profile->id);
1679         if ($remote) {
1680                 return $remote->uri;
1681         }
1682         # XXX: this is a very bad profile!
1683         return NULL;
1684 }
1685
1686 function common_canonical_sms($sms) {
1687         # strip non-digits
1688         preg_replace('/\D/', '', $sms);
1689         return $sms;
1690 }
1691
1692 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1693     switch ($errno) {
1694      case E_USER_ERROR:
1695                 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1696                 exit(1);
1697                 break;
1698
1699          case E_USER_WARNING:
1700                 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1701                 break;
1702
1703      case E_USER_NOTICE:
1704                 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1705                 break;
1706     }
1707
1708         # FIXME: show error page if we're on the Web
1709     /* Don't execute PHP internal error handler */
1710     return true;
1711 }
1712
1713 function common_session_token() {
1714         common_ensure_session();
1715         if (!array_key_exists('token', $_SESSION)) {
1716                 $_SESSION['token'] = common_good_rand(64);
1717         }
1718         return $_SESSION['token'];
1719 }
1720
1721 function common_disfavor_form($notice) {
1722         common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1723                                                                            'method' => 'post',
1724                                                                            'class' => 'disfavor',
1725                                                                            'action' => common_local_url('disfavor')));
1726         common_hidden('token', common_session_token());
1727         common_hidden('notice', $notice->id);
1728         common_element('input', array('type' => 'submit',
1729                                                                   'id' => 'disfavor-submit-' . $notice->id,
1730                                                                   'name' => 'disfavor-submit-' . $notice->id,
1731                                                                   'class' => 'disfavor',
1732                                                                   'value' => '♥'));
1733         common_element_end('form');
1734 }
1735
1736 function common_favor_form($notice) {
1737         common_element_start('form', array('id' => 'favor-' . $notice->id,
1738                                                                            'method' => 'post',
1739                                                                            'class' => 'favor',
1740                                                                            'action' => common_local_url('favor')));
1741         common_hidden('token', common_session_token());
1742         common_hidden('notice', $notice->id);
1743         common_element('input', array('type' => 'submit',
1744                                                                   'id' => 'favor-submit-' . $notice->id,
1745                                                                   'name' => 'favor-submit-' . $notice->id,
1746                                                                   'class' => 'favor',
1747                                                                   'value' => '♡'));
1748         common_element_end('form');
1749 }
1750
1751 function common_cache_key($extra) {
1752         return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1753 }
1754
1755 function common_keyize($str) {
1756         $str = strtolower($str);
1757         $str = preg_replace('/\s/', '_', $str);
1758         return $str;
1759 }
1760
1761 function common_message_form($content, $user, $to) {
1762         
1763         common_element_start('form', array('id' => 'message_form',
1764                                                                            'method' => 'post',
1765                                                                            'action' => common_local_url('newmessage')));
1766         
1767         $mutual_users = $user->mutuallySubscribedUsers();
1768         
1769         $mutual = array();
1770         
1771         while ($mutual_users->fetch()) {
1772                 if ($mutual_users->id != $user->id) {
1773                         $mutual[$mutual_users->id] = $mutual_users->nickname;
1774                 }
1775         }
1776         
1777         $mutual_users->free();
1778         unset($mutual_users);
1779         
1780         common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
1781         
1782         common_element_start('p');
1783         
1784         common_element('textarea', array('id' => 'message_content',
1785                                                                          'cols' => 60,
1786                                                                          'rows' => 3,
1787                                                                          'name' => 'content'),
1788                                    ($content) ? $content : '');
1789         
1790         common_element('input', array('id' => 'message_send',
1791                                                                   'name' => 'message_send',
1792                                                                   'type' => 'submit',
1793                                                                   'value' => _('Send')));
1794         
1795         common_hidden('token', common_session_token());
1796         
1797         common_element_end('p');
1798         common_element_end('form');
1799 }
1800
1801 function common_memcache() {
1802         static $cache = NULL;
1803         if (!common_config('memcached', 'enabled')) {
1804                 return NULL;
1805         } else {
1806                 if (!$cache) {
1807                         $cache = new Memcache();
1808                         $servers = common_config('memcached', 'server');
1809                         if (is_array($servers)) {
1810                                 foreach($servers as $server) {
1811                                         $cache->addServer($server);
1812                                 }
1813                         } else {
1814                                 $cache->addServer($servers);
1815                         }
1816                 }
1817                 return $cache;
1818         }
1819 }