]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
448c049c04827ad98ab88b7aba2578da338856d7
[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_license_block() {
154         global $config, $xw;
155         common_element_start('p', 'license greenBg');
156         common_element_start('span', 'floatLeft width25');
157         common_element_start('a', array('class' => 'license',
158                                                                         'rel' => 'license',
159                                                                         href => $config['license']['url']));
160         common_element('img', array('class' => 'license',
161                                                                 'src' => $config['license']['image'],
162                                                                 'alt' => $config['license']['title']));
163         common_element_end('a');
164         common_element_end('span');
165         common_element_start('span', 'floatRight width75');
166         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
167         common_element('a', array('class' => 'license',
168                                                           'rel' => 'license',
169                                                           href => $config['license']['url']),
170                                    $config['license']['title']);
171         common_text(_t('. Contributors should be attributed by full name or nickname.'));
172         common_element_end('span');
173         common_element_end('p');
174 }
175
176 function common_head_menu() {
177         $user = common_current_user();
178         common_element_start('ul', array('id' => 'menu', 'class' => ($user) ? 'five' : 'three'));
179         common_menu_item(common_local_url('public'), _t('Public'));
180         if ($user) {
181                 common_menu_item(common_local_url('all', array('nickname' =>
182                                                                                                            $user->nickname)),
183                                                  _t('Home'));
184                 common_menu_item(common_local_url('showstream', array('nickname' =>
185                                                                                                                           $user->nickname)),
186                                                  _t('Profile'),  $user->fullname || $user->nickname);
187                 common_menu_item(common_local_url('profilesettings'),
188                                                  _t('Settings'));
189                 common_menu_item(common_local_url('logout'),
190                                                  _t('Logout'));
191         } else {
192                 common_menu_item(common_local_url('login'),
193                                                  _t('Login'));
194                 common_menu_item(common_local_url('register'),
195                                                  _t('Register'));
196         }
197         common_element_end('ul');
198 }
199
200 function common_foot_menu() {
201         common_element_start('ul', 'footmenu menuish');
202         common_menu_item(common_local_url('doc', array('title' => 'about')),
203                                          _t('About'));
204         common_menu_item(common_local_url('doc', array('title' => 'help')),
205                                          _t('Help'));
206         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
207                                          _t('Privacy'));
208         common_menu_item(common_local_url('doc', array('title' => 'source')),
209                                          _t('Source'));
210         common_element_end('ul');
211 }
212
213 function common_menu_item($url, $text, $title=NULL) {
214         $attrs['href'] = $url;
215         if ($title) {
216                 $attrs['title'] = $title;
217         }
218         common_element_start('li', 'menuitem');
219         common_element('a', $attrs, $text);
220         common_element_end('li');
221 }
222
223 function common_input($id, $label, $value=NULL) {
224         common_element_start('p');
225         common_element('label', array('for' => $id), $label);
226         $attrs = array('name' => $id,
227                                    'type' => 'text',
228                                    'id' => $id);
229         if ($value) {
230                 $attrs['value'] = htmlspecialchars($value);
231         }
232         common_element('input', $attrs);
233         common_element_end('p');
234 }
235
236 function common_password($id, $label) {
237         common_element_start('p');
238         common_element('label', array('for' => $id), $label);
239         $attrs = array('name' => $id,
240                                    'type' => 'password',
241                                    'id' => $id);
242         common_element('input', $attrs);
243         common_element_end('p');
244 }
245
246 function common_submit($id, $label) {
247         global $xw;
248         common_element_start('p');
249         common_element_start('label', array('for' => $id));
250         $xw->writeRaw('&nbsp;');
251         common_element_end('label');
252         common_element('input', array('type' => 'submit',
253                                                                   'id' => $id,
254                                                                   'name' => $id,
255                                                                   'value' => $label,
256                                                                   'class' => 'button'));
257         common_element_end('p');
258 }
259
260 function common_textarea($id, $label, $content=NULL) {
261         common_element_start('p');
262         common_element('label', array('for' => $id), $label);
263         common_element('textarea', array('rows' => 3,
264                                                                          'cols' => 40,
265                                                                          'name' => $id,
266                                                                          'id' => $id, 
267                                                                          'class' => 'width50'),
268                                    ($content) ? $content : ' ');
269         common_element_end('p');
270 }
271
272 # salted, hashed passwords are stored in the DB
273
274 function common_munge_password($id, $password) {
275         return md5($id . $password);
276 }
277
278 # check if a username exists and has matching password
279 function common_check_user($nickname, $password) {
280         $user = User::staticGet('nickname', $nickname);
281         if (is_null($user)) {
282                 return false;
283         } else {
284                 return (0 == strcmp(common_munge_password($password, $user->id),
285                                                         $user->password));
286         }
287 }
288
289 # is the current user logged in?
290 function common_logged_in() {
291         return (!is_null(common_current_user()));
292 }
293
294 function common_have_session() {
295         return (0 != strcmp(session_id(), ''));
296 }
297
298 function common_ensure_session() {
299         if (!common_have_session()) {
300                 @session_start();
301         }
302 }
303
304 function common_set_user($nickname) {
305         if (is_null($nickname) && common_have_session()) {
306                 unset($_SESSION['userid']);
307                 return true;
308         } else {
309                 $user = User::staticGet('nickname', $nickname);
310                 if ($user) {
311                         common_ensure_session();
312                         $_SESSION['userid'] = $user->id;
313                         return true;
314                 } else {
315                         return false;
316                 }
317         }
318         return false;
319 }
320
321 # who is the current user?
322 function common_current_user() {
323         static $user = NULL; # FIXME: global memcached
324         if (is_null($user)) {
325                 common_ensure_session();
326                 $id = $_SESSION['userid'];
327                 if ($id) {
328                         $user = User::staticGet($id);
329                 }
330         }
331         return $user;
332 }
333
334 # get canonical version of nickname for comparison
335 function common_canonical_nickname($nickname) {
336         # XXX: UTF-8 canonicalization (like combining chars)
337         return $nickname;
338 }
339
340 # get canonical version of email for comparison
341 function common_canonical_email($email) {
342         # XXX: canonicalize UTF-8
343         # XXX: lcase the domain part
344         return $email;
345 }
346
347 function common_render_content($text) {
348         # XXX: @ messages
349         # XXX: # tags
350         # XXX: machine tags
351         return htmlspecialchars($text);
352 }
353
354 // where should the avatar go for this user?
355
356 function common_avatar_filename($user, $extension, $size=NULL, $extra=NULL) {
357         global $config;
358
359         if ($size) {
360                 return $user->id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
361         } else {
362                 return $user->id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
363         }
364 }
365
366 function common_avatar_path($filename) {
367         global $config;
368         return $config['avatar']['directory'] . '/' . $filename;
369 }
370
371 function common_avatar_url($filename) {
372         global $config;
373         return "http://".$config['site']['server'].$config['avatar']['path'].'/'.$filename;
374 }
375
376 function common_default_avatar($size) {
377         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
378                                                           AVATAR_STREAM_SIZE => 'stream',
379                                                           AVATAR_MINI_SIZE => 'mini');
380         global $config;
381         return "http://".$config['site']['server'].$config['site']['path'].'/'.$config['avatar']['default'][$sizenames[$size]];
382 }
383
384 function common_local_url($action, $args=NULL) {
385         global $config;
386         /* XXX: pretty URLs */
387         $extra = '';
388         if ($args) {
389                 foreach ($args as $key => $value) {
390                         $extra .= "&${key}=${value}";
391                 }
392         }
393         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
394         return "http://".$config['site']['server'].'/'.$pathpart."index.php?action=${action}${extra}";
395 }
396
397 function common_date_string($dt) {
398         // XXX: do some sexy date formatting
399         // return date(DATE_RFC822, $dt);
400         return $dt;
401 }
402
403 function common_date_w3dtf($dt) {
404         $t = strtotime($dt);
405         return date(DATE_W3C, $t);
406 }
407
408 function common_redirect($url, $code=307) {
409         static $status = array(301 => "Moved Permanently",
410                                                    302 => "Found",
411                                                    303 => "See Other",
412                                                    307 => "Temporary Redirect");
413         header("Status: ${code} $status[$code]");
414         header("Location: $url");
415         common_element('a', array('href' => $url), $url);
416 }
417
418 function common_broadcast_notice($notice) {
419         // XXX: broadcast notices to remote subscribers
420         // XXX: broadcast notices to SMS
421         // XXX: broadcast notices to Jabber
422         // XXX: broadcast notices to other IM
423         // XXX: use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
424         return true;
425 }
426
427 function common_profile_url($nickname) {
428         return common_local_url('showstream', array('nickname' => $nickname));
429 }
430
431 function common_notice_form() {
432         common_element_start('form', array('id' => 'newnotice', 'method' => 'POST',
433                                                                            'action' => common_local_url('newnotice')));
434         common_textarea('noticecontent', _t('What\'s up?'));
435         common_submit('submit', _t('Send'));
436         common_element_end('form');
437 }
438
439 function common_mint_tag($extra) {
440         global $config;
441         return 
442           'tag:'.$config['tag']['authority'].','.
443           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
444 }
445
446 # Should make up a reasonable root URL
447
448 function common_root_url() {
449         global $config;
450         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
451         return "http://".$config['site']['server'].'/'.$pathpart;
452 }
453
454 # returns $bytes bytes of random data as a hexadecimal string
455 # "good" here is a goal and not a guarantee
456
457 function common_good_rand($bytes) {
458         # XXX: use random.org...?
459         if (file_exists('/dev/urandom')) {
460                 return common_urandom($bytes);
461         } else { # FIXME: this is probably not good enough
462                 return common_mtrand($bytes);
463         }
464 }
465
466 function common_urandom($bytes) {
467         $h = fopen('/dev/urandom', 'rb');
468         # should not block
469         $src = fread($h, $bytes);
470         fclose($h);
471         $enc = '';
472         for ($i = 0; $i < $bytes; $i++) {
473                 $enc .= sprintf("%02x", (ord($src[$i])));
474         }
475         return $enc;
476 }
477
478 function common_mtrand($bytes) {
479         $enc = '';
480         for ($i = 0; $i < $bytes; $i++) {
481                 $enc .= sprintf("%02x", mt_rand(0, 255));
482         }
483         return $enc;
484 }
485
486 function common_timestamp() {
487         return date('YmdHis');
488 }
489         
490 // XXX: set up gettext
491
492 function _t($str) {
493         return $str;
494 }