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