]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
ar
[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) {
25         header('Status: 500 Server Error');
26         header('Content-type: text/plain');
27
28         print $msg;
29         exit();
30 }
31
32 # Show a user error
33 function common_user_error($msg, $code=200) {
34         common_show_header('Error');
35         common_element('div', array('class' => 'error'), $msg);
36         common_show_footer();
37 }
38
39 $xw = null;
40
41 # Start an HTML element
42 function common_element_start($tag, $attrs=NULL) {
43         global $xw;
44         $xw->startElement($tag);
45         if (is_array($attrs)) {
46                 foreach ($attrs as $name => $value) {
47                         $xw->writeAttribute($name, $value);
48                 }
49         } else if (is_string($attrs)) {
50                 $xw->writeAttribute('class', $attrs);
51         }
52 }
53
54 function common_element_end($tag) {
55         global $xw;
56         $xw->endElement();
57 }
58
59 function common_element($tag, $attrs=NULL, $content=NULL) {
60     common_element_start($tag, $attrs);
61         if ($content) {
62                 global $xw;
63                 $xw->text($content);
64         }
65         common_element_end($tag);
66 }
67
68 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
69         global $xw;
70         $xw = new XMLWriter();
71         $xw->openURI('php://output');
72         $xw->setIndent(true);
73         $xw->startDocument('1.0', 'UTF-8');
74         if ($doc) {
75                 $xw->writeDTD($doc, $public, $system);
76         }
77 }
78
79 function common_end_xml() {
80         global $xw;
81         $xw->endDocument();
82         $xw->flush();
83 }
84
85 function common_show_header($pagetitle, $callable=NULL, $data=NULL) {
86         global $config, $xw;
87
88         header('Content-Type: application/xhtml+xml');
89
90         common_start_xml('html',
91                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
92                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
93
94         # FIXME: correct language for interface
95
96         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
97                                                                            'xml:lang' => 'en',
98                                                                            'lang' => 'en'));
99
100         common_element_start('head');
101         common_element('title', NULL,
102                                    $pagetitle . " - " . $config['site']['name']);
103         common_element('link', array('rel' => 'stylesheet',
104                                                                  'type' => 'text/css',
105                                                                  'href' => $config['site']['path'] . 'theme/default/style/html.css',
106                                                                  'media' => 'screen, projection, tv'));
107         common_element('link', array('rel' => 'stylesheet',
108                                                                  'type' => 'text/css',
109                                                                  'href' => $config['site']['path'] . 'theme/default/style/layout.css',
110                                                                  'media' => 'screen, projection, tv'));
111         common_element('link', array('rel' => 'stylesheet',
112                                                                  'type' => 'text/css',
113                                                                  'href' => $config['site']['path'] . 'theme/default/style/print.css',
114                                                                  'media' => 'print'));
115         if ($callable) {
116                 if ($data) {
117                         call_user_func($callable, $data);
118                 } else {
119                         call_user_func($callable);
120                 }
121         }
122         common_element_end('head');
123         common_element_start('body');
124         common_element_start('div', array('id' => 'wrapper'));
125         common_element_start('div', array('id' => 'content'));
126         common_element_start('div', array('id' => 'header'));
127         common_element('h1', 'title', $pagetitle);
128         common_element('h2', 'subtitle', $config['site']['name']);
129         common_element_end('div');
130         common_head_menu();
131         common_element_start('div', array('id' => 'page'));
132 }
133
134 function common_show_footer() {
135         global $xw, $config;
136         common_element_start('div', 'footer');
137         common_foot_menu();
138         common_license_block();
139         common_element_end('div');
140         common_element_end('div');
141         common_element_end('div');
142         common_element_end('div');
143         common_element_end('body');
144         common_element_end('html');
145         common_end_xml();
146 }
147
148 function common_text($txt) {
149         global $xw;
150         $xw->text($txt);
151 }
152
153 function common_raw($xml) {
154         global $xw;
155         $xw->writeRaw($xml);
156 }
157
158 function common_license_block() {
159         global $config, $xw;
160         common_element_start('p', 'license greenBg');
161         common_element_start('span', 'floatLeft width25');
162         common_element_start('a', array('class' => 'license',
163                                                                         'rel' => 'license',
164                                                                         href => $config['license']['url']));
165         common_element('img', array('class' => 'license',
166                                                                 'src' => $config['license']['image'],
167                                                                 'alt' => $config['license']['title']));
168         common_element_end('a');
169         common_element_end('span');
170         common_element_start('span', 'floatRight width75');
171         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
172         common_element('a', array('class' => 'license',
173                                                           'rel' => 'license',
174                                                           href => $config['license']['url']),
175                                    $config['license']['title']);
176         common_text(_t('. Contributors should be attributed by full name or nickname.'));
177         common_element_end('span');
178         common_element_end('p');
179 }
180
181 function common_head_menu() {
182         $user = common_current_user();
183         common_element_start('ul', array('id' => 'menu', 'class' => ($user) ? 'five' : 'three'));
184         common_menu_item(common_local_url('public'), _t('Public'));
185         if ($user) {
186                 common_menu_item(common_local_url('all', array('nickname' =>
187                                                                                                            $user->nickname)),
188                                                  _t('Home'));
189                 common_menu_item(common_local_url('showstream', array('nickname' =>
190                                                                                                                           $user->nickname)),
191                                                  _t('Profile'),  $user->fullname || $user->nickname);
192                 common_menu_item(common_local_url('profilesettings'),
193                                                  _t('Settings'));
194                 common_menu_item(common_local_url('logout'),
195                                                  _t('Logout'));
196         } else {
197                 common_menu_item(common_local_url('login'),
198                                                  _t('Login'));
199                 common_menu_item(common_local_url('register'),
200                                                  _t('Register'));
201         }
202         common_element_end('ul');
203 }
204
205 function common_foot_menu() {
206         common_element_start('ul', 'footmenu menuish');
207         common_menu_item(common_local_url('doc', array('title' => 'about')),
208                                          _t('About'));
209         common_menu_item(common_local_url('doc', array('title' => 'help')),
210                                          _t('Help'));
211         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
212                                          _t('Privacy'));
213         common_menu_item(common_local_url('doc', array('title' => 'source')),
214                                          _t('Source'));
215         common_element_end('ul');
216 }
217
218 function common_menu_item($url, $text, $title=NULL) {
219         $attrs['href'] = $url;
220         if ($title) {
221                 $attrs['title'] = $title;
222         }
223         common_element_start('li', 'menuitem');
224         common_element('a', $attrs, $text);
225         common_element_end('li');
226 }
227
228 function common_input($id, $label, $value=NULL) {
229         common_element_start('p');
230         common_element('label', array('for' => $id), $label);
231         $attrs = array('name' => $id,
232                                    'type' => 'text',
233                                    'id' => $id);
234         if ($value) {
235                 $attrs['value'] = htmlspecialchars($value);
236         }
237         common_element('input', $attrs);
238         common_element_end('p');
239 }
240
241 function common_password($id, $label) {
242         common_element_start('p');
243         common_element('label', array('for' => $id), $label);
244         $attrs = array('name' => $id,
245                                    'type' => 'password',
246                                    'id' => $id);
247         common_element('input', $attrs);
248         common_element_end('p');
249 }
250
251 function common_submit($id, $label) {
252         global $xw;
253         common_element_start('p');
254         common_element_start('label', array('for' => $id));
255         $xw->writeRaw('&nbsp;');
256         common_element_end('label');
257         common_element('input', array('type' => 'submit',
258                                                                   'id' => $id,
259                                                                   'name' => $id,
260                                                                   'value' => $label,
261                                                                   'class' => 'button'));
262         common_element_end('p');
263 }
264
265 function common_textarea($id, $label, $content=NULL) {
266         common_element_start('p');
267         common_element('label', array('for' => $id), $label);
268         common_element('textarea', array('rows' => 3,
269                                                                          'cols' => 40,
270                                                                          'name' => $id,
271                                                                          'id' => $id, 
272                                                                          'class' => 'width50'),
273                                    ($content) ? $content : ' ');
274         common_element_end('p');
275 }
276
277 # salted, hashed passwords are stored in the DB
278
279 function common_munge_password($id, $password) {
280         return md5($id . $password);
281 }
282
283 # check if a username exists and has matching password
284 function common_check_user($nickname, $password) {
285         $user = User::staticGet('nickname', $nickname);
286         if (is_null($user)) {
287                 return false;
288         } else {
289                 return (0 == strcmp(common_munge_password($password, $user->id),
290                                                         $user->password));
291         }
292 }
293
294 # is the current user logged in?
295 function common_logged_in() {
296         return (!is_null(common_current_user()));
297 }
298
299 function common_have_session() {
300         return (0 != strcmp(session_id(), ''));
301 }
302
303 function common_ensure_session() {
304         if (!common_have_session()) {
305                 @session_start();
306         }
307 }
308
309 function common_set_user($nickname) {
310         if (is_null($nickname) && common_have_session()) {
311                 unset($_SESSION['userid']);
312                 return true;
313         } else {
314                 $user = User::staticGet('nickname', $nickname);
315                 if ($user) {
316                         common_ensure_session();
317                         $_SESSION['userid'] = $user->id;
318                         return true;
319                 } else {
320                         return false;
321                 }
322         }
323         return false;
324 }
325
326 # who is the current user?
327 function common_current_user() {
328         static $user = NULL; # FIXME: global memcached
329         if (is_null($user)) {
330                 common_ensure_session();
331                 $id = $_SESSION['userid'];
332                 if ($id) {
333                         $user = User::staticGet($id);
334                 }
335         }
336         return $user;
337 }
338
339 # get canonical version of nickname for comparison
340 function common_canonical_nickname($nickname) {
341         # XXX: UTF-8 canonicalization (like combining chars)
342         return $nickname;
343 }
344
345 # get canonical version of email for comparison
346 function common_canonical_email($email) {
347         # XXX: canonicalize UTF-8
348         # XXX: lcase the domain part
349         return $email;
350 }
351
352 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$_+!*();/?:~-]))');
353
354 function common_render_content($text, $notice) {
355         $r = htmlspecialchars($text);
356         $id = $notice->profile_id;
357         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
358 #       $r = preg_replace('(^|\b)(https?|ftp)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]', '<a href="\0" class="extlink">\0</a>', $r);
359         # XXX: # tags
360         # XXX: machine tags
361         return $r;
362 }
363
364 function common_at_link($sender_id, $nickname) {
365         # Try to find profiles this profile is subscribed to that have this nickname
366         $recipient = new Profile();
367         # XXX: chokety and bad
368         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
369         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
370         if ($recipient->find(TRUE)) {
371                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
372         }
373         # Try to find profiles that listen to this profile and that have this nickname
374         $recipient = new Profile();
375         # XXX: chokety and bad
376         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
377         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
378         if ($recipient->find(TRUE)) {
379                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
380         }
381         # If this is a local user, try to find a local user with that nickname.
382         $sender = User::staticGet($sender_id);
383         if ($sender) {
384                 $recipient_user = User::staticGet('nickname', $nickname);
385                 if ($recipient_user) {
386                         $recipient = $recipient->getProfile();
387                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
388                 }
389         }
390         # Otherwise, no links. @messages from local users to remote users,
391         # or from remote users to other remote users, are just
392         # outside our ability to make intelligent guesses about
393         return $nickname;
394 }
395
396 // where should the avatar go for this user?
397
398 function common_avatar_filename($user, $extension, $size=NULL, $extra=NULL) {
399         global $config;
400
401         if ($size) {
402                 return $user->id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
403         } else {
404                 return $user->id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
405         }
406 }
407
408 function common_avatar_path($filename) {
409         global $config;
410         return $config['avatar']['directory'] . '/' . $filename;
411 }
412
413 function common_avatar_url($filename) {
414         global $config;
415         return "http://".$config['site']['server'].$config['avatar']['path'].'/'.$filename;
416 }
417
418 function common_default_avatar($size) {
419         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
420                                                           AVATAR_STREAM_SIZE => 'stream',
421                                                           AVATAR_MINI_SIZE => 'mini');
422         global $config;
423         return "http://".$config['site']['server'].$config['site']['path'].'/'.$config['avatar']['default'][$sizenames[$size]];
424 }
425
426 function common_local_url($action, $args=NULL) {
427         global $config;
428         /* XXX: pretty URLs */
429         $extra = '';
430         if ($args) {
431                 foreach ($args as $key => $value) {
432                         $extra .= "&${key}=${value}";
433                 }
434         }
435         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
436         return "http://".$config['site']['server'].'/'.$pathpart."index.php?action=${action}${extra}";
437 }
438
439 function common_date_string($dt) {
440         // XXX: do some sexy date formatting
441         // return date(DATE_RFC822, $dt);
442         return $dt;
443 }
444
445 function common_date_w3dtf($dt) {
446         $t = strtotime($dt);
447         return date(DATE_W3C, $t);
448 }
449
450 function common_redirect($url, $code=307) {
451         static $status = array(301 => "Moved Permanently",
452                                                    302 => "Found",
453                                                    303 => "See Other",
454                                                    307 => "Temporary Redirect");
455         header("Status: ${code} $status[$code]");
456         header("Location: $url");
457         common_element('a', array('href' => $url), $url);
458 }
459
460 function common_broadcast_notice($notice) {
461         // XXX: broadcast notices to remote subscribers
462         // XXX: broadcast notices to SMS
463         // XXX: broadcast notices to Jabber
464         // XXX: broadcast notices to other IM
465         // XXX: use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
466         return true;
467 }
468
469 function common_profile_url($nickname) {
470         return common_local_url('showstream', array('nickname' => $nickname));
471 }
472
473 function common_notice_form() {
474         common_element_start('form', array('id' => 'newnotice', 'method' => 'POST',
475                                                                            'action' => common_local_url('newnotice')));
476         common_textarea('noticecontent', _t('What\'s up?'));
477         common_submit('submit', _t('Send'));
478         common_element_end('form');
479 }
480
481 function common_mint_tag($extra) {
482         global $config;
483         return 
484           'tag:'.$config['tag']['authority'].','.
485           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
486 }
487
488 # Should make up a reasonable root URL
489
490 function common_root_url() {
491         global $config;
492         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
493         return "http://".$config['site']['server'].'/'.$pathpart;
494 }
495
496 # returns $bytes bytes of random data as a hexadecimal string
497 # "good" here is a goal and not a guarantee
498
499 function common_good_rand($bytes) {
500         # XXX: use random.org...?
501         if (file_exists('/dev/urandom')) {
502                 return common_urandom($bytes);
503         } else { # FIXME: this is probably not good enough
504                 return common_mtrand($bytes);
505         }
506 }
507
508 function common_urandom($bytes) {
509         $h = fopen('/dev/urandom', 'rb');
510         # should not block
511         $src = fread($h, $bytes);
512         fclose($h);
513         $enc = '';
514         for ($i = 0; $i < $bytes; $i++) {
515                 $enc .= sprintf("%02x", (ord($src[$i])));
516         }
517         return $enc;
518 }
519
520 function common_mtrand($bytes) {
521         $enc = '';
522         for ($i = 0; $i < $bytes; $i++) {
523                 $enc .= sprintf("%02x", mt_rand(0, 255));
524         }
525         return $enc;
526 }
527
528 function common_timestamp() {
529         return date('YmdHis');
530 }
531         
532 // XXX: set up gettext
533
534 function _t($str) {
535         return $str;
536 }