PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/administrator/components/com_extplorer/include/functions.php

https://github.com/cavila/Astica
PHP | 1437 lines | 1119 code | 87 blank | 231 comment | 198 complexity | 27d26b5cd1cb8b692007e718e4a66a27 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, Apache-2.0, BSD-3-Clause
  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 202 2011-07-20 12:15:45Z 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. * THESE ARE NUMEROUS HELPER FUNCTIONS FOR THE OTHER INCLUDE FILES
  36. */
  37. function ext_make_link($_action,$_dir,$_item=NULL,$_order=NULL,$_srt=NULL,$languages=NULL, $extra=null) {
  38. // make link to next page
  39. if($_action=="" || $_action==NULL) $_action="list";
  40. if($_item=="") $_item=NULL;
  41. if($_order==NULL) $_order=$GLOBALS["order"];
  42. if($_srt==NULL) $_srt=$GLOBALS["direction"];
  43. if($languages==NULL) $languages=(isset($GLOBALS["lang"])?$GLOBALS["lang"]:NULL);
  44. $link=$GLOBALS["script_name"]."?option=com_extplorer&action=".$_action;
  45. if(!is_null($_dir )) {
  46. $link.="&dir=".urlencode($_dir);
  47. }
  48. if($_item!=NULL) $link.="&item=".urlencode($_item);
  49. if($_order!=NULL) $link.="&order=".$_order;
  50. if($_srt!=NULL) $link.="&direction=".$_srt;
  51. if($languages!=NULL) $link.="&lang=".$languages;
  52. if(!is_null($extra)) {
  53. $link .= $extra;
  54. }
  55. return $link;
  56. }
  57. //------------------------------------------------------------------------------
  58. function get_abs_dir($dir) { // get absolute path
  59. if( ext_isFTPMode() ) {
  60. if( $dir != '' && $dir[0] != '/' && $dir[1] != ':') {
  61. $dir = '/'.$dir;
  62. }
  63. return $dir;
  64. }
  65. $abs_dir=$GLOBALS["home_dir"];
  66. if($dir!="" && !@stristr( $dir, $abs_dir )) $abs_dir.="/".$dir;
  67. elseif(@stristr( $dir, $abs_dir )) $abs_dir = "/".$dir;
  68. /*else {
  69. $abs_dir = $dir;
  70. }*/
  71. $realpath = str_replace('\\', '/', realpath($abs_dir) );
  72. if( $realpath == '') {
  73. return $abs_dir;
  74. }
  75. else {
  76. return $realpath;
  77. }
  78. return $realpath;
  79. }
  80. //------------------------------------------------------------------------------
  81. function get_abs_item($dir, $item) { // get absolute file+path
  82. if( is_array( $item )) {
  83. // FTP Mode
  84. $abs_item = '/' . get_abs_dir($dir)."/".$item['name'];
  85. if( get_is_dir($item)) $abs_item.='/';
  86. return extPathName($abs_item);
  87. }
  88. return extPathName( get_abs_dir($dir)."/".$item );
  89. }
  90. /**
  91. * Returns the LS info array from an ftp directory listing
  92. *
  93. * @param unknown_type $dir
  94. * @param unknown_type $item
  95. * @return unknown
  96. */
  97. function get_item_info( $dir, $item ) {
  98. $ls = getCachedFTPListing( $dir );
  99. if( empty($ls)) return false;
  100. foreach( $ls as $entry ) {
  101. if( $entry['name'] == $item ) {
  102. return $entry;
  103. }
  104. }
  105. if( $dir != '') {
  106. return $dir.'/'.$item;
  107. }
  108. return $item;
  109. }
  110. //------------------------------------------------------------------------------
  111. function get_rel_item($dir,$item) { // get file relative from home
  112. if($dir!="") return $dir."/".$item;
  113. else return $item;
  114. }
  115. //------------------------------------------------------------------------------
  116. function get_is_file( $abs_item) { // can this file be edited?
  117. if( ext_isFTPMode() && is_array( $abs_item )) {
  118. return empty($abs_item['is_dir']);
  119. } elseif( ext_isFTPMode() ) {
  120. $info = get_item_info( dirname($abs_item), basename($abs_item));
  121. return empty($info['is_dir']);
  122. }
  123. return @is_file($abs_item);
  124. }
  125. //------------------------------------------------------------------------------
  126. function get_is_dir( $abs_item ) { // is this a directory?
  127. if( ext_isFTPMode() && is_array( $abs_item )) {
  128. return !empty($abs_item['is_dir']);
  129. }
  130. elseif( ext_isFTPMode() ) {
  131. $info = get_item_info( dirname( $abs_item), basename( $abs_item ));
  132. return !empty($info['is_dir']);
  133. }
  134. return @is_dir( $abs_item );
  135. }
  136. //------------------------------------------------------------------------------
  137. function parse_file_type( $abs_item ) { // parsed file type (d / l / -)
  138. if(@get_is_dir($abs_item)) return "d";
  139. if(@is_link($abs_item)) return "l";
  140. return "-";
  141. }
  142. //------------------------------------------------------------------------------
  143. function get_file_perms( $item) { // file permissions
  144. if( ext_isFTPMode() && isset($item['rights']) ) {
  145. $perms = decoct( bindec( decode_ftp_rights($item['rights']) ) );
  146. return $perms;
  147. } elseif( is_numeric($item['mode'])) { //SFTP
  148. return @decoct($item['mode'] & 0777);
  149. }
  150. return @decoct(@fileperms( $item ) & 0777);
  151. }
  152. function get_languages() {
  153. $langfiles = extReadDirectory( _EXT_PATH.'/languages' );
  154. $langs = array();
  155. foreach( $langfiles as $lang ) {
  156. if( stristr( $lang, '_mimes') || $lang == 'index.html') continue;
  157. $langs[basename( $lang, '.php' )] = ucwords(str_replace( '_', ' ', basename( $lang, '.php' )));
  158. }
  159. return $langs;
  160. }
  161. //------------------------------------------------------------------------------
  162. function parse_file_perms($mode) { // parsed file permisions
  163. if(strlen($mode)<3) return "---------";
  164. $parsed_mode="";
  165. for($i=0;$i<3;$i++) {
  166. // read
  167. if(($mode{$i} & 04)) $parsed_mode .= "r";
  168. else $parsed_mode .= "-";
  169. // write
  170. if(($mode{$i} & 02)) $parsed_mode .= "w";
  171. else $parsed_mode .= "-";
  172. // execute
  173. if(($mode{$i} & 01)) $parsed_mode .= "x";
  174. else $parsed_mode .= "-";
  175. }
  176. return $parsed_mode;
  177. }
  178. function decode_ftp_rights( $rights) {
  179. $parsed_mode="";
  180. for($i=0;$i<9;$i++) {
  181. // read
  182. if( $rights[$i] != '-' ) {
  183. $parsed_mode .= '1';
  184. }
  185. else {
  186. $parsed_mode.= '0';
  187. }
  188. }
  189. return $parsed_mode;
  190. }
  191. //------------------------------------------------------------------------------
  192. function get_file_size( $abs_item) { // file size
  193. return @$GLOBALS['ext_File']->filesize( $abs_item );
  194. }
  195. //------------------------------------------------------------------------------
  196. function get_dir_size($dir) {
  197. if(is_file($dir)) return array('size'=>filesize($dir),'howmany'=>0);
  198. if($dh=opendir($dir)) {
  199. $size=0;
  200. $n = 0;
  201. while(($file=readdir($dh))!==false) {
  202. if($file=='.' || $file=='..') continue;
  203. $n++;
  204. $data = get_dir_size($dir.'/'.$file);
  205. $size += $data['size'];
  206. $n += $data['howmany'];
  207. }
  208. closedir($dh);
  209. return array('size'=>$size,'howmany'=>$n);
  210. }
  211. return array('size'=>0,'howmany'=>0);
  212. }
  213. function parse_file_size($bytes, $precision = 2) {
  214. $units = array('B', 'KB', 'MB', 'GB', 'TB');
  215. if( !is_float($bytes)) {
  216. $bytes = (float)sprintf("%u", $bytes);
  217. }
  218. $bytes = max($bytes, 0);
  219. $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
  220. $pow = min($pow, count($units) - 1);
  221. $bytes /= pow(1024, $pow);
  222. return round($bytes, $precision) . ' ' . $units[$pow];
  223. }
  224. //------------------------------------------------------------------------------
  225. function get_file_date( $item) { // file date
  226. return @$GLOBALS['ext_File']->filemtime( $item );
  227. }
  228. //------------------------------------------------------------------------------
  229. function parse_file_date($date) { // parsed file date
  230. if ($date) {
  231. return @date($GLOBALS["date_fmt"],$date);
  232. } else {
  233. return " (unknown) ";
  234. }
  235. }
  236. //------------------------------------------------------------------------------
  237. function get_is_image( $abs_item ) { // is this file an image?
  238. if(!get_is_file($abs_item)) return false;
  239. if( isset($abs_item['name'])) {
  240. $abs_item = $abs_item['name'];
  241. }
  242. return @eregi($GLOBALS["images_ext"], $abs_item);
  243. }
  244. //-----------------------------------------------------------------------------
  245. function get_is_editable( $abs_item ) { // is this file editable?
  246. if(!get_is_file( $abs_item )) return false;
  247. if( is_array( $abs_item ) ) {
  248. $abs_item = $abs_item['name'];
  249. }
  250. if(preg_match('/'.$GLOBALS["editable_ext"].'/i',$abs_item)) return true;
  251. return strpos( basename($abs_item), "." ) ? false : true;
  252. }
  253. //-----------------------------------------------------------------------------
  254. function get_mime_type( $abs_item, $query) { // get file's mimetype
  255. if(get_is_dir( $abs_item )) { // directory
  256. $mime_type = $GLOBALS["super_mimes"]["dir"][0];
  257. $image = $GLOBALS["super_mimes"]["dir"][1];
  258. if($query=="img") return $image;
  259. else return $mime_type;
  260. }
  261. $extra = $GLOBALS['ext_File']->is_link( $abs_item ) ? ' ('.$GLOBALS['mimes']['symlink'].')' : '';
  262. if( ext_isFTPMode() && isset($abs_item['name']) ) {
  263. $abs_item=$abs_item['name'];
  264. }
  265. // mime_type
  266. foreach($GLOBALS["used_mime_types"] as $mime) {
  267. list($desc,$img,$ext) = $mime;
  268. if(@eregi($ext,basename($abs_item) )) {
  269. $mime_type = $desc;
  270. $image = $img;
  271. if($query=="img") return $image;
  272. else return $mime_type . $extra;
  273. }
  274. }
  275. if((function_exists("is_executable") &&
  276. @is_executable( $abs_item )) ||
  277. @eregi($GLOBALS["super_mimes"]["exe"][2],$abs_item))
  278. { // executable
  279. $mime_type = $GLOBALS["super_mimes"]["exe"][0];
  280. $image = $GLOBALS["super_mimes"]["exe"][1];
  281. } else { // unknown file
  282. $mime_type = $GLOBALS["super_mimes"]["file"][0];
  283. $image = $GLOBALS["super_mimes"]["file"][1];
  284. }
  285. if($query=="img")
  286. return $image;
  287. else
  288. return $mime_type . $extra;
  289. }
  290. //------------------------------------------------------------------------------
  291. function get_show_item($dir, $item) { // show this file?
  292. if( is_array( $item )) {
  293. $item = $item['name'];
  294. }
  295. if($item == "." || $item == ".." ||
  296. (substr($item,0,1)=="." && $GLOBALS["show_hidden"]==false)) return false;
  297. if($GLOBALS["no_access"]!="" && @eregi($GLOBALS["no_access"],$item)) return false;
  298. if($GLOBALS["show_hidden"]==false) {
  299. $dirs=explode("/",$dir);
  300. foreach($dirs as $i) if(substr($i,0,1)==".") return false;
  301. }
  302. return true;
  303. }
  304. //------------------------------------------------------------------------------
  305. function get_dir_list( $dir='' ) {
  306. if( ext_isFTPMode()) {
  307. $files = getCachedFTPListing(empty($dir) ? '.' : $dir);
  308. } else {
  309. $files = extReadDirectory( get_abs_dir( $dir), '.', false, true );
  310. }
  311. $dirs =array();
  312. foreach( $files as $item) {
  313. $itemname = ext_isFTPMode() ? (empty($dir) ? '' : $dir.'/') .$item['name'] : $item;
  314. $itemname = str_replace( '\\', '/', $itemname );
  315. if( get_is_dir($item)) {
  316. $index = str_replace(
  317. str_replace('\\', '/', $GLOBALS['home_dir'].$GLOBALS['separator']),
  318. '', $itemname );
  319. $dirs[$index]= basename($index);
  320. }
  321. }
  322. return $dirs;
  323. }
  324. /**
  325. * Returns select lists with all the subdirectories along the current directory path
  326. *
  327. * @param string $dir
  328. * @return string
  329. */
  330. function get_dir_selects( $dir ) {
  331. $dirs = explode( "/", str_replace( "\\", '/', $dir ) );
  332. $subdirs = get_dir_list();
  333. if( sizeof( $subdirs ) > 0) {
  334. $subdirs = array_merge(Array('ext_disabled' => '-'), $subdirs );
  335. }
  336. if( empty($dirs[0]) ) array_shift($dirs);
  337. $dirsCopy = $dirs;
  338. $implode = '';
  339. $selectedDir = @$dirs[0];
  340. foreach( $subdirs as $index => $val ) {
  341. if ($GLOBALS['use_mb']) {
  342. if (mb_detect_encoding($val) == 'ASCII') {
  343. $subdirs[$index] = utf8_encode($val);
  344. } else {
  345. $subdirs[$index] = $val;
  346. }
  347. } else {
  348. $subdirs[$index] = utf8_encode($val);
  349. }
  350. }
  351. $dir_links = ext_selectList('dirselect1', $selectedDir, $subdirs, 1, '', 'onchange="theDir=this.options[this.selectedIndex].value;if(theDir!=\'ext_disabled\' ) chDir(theDir);"' );
  352. $i = 2;
  353. foreach( $dirs as $directory ) {
  354. if( $directory != "" ) {
  355. $implode .= $directory;
  356. $next = next($dirsCopy);
  357. $subdirs = get_dir_list( $implode );
  358. foreach( $subdirs as $index => $val ) {
  359. unset( $subdirs[$index]);
  360. if ($GLOBALS['use_mb']) {
  361. if (mb_detect_encoding($index) == 'ASCII') {
  362. if (mb_detect_encoding($val) == 'ASCII') {
  363. $subdirs[utf8_encode($index)] = utf8_encode($val);
  364. } else {
  365. $subdirs[utf8_encode($index)] = $val;
  366. }
  367. } else {
  368. if (mb_detect_encoding($val) == 'ASCII') {
  369. $subdirs[$index] = utf8_encode($val);
  370. } else {
  371. $subdirs[$index] = $val;
  372. }
  373. }
  374. } else {
  375. $subdirs[utf8_encode($index)] = utf8_encode($val);
  376. }
  377. }
  378. if( $next !== false ) {
  379. $selectedDir .= '/'.$next;
  380. } else {
  381. if( sizeof( $subdirs ) > 0) {
  382. $subdirs = array_merge(Array('ext_disabled' => '-'), $subdirs );
  383. }
  384. }
  385. $dir_links .= ' / '.ext_selectList('dirselect'.$i++, $selectedDir, $subdirs, 1, '', 'onchange="theDir=this.options[this.selectedIndex].value;if(theDir!=\'ext_disabled\' ) chDir(theDir);"' );
  386. $implode .= '/';
  387. }
  388. }
  389. //echo '<pre>'.htmlspecialchars($dir_links).'</pre>';exit;
  390. return $dir_links;
  391. }
  392. //------------------------------------------------------------------------------
  393. function ext_copy_dir($source,$dest) { // copy dir
  394. $ok = true;
  395. $source = str_replace( '\\', '/', $source );
  396. $dest = str_replace( '\\', '/', $dest );
  397. if(!@mkdir($dest,0777)) return false;
  398. $itemlist = extReadDirectory( $source, '.', true, true );
  399. if( empty( $itemlist )) return true;
  400. foreach( $itemlist as $file ) {
  401. if(($file==".." || $file==".")) continue;
  402. $file = str_replace( '\\', '/', $file );
  403. $new_dest = str_replace( $source, $dest, $file );
  404. if(@is_dir($file)) {
  405. @mkdir($new_dest,0777);
  406. } else {
  407. $ok=@copy($file,$new_dest);
  408. }
  409. }
  410. return $ok;
  411. }
  412. //------------------------------------------------------------------------------
  413. function remove($item) { // remove file / dir
  414. if( !is_link( $item )) {
  415. $item = realpath($item);
  416. }
  417. $ok = true;
  418. if( is_link($item) || is_file($item))
  419. $ok = unlink($item);
  420. elseif( @is_dir($item)) {
  421. if(($handle= opendir($item))===false)
  422. ext_Result::sendResult('delete', false, basename($item).": ".$GLOBALS["error_msg"]["opendir"]);
  423. while(($file=readdir($handle))!==false) {
  424. if(($file==".." || $file==".")) continue;
  425. $new_item = $item."/".$file;
  426. if(!file_exists($new_item))
  427. ext_Result::sendResult('delete', false, basename($item).": ".$GLOBALS["error_msg"]["readdir"]);
  428. //if(!get_show_item($item, $new_item)) continue;
  429. if( @is_dir($new_item)) {
  430. $ok=remove($new_item);
  431. } else {
  432. $ok= unlink($new_item);
  433. }
  434. }
  435. closedir($handle);
  436. $ok=@rmdir($item);
  437. }
  438. return $ok;
  439. }
  440. function chmod_recursive($item, $mode) { // chmod file / dir
  441. $ok = true;
  442. if(@is_link($item) || @is_file($item)) {
  443. $ok=@chmod( $item, $mode );
  444. if($ok) ext_Result::add_message($GLOBALS['messages']['permchange'].' '.$new_item);
  445. else ext_Result::add_error($GLOBALS['error_msg']['permchange'].' '.$new_item);
  446. }
  447. elseif(@is_dir($item)) {
  448. if(($handle=@opendir($item))===false) {
  449. ext_Result::add_error(basename($item).": ".$GLOBALS["error_msg"]["opendir"]);
  450. return false;
  451. }
  452. while(($file=readdir($handle))!==false) {
  453. if(($file==".." || $file==".")) continue;
  454. $new_item = $item."/".$file;
  455. if(!@file_exists($new_item)) {
  456. ext_Result::add_error(basename($item).": ".$GLOBALS["error_msg"]["readdir"]);
  457. continue;
  458. }
  459. //if(!get_show_item($item, $new_item)) continue;
  460. if(@is_dir($new_item)) {
  461. $ok=chmod_recursive($new_item, $mode);
  462. } else {
  463. $ok=@chmod($new_item, $mode);
  464. if($ok) ext_Result::add_message($GLOBALS['messages']['permchange'].' '.$new_item);
  465. else ext_Result::add_error($GLOBALS['error_msg']['permchange'].' '.$new_item);
  466. }
  467. }
  468. closedir($handle);
  469. if( @is_dir( $item )) {
  470. $bin = decbin( $mode );
  471. // when we chmod a directory we must care for the permissions
  472. // to prevent that the directory becomes not readable (when the "execute bits" are removed)
  473. $bin = substr_replace( $bin, '1', 2, 1 ); // set 1st x bit to 1
  474. $bin = substr_replace( $bin, '1', 5, 1 );// set 2nd x bit to 1
  475. $bin = substr_replace( $bin, '1', 8, 1 );// set 3rd x bit to 1
  476. $mode = bindec( $bin );
  477. }
  478. $ok=@chmod( $item, $mode );
  479. if($ok) ext_Result::add_message($GLOBALS['messages']['permchange'].' '.$item);
  480. else ext_Result::add_error($GLOBALS['error_msg']['permchange'].' '.$item);
  481. }
  482. return $ok;
  483. }
  484. //------------------------------------------------------------------------------
  485. function get_max_file_size() { // get php max_upload_file_size
  486. return calc_php_setting_bytes( ini_get("upload_max_filesize") );
  487. }
  488. function get_max_upload_limit() {
  489. return calc_php_setting_bytes( ini_get('post_max_size'));
  490. }
  491. function calc_php_setting_bytes( $value ) {
  492. if(@eregi("G$",$value)) {
  493. $value = substr($value,0,-1);
  494. $value = round($value*1073741824);
  495. } elseif(@eregi("M$",$value)) {
  496. $value = substr($value,0,-1);
  497. $value = round($value*1048576);
  498. } elseif(@eregi("K$",$value)) {
  499. $value = substr($value,0,-1);
  500. $value = round($value*1024);
  501. }
  502. return $value;
  503. }
  504. //------------------------------------------------------------------------------
  505. function down_home($abs_dir) { // dir deeper than home?
  506. if( ext_isFTPMode() ) {
  507. return true;
  508. }
  509. $real_home = @realpath($GLOBALS["home_dir"]);
  510. $real_dir = @realpath($abs_dir);
  511. if($real_home===false || $real_dir===false) {
  512. if(@eregi("\\.\\.",$abs_dir)) return false;
  513. } else if(strcmp($real_home,@substr($real_dir,0,strlen($real_home)))) {
  514. return false;
  515. }
  516. return true;
  517. }
  518. //------------------------------------------------------------------------------
  519. function id_browser() {
  520. $browser=$GLOBALS['__SERVER']['HTTP_USER_AGENT'];
  521. if(preg_match('/Opera(\/| )([0-9]\.[0-9]{1,2})/', $browser)) {
  522. return 'OPERA';
  523. } else if(preg_match('/MSIE ([0-9]\.[0-9]{1,2})/', $browser)) {
  524. return 'IE';
  525. } else if(preg_match('/OmniWeb\/([0-9]\.[0-9]{1,2})/', $browser)) {
  526. return 'OMNIWEB';
  527. } else if(preg_match('/(Konqueror\/)(.*)/', $browser)) {
  528. return 'KONQUEROR';
  529. } else if(preg_match('/Mozilla\/([0-9]\.[0-9]{1,2})/', $browser)) {
  530. return 'MOZILLA';
  531. } else {
  532. return 'OTHER';
  533. }
  534. }
  535. function ext_isArchive( $file ) {
  536. $file_info = pathinfo($file);
  537. $ext = @strtolower($file_info["extension"]);
  538. $archive_types = array("tar", "gz", "tgz", "zip", "bzip2", "bz2", "tbz", 'rar');
  539. if( in_array( $ext, $archive_types )) {
  540. return true;
  541. }
  542. return false;
  543. }
  544. if( !extension_loaded('posix') ) {
  545. function posix_geteuid() {
  546. return false;
  547. }
  548. function posix_getpwnam() {
  549. }
  550. }
  551. //------------------------------------------------------------------------------
  552. /**
  553. * Checks if the User Agent String identifies the browser as Internet Explorer
  554. *
  555. * @return boolean
  556. */
  557. function ext_isWindows() {
  558. if(empty($GLOBALS['isWindows'])) {
  559. $GLOBALS['isWindows'] = substr(PHP_OS, 0, 3) == 'WIN';
  560. }
  561. return $GLOBALS['isWindows'];
  562. }
  563. /**
  564. * Returns the valid directory separator for this OS & Webserver combination
  565. *
  566. * @return string
  567. */
  568. function ext_getSeparator() {
  569. if( defined( 'DIRECTORY_SEPARATOR')) {
  570. return DIRECTORY_SEPARATOR;
  571. }
  572. elseif (@preg_match('/Microsoft|WebSTAR|Xitami/', $_SERVER['SERVER_SOFTWARE']) ) {
  573. return '\\';
  574. } else {
  575. return '/';
  576. }
  577. }
  578. /**
  579. * Checks if the User Agent String identifies the browser as Internet Explorer
  580. *
  581. * @return boolean
  582. */
  583. function ext_isIE() {
  584. return (preg_match('/MSIE ([0-9]\.[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']));
  585. }
  586. /**
  587. * Prints an HTML dropdown box named $name using $arr to
  588. * load the drop down. If $value is in $arr, then $value
  589. * will be the selected option in the dropdown.
  590. * @author gday
  591. * @author soeren
  592. *
  593. * @param string $name The name of the select element
  594. * @param string $value The pre-selected value
  595. * @param array $arr The array containting $key and $val
  596. * @param int $size The size of the select element
  597. * @param string $multiple use "multiple=\"multiple\" to have a multiple choice select list
  598. * @param string $extra More attributes when needed
  599. * @return string HTML drop-down list
  600. */
  601. function ext_selectList($name, $value, $arr, $size=1, $multiple="", $extra="") {
  602. $html = '';
  603. if( !empty( $arr ) ) {
  604. $html = "<select class=\"inputbox\" name=\"$name\" id=\"$name\" size=\"$size\" $multiple $extra>\n";
  605. while (list($key, $val) = each($arr)) {
  606. $selected = "";
  607. if( is_array( $value )) {
  608. if( in_array( $key, $value )) {
  609. $selected = "selected=\"selected\"";
  610. }
  611. }
  612. else {
  613. if(strtolower($value) == strtolower($key) ) {
  614. $selected = "selected=\"selected\"";
  615. }
  616. }
  617. if( $val == '-') {
  618. //$selected .= ' disabled="disabled"';
  619. $val = '- - - - -';
  620. }
  621. $html .= "<option value=\"$key\" $selected>$val";
  622. $html .= "</option>\n";
  623. }
  624. $html .= "</select>\n";
  625. }
  626. return $html;
  627. }
  628. function ext_scriptTag( $src = '', $script = '') {
  629. if( $src!='') {
  630. return '<script type="text/javascript" src="'.$src.'"></script>';
  631. }
  632. if( $script != '') {
  633. return '<script type="text/javascript">'.$script.'</script>';
  634. }
  635. }
  636. function ext_alertBox( $msg ) {
  637. return ext_scriptTag('', 'Ext.Msg.alert( \''.$GLOBALS["error_msg"]['message'].'\', \''. @mysql_escape_string( $msg ) .'\' );' );
  638. }
  639. function ext_successBox( $msg ) {
  640. return ext_scriptTag('', 'Ext.msgBoxSlider.msg( \''.ext_Lang::msg('success', true ).'\', \''. @mysql_escape_string( $msg ) .'\' );' );
  641. }
  642. function ext_docLocation( $url ) {
  643. return ext_scriptTag('', 'document.location=\''. $url .'\';' );
  644. }
  645. function ext_isXHR() {
  646. return strtolower(extGetParam($_SERVER,'HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest'
  647. || strtolower(extGetParam($_POST,'requestType')) == 'xmlhttprequest';
  648. }
  649. function ext_exit() {
  650. global $mainframe;
  651. if( class_exists( 'jfactory' )) {
  652. $app = jfactory::getApplication();
  653. $app->close();
  654. }
  655. if( is_callable( array( $mainframe, 'close' ) ) ) {
  656. $mainframe->close();
  657. } else {
  658. session_write_close();
  659. exit;
  660. }
  661. }
  662. function ext_isJoomla( $version='', $operator='=', $compare_minor_versions=true) {
  663. $this_version = '';
  664. if( !empty($GLOBALS['_VERSION']) && is_object($GLOBALS['_VERSION'])) {
  665. $jversion =& $GLOBALS['_VERSION'];
  666. $this_version = $jversion->RELEASE .'.'. $jversion->DEV_LEVEL;
  667. }
  668. elseif ( class_exists('JVersion') ) {
  669. $jversion = new JVersion();
  670. $this_version = $jversion->RELEASE .'.'. $jversion->DEV_LEVEL;
  671. } else {
  672. return false;
  673. }
  674. if( empty( $version ) ) {
  675. return !empty($this_version);
  676. }
  677. $allowed_operators = array( '<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne' );
  678. if( $compare_minor_versions ) {
  679. $this_version = $jversion->RELEASE;
  680. }
  681. if( in_array($operator, $allowed_operators )) {
  682. return version_compare( $this_version, $version, $operator );
  683. }
  684. return false;
  685. }
  686. /**
  687. * Raise the memory limit when it is lower than the needed value
  688. *
  689. * @param string $setLimit Example: 16M
  690. */
  691. function ext_RaiseMemoryLimit( $setLimit ) {
  692. $memLimit = @ini_get('memory_limit');
  693. if( stristr( $memLimit, 'k') ) {
  694. $memLimit = str_replace( 'k', '', str_replace( 'K', '', $memLimit )) * 1024;
  695. }
  696. elseif( stristr( $memLimit, 'm') ) {
  697. $memLimit = str_replace( 'm', '', str_replace( 'M', '', $memLimit )) * 1024 * 1024;
  698. }
  699. if( stristr( $setLimit, 'k') ) {
  700. $setLimitB = str_replace( 'k', '', str_replace( 'K', '', $setLimit )) * 1024;
  701. }
  702. elseif( stristr( $setLimit, 'm') ) {
  703. $setLimitB = str_replace( 'm', '', str_replace( 'M', '', $setLimit )) * 1024 * 1024;
  704. }
  705. if( $memLimit < $setLimitB ) {
  706. @ini_set('memory_limit', $setLimit );
  707. }
  708. }
  709. /**
  710. * Reads a file and sends them in chunks to the browser
  711. * This should overcome memory problems
  712. * http://www.php.net/manual/en/function.readfile.php#54295
  713. *
  714. * @since 1.4.1
  715. * @param string $filename
  716. * @param boolean $retbytes
  717. * @return mixed
  718. */
  719. function readFileChunked($filename,$retbytes=true) {
  720. $chunksize = 1*(1024*1024); // how many bytes per chunk
  721. $buffer = '';
  722. $cnt =0;
  723. // $handle = fopen($filename, 'rb');
  724. $handle = fopen($filename, 'rb');
  725. if ($handle === false) {
  726. return false;
  727. }
  728. while (!feof($handle)) {
  729. $buffer = fread($handle, $chunksize);
  730. echo $buffer;
  731. sleep(1);
  732. ob_flush();
  733. flush();
  734. if ($retbytes) {
  735. $cnt += strlen($buffer);
  736. }
  737. }
  738. $status = fclose($handle);
  739. if ($retbytes && $status) {
  740. return $cnt; // return num. bytes delivered like readfile() does.
  741. }
  742. return $status;
  743. }
  744. //implements file_put_contents function for compatability with PHP < 4.3
  745. if ( ! function_exists('file_put_contents') ) {
  746. function file_put_contents ( $filename, $filecont ){
  747. $handle = fopen( $filename, 'w' );
  748. if ( is_array($filecont) ) {
  749. $size = 0;
  750. foreach ( $filecont as $filestring ) {
  751. fwrite( $handle, $filestring );
  752. $size += strlen( $filestring );
  753. }
  754. fclose($handle);
  755. return $size;
  756. } else {
  757. fwrite( $handle, $filecont );
  758. fclose($handle);
  759. return strlen( $filecont );
  760. }
  761. }
  762. }
  763. if ( ! function_exists('scandir') ) {
  764. function scandir($dir,$listDirectories=false, $skipDots=true) {
  765. $dirArray = array();
  766. if ($handle = opendir($dir)) {
  767. while (false !== ($file = readdir($handle))) {
  768. if (($file != "." && $file != "..") || $skipDots == true) {
  769. if($listDirectories == false) { if(@is_dir($file)) { continue; } }
  770. array_push($dirArray,basename($file));
  771. }
  772. }
  773. closedir($handle);
  774. }
  775. return $dirArray;
  776. }
  777. }
  778. /**
  779. * Page generation time
  780. * @package Joomla
  781. */
  782. class extProfiler {
  783. /** @var int Start time stamp */
  784. var $start=0;
  785. /** @var string A prefix for mark messages */
  786. var $prefix='';
  787. /**
  788. * Constructor
  789. * @param string A prefix for mark messages
  790. */
  791. function extProfiler( $prefix='' ) {
  792. $this->start = $this->getmicrotime();
  793. $this->prefix = $prefix;
  794. }
  795. /**
  796. * @return string A format message of the elapsed time
  797. */
  798. function mark( $label ) {
  799. return sprintf ( "\n<div class=\"profiler\">$this->prefix %.3f $label</div>", $this->getmicrotime() - $this->start );
  800. }
  801. /**
  802. * @return float The current time in milliseconds
  803. */
  804. function getmicrotime(){
  805. list($usec, $sec) = explode(" ",microtime());
  806. return ((float)$usec + (float)$sec);
  807. }
  808. }
  809. /**
  810. * Utility class for all HTML drawing classes
  811. * @package eXtplorer
  812. */
  813. class extHTML {
  814. function loadExtJS() {
  815. $scripts[] = array('dir' => 'scripts/editarea/', 'file' => 'edit_area_full_with_plugins.js');
  816. $scripts[] = array('dir' => 'scripts/extjs3/adapter/ext/', 'file' => 'ext-base.js');
  817. $scripts[] = array('dir' => 'scripts/extjs3/', 'file' => 'ext-all.js');
  818. $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.ondemandload/', 'file' => 'scriptloader.js');
  819. $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.editareaadapater/', 'file' => 'ext-editarea-adapter.js');
  820. $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.statusbar/', 'file' => 'ext-statusbar.js');
  821. $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.fileuploadfield/', 'file' => 'ext-fileUploadField.js');
  822. $scripts[] = array('dir' => 'scripts/extjs3-ext/ux.locationbar/', 'file' => 'Ext.ux.LocationBar.js');
  823. $styles[] = array('dir' => 'scripts/extjs3/resources/css/', 'file' => 'ext-all.css');
  824. $styles[] = array('dir' => 'scripts/extjs3-ext/ux.locationbar/', 'file' => 'LocationBar.css');
  825. $styles[] = array('dir' => 'scripts/extjs3-ext/ux.fileuploadfield/', 'file' => 'fileuploadfield.css');
  826. $scriptTag = '';
  827. if( !empty($_GET['nofetchscript']) || !empty( $_COOKIE['nofetchscript'])) {
  828. foreach( $scripts as $script ) {
  829. $scriptTag .= '<script type="text/javascript" src="'.$script['dir'].$script['file'].'"></script>';
  830. }
  831. foreach( $styles as $style ) {
  832. $scriptTag .= '<link type="text/css" href="'.$style['dir'].$style['file'].'" rel="stylesheet" />';
  833. }
  834. } else {
  835. $scriptTag = '
  836. <script type="text/javascript" src="'. _EXT_URL . '/fetchscript.php?'
  837. .'&amp;subdir[]=scripts/editarea/&amp;file[]=edit_area_full_with_plugins.js'
  838. .'&amp;subdir[]=scripts/extjs3/adapter/ext/&amp;file[]=ext-base.js'
  839. .'&amp;subdir[]=scripts/extjs3/&amp;file[]=ext-all.js'
  840. .'&amp;subdir[]=scripts/extjs3-ext/ux.ondemandload/&amp;file[]=scriptloader.js'
  841. .'&amp;subdir[]=scripts/extjs3-ext/ux.editareaadapater/&amp;file[]=ext-editarea-adapter.js'
  842. .'&amp;subdir[]=scripts/extjs3-ext/ux.statusbar/&amp;file[]=ext-statusbar.js'
  843. .'&amp;subdir[]=scripts/extjs3-ext/ux.fileuploadfield/&amp;file[]=ext-fileUploadField.js'
  844. .'&amp;subdir[]=scripts/extjs3-ext/ux.locationbar/&amp;file[]=Ext.ux.LocationBar.js'
  845. .'&amp;gzip=1"></script>';
  846. $scriptTag .= '
  847. <link rel="stylesheet" href="'. _EXT_URL . '/fetchscript.php?'
  848. .'subdir[]=scripts/extjs3/resources/css/&amp;file[]=ext-all.css'
  849. .'&amp;subdir[]=scripts/extjs3-ext/ux.locationbar/&amp;file[]=LocationBar.css'
  850. .'&amp;subdir[]=scripts/extjs3-ext/ux.fileuploadfield/&amp;file[]=fileuploadfield.css'
  851. .'&amp;gzip=1" />';
  852. }
  853. $scriptTag .= '
  854. <script type="text/javascript" src="'. $GLOBALS['script_name'].'?option=com_extplorer&amp;action=include_javascript&amp;file=functions.js"></script>
  855. <script type="text/javascript" >editAreaLoader.baseURL = "'. _EXT_URL .'/scripts/editarea/";</script>';
  856. if (defined('EXT_STANDALONE')) {
  857. $GLOBALS['mainframe']->addcustomheadtag($scriptTag);
  858. } else {
  859. echo $scriptTag;
  860. }
  861. }
  862. function makeOption( $value, $text='', $value_name='value', $text_name='text' ) {
  863. $obj = new stdClass;
  864. $obj->$value_name = $value;
  865. $obj->$text_name = trim( $text ) ? $text : $value;
  866. return $obj;
  867. }
  868. function writableCell( $folder, $relative=1, $text='', $visible=1 ) {
  869. $writeable = '<b><font color="green">Writeable</font></b>';
  870. $unwriteable = '<b><font color="red">Unwriteable</font></b>';
  871. echo '<tr>';
  872. echo '<td class="item">';
  873. echo $text;
  874. if ( $visible ) {
  875. echo $folder . '/';
  876. }
  877. echo '</td>';
  878. echo '<td align="left">';
  879. if ( $relative ) {
  880. echo is_writable( "../$folder" ) ? $writeable : $unwriteable;
  881. } else {
  882. echo is_writable( "$folder" ) ? $writeable : $unwriteable;
  883. }
  884. echo '</td>';
  885. echo '</tr>';
  886. }
  887. /**
  888. * Generates an HTML select list
  889. * @param array An array of objects
  890. * @param string The value of the HTML name attribute
  891. * @param string Additional HTML attributes for the <select> tag
  892. * @param string The name of the object variable for the option value
  893. * @param string The name of the object variable for the option text
  894. * @param mixed The key that is selected
  895. * @returns string HTML for the select list
  896. */
  897. function selectList( &$arr, $tag_name, $tag_attribs, $key, $text, $selected=NULL ) {
  898. // check if array
  899. if ( is_array( $arr ) ) {
  900. reset( $arr );
  901. }
  902. $html = "\n<select name=\"$tag_name\" $tag_attribs>";
  903. $count = count( $arr );
  904. for ($i=0, $n=$count; $i < $n; $i++ ) {
  905. $k = $arr[$i]->$key;
  906. $t = $arr[$i]->$text;
  907. $id = ( isset($arr[$i]->id) ? @$arr[$i]->id : null);
  908. $extra = '';
  909. $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
  910. if (is_array( $selected )) {
  911. foreach ($selected as $obj) {
  912. $k2 = $obj->$key;
  913. if ($k == $k2) {
  914. $extra .= " selected=\"selected\"";
  915. break;
  916. }
  917. }
  918. } else {
  919. $extra .= ($k == $selected ? " selected=\"selected\"" : '');
  920. }
  921. $html .= "\n\t<option value=\"".$k."\"$extra>" . $t . "</option>";
  922. }
  923. $html .= "\n</select>\n";
  924. return $html;
  925. }
  926. /**
  927. * Writes a select list of integers
  928. * @param int The start integer
  929. * @param int The end integer
  930. * @param int The increment
  931. * @param string The value of the HTML name attribute
  932. * @param string Additional HTML attributes for the <select> tag
  933. * @param mixed The key that is selected
  934. * @param string The printf format to be applied to the number
  935. * @returns string HTML for the select list
  936. */
  937. function integerSelectList( $start, $end, $inc, $tag_name, $tag_attribs, $selected, $format="" ) {
  938. $start = intval( $start );
  939. $end = intval( $end );
  940. $inc = intval( $inc );
  941. $arr = array();
  942. for ($i=$start; $i <= $end; $i+=$inc) {
  943. $fi = $format ? sprintf( "$format", $i ) : "$i";
  944. $arr[] = extHTML::makeOption( $fi, $fi );
  945. }
  946. return extHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
  947. }
  948. /**
  949. * Writes a select list of month names based on Language settings
  950. * @param string The value of the HTML name attribute
  951. * @param string Additional HTML attributes for the <select> tag
  952. * @param mixed The key that is selected
  953. * @returns string HTML for the select list values
  954. */
  955. function monthSelectList( $tag_name, $tag_attribs, $selected ) {
  956. $arr = array(
  957. extHTML::makeOption( '01', _JAN ),
  958. extHTML::makeOption( '02', _FEB ),
  959. extHTML::makeOption( '03', _MAR ),
  960. extHTML::makeOption( '04', _APR ),
  961. extHTML::makeOption( '05', _MAY ),
  962. extHTML::makeOption( '06', _JUN ),
  963. extHTML::makeOption( '07', _JUL ),
  964. extHTML::makeOption( '08', _AUG ),
  965. extHTML::makeOption( '09', _SEP ),
  966. extHTML::makeOption( '10', _OCT ),
  967. extHTML::makeOption( '11', _NOV ),
  968. extHTML::makeOption( '12', _DEC )
  969. );
  970. return extHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
  971. }
  972. /**
  973. * Writes a yes/no select list
  974. * @param string The value of the HTML name attribute
  975. * @param string Additional HTML attributes for the <select> tag
  976. * @param mixed The key that is selected
  977. * @returns string HTML for the select list values
  978. */
  979. function yesnoSelectList( $tag_name, $tag_attribs, $selected, $yes=_CMN_YES, $no=_CMN_NO ) {
  980. $arr = array(
  981. extHTML::makeOption( '0', $no ),
  982. extHTML::makeOption( '1', $yes ),
  983. );
  984. return extHTML::selectList( $arr, $tag_name, $tag_attribs, 'value', 'text', $selected );
  985. }
  986. /**
  987. * Generates an HTML radio list
  988. * @param array An array of objects
  989. * @param string The value of the HTML name attribute
  990. * @param string Additional HTML attributes for the <select> tag
  991. * @param mixed The key that is selected
  992. * @param string The name of the object variable for the option value
  993. * @param string The name of the object variable for the option text
  994. * @returns string HTML for the select list
  995. */
  996. function radioList( &$arr, $tag_name, $tag_attribs, $selected=null, $key='value', $text='text' ) {
  997. reset( $arr );
  998. $html = "";
  999. for ($i=0, $n=count( $arr ); $i < $n; $i++ ) {
  1000. $k = $arr[$i]->$key;
  1001. $t = $arr[$i]->$text;
  1002. $id = ( isset($arr[$i]->id) ? @$arr[$i]->id : null);
  1003. $extra = '';
  1004. $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
  1005. if (is_array( $selected )) {
  1006. foreach ($selected as $obj) {
  1007. $k2 = $obj->$key;
  1008. if ($k == $k2) {
  1009. $extra .= " selected=\"selected\"";
  1010. break;
  1011. }
  1012. }
  1013. } else {
  1014. $extra .= ($k == $selected ? " checked=\"checked\"" : '');
  1015. }
  1016. $html .= "\n\t<input type=\"radio\" name=\"$tag_name\" id=\"$tag_name$k\" value=\"".$k."\"$extra $tag_attribs />";
  1017. $html .= "\n\t<label for=\"$tag_name$k\">$t</label>";
  1018. }
  1019. $html .= "\n";
  1020. return $html;
  1021. }
  1022. /**
  1023. * Writes a yes/no radio list
  1024. * @param string The value of the HTML name attribute
  1025. * @param string Additional HTML attributes for the <select> tag
  1026. * @param mixed The key that is selected
  1027. * @returns string HTML for the radio list
  1028. */
  1029. function yesnoRadioList( $tag_name, $tag_attribs, $selected, $yes=_CMN_YES, $no=_CMN_NO ) {
  1030. $arr = array(
  1031. extHTML::makeOption( '0', $no ),
  1032. extHTML::makeOption( '1', $yes )
  1033. );
  1034. return extHTML::radioList( $arr, $tag_name, $tag_attribs, $selected );
  1035. }
  1036. /**
  1037. * Cleans text of all formating and scripting code
  1038. */
  1039. function cleanText ( &$text ) {
  1040. $text = preg_replace( "'<script[^>]*>.*?</script>'si", '', $text );
  1041. $text = preg_replace( '/<a\s+.*?href="([^"]+)"[^>]*>([^<]+)<\/a>/is', '\2 (\1)', $text );
  1042. $text = preg_replace( '/<!--.+?-->/', '', $text );
  1043. $text = preg_replace( '/{.+?}/', '', $text );
  1044. $text = preg_replace( '/&nbsp;/', ' ', $text );
  1045. $text = preg_replace( '/&amp;/', ' ', $text );
  1046. $text = preg_replace( '/&quot;/', ' ', $text );
  1047. $text = strip_tags( $text );
  1048. $text = htmlspecialchars( $text );
  1049. return $text;
  1050. }
  1051. }
  1052. /**
  1053. * Utility function to return a value from a named array or a specified default
  1054. * @param array A named array
  1055. * @param string The key to search for
  1056. * @param mixed The default value to give if no key found
  1057. * @param int An options mask: _MOS_NOTRIM prevents trim, _MOS_ALLOWHTML allows safe html, _MOS_ALLOWRAW allows raw input
  1058. */
  1059. define( "_ext_NOTRIM", 0x0001 );
  1060. define( "_ext_ALLOWHTML", 0x0002 );
  1061. define( "_ext_ALLOWRAW", 0x0004 );
  1062. function extGetParam( &$arr, $name, $def=null, $mask=0 ) {
  1063. static $noHtmlFilter = null;
  1064. static $safeHtmlFilter = null;
  1065. $return = null;
  1066. if (isset( $arr[$name] )) {
  1067. $return = $arr[$name];
  1068. if (is_string( $return )) {
  1069. // trim data
  1070. if (!($mask&_ext_NOTRIM)) {
  1071. $return = trim( $return );
  1072. }
  1073. if ($mask&_ext_ALLOWRAW) {
  1074. // do nothing
  1075. } else if ($mask&_ext_ALLOWHTML) {
  1076. // do nothing - compatibility mode
  1077. } else {
  1078. // send to inputfilter
  1079. if (is_null( $noHtmlFilter )) {
  1080. $noHtmlFilter = new InputFilter( /* $tags, $attr, $tag_method, $attr_method, $xss_auto */ );
  1081. }
  1082. $return = $noHtmlFilter->process( $return );
  1083. if (empty($return) && is_numeric($def)) {
  1084. // if value is defined and default value is numeric set variable type to integer
  1085. $return = intval($return);
  1086. }
  1087. }
  1088. // account for magic quotes setting
  1089. if (!get_magic_quotes_gpc()) {
  1090. $return = stripslashes( $return );
  1091. }
  1092. }
  1093. return $return;
  1094. } else {
  1095. return $def;
  1096. }
  1097. }
  1098. /**
  1099. * Strip slashes from strings or arrays of strings
  1100. * @param mixed The input string or array
  1101. * @return mixed String or array stripped of slashes
  1102. */
  1103. function extStripslashes( &$value ) {
  1104. $ret = '';
  1105. if (is_string( $value )) {
  1106. $ret = stripslashes( $value );
  1107. } else {
  1108. if (is_array( $value )) {
  1109. $ret = array();
  1110. foreach ($value as $key => $val) {
  1111. $ret[$key] = extStripslashes( $val );
  1112. }
  1113. } else {
  1114. $ret = $value;
  1115. }
  1116. }
  1117. return $ret;
  1118. }
  1119. /**
  1120. * Recursively creates a new directory
  1121. *
  1122. * @param unknown_type $path
  1123. * @param unknown_type $rights
  1124. * @return unknown
  1125. */
  1126. function extMkdirR($path, $rights = 0777) {
  1127. $folder_path = array(
  1128. strstr($path, '.') ? dirname($path) : $path);
  1129. while(!@is_dir(dirname(end($folder_path)))
  1130. && dirname(end($folder_path)) != '/'
  1131. && dirname(end($folder_path)) != '.'
  1132. && dirname(end($folder_path)) != '') {
  1133. array_push($folder_path, dirname(end($folder_path)));
  1134. }
  1135. while($parent_folder_path = array_pop($folder_path)) {
  1136. @mkdir($parent_folder_path, $rights);
  1137. }
  1138. @mkdir( $path );
  1139. return is_dir( $path );
  1140. }
  1141. /**
  1142. * Utility function to read the files in a directory
  1143. * @param string The file system path
  1144. * @param string A filter for the names
  1145. * @param boolean Recurse search into sub-directories
  1146. * @param boolean True if to prepend the full path to the file name
  1147. */
  1148. function extReadDirectory( $path, $filter='.', $recurse=false, $fullpath=false ) {
  1149. $arr = array();
  1150. if (!@is_dir( $path )) {
  1151. return $arr;
  1152. }
  1153. $handle = opendir( $path );
  1154. while ($file = readdir($handle)) {
  1155. if( is_array( $file )) $file = $file['name'];
  1156. $dir = extPathName( $path.'/'.$file, false );
  1157. $isDir = @is_dir( $dir );
  1158. if (($file != ".") && ($file != "..")) {
  1159. if (preg_match( "/$filter/", $file )) {
  1160. if ($fullpath) {
  1161. $arr[] = trim( extPathName( $path.'/'.$file, false ) );
  1162. } else {
  1163. $arr[] = trim( $file );
  1164. }
  1165. }
  1166. if ($recurse && $isDir) {
  1167. $arr2 = extReadDirectory( $dir, $filter, $recurse, $fullpath );
  1168. $arr = array_merge( $arr, $arr2 );
  1169. }
  1170. }
  1171. }
  1172. closedir($handle);
  1173. asort($arr);
  1174. return $arr;
  1175. }
  1176. /**
  1177. * Function to strip additional / or \ in a path name
  1178. * @param string The path
  1179. * @param boolean Add trailing slash
  1180. */
  1181. function extPathName($p_path,$p_addtrailingslash = false) {
  1182. $retval = "";
  1183. $isWin = (substr(PHP_OS, 0, 3) == 'WIN');
  1184. if ($isWin) {
  1185. $retval = str_replace( '/', '\\', $p_path );
  1186. if ($p_addtrailingslash) {
  1187. if (substr( $retval, -1 ) != '\\') {
  1188. $retval .= '\\';
  1189. }
  1190. }
  1191. // Check if UNC path
  1192. $unc = substr($retval,0,2) == '\\\\' ? 1 : 0;
  1193. // Remove double \\
  1194. $retval = str_replace( '\\\\', '\\', $retval );
  1195. // If UNC path, we have to add one \ in front or everything breaks!
  1196. if ( $unc == 1 ) {
  1197. $retval = '\\'.$retval;
  1198. }
  1199. } else {
  1200. $retval = str_replace( '\\', '/', $p_path );
  1201. if ($p_addtrailingslash) {
  1202. if (substr( $retval, -1 ) != '/') {
  1203. $retval .= '/';
  1204. }
  1205. }
  1206. // Check if UNC path
  1207. $unc = substr($retval,0,2) == '//' ? 1 : 0;
  1208. // Remove double //
  1209. $retval = str_replace('//','/',$retval);
  1210. // If UNC path, we have to add one / in front or everything breaks!
  1211. if ( $unc == 1 ) {
  1212. $retval = '/'.$retval;
  1213. }
  1214. }
  1215. return $retval;
  1216. }
  1217. /**
  1218. * Utility function redirect the browser location to another url
  1219. *
  1220. * Can optionally provide a message.
  1221. * @param string The file system path
  1222. * @param string A filter for the names
  1223. */
  1224. function extRedirect( $url, $msg='' ) {
  1225. global $mainframe;
  1226. // specific filters
  1227. $iFilter = new InputFilter();
  1228. $url = $iFilter->process( $url );
  1229. if (!empty($msg)) {
  1230. $msg = $iFilter->process( $msg );
  1231. }
  1232. if ($iFilter->badAttributeValue( array( 'href', $url ))) {
  1233. $url = $GLOBALS['home_dir'];
  1234. }
  1235. if (trim( $msg )) {
  1236. if (strpos( $url, '?' )) {
  1237. $url .= '&extmsg=' . urlencode( $msg );
  1238. } else {
  1239. $url .= '?extmsg=' . urlencode( $msg );
  1240. }
  1241. }
  1242. if (headers_sent()) {
  1243. echo "<script>document.location.href='$url';</script>\n";
  1244. } else {
  1245. @ob_end_clean(); // clear output buffer
  1246. header( 'HTTP/1.1 301 Moved Permanently' );
  1247. header( "Location: ". $url );
  1248. }
  1249. exit();
  1250. }
  1251. /**
  1252. * Random password generator
  1253. * @return password
  1254. */
  1255. function extMakePassword($length=8) {
  1256. $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1257. $makepass = '';
  1258. mt_srand(10000000*(double)microtime());
  1259. for ($i = 0; $i < $length; $i++)
  1260. $makepass .= $salt[mt_rand(0,61)];
  1261. return $makepass;
  1262. }
  1263. /**
  1264. * Wrapper Function to encode passwords (maybe sometimes we don't use md5 anymore?)
  1265. *
  1266. * @param string $pass
  1267. * @return string
  1268. */
  1269. function extEncodePassword( $pass ) {
  1270. require_once( _EXT_PATH.'/libraries/PasswordHash.php');
  1271. $hasher = new PasswordHash(8, FALSE);
  1272. $hash = $hasher->HashPassword($pass);
  1273. return $hash;
  1274. }
  1275. if (!function_exists('html_entity_decode')) {
  1276. /**
  1277. * html_entity_decode function for backward compatability in PHP
  1278. * @param string
  1279. * @param string
  1280. */
  1281. function html_entity_decode ($string, $opt = ENT_COMPAT) {
  1282. $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  1283. $trans_tbl = array_flip ($trans_tbl);
  1284. if ($opt & 1) { // Translating single quotes
  1285. // Add single quote to translation table;
  1286. // doesn't appear to be there by default
  1287. $trans_tbl["&apos;"] = "'";
  1288. }
  1289. if (!($opt & 2)) { // Not translating double quotes
  1290. // Remove double quote from translation table
  1291. unset($trans_tbl["&quot;"]);
  1292. }
  1293. return strtr ($string, $trans_tbl);
  1294. }
  1295. }
  1296. //------------------------------------------------------------------------------
  1297. function logout() {
  1298. session_destroy();
  1299. session_write_close();
  1300. header("Location: ".$GLOBALS["script_name"]);
  1301. }
  1302. //------------------------------------------------------------------------------
  1303. /**
  1304. * Returns an IP- and BrowserID- based Session ID
  1305. *
  1306. * @param string $id
  1307. * @return string
  1308. */
  1309. function get_session_id( $id=null ) {
  1310. return extMakePassword( 32 );
  1311. }