Project

General

Profile

functions.php

fixed - Magh S, 01/03/2021 06:55 PM

 
1
<?php
2
// ensure this file is being included by a parent file
3
if( !defined( '_JEXEC' ) && !defined( '_VALID_MOS' ) ) die( 'Restricted access' );
4
/**
5
 * @version $Id: functions.php 248 2016-02-26 18:29:50Z soeren $
6
 * @package eXtplorer
7
 * @copyright soeren 2007-2011
8
 * @author The eXtplorer project (http://extplorer.net)
9
 * @author The        The QuiX project (http://quixplorer.sourceforge.net)
10
 * 
11
 * @license
12
 * The contents of this file are subject to the Mozilla Public License
13
 * Version 1.1 (the "License"); you may not use this file except in
14
 * compliance with the License. You may obtain a copy of the License at
15
 * http://www.mozilla.org/MPL/
16
 * 
17
 * Software distributed under the License is distributed on an "AS IS"
18
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
19
 * License for the specific language governing rights and limitations
20
 * under the License.
21
 * 
22
 * Alternatively, the contents of this file may be used under the terms
23
 * of the GNU General Public License Version 2 or later (the "GPL"), in
24
 * which case the provisions of the GPL are applicable instead of
25
 * those above. If you wish to allow use of your version of this file only
26
 * under the terms of the GPL and not to allow others to use
27
 * your version of this file under the MPL, indicate your decision by
28
 * deleting  the provisions above and replace  them with the notice and
29
 * other provisions required by the GPL.  If you do not delete
30
 * the provisions above, a recipient may use your version of this file
31
 * under either the MPL or the GPL."
32
 * 
33
 */
34

    
35
/**
36
 * THESE ARE NUMEROUS HELPER FUNCTIONS FOR THE OTHER INCLUDE FILES
37
 */
38

    
39
function ext_make_link($_action,$_dir,$_item=NULL,$_order=NULL,$_srt=NULL,$languages=NULL, $extra=null) {
40
        // make link to next page
41
        if($_action=="" || $_action==NULL) $_action="list";
42

    
43
        if($_item=="") $_item=NULL;
44
        if($_order==NULL) $_order=$GLOBALS["order"];
45
        if($_srt==NULL) $_srt=$GLOBALS["direction"];
46
        if($languages==NULL) $languages=(isset($GLOBALS["lang"])?$GLOBALS["lang"]:NULL);
47

    
48
        $link=$GLOBALS["script_name"]."?option=com_extplorer&action=".$_action;
49
        if(!is_null($_dir )) {
50
                $link.="&dir=".urlencode($_dir);
51
        }
52
        if($_item!=NULL) $link.="&item=".urlencode($_item);
53
        if($_order!=NULL) $link.="&order=".$_order;
54
        if($_srt!=NULL) $link.="&direction=".$_srt;
55
        if($languages!=NULL) $link.="&lang=".$languages;
56
        if(!is_null($extra)) {
57
                $link .= $extra;
58
        }
59
        return $link;
60
}
61
//------------------------------------------------------------------------------
62
function get_abs_dir($dir) {                        // get absolute path
63
        if( ext_isFTPMode() ) {
64
                if( $dir != '' && $dir[0] != '/' && $dir[1] != ':') {
65
                        $dir = '/'.$dir;
66
                }
67
                return $dir;
68
        }
69
        $abs_dir=file_exists($GLOBALS["home_dir"]) ? $GLOBALS["home_dir"] : $_SERVER["DOCUMENT_ROOT"];
70

    
71
        if($dir!="" && !@stristr( $dir, $abs_dir )) $abs_dir.="/".$dir;
72
        elseif(@stristr( $dir, $abs_dir )) $abs_dir = "/".$dir;
73
        /*else {
74
                $abs_dir = $dir;
75
        }*/
76
        $realpath = str_replace('\\', '/', realpath($abs_dir) );
77
        if( $realpath == '') {
78
                return $abs_dir;
79
        }
80
        else {
81
                return $realpath;
82
        }
83

    
84
        return $realpath;
85
}
86
//------------------------------------------------------------------------------
87
function get_abs_item($dir, $item) {                // get absolute file+path
88
        if( is_array( $item )) {
89
                // FTP Mode
90
                $abs_item = '/' . get_abs_dir($dir)."/".$item['name'];
91
                if( get_is_dir($item)) $abs_item.='/';
92
                return extPathName($abs_item); 
93
        }
94
        return extPathName( get_abs_dir($dir)."/".basename($item) );
95
}
96
/**
97
 * Returns the LS info array from an ftp directory listing
98
 *
99
 * @param unknown_type $dir
100
 * @param unknown_type $item
101
 * @return unknown
102
 */
103
function get_item_info( $dir, $item ) {
104
        $ls = getCachedFTPListing( $dir );
105
        if( empty($ls)) return false;
106
        foreach( $ls as $entry ) {
107
                if( $entry['name'] == $item ) {
108
                        return $entry;
109
                }
110
        }
111
        if( $dir != '') {
112
                return $dir.'/'.$item;
113
        }
114
        return $item;
115
}
116
//------------------------------------------------------------------------------
117
function get_rel_item($dir,$item) {                // get file relative from home
118
        if($dir!="") return $dir."/".$item;
119
        else return $item;
120
}
121
//------------------------------------------------------------------------------
122
function get_is_file( $abs_item) {                // can this file be edited?
123
        if( ext_isFTPMode() && is_array( $abs_item )) {
124
                return empty($abs_item['is_dir']);
125
        } elseif( ext_isFTPMode() ) {
126
                $info = get_item_info( dirname($abs_item), basename($abs_item));
127
                return empty($info['is_dir']);
128
        }
129

    
130
        return @is_file($abs_item);
131
}
132
//------------------------------------------------------------------------------
133
function get_is_dir( $abs_item ) {                // is this a directory?
134
        if( ext_isFTPMode() && is_array( $abs_item )) {
135
                return !empty($abs_item['is_dir']);
136
        }
137
        elseif( ext_isFTPMode() ) {
138
                $info = get_item_info( dirname( $abs_item), basename( $abs_item ));
139
                return !empty($info['is_dir']);
140
        }
141
        return @is_dir( $abs_item );
142
}
143
//------------------------------------------------------------------------------
144
function parse_file_type( $abs_item ) {                // parsed file type (d / l / -)
145

    
146
        if(@get_is_dir($abs_item)) return "d";
147
        if(@is_link($abs_item)) return "l";
148
        return "-";
149
}
150
//------------------------------------------------------------------------------
151
function get_file_perms( $item) {                // file permissions
152
        if( ext_isFTPMode() && isset($item['rights']) ) {
153
                $perms = decoct( bindec( decode_ftp_rights($item['rights']) ) );
154
                return $perms;
155
        } elseif( is_numeric($item['mode'])) { //SFTP
156
                return @decoct($item['mode']  & 0777);
157
        }        
158
        return @decoct(@fileperms( $item ) & 0777);
159
}
160

    
161
function get_languages() {
162
        $langfiles = extReadDirectory( _EXT_PATH.'/languages' );
163
        $langs = array();
164
        foreach( $langfiles as $lang ) {
165
                if( stristr( $lang, '_mimes') || $lang == 'index.html') continue;
166
                $langs[basename( $lang, '.php' )] = ucwords(str_replace( '_', ' ', basename( $lang, '.php' )));
167
        }
168
        return $langs;
169
}
170
//------------------------------------------------------------------------------
171
function parse_file_perms($mode) {                // parsed file permisions
172

    
173
        if(strlen($mode)<3) return "---------";
174
        $parsed_mode="";
175
        for($i=0;$i<3;$i++) {
176
                // read
177
                if(($mode[$i] & 04)) $parsed_mode .= "r";
178
                else $parsed_mode .= "-";
179
                // write
180
                if(($mode[$i] & 02)) $parsed_mode .= "w";
181
                else $parsed_mode .= "-";
182
                // execute
183
                if(($mode[$i] & 01)) $parsed_mode .= "x";
184
                else $parsed_mode .= "-";
185
        }
186
        return $parsed_mode;
187
}
188

    
189
function decode_ftp_rights( $rights) {
190
        $parsed_mode="";
191
        for($i=0;$i<9;$i++) {
192
                // read
193
                if( $rights[$i] != '-' ) {
194
                        $parsed_mode .= '1';
195
                }
196
                else {
197
                        $parsed_mode.= '0';
198
                }
199
        }
200

    
201
        return $parsed_mode;
202
}
203
//------------------------------------------------------------------------------
204
function get_file_size( $abs_item) {                // file size
205
        return @$GLOBALS['ext_File']->filesize( $abs_item );
206
}
207
//------------------------------------------------------------------------------
208

    
209
function get_dir_size($dir) {
210
        if(is_file($dir)) return array('size'=>filesize($dir),'howmany'=>0);
211
        if($dh=opendir($dir)) {
212
                $size=0;
213
                $n = 0;
214
                while(($file=readdir($dh))!==false) {
215
                        if($file=='.' || $file=='..') continue;
216
                        $n++;
217
                        $data = get_dir_size($dir.'/'.$file);
218
                        $size += $data['size'];
219
                        $n += $data['howmany'];
220
                }
221
                closedir($dh);
222
                return array('size'=>$size,'howmany'=>$n);
223
        }
224
        return array('size'=>0,'howmany'=>0);
225
}
226

    
227
function parse_file_size($bytes, $precision = 2) {
228
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
229
    if( !is_float($bytes)) {
230
            $bytes = (float)sprintf("%u", $bytes);
231
    }
232
    $bytes = max($bytes, 0);
233
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
234
    $pow = min($pow, count($units) - 1);
235
  
236
    $bytes /= pow(1024, $pow);
237
  
238
    return round($bytes, $precision) . ' ' . $units[$pow];
239
} 
240
//------------------------------------------------------------------------------
241
function get_file_date( $item) {                // file date
242
        return @$GLOBALS['ext_File']->filemtime( $item );
243
}
244
//------------------------------------------------------------------------------
245
function parse_file_date($date) {                // parsed file date
246
        if ($date) {
247
                return @date($GLOBALS["date_fmt"],$date);
248
        } else {
249
                return " (unknown) ";
250
        }
251
}
252
//------------------------------------------------------------------------------
253
function get_is_image( $abs_item ) {                // is this file an image?
254
        if(!get_is_file($abs_item)) return false;
255
        if( isset($abs_item['name'])) {
256
                $abs_item = $abs_item['name'];
257
        }
258
        return in_array(pathinfo($abs_item,PATHINFO_EXTENSION ), $GLOBALS["images_ext"]);
259
}
260
//-----------------------------------------------------------------------------
261
function get_is_editable( $abs_item ) {                // is this file editable?
262
        if(!get_is_file( $abs_item )) return false;
263
        
264
        if( is_array( $abs_item ) ) {
265
                $abs_item = $abs_item['name'];
266
        }
267

    
268
        if(in_array(".".strtolower(pathinfo($abs_item,PATHINFO_EXTENSION )), $GLOBALS["editable_ext"])) {
269
                return true;
270
        }
271

    
272
        return strpos( basename($abs_item), "." ) ? false : true;
273

    
274
}
275
//-----------------------------------------------------------------------------
276
function get_mime_type( $abs_item, $query) {        // get file's mimetype
277

    
278
        if(get_is_dir( $abs_item )) {                        // directory
279
                $mime_type        = $GLOBALS["super_mimes"]["dir"][0];
280
                $image                = $GLOBALS["super_mimes"]["dir"][1];
281

    
282
                if($query=="img") return $image;
283
                else return $mime_type;
284
        }
285
        $extra = $GLOBALS['ext_File']->is_link( $abs_item ) ? ' ('.$GLOBALS['mimes']['symlink'].')' : '';
286
        if( ext_isFTPMode() && isset($abs_item['name']) ) {
287
                $abs_item=$abs_item['name'];
288
        }
289
                                // mime_type
290
        foreach($GLOBALS["used_mime_types"] as $mime) {
291
                list($desc,$img,$ext)        = $mime;
292

    
293
                if(stristr(basename($abs_item), $ext )) {
294
                        $mime_type        = $desc;
295
                        $image                = $img;
296
                        if($query=="img") return $image;
297
                        else return $mime_type . $extra;
298
                }
299
        }
300

    
301
        if((function_exists("is_executable") &&
302
                @is_executable( $abs_item )) ||
303
                @stristr($abs_item,$GLOBALS["super_mimes"]["exe"][2]))
304
        {                                                // executable
305
                $mime_type        = $GLOBALS["super_mimes"]["exe"][0];
306
                $image                = $GLOBALS["super_mimes"]["exe"][1];
307
        } else {                                        // unknown file
308
                $mime_type        = $GLOBALS["super_mimes"]["file"][0];
309
                $image                = $GLOBALS["super_mimes"]["file"][1];
310
        }
311

    
312
        if($query=="img") {
313
                return $image;
314
        }
315
        else {
316
                return $mime_type . $extra;
317
        }
318
}
319
//------------------------------------------------------------------------------
320
function get_show_item($dir, $item) {                // show this file?
321
        if( is_array( $item )) {
322
                $item = $item['name'];
323
        }
324
        if($item == "." || $item == ".." ||
325
                (substr($item,0,1)=="." && $GLOBALS["show_hidden"]==false)) return false;
326

    
327
        if($GLOBALS["no_access"]!="" && @preg_match($GLOBALS["no_access"],$item)) return false;
328

    
329
        if($GLOBALS["show_hidden"]==false) {
330
                $dirs=explode("/",$dir);
331
                foreach($dirs as $i) if(substr($i,0,1)==".") return false;
332
        }
333

    
334
        return true;
335
}
336
//------------------------------------------------------------------------------
337
function get_dir_list( $dir='' ) {
338
        if( ext_isFTPMode()) {
339
                $files = getCachedFTPListing(empty($dir) ? '.' : $dir);
340
        } else {
341
                $files = extReadDirectory( get_abs_dir( $dir), '.', false, true );
342
        }
343

    
344
        $dirs =array();
345
        foreach( $files as $item) {
346
                $itemname = ext_isFTPMode() ? (empty($dir) ? '' : $dir.'/') .$item['name'] :  $item;
347

    
348
                $itemname = str_replace( '\\', '/', $itemname );
349
                if( get_is_dir($item)) {
350
                        $index = str_replace( 
351
                                                str_replace('\\', '/', $GLOBALS['home_dir'].$GLOBALS['separator']), 
352
                                                        '', $itemname );
353

    
354
                        $dirs[$index]= basename($index);
355
                }
356
        }
357

    
358
        return $dirs;
359
}
360
/**
361
 * Returns select lists with all the subdirectories along the current directory path
362
 *
363
 * @param string $dir
364
 * @return string
365
 */
366
function get_dir_selects( $dir ) {
367
        $dirs = explode( "/", str_replace( "\\", '/', $dir ) );
368

    
369
        $subdirs = get_dir_list();
370
        if( sizeof( $subdirs ) > 0) {
371
                $subdirs = array_merge(Array('ext_disabled' => '-'), $subdirs );
372
        }
373

    
374
        if( empty($dirs[0]) ) array_shift($dirs);
375
        $dirsCopy = $dirs;
376
        $implode = '';
377
        $selectedDir = @$dirs[0];
378
        foreach( $subdirs as $index => $val ) {
379
                if ($GLOBALS['use_mb']) {
380
                        if (mb_detect_encoding($val) == 'ASCII') {
381
                                $subdirs[$index] = utf8_encode($val);
382
                        } else {
383
                                $subdirs[$index] = $val;
384
                        }
385
                } else {
386
                        $subdirs[$index] = utf8_encode($val);
387
                }
388
        }
389

    
390
        $dir_links = ext_selectList('dirselect1', $selectedDir, $subdirs, 1, '', 'onchange="theDir=this.options[this.selectedIndex].value;if(theDir!=\'ext_disabled\' ) chDir(theDir);"' );
391
        $i = 2;
392
        foreach( $dirs as $directory ) {
393
                if( $directory != "" ) {
394
                        $implode .= $directory;
395
                        $next = next($dirsCopy);
396
                        $subdirs = get_dir_list( $implode );
397

    
398
                        foreach( $subdirs as $index => $val ) {
399
                                unset( $subdirs[$index]);
400
                                if ($GLOBALS['use_mb']) {
401
                                        if (mb_detect_encoding($index) == 'ASCII') {
402
                                                if (mb_detect_encoding($val) == 'ASCII') {
403
                                                        $subdirs[utf8_encode($index)] = utf8_encode($val);
404
                                                } else {
405
                                                        $subdirs[utf8_encode($index)] = $val;
406
                                                }
407
                                        } else {
408
                                                if (mb_detect_encoding($val) == 'ASCII') {
409
                                                        $subdirs[$index] = utf8_encode($val);
410
                                                } else {
411
                                                        $subdirs[$index] = $val;
412
                                                }
413
                                        }
414
                                } else {
415
                                        $subdirs[utf8_encode($index)] = utf8_encode($val);
416
                                }
417
                        }
418
                        if( $next !== false ) {
419
                                $selectedDir .= '/'.$next;
420
                        } else {
421
                                if( sizeof( $subdirs ) > 0) {
422
                                        $subdirs = array_merge(Array('ext_disabled' => '-'), $subdirs );
423
                                }
424
                        }
425
                        $dir_links .= ' / '.ext_selectList('dirselect'.$i++, $selectedDir, $subdirs, 1, '', 'onchange="theDir=this.options[this.selectedIndex].value;if(theDir!=\'ext_disabled\' ) chDir(theDir);"' );
426
                        $implode .= '/';
427
                }
428

    
429
        }
430
        //echo '<pre>'.htmlspecialchars($dir_links).'</pre>';exit;
431
        return $dir_links;
432
}
433
//------------------------------------------------------------------------------
434
function ext_copy_dir($source,$dest) {                // copy dir
435
        $ok = true;
436
        $source = str_replace( '\\', '/', $source );
437
        $dest = str_replace( '\\', '/', $dest );
438
        if(!@mkdir($dest,0777)) return false;
439
        $itemlist = extReadDirectory( $source, '.', true, true );
440
        if( empty( $itemlist )) return true;
441

    
442
        foreach( $itemlist as $file ) {
443
                if(($file==".." || $file==".")) continue;
444
                $file = str_replace( '\\', '/', $file );
445
                $new_dest = str_replace( $source, $dest, $file );
446

    
447
                if(@is_dir($file)) {
448
                        @mkdir($new_dest,0777);
449
                } else {
450
                        $ok=@copy($file,$new_dest);
451
                }
452
        }
453

    
454
        return $ok;
455
}
456

    
457
//------------------------------------------------------------------------------
458
function remove($item) {                        // remove file / dir
459

    
460
        if( !is_link( $item )) {
461
                $item = realpath($item);
462
        }
463
        $ok = true;
464
        if( is_link($item) ||  is_file($item)) 
465
        $ok =  unlink($item);
466
        elseif( @is_dir($item)) {
467

    
468
                if(($handle= opendir($item))===false) 
469
                ext_Result::sendResult('delete', false, basename($item).": ".$GLOBALS["error_msg"]["opendir"]);
470

    
471
                while(($file=readdir($handle))!==false) {
472
                        if(($file==".." || $file==".")) continue;
473

    
474
                        $new_item = $item."/".$file;
475
                        if(!file_exists($new_item)) 
476
                        ext_Result::sendResult('delete', false, basename($item).": ".$GLOBALS["error_msg"]["readdir"]);
477
                        //if(!get_show_item($item, $new_item)) continue;
478

    
479
                        if( @is_dir($new_item)) {
480
                                $ok=remove($new_item);
481
                        } else {
482
                                $ok= unlink($new_item);
483
                        }
484
                }
485

    
486
                closedir($handle);
487
                $ok=@rmdir($item);
488
        }
489
        return $ok;
490
}
491
function chmod_recursive($item, $mode) {                        // chmod file / dir
492
        $ok = true;
493

    
494
        if(@is_link($item) || @is_file($item)) {
495
                $ok=@chmod( $item, $mode );
496
                if($ok) ext_Result::add_message($GLOBALS['messages']['permchange'].' '.$new_item);
497
                else ext_Result::add_error($GLOBALS['error_msg']['permchange'].' '.$new_item);
498
        }
499
        elseif(@is_dir($item)) {
500
                if(($handle=@opendir($item))===false) {
501

    
502
                        ext_Result::add_error(basename($item).": ".$GLOBALS["error_msg"]["opendir"]);
503
                        return false; 
504
                }
505

    
506
                while(($file=readdir($handle))!==false) {
507
                        if(($file==".." || $file==".")) continue;
508

    
509
                        $new_item = $item."/".$file;
510
                        if(!@file_exists($new_item)) {
511
                                ext_Result::add_error(basename($item).": ".$GLOBALS["error_msg"]["readdir"]);
512
                                continue; 
513
                        }
514
                        //if(!get_show_item($item, $new_item)) continue;
515

    
516
                        if(@is_dir($new_item)) {
517
                                $ok=chmod_recursive($new_item, $mode);
518
                        } else {
519
                                $ok=@chmod($new_item, $mode);
520
                                if($ok) ext_Result::add_message($GLOBALS['messages']['permchange'].' '.$new_item);
521
                                else ext_Result::add_error($GLOBALS['error_msg']['permchange'].' '.$new_item);
522
                        }
523
                }
524
                closedir($handle);
525
                if( @is_dir( $item )) {
526
                        $bin = decbin( $mode );
527
                        // when we chmod a directory we must care for the permissions
528
                        // to prevent that the directory becomes not readable (when the "execute bits" are removed)
529
                        $bin = substr_replace( $bin, '1', 2, 1 ); // set 1st x bit to 1
530
                        $bin = substr_replace( $bin, '1', 5, 1 );// set  2nd x bit to 1
531
                        $bin = substr_replace( $bin, '1', 8, 1 );// set 3rd x bit to 1
532
                        $mode = bindec( $bin ); 
533
                }
534
                $ok=@chmod( $item, $mode );
535
                if($ok) ext_Result::add_message($GLOBALS['messages']['permchange'].' '.$item);
536
                else ext_Result::add_error($GLOBALS['error_msg']['permchange'].' '.$item);
537
        }
538

    
539
        return $ok;
540
}
541
//------------------------------------------------------------------------------
542
function get_max_file_size() {                        // get php max_upload_file_size
543
        return calc_php_setting_bytes( ini_get("upload_max_filesize") );
544
}
545
function get_max_upload_limit() {
546
        return calc_php_setting_bytes( ini_get('post_max_size'));
547
}
548

    
549
function calc_php_setting_bytes( $value ) {
550
        switch(strtoupper(substr($value,-1))) {
551
                case 'G':
552
                $value = substr($value,0,-1);
553
                $value = round($value*1073741824);
554
                break;
555
        case 'M':
556
                $value = substr($value,0,-1);
557
                $value = round($value*1048576);
558
                break;
559
        case 'K':
560
                $value = substr($value,0,-1);
561
                $value = round($value*1024);
562
                break;
563
        }
564

    
565
        return $value;
566
}
567
//------------------------------------------------------------------------------
568
function down_home($abs_dir) {                        // dir deeper than home?
569
        if( ext_isFTPMode() ) {
570
                return true;
571
        }
572
        $real_home = @realpath($GLOBALS["home_dir"]);
573
        $real_dir = @realpath($abs_dir);
574
        if( $real_dir == '' ) $real_dir = dirname( $abs_dir );
575
        if( $real_home == '' ) $real_home = $_SERVER['DOCUMENT_ROOT'];
576
        //echo 'NOW: $real_home = '.$real_home;
577
        //echo ', $real_dir = '.$real_dir;
578

    
579
        if(@stristr($abs_dir,"\\.\\.")) return false;
580
        if(strcmp($real_home,@substr($real_dir,0,strlen($real_home)))) {
581
                return false;
582
        }
583
        return true;
584
}
585
//------------------------------------------------------------------------------
586
function id_browser() {
587
        $browser=$GLOBALS['__SERVER']['HTTP_USER_AGENT'];
588

    
589
        if(preg_match('/Opera(\/| )([0-9]\.[0-9]{1,2})/', $browser)) {
590
                 return 'OPERA';
591
        } else if(preg_match('/MSIE ([0-9]\.[0-9]{1,2})/', $browser)) {
592
                 return 'IE';
593
        } else if(preg_match('/OmniWeb\/([0-9]\.[0-9]{1,2})/', $browser)) {
594
                 return 'OMNIWEB';
595
        } else if(preg_match('/(Konqueror\/)(.*)/', $browser)) {
596
                 return 'KONQUEROR';
597
        } else if(preg_match('/Mozilla\/([0-9]\.[0-9]{1,2})/', $browser)) {
598
                return 'MOZILLA';
599
        } else {
600
                return 'OTHER';
601
        }
602
}
603
function ext_isArchive( $file ) {
604
  
605
        $file_info = pathinfo($file);
606
        $ext = @strtolower($file_info["extension"]);
607
        $archive_types = array("tar", "gz", "tgz", "zip", "bzip2", "bz2", "tbz", 'rar');
608
        if( in_array( $ext, $archive_types )) {
609
                return true;
610
        }
611
        return false;
612
}
613
if( !extension_loaded('posix') ) {
614
        function posix_geteuid() {
615
                return false;
616
        }
617
        function posix_getpwnam() {
618

    
619
        }
620
}
621

    
622
//------------------------------------------------------------------------------
623
/**
624
 * Checks if the User Agent String identifies the browser as Internet Explorer
625
 *
626
 * @return boolean
627
 */
628
function ext_isWindows() {
629
        if(empty($GLOBALS['isWindows'])) {
630
                $GLOBALS['isWindows'] = substr(PHP_OS, 0, 3) == 'WIN';
631
        }
632
        return $GLOBALS['isWindows'];
633
}
634
/**
635
 * Returns the valid directory separator for this OS & Webserver combination
636
 *
637
 * @return string
638
 */
639
function ext_getSeparator() {
640
        if( defined( 'DIRECTORY_SEPARATOR')) {
641
                return DIRECTORY_SEPARATOR;
642
        }
643
        elseif (@preg_match('/Microsoft|WebSTAR|Xitami/', $_SERVER['SERVER_SOFTWARE']) ) {
644
                return '\\';
645
        } else {
646
                return '/';
647
        }
648
}
649
/**
650
 * Checks if the User Agent String identifies the browser as Internet Explorer
651
 *
652
 * @return boolean
653
 */
654
function ext_isIE() {
655
        return (preg_match('/MSIE ([0-9]\.[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']));
656
}
657

    
658
/**
659
 * Prints an HTML dropdown box named $name using $arr to
660
 * load the drop down.        If $value is in $arr, then $value
661
 * will be the selected option in the dropdown.
662
 * @author gday
663
 * @author soeren
664
 * 
665
 * @param string $name The name of the select element
666
 * @param string $value The pre-selected value
667
 * @param array $arr The array containting $key and $val
668
 * @param int $size The size of the select element
669
 * @param string $multiple use "multiple=\"multiple\" to have a multiple choice select list
670
 * @param string $extra More attributes when needed
671
 * @return string HTML drop-down list
672
 */
673
function ext_selectList($name, $selectedkey, $arr, $size=1, $multiple="", $extra="") {
674
        $html = '';
675
        if( !empty( $arr ) ) {
676
                $html = "<select class=\"inputbox\" name=\"$name\" id=\"$name\" size=\"$size\" $multiple $extra>\n";
677

    
678
                foreach($arr as $key => $value) {
679
                        $selected = "";
680
                        if( is_array( $selectedkey )) {
681
                            if( in_array( $key, $selectedkey )) {
682
                                        $selected = "selected=\"selected\"";
683
                                }
684
                        }
685
                        else {
686
                            if(strtolower($selectedkey) == strtolower($key) ) {
687
                                        $selected = "selected=\"selected\"";
688
                                }
689
                        }
690
                        if( $value == '-') {
691
                                //$selected .= ' disabled="disabled"';
692
                            $value = '- - - - -';
693
                        }
694
                        $html .= "<option value=\"$key\" $selected>$value";
695
                        $html .= "</option>\n";
696
                }
697

    
698
                $html .= "</select>\n";
699
        }
700
        return $html;
701
}
702
function ext_scriptTag( $src = '', $script = '') {
703
        if( $src!='') {
704
                return '<script type="text/javascript" src="'.$src.'"></script>';
705
        }
706
        if( $script != '') {
707
                return '<script type="text/javascript">'.$script.'</script>';
708
        }
709
}
710
function ext_alertBox( $msg ) {
711
        return ext_scriptTag('', 'Ext.Msg.alert( \''.$GLOBALS["error_msg"]['message'].'\', \''. @mysql_escape_string( $msg ) .'\' );' );
712
}
713
function ext_successBox( $msg ) {
714
        return ext_scriptTag('', 'Ext.msgBoxSlider.msg( \''.ext_Lang::msg('success', true ).'\', \''. @mysql_escape_string( $msg ) .'\' );' );
715
}
716
function ext_docLocation( $url ) {
717
        return ext_scriptTag('', 'document.location=\''. $url .'\';' );
718
}
719
function ext_isXHR() {
720
        return strtolower(extGetParam($_SERVER,'HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest'
721
                || strtolower(extGetParam($_POST,'requestType')) == 'xmlhttprequest';
722
}
723
function ext_exit() {
724
        global $mainframe;
725
        if( class_exists( 'jfactory' )) {
726
                $app = jfactory::getApplication();
727
                $app->close();
728
        }
729
        if( is_callable( array( $mainframe, 'close' ) ) ) {
730
                $mainframe->close();
731
        } else {
732
                session_write_close();
733
                exit;
734
        }
735
}
736
function ext_isJoomla( $version='', $operator='=', $compare_minor_versions=true) {
737
        $this_version = '';
738
        if( !empty($GLOBALS['_VERSION']) && is_object($GLOBALS['_VERSION'])) {
739
                $jversion =& $GLOBALS['_VERSION'];
740
                $this_version = $jversion->RELEASE .'.'. $jversion->DEV_LEVEL;
741
        }
742
        elseif ( class_exists('JVersion') ) {
743
                $jversion = new JVersion();
744
                $this_version = $jversion->RELEASE .'.'. $jversion->DEV_LEVEL;
745
        } else {
746
                return false;
747
        }
748
        if( empty( $version ) ) {
749
                return !empty($this_version);
750
        }
751
        $allowed_operators = array( '<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne' );
752

    
753
        if( $compare_minor_versions ) {
754
                $this_version = $jversion->RELEASE;
755
        }
756
        if( in_array($operator, $allowed_operators )) {
757
        
758
                return version_compare( $this_version, $version, $operator );
759
        }
760
        return false;
761
}
762
/**
763
 * Raise the memory limit when it is lower than the needed value
764
 *
765
 * @param string $setLimit Example: 16M
766
 */
767
function ext_RaiseMemoryLimit( $setLimit ) {
768

    
769
        $memLimit = @ini_get('memory_limit');
770

    
771
        if( stristr( $memLimit, 'k') ) {
772
                $memLimit = str_replace( 'k', '', str_replace( 'K', '', $memLimit )) * 1024;
773
        }
774
        elseif( stristr( $memLimit, 'm') ) {
775
                $memLimit = str_replace( 'm', '', str_replace( 'M', '', $memLimit )) * 1024 * 1024;
776
        }
777

    
778
        if( stristr( $setLimit, 'k') ) {
779
                $setLimitB = str_replace( 'k', '', str_replace( 'K', '', $setLimit )) * 1024;
780
        }
781
        elseif( stristr( $setLimit, 'm') ) {
782
                $setLimitB = str_replace( 'm', '', str_replace( 'M', '', $setLimit )) * 1024 * 1024;
783
        }
784

    
785
        if( $memLimit < $setLimitB ) {
786
                @ini_set('memory_limit', $setLimit );
787
        }
788
}
789
/**
790
 * Reads a file and sends them in chunks to the browser
791
 * This should overcome memory problems
792
 * http://www.php.net/manual/en/function.readfile.php#54295
793
 *
794
 * @since 1.4.1
795
 * @param string $filename
796
 * @param boolean $retbytes
797
 * @return mixed
798
 */
799
function readFileChunked($filename,$retbytes=true) {
800
        $chunksize = 1*(1024*1024); // how many bytes per chunk
801
        $buffer = '';
802
        $cnt =0;
803
        // $handle = fopen($filename, 'rb');
804
        $handle = fopen($filename, 'rb');
805
        if ($handle === false) {
806
                return false;
807
        }
808
        while (!feof($handle)) {
809
                $buffer = fread($handle, $chunksize);
810
                echo $buffer;
811
                sleep(1);
812
                ob_flush();
813
                flush();
814
                if ($retbytes) {
815
                        $cnt += strlen($buffer);
816
                }
817
        }
818
        $status = fclose($handle);
819
        if ($retbytes && $status) {
820
                return $cnt; // return num. bytes delivered like readfile() does.
821
        }
822
        return $status;
823
}
824
//implements file_put_contents function for compatability with PHP < 4.3
825
if ( ! function_exists('file_put_contents') ) {
826
        function file_put_contents ( $filename, $filecont ){
827
                $handle = fopen( $filename, 'w' );
828
                if ( is_array($filecont) ) {
829
                        $size = 0;
830
                        foreach ( $filecont as $filestring ) {
831
                                fwrite( $handle, $filestring );
832
                                $size += strlen( $filestring );
833
                        }
834
                        fclose($handle);
835
                        return $size;
836
                } else {
837
                        fwrite( $handle, $filecont );
838
                        fclose($handle);
839
                        return strlen( $filecont );
840
                }
841
        }
842
}
843
if ( ! function_exists('scandir') ) {
844
function scandir($dir,$listDirectories=false, $skipDots=true) {
845
        $dirArray = array();
846
        if ($handle = opendir($dir)) {
847
                while (false !== ($file = readdir($handle))) {
848
                        if (($file != "." && $file != "..") || $skipDots == true) {
849
                                if($listDirectories == false) { if(@is_dir($file)) { continue; } }
850
                                array_push($dirArray,basename($file));
851
                        }
852
                }
853
                closedir($handle);
854
        }
855
        return $dirArray;
856
}
857
}
858

    
859
/**
860
 * Page generation time
861
 * @package Joomla
862
 */
863
class extProfiler {
864
        /** @var int Start time stamp */
865
        var $start=0;
866
        /** @var string A prefix for mark messages */
867
        var $prefix='';
868

    
869
        /**
870
        * Constructor
871
        * @param string A prefix for mark messages
872
        */
873
        function __construct( $prefix='' ) {
874
                $this->start = $this->getmicrotime();
875
                $this->prefix = $prefix;
876
        }
877

    
878
        /**
879
        * @return string A format message of the elapsed time
880
        */
881
        function mark( $label ) {
882
                return sprintf ( "\n<div class=\"profiler\">$this->prefix %.3f $label</div>", $this->getmicrotime() - $this->start );
883
        }
884

    
885
        /**
886
        * @return float The current time in milliseconds
887
        */
888
        function getmicrotime(){
889
                list($usec, $sec) = explode(" ",microtime());
890
                return ((float)$usec + (float)$sec);
891
        }
892
}
893
/**
894
* Utility class for all HTML drawing classes
895
* @package eXtplorer
896
*/
897
class extHTML {
898
    static function loadExtJS() {
899
                $scripts[] = array('dir' => 'scripts/editarea/', 'file' => 'edit_area_full_with_plugins.js');
900
                $scripts[] = array('dir' => 'scripts/extjs3/adapter/ext/', 'file' => 'ext-base.js');
901
                $scripts[] = array('dir' => 'scripts/extjs3/', 'file' => 'ext-all.js');
902
                $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.ondemandload/', 'file' => 'scriptloader.js');
903
                $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.editareaadapater/', 'file' => 'ext-editarea-adapter.js');
904
                $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.statusbar/', 'file' => 'ext-statusbar.js');
905
                $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.fileuploadfield/', 'file' => 'ext-fileUploadField.js');
906
                $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.locationbar/', 'file' => 'Ext.ux.LocationBar.js');
907
                
908
                $styles[] = array('dir' => 'scripts/extjs3/resources/css/', 'file' => 'ext-all.css');
909
                $styles[] = array('dir' => 'scripts/extjs3-ext/ux.locationbar/', 'file' => 'LocationBar.css');
910
                $styles[] = array('dir' => 'scripts/extjs3-ext/ux.fileuploadfield/', 'file' => 'fileuploadfield.css');
911
                $scriptTag = '';
912
                if( !empty($_GET['nofetchscript']) || !empty( $_COOKIE['nofetchscript'])) {
913
                        foreach( $scripts as $script ) {
914
                                $scriptTag .= '<script type="text/javascript" src="'.$script['dir'].$script['file'].'"></script>';
915
                        }
916
                        foreach( $styles as $style ) {
917
                                $scriptTag .= '<link type="text/css" href="'.$style['dir'].$style['file'].'" rel="stylesheet" />';
918
                        }                        
919
                } else {
920
                        $scriptTag = '
921
                <script type="text/javascript" src="'. _EXT_URL . '/fetchscript.php?'
922
                        .'&amp;subdir[]=scripts/editarea/&amp;file[]=edit_area_full_with_plugins.js'
923
                        .'&amp;subdir[]=scripts/extjs3/adapter/ext/&amp;file[]=ext-base.js'
924
                        .'&amp;subdir[]=scripts/extjs3/&amp;file[]=ext-all.js'
925
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.ondemandload/&amp;file[]=scriptloader.js'
926
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.editareaadapater/&amp;file[]=ext-editarea-adapter.js'
927
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.statusbar/&amp;file[]=ext-statusbar.js'
928
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.fileuploadfield/&amp;file[]=ext-fileUploadField.js'
929
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.locationbar/&amp;file[]=Ext.ux.LocationBar.js'
930
                        .'&amp;gzip=1"></script>';
931
                        $scriptTag .= '
932
                <link rel="stylesheet" href="'. _EXT_URL . '/fetchscript.php?'
933
                        .'subdir[]=scripts/extjs3/resources/css/&amp;file[]=ext-all.css'
934
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.locationbar/&amp;file[]=LocationBar.css'
935
                        .'&amp;subdir[]=scripts/extjs3-ext/ux.fileuploadfield/&amp;file[]=fileuploadfield.css'
936
                        .'&amp;gzip=1" />';
937
                }
938
                $scriptTag .= '
939
                <script type="text/javascript" src="'. $GLOBALS['script_name'].'?option=com_extplorer&amp;action=include_javascript&amp;file=functions.js"></script>
940
                <script type="text/javascript" >editAreaLoader.baseURL = "'. _EXT_URL .'/scripts/editarea/";</script>';
941

    
942
        
943
                if (defined('EXT_STANDALONE')) {
944
                        $GLOBALS['mainframe']->addcustomheadtag($scriptTag);
945
                } else {
946
                        echo $scriptTag;
947
                }
948
        }
949

    
950
    static function makeOption( $value, $text='', $value_name='value', $text_name='text' ) {
951
                $obj = new stdClass;
952
                $obj->$value_name = $value;
953
                $obj->$text_name = trim( $text ) ? $text : $value;
954
                return $obj;
955
        }
956

    
957
    static function writableCell( $folder, $relative=1, $text='', $visible=1 ) {
958
        $writeable                 = '<b><font color="green">Writeable</font></b>';
959
        $unwriteable         = '<b><font color="red">Unwriteable</font></b>';
960

    
961
          echo '<tr>';
962
          echo '<td class="item">';
963
        echo $text;
964
        if ( $visible ) {
965
                echo $folder . '/';
966
        }
967
        echo '</td>';
968
          echo '<td align="left">';
969
        if ( $relative ) {
970
                echo is_writable( "../$folder" )         ? $writeable : $unwriteable;
971
        } else {
972
                echo is_writable( "$folder" )                 ? $writeable : $unwriteable;
973
        }
974
        echo '</td>';
975
          echo '</tr>';
976
  }
977

    
978
        /**
979
        * Generates an HTML select list
980
        * @param array An array of objects
981
        * @param string The value of the HTML name attribute
982
        * @param string Additional HTML attributes for the <select> tag
983
        * @param string The name of the object variable for the option value
984
        * @param string The name of the object variable for the option text
985
        * @param mixed The key that is selected
986
        * @returns string HTML for the select list
987
        */
988
    static function selectList( &$arr, $tag_name, $tag_attribs, $key, $text, $selected=NULL ) {
989
                // check if array
990
                if ( is_array( $arr ) ) {
991
                        reset( $arr );
992
                }
993

    
994
                $html         = "\n<select name=\"$tag_name\" $tag_attribs>";
995
                $count         = count( $arr );
996

    
997
                for ($i=0, $n=$count; $i < $n; $i++ ) {
998
                        $k = $arr[$i]->$key;
999
                        $t = $arr[$i]->$text;
1000
                        $id = ( isset($arr[$i]->id) ? @$arr[$i]->id : null);
1001

    
1002
                        $extra = '';
1003
                        $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
1004
                        if (is_array( $selected )) {
1005
                                foreach ($selected as $obj) {
1006
                                        $k2 = $obj->$key;
1007
                                        if ($k == $k2) {
1008
                                                $extra .= " selected=\"selected\"";
1009
                                                break;
1010
                                        }
1011
                                }
1012
                        } else {
1013
                                $extra .= ($k == $selected ? " selected=\"selected\"" : '');
1014
                        }
1015
                        $html .= "\n\t<option value=\"".$k."\"$extra>" . $t . "</option>";
1016
                }
1017
                $html .= "\n</select>\n";
1018

    
1019
                return $html;
1020
        }
1021

    
1022
        /**
1023
        * Writes a select list of integers
1024
        * @param int The start integer
1025
        * @param int The end integer
1026
        * @param int The increment
1027
        * @param string The value of the HTML name attribute
1028
        * @param string Additional HTML attributes for the <select> tag
1029
        * @param mixed The key that is selected
1030
        * @param string The printf format to be applied to the number
1031
        * @returns string HTML for the select list
1032
        */
1033
    static function integerSelectList( $start, $end, $inc, $tag_name, $tag_attribs, $selected, $format="" ) {
1034
                $start         = intval( $start );
1035
                $end         = intval( $end );
1036
                $inc         = intval( $inc );
1037
                $arr         = array();
1038

    
1039
                for ($i=$start; $i <= $end; $i+=$inc) {
1040
                        $fi = $format ? sprintf( "$format", $i ) : "$i";
1041
                        $arr[] = extHTML::makeOption( $fi, $fi );
1042
                }
1043

    
1044
                return extHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
1045
        }
1046

    
1047
        /**
1048
        * Writes a select list of month names based on Language settings
1049
        * @param string The value of the HTML name attribute
1050
        * @param string Additional HTML attributes for the <select> tag
1051
        * @param mixed The key that is selected
1052
        * @returns string HTML for the select list values
1053
        */
1054
    static function monthSelectList( $tag_name, $tag_attribs, $selected ) {
1055
                $arr = array(
1056
                        extHTML::makeOption( '01', _JAN ),
1057
                        extHTML::makeOption( '02', _FEB ),
1058
                        extHTML::makeOption( '03', _MAR ),
1059
                        extHTML::makeOption( '04', _APR ),
1060
                        extHTML::makeOption( '05', _MAY ),
1061
                        extHTML::makeOption( '06', _JUN ),
1062
                        extHTML::makeOption( '07', _JUL ),
1063
                        extHTML::makeOption( '08', _AUG ),
1064
                        extHTML::makeOption( '09', _SEP ),
1065
                        extHTML::makeOption( '10', _OCT ),
1066
                        extHTML::makeOption( '11', _NOV ),
1067
                        extHTML::makeOption( '12', _DEC )
1068
                );
1069

    
1070
                return extHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
1071
        }
1072

    
1073
        /**
1074
        * Writes a yes/no select list
1075
        * @param string The value of the HTML name attribute
1076
        * @param string Additional HTML attributes for the <select> tag
1077
        * @param mixed The key that is selected
1078
        * @returns string HTML for the select list values
1079
        */
1080
    static function yesnoSelectList( $tag_name, $tag_attribs, $selected, $yes=_CMN_YES, $no=_CMN_NO ) {
1081
                $arr = array(
1082
                extHTML::makeOption( '0', $no ),
1083
                extHTML::makeOption( '1', $yes ),
1084
                );
1085

    
1086
                return extHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
1087
        }
1088

    
1089
        /**
1090
        * Generates an HTML radio list
1091
        * @param array An array of objects
1092
        * @param string The value of the HTML name attribute
1093
        * @param string Additional HTML attributes for the <select> tag
1094
        * @param mixed The key that is selected
1095
        * @param string The name of the object variable for the option value
1096
        * @param string The name of the object variable for the option text
1097
        * @returns string HTML for the select list
1098
        */
1099
    static function radioList( &$arr, $tag_name, $tag_attribs, $selected=null, $key='value', $text='text' ) {
1100
                reset( $arr );
1101
                $html = "";
1102
                for ($i=0, $n=count( $arr ); $i < $n; $i++ ) {
1103
                        $k = $arr[$i]->$key;
1104
                        $t = $arr[$i]->$text;
1105
                        $id = ( isset($arr[$i]->id) ? @$arr[$i]->id : null);
1106

    
1107
                        $extra = '';
1108
                        $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
1109
                        if (is_array( $selected )) {
1110
                                foreach ($selected as $obj) {
1111
                                        $k2 = $obj->$key;
1112
                                        if ($k == $k2) {
1113
                                                $extra .= " selected=\"selected\"";
1114
                                                break;
1115
                                        }
1116
                                }
1117
                        } else {
1118
                                $extra .= ($k == $selected ? " checked=\"checked\"" : '');
1119
                        }
1120
                        $html .= "\n\t<input type=\"radio\" name=\"$tag_name\" id=\"$tag_name$k\" value=\"".$k."\"$extra $tag_attribs />";
1121
                        $html .= "\n\t<label for=\"$tag_name$k\">$t</label>";
1122
                }
1123
                $html .= "\n";
1124

    
1125
                return $html;
1126
        }
1127

    
1128
        /**
1129
        * Writes a yes/no radio list
1130
        * @param string The value of the HTML name attribute
1131
        * @param string Additional HTML attributes for the <select> tag
1132
        * @param mixed The key that is selected
1133
        * @returns string HTML for the radio list
1134
        */
1135
    static function yesnoRadioList( $tag_name, $tag_attribs, $selected, $yes=_CMN_YES, $no=_CMN_NO ) {
1136
                $arr = array(
1137
                        extHTML::makeOption( '0', $no ),
1138
                        extHTML::makeOption( '1', $yes )
1139
                );
1140

    
1141
                return extHTML::radioList( $arr, $tag_name, $tag_attribs, $selected );
1142
        }
1143

    
1144
        /**
1145
        * Cleans text of all formating and scripting code
1146
        */
1147
    static function cleanText ( &$text ) {
1148
                $text = preg_replace( "'<script[^>]*>.*?</script>'si", '', $text );
1149
                $text = preg_replace( '/<a\s+.*?href="([^"]+)"[^>]*>([^<]+)<\/a>/is', '\2 (\1)', $text );
1150
                $text = preg_replace( '/<!--.+?-->/', '', $text );
1151
                $text = preg_replace( '/{.+?}/', '', $text );
1152
                $text = preg_replace( '/&nbsp;/', ' ', $text );
1153
                $text = preg_replace( '/&amp;/', ' ', $text );
1154
                $text = preg_replace( '/&quot;/', ' ', $text );
1155
                $text = strip_tags( $text );
1156
                $text = htmlspecialchars( $text );
1157

    
1158
                return $text;
1159
        }
1160
}
1161
/**
1162
 * Utility function to return a value from a named array or a specified default
1163
 * @param array A named array
1164
 * @param string The key to search for
1165
 * @param mixed The default value to give if no key found
1166
 * @param int An options mask: _MOS_NOTRIM prevents trim, _MOS_ALLOWHTML allows safe html, _MOS_ALLOWRAW allows raw input
1167
 */
1168
define( "_ext_NOTRIM", 0x0001 );
1169
define( "_ext_ALLOWHTML", 0x0002 );
1170
define( "_ext_ALLOWRAW", 0x0004 );
1171
function extGetParam( &$arr, $name, $def=null, $mask=0 ) {
1172
        static $noHtmlFilter         = null;
1173
        static $safeHtmlFilter         = null;
1174

    
1175
        $return = null;
1176
        if (isset( $arr[$name] )) {
1177
                $return = $arr[$name];
1178

    
1179
                if (is_string( $return )) {
1180
                        // trim data
1181
                        if (!($mask&_ext_NOTRIM)) {
1182
                                $return = trim( $return );
1183
                        }
1184

    
1185
                        if ($mask&_ext_ALLOWRAW) {
1186
                                // do nothing
1187
                        } else if ($mask&_ext_ALLOWHTML) {
1188
                                // do nothing - compatibility mode
1189
                        } else {
1190
                                // send to inputfilter
1191
                                if (is_null( $noHtmlFilter )) {
1192
                                        $noHtmlFilter = new InputFilter( /* $tags, $attr, $tag_method, $attr_method, $xss_auto */ );
1193
                                }
1194

    
1195
                $return = $noHtmlFilter->sanitize( array($return) );
1196
                $return = $return[0];
1197

    
1198
                                if (empty($return) && is_numeric($def)) {
1199
                                // if value is defined and default value is numeric set variable type to integer
1200
                                        $return = intval($return);
1201
                                }
1202
                        }
1203

    
1204
                        // account for magic quotes setting
1205
//                        if (!get_magic_quotes_gpc()) {
1206
//                                $return = stripslashes( $return );
1207
//                        }
1208
                }
1209

    
1210
                return $return;
1211
        } else {
1212
                return $def;
1213
        }
1214
}
1215

    
1216
/**
1217
 * Strip slashes from strings or arrays of strings
1218
 * @param mixed The input string or array
1219
 * @return mixed String or array stripped of slashes
1220
 */
1221
function extStripslashes( &$value ) {
1222
        $ret = '';
1223
        if (is_string( $value )) {
1224
                $ret = stripslashes( $value );
1225
        } else {
1226
                if (is_array( $value )) {
1227
                        $ret = array();
1228
                        foreach ($value as $key => $val) {
1229
                                $ret[$key] = extStripslashes( $val );
1230
                        }
1231
                } else {
1232
                        $ret = $value;
1233
                }
1234
        }
1235
        return $ret;
1236
}
1237
/**
1238
 * Recursively creates a new directory
1239
 *
1240
 * @param unknown_type $path
1241
 * @param unknown_type $rights
1242
 * @return unknown
1243
 */
1244
function extMkdirR($path, $rights = 0777) {
1245

    
1246
        $folder_path = array(
1247
        strstr($path, '.') ? dirname($path) : $path);
1248

    
1249
        while(!@is_dir(dirname(end($folder_path)))
1250
                && dirname(end($folder_path)) != '/'
1251
                && dirname(end($folder_path)) != '.'
1252
                && dirname(end($folder_path)) != '') {
1253
                array_push($folder_path, dirname(end($folder_path)));
1254
        }
1255

    
1256
        while($parent_folder_path = array_pop($folder_path)) {
1257
                @mkdir($parent_folder_path, $rights);
1258
        }
1259
        @mkdir( $path );
1260
        return is_dir( $path );
1261
}
1262
/**
1263
* Utility function to read the files in a directory
1264
* @param string The file system path
1265
* @param string A filter for the names
1266
* @param boolean Recurse search into sub-directories
1267
* @param boolean True if to prepend the full path to the file name
1268
*/
1269
function extReadDirectory( $path, $filter='.', $recurse=false, $fullpath=false        ) {
1270
        $arr = array();
1271
        if (!@is_dir( $path )) {
1272
                return $arr;
1273
        }
1274
        $handle = opendir( $path );
1275

    
1276
        while ($file = readdir($handle)) {
1277
                if( is_array( $file )) $file = $file['name'];
1278
                $dir = extPathName( $path.'/'.$file, false );
1279
                $isDir = @is_dir( $dir );
1280
                if (($file != ".") && ($file != "..")) {
1281
                        if (preg_match( "/$filter/", $file )) {
1282
                                if ($fullpath) {
1283
                                        $arr[] = trim( extPathName( $path.'/'.$file, false ) );
1284
                                } else {
1285
                                        $arr[] = trim( $file );
1286
                                }
1287
                        }
1288
                        if ($recurse && $isDir) {
1289
                                $arr2 = extReadDirectory( $dir, $filter, $recurse, $fullpath );
1290
                                $arr = array_merge( $arr, $arr2 );
1291
                        }
1292
                }
1293
        }
1294
        closedir($handle);
1295
        asort($arr);
1296
        return $arr;
1297
}
1298
/**
1299
* Function to strip additional / or \ in a path name
1300
* @param string The path
1301
* @param boolean Add trailing slash
1302
*/
1303
function extPathName($p_path,$p_addtrailingslash = false) {
1304
        $retval = "";
1305

    
1306
        $isWin = (substr(PHP_OS, 0, 3) == 'WIN');
1307

    
1308
        if ($isWin)        {
1309
                $retval = str_replace( '/', '\\', $p_path );
1310
                if ($p_addtrailingslash) {
1311
                        if (substr( $retval, -1 ) != '\\') {
1312
                                $retval .= '\\';
1313
                        }
1314
                }
1315

    
1316
                // Check if UNC path
1317
                $unc = substr($retval,0,2) == '\\\\' ? 1 : 0;
1318

    
1319
                // Remove double \\
1320
                $retval = str_replace( '\\\\', '\\', $retval );
1321

    
1322
                // If UNC path, we have to add one \ in front or everything breaks!
1323
                if ( $unc == 1 ) {
1324
                        $retval = '\\'.$retval;
1325
                }
1326
        } else {
1327
                $retval = str_replace( '\\', '/', $p_path );
1328
                if ($p_addtrailingslash) {
1329
                        if (substr( $retval, -1 ) != '/') {
1330
                                $retval .= '/';
1331
                        }
1332
                }
1333

    
1334
                // Check if UNC path
1335
                $unc = substr($retval,0,2) == '//' ? 1 : 0;
1336

    
1337
                // Remove double //
1338
                $retval = str_replace('//','/',$retval);
1339

    
1340
                // If UNC path, we have to add one / in front or everything breaks!
1341
                if ( $unc == 1 ) {
1342
                        $retval = '/'.$retval;
1343
                }
1344
        }
1345

    
1346
        return $retval;
1347
}
1348
/**
1349
* Utility function redirect the browser location to another url
1350
*
1351
* Can optionally provide a message.
1352
* @param string The file system path
1353
* @param string A filter for the names
1354
*/
1355
function extRedirect( $url, $msg='' ) {
1356

    
1357
   global $mainframe;
1358

    
1359
        // specific filters
1360
        $iFilter = new InputFilter();
1361
        $url = $iFilter->process( $url );
1362
        if (!empty($msg)) {
1363
                $msg = $iFilter->process( $msg );
1364
        }
1365

    
1366
        if ($iFilter->badAttributeValue( array( 'href', $url ))) {
1367
                $url = $GLOBALS['home_dir'];
1368
        }
1369

    
1370
        if (trim( $msg )) {
1371
                if (strpos( $url, '?' )) {
1372
                        $url .= '&extmsg=' . urlencode( $msg );
1373
                } else {
1374
                        $url .= '?extmsg=' . urlencode( $msg );
1375
                }
1376
        }
1377

    
1378
        if (headers_sent()) {
1379
                echo "<script>document.location.href='$url';</script>\n";
1380
        } else {
1381
                @ob_end_clean(); // clear output buffer
1382
                header( 'HTTP/1.1 301 Moved Permanently' );
1383
                header( "Location: ". $url );
1384
        }
1385
        exit();
1386
}
1387
/**
1388
* Random password generator
1389
* @return password
1390
*/
1391
function extMakePassword($length=8) {
1392
        $salt                 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1393
        $makepass        = '';
1394
        mt_srand(10000000*(double)microtime());
1395
        for ($i = 0; $i < $length; $i++)
1396
                $makepass .= $salt[mt_rand(0,61)];
1397
        return $makepass;
1398
}
1399
/**
1400
 * Wrapper Function to encode passwords (maybe sometimes we don't use md5 anymore?)
1401
 *
1402
 * @param string $pass
1403
 * @return string
1404
 */
1405
function extEncodePassword( $pass ) {
1406
        require_once( _EXT_PATH.'/libraries/PasswordHash.php');
1407
        $hasher = new PasswordHash(8, FALSE);
1408
        $hash = $hasher->HashPassword($pass);
1409
        return $hash;
1410
}
1411

    
1412
if (!function_exists('html_entity_decode')) {
1413
        /**
1414
        * html_entity_decode function for backward compatability in PHP
1415
        * @param string
1416
        * @param string
1417
        */
1418
        function html_entity_decode ($string, $opt = ENT_COMPAT) {
1419

    
1420
                $trans_tbl = get_html_translation_table (HTML_ENTITIES);
1421
                $trans_tbl = array_flip ($trans_tbl);
1422

    
1423
                if ($opt & 1) { // Translating single quotes
1424
                        // Add single quote to translation table;
1425
                        // doesn't appear to be there by default
1426
                        $trans_tbl["&apos;"] = "'";
1427
                }
1428

    
1429
                if (!($opt & 2)) { // Not translating double quotes
1430
                        // Remove double quote from translation table
1431
                        unset($trans_tbl["&quot;"]);
1432
                }
1433

    
1434
                return strtr ($string, $trans_tbl);
1435
        }
1436
}
1437
//------------------------------------------------------------------------------
1438
function logout() {
1439
        session_destroy();
1440
        session_write_close();
1441
        header("Location: ".$GLOBALS["script_name"]);
1442
}
1443
//------------------------------------------------------------------------------
1444
/**
1445
 * Returns an IP- and BrowserID- based Session ID
1446
 *
1447
 * @param string $id
1448
 * @return string
1449
 */
1450
function generate_session_id( $id=null ) {
1451
        return extMakePassword( 32 );
1452
}
1453
function ext_getToken() {
1454
    return md5(session_id());
1455
}
1456
function ext_checkToken($token) {
1457
    return md5(session_id()) == $token;
1458
}