]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
make last parameter for common_menu_item() optional
[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         global $xw;
97         $xw->endElement();
98 }
99
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101     common_element_start($tag, $attrs);
102         if ($content) {
103                 global $xw;
104                 $xw->text($content);
105         }
106         common_element_end($tag);
107 }
108
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
110         global $xw;
111         $xw = new XMLWriter();
112         $xw->openURI('php://output');
113         $xw->setIndent(true);
114         $xw->startDocument('1.0', 'UTF-8');
115         if ($doc) {
116                 $xw->writeDTD($doc, $public, $system);
117         }
118 }
119
120 function common_end_xml() {
121         global $xw;
122         $xw->endDocument();
123         $xw->flush();
124 }
125
126 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $notice=NULL) {
127         global $config, $xw;
128
129         header('Content-Type: application/xhtml+xml');
130
131         common_start_xml('html',
132                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
133                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
134
135         # FIXME: correct language for interface
136
137         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
138                                                                            'xml:lang' => 'en',
139                                                                            'lang' => 'en'));
140
141         common_element_start('head');
142         common_element('title', NULL,
143                                    $pagetitle . " - " . $config['site']['name']);
144         common_element('link', array('rel' => 'stylesheet',
145                                                                  'type' => 'text/css',
146                                                                  'href' => theme_path('display.css'),
147                                                                  'media' => 'screen, projection, tv'));
148         foreach (array(6,7) as $ver) {
149                 if (file_exists(theme_file('ie'.$ver.'.css'))) {
150                         # Yes, IE people should be put in jail.
151                         $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
152                                                           'href="'.theme_path('ie'.$ver.'.css').' /><![endif]');
153                 }
154         }
155         if ($callable) {
156                 if ($data) {
157                         call_user_func($callable, $data);
158                 } else {
159                         call_user_func($callable);
160                 }
161         }
162         common_element_end('head');
163         common_element_start('body');
164         common_element_start('div', array('id' => 'wrap'));
165         common_element_start('div', array('id' => 'header'));
166         common_nav_menu();
167         common_element_start('a', array('href' => common_local_url('public')));
168         common_element('img', array('src' => ($config['site']['logo']) ? 
169                                                                 ($config['site']['logo']) : theme_path('logo.png'),
170                                                                 'alt' => $config['site']['name'],
171                                                                 'id' => 'logo'));
172         common_element_end('a');
173         if (common_logged_in()) {
174                 common_notice_form();
175         }
176         common_element_end('div');
177         common_element_start('div', array('id' => 'content'));
178 }
179
180 function common_show_footer() {
181         global $xw, $config;
182         common_element_end('div'); # content div
183         common_foot_menu();
184         common_element_start('div', array('id' => 'footer'));
185         common_element('img', array('id' => 'cc',
186                                                                 'src' => $config['license']['image'],
187                                                                 'alt' => $config['license']['title']));
188         common_element_start('p');
189         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
190         common_element('a', array('class' => 'license',
191                                                           'rel' => 'license',
192                                                           href => $config['license']['url']),
193                                    $config['license']['title']);
194         common_text(_t('. Contributors should be attributed by full name or nickname.'));
195         common_element_end('p');
196         common_element_end('div');
197         common_element_end('div');
198         common_element_end('body');
199         common_element_end('html');
200         common_end_xml();
201 }
202
203 function common_text($txt) {
204         global $xw;
205         $xw->text($txt);
206 }
207
208 function common_raw($xml) {
209         global $xw;
210         $xw->writeRaw($xml);
211 }
212
213 function common_nav_menu() {
214         $user = common_current_user();
215         common_element_start('ul', array('id' => 'nav'));
216         if ($user) {
217                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
218                                                  _t('Home'));
219         }
220         common_menu_item(common_local_url('public'), _t('Public'));
221         common_menu_item(common_local_url('doc', array('title' => 'help')),
222                                          _t('Help'));
223         if ($user) {
224                 common_menu_item(common_local_url('profilesettings'),
225                                                  _t('Settings'));
226                 common_menu_item(common_local_url('logout'),
227                                                  _t('Logout'));
228         } else {
229                 common_menu_item(common_local_url('login'), _t('Login'));
230                 common_menu_item(common_local_url('register'), _t('Register'));
231         }
232         common_element_end('ul');
233 }
234
235 function common_foot_menu() {
236         common_element_start('ul', array('id' => 'nav_sub'));
237         common_menu_item(common_local_url('doc', array('title' => 'about')),
238                                          _t('About'));
239         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
240                                          _t('Privacy'));
241         common_menu_item(common_local_url('doc', array('title' => 'source')),
242                                          _t('Source'));
243         common_element_end('ul');
244 }
245
246 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
247         $lattrs = array();
248         if ($is_selected) {
249                 $lattrs['class'] = 'current';
250         }
251         common_element_start('li', $lattrs);
252         $attrs['href'] = $url;
253         if ($title) {
254                 $attrs['title'] = $title;
255         }
256         common_element('a', $attrs, $text);
257         common_element_end('li');
258 }
259
260 function common_input($id, $label, $value=NULL) {
261         common_element_start('p');
262         common_element('label', array('for' => $id), $label);
263         $attrs = array('name' => $id,
264                                    'type' => 'text',
265                                    'id' => $id);
266         if ($value) {
267                 $attrs['value'] = htmlspecialchars($value);
268         }
269         common_element('input', $attrs);
270         common_element_end('p');
271 }
272
273 function common_hidden($id, $value) {
274         common_element('input', array('name' => $id,
275                                                                   'type' => 'hidden',
276                                                                   'id' => $id,
277                                                                   'value' => $value));
278 }
279
280 function common_password($id, $label) {
281         common_element_start('p');
282         common_element('label', array('for' => $id), $label);
283         $attrs = array('name' => $id,
284                                    'type' => 'password',
285                                    'id' => $id);
286         common_element('input', $attrs);
287         common_element_end('p');
288 }
289
290 function common_submit($id, $label) {
291         global $xw;
292         common_element_start('p');
293         common_element('input', array('type' => 'submit',
294                                                                   'id' => $id,
295                                                                   'name' => $id,
296                                                                   'value' => $label));
297         common_element_end('p');
298 }
299
300 function common_textarea($id, $label, $content=NULL) {
301         common_element_start('p');
302         common_element('label', array('for' => $id), $label);
303         common_element('textarea', array('rows' => 3,
304                                                                          'cols' => 40,
305                                                                          'name' => $id,
306                                                                          'id' => $id),
307                                    ($content) ? $content : ' ');
308         common_element_end('p');
309 }
310
311 # salted, hashed passwords are stored in the DB
312
313 function common_munge_password($id, $password) {
314         return md5($id . $password);
315 }
316
317 # check if a username exists and has matching password
318 function common_check_user($nickname, $password) {
319         $user = User::staticGet('nickname', $nickname);
320         if (is_null($user)) {
321                 return false;
322         } else {
323                 return (0 == strcmp(common_munge_password($password, $user->id),
324                                                         $user->password));
325         }
326 }
327
328 # is the current user logged in?
329 function common_logged_in() {
330         return (!is_null(common_current_user()));
331 }
332
333 function common_have_session() {
334         return (0 != strcmp(session_id(), ''));
335 }
336
337 function common_ensure_session() {
338         if (!common_have_session()) {
339                 @session_start();
340         }
341 }
342
343 function common_set_user($nickname) {
344         if (is_null($nickname) && common_have_session()) {
345                 unset($_SESSION['userid']);
346                 return true;
347         } else {
348                 $user = User::staticGet('nickname', $nickname);
349                 if ($user) {
350                         common_ensure_session();
351                         $_SESSION['userid'] = $user->id;
352                         return true;
353                 } else {
354                         return false;
355                 }
356         }
357         return false;
358 }
359
360 # who is the current user?
361 function common_current_user() {
362         static $user = NULL; # FIXME: global memcached
363         if (is_null($user)) {
364                 common_ensure_session();
365                 $id = $_SESSION['userid'];
366                 if ($id) {
367                         $user = User::staticGet($id);
368                 }
369         }
370         return $user;
371 }
372
373 # get canonical version of nickname for comparison
374 function common_canonical_nickname($nickname) {
375         # XXX: UTF-8 canonicalization (like combining chars)
376         return strtolower($nickname);
377 }
378
379 # get canonical version of email for comparison
380 function common_canonical_email($email) {
381         # XXX: canonicalize UTF-8
382         # XXX: lcase the domain part
383         return $email;
384 }
385
386 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$_+!*();/?:~-]))');
387
388 function common_render_content($text, $notice) {
389         $r = htmlspecialchars($text);
390         $id = $notice->profile_id;
391         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
392         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
393         # XXX: # tags
394         # XXX: machine tags
395         return $r;
396 }
397
398 function common_at_link($sender_id, $nickname) {
399         # Try to find profiles this profile is subscribed to that have this nickname
400         $recipient = new Profile();
401         # XXX: chokety and bad
402         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
403         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
404         if ($recipient->find(TRUE)) {
405                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
406         }
407         # Try to find profiles that listen to this profile and that have this nickname
408         $recipient = new Profile();
409         # XXX: chokety and bad
410         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
411         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
412         if ($recipient->find(TRUE)) {
413                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
414         }
415         # If this is a local user, try to find a local user with that nickname.
416         $sender = User::staticGet($sender_id);
417         if ($sender) {
418                 $recipient_user = User::staticGet('nickname', $nickname);
419                 if ($recipient_user) {
420                         $recipient = $recipient->getProfile();
421                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
422                 }
423         }
424         # Otherwise, no links. @messages from local users to remote users,
425         # or from remote users to other remote users, are just
426         # outside our ability to make intelligent guesses about
427         return $nickname;
428 }
429
430 // where should the avatar go for this user?
431
432 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
433         global $config;
434
435         if ($size) {
436                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
437         } else {
438                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
439         }
440 }
441
442 function common_avatar_path($filename) {
443         global $config;
444         return INSTALLDIR . '/avatar/' . $filename;
445 }
446
447 function common_avatar_url($filename) {
448         return common_path('avatar/'.$filename);
449 }
450
451 function common_default_avatar($size) {
452         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
453                                                           AVATAR_STREAM_SIZE => 'stream',
454                                                           AVATAR_MINI_SIZE => 'mini');
455         global $config;
456
457         return common_path($config['avatar']['default'][$sizenames[$size]]);
458 }
459
460 function common_local_url($action, $args=NULL) {
461         global $config;
462         if ($config['site']['fancy']) {
463                 return common_fancy_url($action, $args);
464         } else {
465                 return common_simple_url($action, $args);
466         }
467 }
468
469 function common_fancy_url($action, $args=NULL) {
470         switch (strtolower($action)) {
471          case 'public':
472                 return common_path('');
473          case 'publicrss':
474                 return common_path('rss');
475          case 'doc':
476                 return common_path('doc/'.$args['title']);
477          case 'login':
478          case 'logout':
479          case 'register':
480          case 'subscribe':
481          case 'unsubscribe':
482                 return common_path('main/'.$action);
483          case 'avatar':
484          case 'password':
485                 return common_path('settings/'.$action);
486          case 'profilesettings':
487                 return common_path('settings/profile');
488          case 'newnotice':
489                 return common_path('notice/new');
490          case 'shownotice':
491                 return common_path('notice/'.$args['notice']);
492          case 'subscriptions':
493          case 'subscribed':
494          case 'xrds':           
495          case 'all':
496          case 'foaf':
497                 return common_path($args['nickname'].'/'.$action);
498          case 'allrss':
499                 return common_path($args['nickname'].'/all/rss');
500          case 'userrss':
501                 return common_path($args['nickname'].'/rss');
502          case 'showstream':
503                 return common_path($args['nickname']);
504          default:
505                 return common_simple_url($action, $args);
506         }
507 }
508
509 function common_simple_url($action, $args=NULL) {
510         global $config;
511         /* XXX: pretty URLs */
512         $extra = '';
513         if ($args) {
514                 foreach ($args as $key => $value) {
515                         $extra .= "&${key}=${value}";
516                 }
517         }
518         return common_path("index.php?action=${action}${extra}");
519 }
520
521 function common_path($relative) {
522         global $config;
523         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
524         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
525 }
526
527 function common_date_string($dt) {
528         // XXX: do some sexy date formatting
529         // return date(DATE_RFC822, $dt);
530         return $dt;
531 }
532
533 function common_date_w3dtf($dt) {
534         $t = strtotime($dt);
535         return date(DATE_W3C, $t);
536 }
537
538 function common_redirect($url, $code=307) {
539         static $status = array(301 => "Moved Permanently",
540                                                    302 => "Found",
541                                                    303 => "See Other",
542                                                    307 => "Temporary Redirect");
543         header("Status: ${code} $status[$code]");
544         header("Location: $url");
545         common_element('a', array('href' => $url), $url);
546 }
547
548 function common_broadcast_notice($notice, $remote=false) {
549         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
550         if (!$remote) {
551                 # Make sure we have the OMB stuff
552                 require_once(INSTALLDIR.'/lib/omb.php');
553                 omb_broadcast_remote_subscribers($notice);
554         }
555         // XXX: broadcast notices to Jabber
556         // XXX: broadcast notices to SMS
557         // XXX: broadcast notices to other IM
558         return true;
559 }
560
561
562 function common_profile_url($nickname) {
563         return common_local_url('showstream', array('nickname' => $nickname));
564 }
565
566 # Don't call if nobody's logged in
567
568 function common_notice_form() {
569         $user = common_current_user();
570         assert(!is_null($user));
571         common_element_start('form', array('id' => 'status_form',
572                                                                            'method' => 'POST',
573                                                                            'action' => common_local_url('newnotice')));
574         common_element_start('p');
575         common_element('label', array('for' => 'status_update',
576                                                                   'id' => 'status_label'),
577                                    _t('What\'s up, ').$user->nickname.'?');
578         common_element('textarea', array('id' => 'status_textarea',
579                                                                          'name' => 'status_textarea'));
580         common_element('input', array('id' => 'status_submit',
581                                                                   'name' => 'status_submit',
582                                                                   'type' => 'submit',
583                                                                   'value' => _t('Send')));
584         common_element_end('p');
585         common_element_end('form');
586 }
587
588 function common_mint_tag($extra) {
589         global $config;
590         return
591           'tag:'.$config['tag']['authority'].','.
592           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
593 }
594
595 # Should make up a reasonable root URL
596
597 function common_root_url() {
598         return common_path('');
599 }
600
601 # returns $bytes bytes of random data as a hexadecimal string
602 # "good" here is a goal and not a guarantee
603
604 function common_good_rand($bytes) {
605         # XXX: use random.org...?
606         if (file_exists('/dev/urandom')) {
607                 return common_urandom($bytes);
608         } else { # FIXME: this is probably not good enough
609                 return common_mtrand($bytes);
610         }
611 }
612
613 function common_urandom($bytes) {
614         $h = fopen('/dev/urandom', 'rb');
615         # should not block
616         $src = fread($h, $bytes);
617         fclose($h);
618         $enc = '';
619         for ($i = 0; $i < $bytes; $i++) {
620                 $enc .= sprintf("%02x", (ord($src[$i])));
621         }
622         return $enc;
623 }
624
625 function common_mtrand($bytes) {
626         $enc = '';
627         for ($i = 0; $i < $bytes; $i++) {
628                 $enc .= sprintf("%02x", mt_rand(0, 255));
629         }
630         return $enc;
631 }
632
633 function common_set_returnto($url) {
634         common_ensure_session();
635         $_SESSION['returnto'] = $url;
636 }
637
638 function common_get_returnto() {
639         common_ensure_session();
640         return $_SESSION['returnto'];
641 }
642
643 function common_timestamp() {
644         return date('YmdHis');
645 }
646
647 // XXX: set up gettext
648
649 function _t($str) {
650         return $str;
651 }
652
653 function common_ensure_syslog() {
654         static $initialized = false;
655         if (!$initialized) {
656                 global $config;
657                 define_syslog_variables();
658                 openlog($config['syslog']['appname'], 0, LOG_USER);
659                 $initialized = true;
660         }
661 }
662
663 function common_log($priority, $msg, $filename=NULL) {
664         common_ensure_syslog();
665         syslog($priority, $msg);
666 }
667
668 function common_debug($msg, $filename=NULL) {
669         if ($filename) {
670                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
671         } else {
672                 common_log(LOG_DEBUG, $msg);
673         }
674 }
675
676 function common_valid_http_url($url) {
677         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
678 }
679
680 function common_valid_tag($tag) {
681         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
682                 return (Validate::email($matches[1]) ||
683                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
684         }
685         return false;
686 }
687
688 # Does a little before-after block for next/prev page
689
690 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {             
691         
692         if ($have_before || $have_after) {
693                 common_element_start('div', array('id' => 'pagination'));
694                 common_element_start('ul', array('id' => 'nav_pagination'));
695         }
696         
697         if ($have_before) {
698                 $pargs = array('page' => $page-1);
699                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
700                                                                                  
701                 common_element_start('li', 'before');
702                 common_element('a', array('href' => common_local_url($action, $newargs)),
703                                            _t('« Before'));
704                 common_element_end('li');
705         }
706
707         if ($have_after) {
708                 $pargs = array('page' => $page+1);
709                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
710                 common_element_start('li', 'after');
711                 common_element('a', array('href' => common_local_url($action, $newargs)),
712                                                    _t('After »'));
713                 common_element_end('li');
714         }
715         
716         if ($have_before || $have_after) {
717                 common_element_end('ul');
718                 common_element_end('div');
719         }
720 }