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