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