PageRenderTime 62ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/wordpress-flash-uploader/tfu/tfu_helper.php

https://bitbucket.org/sidi09/aryans
PHP | 2663 lines | 2286 code | 163 blank | 214 comment | 633 complexity | 7771ab0174e4ff16a1de50286d71e374 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-3.0, GPL-2.0
  1. <?php
  2. /**
  3. * TWG Flash uploader 2.14.x
  4. *
  5. * Copyright (c) 2004-2011 TinyWebGallery
  6. * written by Michael Dempfle
  7. *
  8. *
  9. * This file has all the helper functions.
  10. * Normally you don't have to modify anything here.
  11. * Only the timezone can be interesting for you: $timezone
  12. */
  13. /**
  14. * * ensure this file is being included by a parent file
  15. */
  16. defined('_VALID_TWG') or die('Direct Access to this location is not allowed.');
  17. $tfu_help_version = '2.14';
  18. // some globals you can change
  19. $check_safemode = true; // New 2.12.x - By default TFU checks if you have a safe mode problem. On some server this test does not work. There you can try to turn it off and test if you can e.g. create directories, upload files to new created directories.
  20. $session_double_fix = false; // this is only needed if you get errors because of corrupt sessions. If you turn this on a backup is made and checked if the first one is corrupt
  21. $timezone = ''; // Please set your timezone here if you have problems with timezones - if you need exact times - enter your timezone - see http://www.dynamicwebpages.de/php/timezones.php
  22. if (function_exists('date_default_timezone_set')) { // php 5.1.x
  23. if ($timezone != '') {
  24. @date_default_timezone_set($timezone);
  25. } else if (function_exists('date_default_timezone_get')) {
  26. set_error_handler('on_error_no_output');
  27. @date_default_timezone_set(@date_default_timezone_get());
  28. set_error_handler('on_error');
  29. } else {
  30. @date_default_timezone_set('Europe/Berlin');
  31. }
  32. }
  33. // default settings you should normally not change.
  34. $bg_color_preview_R = 255;
  35. $bg_color_preview_G = 255;
  36. $bg_color_preview_B = 255;
  37. $input_invalid = false;
  38. $old_error_handler = false;
  39. $master_profile = false;
  40. $debug_file = dirname(__FILE__) . "/tfu.log"; // can be overwritten in the config!
  41. tfu_setHeader();
  42. @ob_start();
  43. include dirname(__FILE__) . '/tfu_zip.class.php';
  44. // check if all included files have the same version to avoid problems during update!
  45. if ($tfu_zip_version != '2.14') {
  46. tfu_debug('Not all files belong to this version. Please update all files.');
  47. }
  48. /**
  49. * * Needed for Https and IE!
  50. */
  51. function tfu_setHeader()
  52. {
  53. // header("Pragma: public");
  54. // header("Expires: 0");
  55. // header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  56. // header('Pragma: I-hate-internet-explorer');
  57. // header('Cache-Control:no-store');
  58. if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
  59. {
  60. header('Pragma: private');
  61. header('Cache-Control: private');
  62. }
  63. else
  64. {
  65. header('Pragma: public');
  66. header('Cache-Control: no-store, no-cache, must-revalidate' );
  67. header('Cache-Control: post-check=0, pre-check=0', false );
  68. }
  69. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
  70. header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
  71. header('Vary: User-Agent');
  72. }
  73. /**
  74. * function:tfu_debug()
  75. */
  76. function tfu_debug($data)
  77. {
  78. global $debug_file; // set in the tfu_config.php or is overwritten by the twg config
  79. global $enable_enhanced_debug;
  80. $data = replaceInput($data); // we check output data too - you never know!
  81. $input_invalid = false;
  82. if(stristr($data, 'called statically') === false && stristr($data, 'deprecated') === false) { // This error can happen in Joomla and can be ignored
  83. $debug_string = date('m.d.Y G:i:s') . ' - ' . $data . "\n";
  84. if ($enable_enhanced_debug) {
  85. $debug_string .= ' Request: ' . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] . "\n";
  86. foreach (debug_backtrace() as $element) {
  87. $debug_string .= ' Stack: ' . basename($element['file']) . ":" . $element['line'] . ":" . $element['function'];
  88. foreach ($element['args'] as $par) {
  89. if (is_array($par)) {
  90. $par = str_replace("\n", "", print_r($par, true));
  91. }
  92. $debug_string .= ":" . substr($par, 0, 100); // max 100 chars
  93. }
  94. $debug_string .= "\n";
  95. }
  96. }
  97. if ($debug_file == '') {
  98. @ob_start();
  99. @error_log($debug_string, 0);
  100. @ob_end_clean();
  101. return;
  102. }
  103. if (file_exists($debug_file)) {
  104. if (filesize($debug_file) > 2000000) { // debug file max = 2MB !
  105. // we move the old one and start a new one - but only once!
  106. rename (dirname(__FILE__) . '/tfu.log', dirname(__FILE__) . '/tfu.log.bak');
  107. $debug_file_local = fopen($debug_file, 'w');
  108. } else {
  109. $debug_file_local = fopen($debug_file, 'a');
  110. }
  111. fputs($debug_file_local, $debug_string);
  112. fclose($debug_file_local);
  113. } else {
  114. if (is_writeable(dirname(__FILE__))) {
  115. if (!isset($debug_file)) { // if helper is included somewhere else!
  116. $debug_file = dirname(__FILE__) . "/tfu.log";
  117. }
  118. $debug_file_local = @fopen($debug_file, 'a');
  119. @fputs($debug_file_local, $debug_string);
  120. @fclose($debug_file_local);
  121. clearstatcache();
  122. } else {
  123. @ob_start();
  124. @error_log($debug_string, 0);
  125. @ob_end_clean();
  126. }
  127. }
  128. }
  129. }
  130. function on_error($num, $str, $file, $line)
  131. {
  132. if ((strpos ($file, 'email.inc.php') === false) && (strpos ($str, 'fopen') === false) && (strpos ($str, 'Deprecated') === false)) {
  133. tfu_debug("ERROR $num in " . substr($file, -40) . ", line $line: $str");
  134. }
  135. }
  136. function on_error_no_output($num, $str, $file, $line)
  137. {
  138. }
  139. if (!isset($skip_error_handling)) {
  140. @ini_set('display_errors','On');
  141. $old_error_handler = set_error_handler("on_error");
  142. }
  143. /**
  144. * Resizes a jpg/png/gif file if needed and stores it back to the original location
  145. * Needs gdlib > 2.0!
  146. * All other files are untouched
  147. * 1 = ok
  148. * 0 = failed
  149. * 2 = unknown - we retry after the save later.
  150. *
  151. */
  152. function resize_file($image, $size, $compression, $image_name, $dest_image = false)
  153. {
  154. global $use_image_magic, $image_magic_path, $enable_upload_debug, $store;
  155. if (!isset($store)) {
  156. $store = 0;
  157. }
  158. set_error_handler('on_error_no_output');
  159. ini_set('gd.jpeg_ignore_warning', 1); // since php 5.1.3 this leads that corrupt jpgs are read much better!
  160. set_error_handler('on_error');
  161. // we can do some caching here! - nice for 2.6 ;).
  162. if ($size == 'undefined') {
  163. tfu_debug('Resize: ERROR - No size is sent from the flash. Make sure that you have at least one value entered in the config. The image is NOT resized.');
  164. return 1;
  165. }
  166. $srcx = 0;
  167. $srcy = 0;
  168. if ($enable_upload_debug) { tfu_debug('Resize: Preparing to resize "' . $image . ' with size: '.$size.'"'); }
  169. if (file_exists($image)) {
  170. $oldsize = getimagesize($image);
  171. if ($oldsize[0] == 0) {
  172. // for broken images we try to read the exif data!
  173. $oldsize = get_exif_size($image, $image_name);
  174. }
  175. $oldsizex = $oldsize[0];
  176. $oldsizey = $oldsize[1];
  177. if (strpos($size, "x") !== false) {
  178. $s = explode("x", $size);
  179. $width = $s[0];
  180. $height = $s[1] ;
  181. } else {
  182. if (($oldsizex < $size) && ($oldsizey < $size)) {
  183. if ($enable_upload_debug) { tfu_debug('Resize: Image ('. $oldsizex .'x' .$oldsizey. ') is not resized with setting "' . $size . '"'); }
  184. return 1;
  185. }
  186. if ($oldsizex > $oldsizey) { // querformat - this keeps the dimension between horzonal and vertical
  187. $width = $size;
  188. $height = ($width / $oldsizex) * $oldsizey;
  189. } else { // hochformat - this keeps the dimension between horzonal an vertical
  190. $height = $size;
  191. $width = ($height / $oldsizey) * $oldsizex;
  192. }
  193. $width = round($width);
  194. $height = round($height);
  195. }
  196. if ($use_image_magic) {
  197. if ($enable_upload_debug) {
  198. tfu_debug("Resize: Image magick is used");
  199. }
  200. $ima = $loc_ima = realpath($image);
  201. $resize = $width . 'x' . $height;
  202. if ($dest_image) {
  203. $store = 1;
  204. $loc_ima = $dest_image;
  205. } else {
  206. if ($store == 2) { // 1st attempt was not o.k. - we try it with a backup name.
  207. $loc_ima = $ima . '.bak';
  208. }
  209. }
  210. $command = $image_magic_path . ' "' . $ima . '" -quality ' . $compression . ' -resize ' . $resize . ' "' . $loc_ima . '"';
  211. if ($enable_upload_debug) {
  212. tfu_debug("Resize: Image magick command: " . $command);
  213. }
  214. execute_command ($command);
  215. // we check if the resize was o.k.
  216. if ($store == 0) { // we do the resize to the same image again
  217. // we check if the resize was o.k.
  218. $newsize = getimagesize($ima);
  219. if ($width != $newsize[0]) { // resize failed for unknown reasons.
  220. if ($enable_upload_debug) { tfu_debug("Resize: Image could not be resized."); }
  221. return 2; // we try to resize again later!
  222. } else {
  223. return 1;
  224. }
  225. } else { // we resize to a temp file
  226. if (file_exists($ima . '.bak')) {
  227. $newsize = getimagesize($ima . '.bak');
  228. if ($width != $newsize[0]) { // resize failed for unknown reasons.
  229. if ($enable_upload_debug) { tfu_debug("Resize: Image could not be resized - wrong size"); }
  230. unlink($ima . '.bak');
  231. return 2; // we try to resize again later!
  232. } else { // resize is o.k.
  233. unlink($ima);
  234. rename($ima . '.bak',$ima);
  235. return 1;
  236. }
  237. } else {
  238. if ($enable_upload_debug) { tfu_debug("Resize: Image could not be resized in temp upload dir. Retry after move to final destination."); }
  239. return 2;
  240. }
  241. }
  242. } else {
  243. if ($enable_upload_debug) { tfu_debug("Resize: gd-lib is used."); }
  244. if (!isMemoryOk($oldsize, $size, $image_name, true)) {
  245. return 0;
  246. }
  247. if ($enable_upload_debug) { tfu_debug("Resize: memory seems o.k."); }
  248. $src = get_image_src($image, $oldsize[2]);
  249. if (!$src) {
  250. tfu_debug('File ' . $image_name . ' cannot be resized!');
  251. return false;
  252. }
  253. $dst = ImageCreateTrueColor($width, $height);
  254. imagecopyresampled($dst, $src, 0, 0, $srcx, $srcy , $width, $height, $oldsizex, $oldsizey);
  255. @imagedestroy($src);
  256. if ($dest_image) {
  257. $image = $dest_image;
  258. }
  259. if ($enable_upload_debug) { tfu_debug("Resize: image was resampled."); }
  260. if ($oldsize[2] == 1) { // gif
  261. $res = imagegif($dst, $image);
  262. } else if ($oldsize[2] == 2) { // jpg
  263. $res = imagejpeg($dst, $image, $compression);
  264. } else if ($oldsize[2] == 3) { // png
  265. $res = imagepng($dst, $image);
  266. } else {
  267. $res = imagejpeg($dst, $image, $compression);
  268. }
  269. if ($res) {
  270. // we check if the resize was o.k.
  271. $newsize = getimagesize($image);
  272. if ($width != $newsize[0]) { // resize failed for unknown reasons.
  273. if ($enable_upload_debug) { tfu_debug("Resize: Image could not be resized."); }
  274. return 2;
  275. }
  276. if ($enable_upload_debug) { tfu_debug("Resize: Image was saved and resized."); }
  277. @imagedestroy($dst);
  278. return 1;
  279. } else {
  280. tfu_debug('cannot save: ' . $image);
  281. return 0;
  282. }
  283. }
  284. } else
  285. return 2;
  286. }
  287. /**
  288. * resizes a file and writes it back to the user! - can do jpg, png and gif if the support is there !
  289. * renamed png's (that that are actually jpg's are handled as well!)
  290. * Needs gdlib > 2.0!
  291. */
  292. function send_thumb($image, $compression, $sizex, $sizey, $generateOnly = false)
  293. {
  294. global $bg_color_preview_R, $bg_color_preview_G, $bg_color_preview_B;
  295. global $info_text, $info_textcolor_R, $info_textcolor_G, $info_textcolor_B, $info_font, $info_fontsize;
  296. set_error_handler('on_error_no_output');
  297. ini_set('gd.jpeg_ignore_warning', 1); // since php 5.1.3 this leads that corrupt jpgs are read much better!
  298. set_error_handler('on_error');
  299. $srcx = 0;
  300. $srcy = 0;
  301. $dimx = $sizex;
  302. $dimy = $sizey;
  303. $usethumbs = false;
  304. if (file_exists(dirname(__FILE__) . '/thumbs') && is_writable(dirname(__FILE__) . '/thumbs')) { // is a caching dir available and writeable?
  305. $cachename = dirname(__FILE__) . '/thumbs/' . sha1($image . $sizex) . '.jpg';
  306. $usethumbs = true;
  307. }
  308. if ($usethumbs && file_exists($cachename)) {
  309. // we return the jpg!
  310. header('Content-type: image/jpg');
  311. header('Content-Length: ' . filesize($cachename));
  312. $fp = fopen($cachename, 'rb');
  313. while ($content = fread($fp, 8192)) {
  314. print $content;
  315. }
  316. fclose($fp);
  317. return true;
  318. } else if (file_exists($image)) {
  319. if (filesize($image) == 0) {
  320. return false;
  321. }
  322. $oldsize = getimagesize($image);
  323. // for broken images we try to read the exif data!
  324. if ($oldsize[0] == 0) {
  325. $oldsize = get_exif_size($image, $image);
  326. }
  327. $oldsizex = $oldsize[0];
  328. $oldsizey = $oldsize[1];
  329. if ($oldsizex < $sizex && $oldsizey < $sizey) {
  330. $sizex = $oldsizex;
  331. $sizey = $oldsizey;
  332. }
  333. $height = $sizey;
  334. $width = ($height / $oldsizey) * $oldsizex;
  335. if ($width > $sizex) {
  336. $width = $sizex;
  337. $height = ($width / $oldsizex) * $oldsizey;
  338. }
  339. if (isMemoryOk($oldsize, $sizex, '')) {
  340. $src = get_image_src($image, $oldsize[2]);
  341. if (!$src) { // error in image!
  342. if ($sizex < 100) {
  343. // we return an empty white one ;).
  344. $src = ImageCreateTrueColor($oldsizex, $oldsizey);
  345. $back = imagecolorallocate($src, 255, 255, 255);
  346. imagefilledrectangle($src, 0, 0, $oldsizex, $oldsizex, $back);
  347. }
  348. tfu_debug($image . ' is not a valid image - please check the file.');
  349. return false;
  350. }
  351. // $dst = ImageCreateTrueColor($width, $height);
  352. $dst = ImageCreateTrueColor($dimx, $dimy);
  353. if ($dimx < 100) { // white bg for small preview
  354. $back = imagecolorallocate($dst, $bg_color_preview_R, $bg_color_preview_G, $bg_color_preview_B);
  355. } else { // gray bg for big preview
  356. $back = imagecolorallocate($dst, 245, 245, 245);
  357. }
  358. imagefilledrectangle($dst, 0, 0, $dimx, $dimy, $back);
  359. if ($dimx > 100) { // border
  360. imagerectangle ($dst, 0, 0, $dimx-1, $dimy-1, imagecolorallocate($dst, 160, 160, 160));
  361. }
  362. $offsetx = 0;
  363. $offsetx_b = 0;
  364. if ($dimx > $width) { // we have to center!
  365. $offsetx = floor(($dimx - $width) / 2);
  366. } else if ($dimx > 100) {
  367. $offsetx = 4;
  368. $offsetx_b = 8;
  369. }
  370. $offsety = 0;
  371. $offsety_b = 0;
  372. if ($dimy > $height) { // we have to center!
  373. $offsety = floor(($dimy - $height) / 2);
  374. } else if ($dimx > 100) {
  375. $offsety = 4;
  376. $offsety_b = 8;
  377. }
  378. $trans = imagecolortransparent ($src);
  379. imagecolorset ($src, $trans, 255, 255, 255);
  380. imagecolortransparent($src, imagecolorallocate($src, 0, 0, 0));
  381. imagecopyresampled($dst, $src, $offsetx, $offsety, $srcx, $srcy, $width - $offsetx_b, $height - $offsety_b, $oldsizex, $oldsizey);
  382. if (function_exists("imagettftext") && $dimx > 100 && $info_text != '' ) {
  383. // some extra info at the bottom of the image. Available parameters: {date} {size} {dimension}
  384. $text = str_replace('{dimension}', $oldsizex."x".$oldsizey, $info_text);
  385. $text = str_replace('{size}', formatSize(filesize($image)), $text);
  386. $text = str_replace('{date}', date("d.m.Y",filemtime($image)), $text);
  387. $color = imagecolorclosest ($dst, $info_textcolor_R, $info_textcolor_G, $info_textcolor_B);
  388. imagettftext($dst, $info_fontsize, 0, 8, $dimy-8, $color, $info_font, $text);
  389. }
  390. header('Content-type: image/jpg');
  391. if ($usethumbs) { // we save the thumb
  392. imagejpeg($dst, $cachename, $compression);
  393. }
  394. if (!$generateOnly) {
  395. ob_start();
  396. if (imagejpeg($dst, '', $compression)) {
  397. $buffer = ob_get_contents();
  398. header('Content-Length: ' . strlen($buffer));
  399. ob_end_clean();
  400. echo $buffer;
  401. @imagedestroy($dst);
  402. return true;
  403. } else {
  404. ob_end_flush();
  405. tfu_debug('cannot save: ' . $image);
  406. @imagedestroy($src);
  407. }
  408. }
  409. }
  410. }
  411. return false;
  412. }
  413. // we check if we can get a memory problem!
  414. function isMemoryOk($oldsize, $newsize, $image_name, $debug = true)
  415. {
  416. $memory_read = (($oldsize[0] * $oldsize[1] * 6) + 2048576) * 1.1; // mem and we add 2 MB + 10% for safty
  417. $memory_orig = ($newsize * $newsize * 6) * 1.1; // 10% overhead.
  418. $memory = $memory_read + $memory_orig;
  419. // I try to increase the memory if more is needed and if it is possible.
  420. if (function_exists("memory_get_usage")) {
  421. $InUse=memory_get_usage();
  422. if ($memory > return_kbytes(ini_get('memory_limit')*1024) - $InUse)
  423. {
  424. @ini_set('memory_limit',$memory + $InUse + 5000000); // 5 MB for processing extra!
  425. }
  426. }
  427. $memory_limit = return_kbytes(ini_get('memory_limit')) * 1024;
  428. if ($memory > $memory_limit && $memory_limit > 0) { // we store the number of images that have a size problem in the session and output this in the readDir file
  429. $mem_errors = 0;
  430. if (isset($_SESSION['upload_memory_limit'])) {
  431. $mem_errors = $_SESSION['upload_memory_limit'];
  432. }
  433. $_SESSION['upload_memory_limit'] = ($mem_errors + 1);
  434. if ($debug) {
  435. tfu_debug('File ' . $image_name . ' cannot be processed because not enough memory is available! Needed: ~' . $memory . '. Available: ' . $memory_limit);
  436. }
  437. return false;
  438. } else {
  439. return true;
  440. }
  441. }
  442. $sn = get_server_name();
  443. function get_image_src($image, $type)
  444. {
  445. set_error_handler('on_error_no_output'); // No error shown because we handle this error!
  446. if ($type == 1) { // gif
  447. $src = imagecreatefromgif($image);
  448. } else if ($type == 2) { // jpg
  449. $src = imagecreatefromjpeg($image);
  450. } else if ($type == 3) { // png
  451. $src = @imagecreatefrompng($image);
  452. } else {
  453. $src = imagecreatefromjpeg($image); // if error we try read an jpg!
  454. }
  455. set_error_handler('on_error');
  456. return $src;
  457. }
  458. /**
  459. * A small helper function !
  460. */
  461. function return_kbytes($val)
  462. {
  463. $val = trim($val);
  464. if (strlen($val) == 0) {
  465. return 0;
  466. }
  467. $last = strtolower($val{strlen($val)-1});
  468. switch ($last) {
  469. // The 'G' modifier is available since PHP 5.1.0
  470. case 'g':
  471. $val *= 1024;
  472. case 'm':
  473. $val *= 1024;
  474. case 'k':
  475. $val *= 1;
  476. }
  477. return $val;
  478. }
  479. $m = is_renameable();
  480. /**
  481. * get maximum upload size
  482. */
  483. function getMaximumUploadSize()
  484. {
  485. $upload_max = return_kbytes(ini_get('upload_max_filesize'));
  486. $post_max = return_kbytes(ini_get('post_max_size'));
  487. return $upload_max < $post_max ? $upload_max : $post_max;
  488. }
  489. /**
  490. * compares caseinsensitive - normally this could be done with natcasesort -
  491. * but this seems to be buggy on my test system!
  492. */
  493. function mycmp ($a, $b)
  494. {
  495. return strnatcasecmp ($a, $b);
  496. }
  497. /**
  498. * compares caseinsensitive - ascending for date
  499. */
  500. function mycmp_date ($a, $b)
  501. {
  502. return strnatcasecmp ($b, $a);
  503. }
  504. function cmp_dec ($a, $b)
  505. {
  506. return mycmp(urldecode($a), urldecode($b));
  507. }
  508. function cmp_dir_dec ($a, $b)
  509. {
  510. $a = substr($a, 0);
  511. $b = substr($b, 0);
  512. return mycmp(urldecode($a), urldecode($b));
  513. }
  514. function cmp_date_dec ($a, $b)
  515. {
  516. return mycmp_date(urldecode($a), urldecode($b));
  517. }
  518. /**
  519. * deletes everything from the starting dir on! tfu deletes only one level by default - but this
  520. * is triggered by the endableing/disabling of the delete Folder status! not by this function!
  521. */
  522. function remove($item) // remove file / dir
  523. {
  524. $item = realpath($item);
  525. $ok = true;
  526. if (is_link($item) || is_file($item))
  527. $ok = @unlink($item);
  528. elseif (is_dir($item)) {
  529. if (($handle = opendir($item)) === false)
  530. return false;
  531. while (($file = readdir($handle)) !== false) {
  532. if (($file == '..' || $file == '.')) continue;
  533. $new_item = $item . '/' . $file;
  534. if (!file_exists($new_item))
  535. return false;
  536. if (is_dir($new_item)) {
  537. $ok = remove($new_item);
  538. } else {
  539. $ok = @unlink($new_item);
  540. }
  541. }
  542. closedir($handle);
  543. $ok = @rmdir($item);
  544. }
  545. return $ok;
  546. }
  547. function is_tfu_deletable($file)
  548. {
  549. $isWindows = substr(PHP_OS, 0, 3) == 'WIN';
  550. set_error_handler('on_error_no_output');
  551. $owner = @fileowner($file);
  552. set_error_handler('on_error');
  553. // if we cannot read the owner we assume that the safemode is on and we cannot access this file!
  554. if ($owner === false) {
  555. return false;
  556. }
  557. // if dir owner not same as effective uid of this process, then perms must be full 777.
  558. // No other perms combo seems reliable across system implementations
  559. if (function_exists('posix_getpwuid')) {
  560. if (!$isWindows && posix_geteuid() !== $owner) {
  561. return (substr(decoct(@fileperms($file)), -3) == '777' || @is_writable(dirname($file)));
  562. }
  563. }
  564. if ($isWindows && getmyuid() != $owner) {
  565. return (substr(decoct(fileperms($file)), -3) == '777');
  566. }
  567. // otherwise if this process owns the directory, we can chmod it ourselves to delete it
  568. return is_writable(dirname($file));
  569. }
  570. function replaceInput($input)
  571. {
  572. global $input_invalid;
  573. $output = str_replace('<', '_', $input);
  574. $output = str_replace('>', '_', $output);
  575. $output = str_replace('?', '_Q_', $input);
  576. // we check some other settings too :)
  577. if (strpos($output, 'cookie(') || strpos($output, 'popup(') || strpos($output, 'open(') || strpos($output, 'alert(') || strpos($output, 'reload(') || strpos($output, 'refresh(')) {
  578. $output = 'XSS';
  579. }
  580. // we check for security if a .. is in the path we remove this! and .// like in http:// is invalid too!
  581. $output = str_replace("..", "__", $output);
  582. $output = str_replace("//", "__", $output);
  583. return $output;
  584. }
  585. function getCurrentDir()
  586. {
  587. // we read the dir - first session, then parameter, then default!
  588. if (isset($_SESSION['TFU_DIR'])) {
  589. $dir = $_SESSION['TFU_DIR'];
  590. } else {
  591. $dir = 'upload';
  592. }
  593. return $dir;
  594. }
  595. function getFileName($dir)
  596. {
  597. global $fix_utf8, $exclude_directories, $sort_files_by_date, $hide_hidden_files, $enable_enhanced_debug;
  598. if (!isset($_GET['index']) || $_GET['index'] == '') {
  599. return '';
  600. }
  601. $index = parseInputParameter($_GET['index']);
  602. // All files are sorted in the array myFiles
  603. $dirhandle = opendir($dir);
  604. $myFiles = array();
  605. while (($file = readdir($dirhandle)) !== false) {
  606. if ($file != '.' && $file != '..' && !in_array($file, $exclude_directories)&& (!($hide_hidden_files && (strpos($file, '.') === 0)))) {
  607. if (!is_dir($dir . '/' . $file) && check_view_extension($file)) {
  608. if ($sort_files_by_date) {
  609. $file = filemtime(($dir . '/' . $file)) . $file;
  610. }
  611. array_push($myFiles, fix_encoding($file, $fix_utf8));
  612. }
  613. }
  614. }
  615. closedir ($dirhandle);
  616. if ($sort_files_by_date) {
  617. usort ($myFiles, 'mycmp_date');
  618. } else {
  619. usort ($myFiles, 'mycmp');
  620. }
  621. // now we have the same order as in the listing and check if we have one or multiple indexes !
  622. if (strpos($index, ',') === false) { // only 1 selection
  623. if (isset($myFiles[$index])) {
  624. return get_decoded_string($dir, $myFiles[$index]);
  625. } else {
  626. if ($enable_enhanced_debug) {
  627. tfu_debug("File index not found.");
  628. }
  629. return "_FILE_NOT_FOUND";
  630. }
  631. } else { // we return an array !
  632. // we need the offset
  633. $offset = parseInputParameter($_GET['offset']);
  634. $filenames = array();
  635. $index = trim($index, ',');
  636. $indices = explode(',', $index);
  637. foreach ($indices as $ind) {
  638. $filenames[] = get_decoded_string($dir, $myFiles[$ind - $offset]);
  639. }
  640. return $filenames;
  641. }
  642. }
  643. function get_decoded_string($dir, $string)
  644. {
  645. global $fix_utf8;
  646. if ($fix_utf8 == 'none') {
  647. return $dir . '/' . $string;
  648. } else if ($fix_utf8 == '') {
  649. return $dir . '/' . utf8_decode(remove_sort_prefix($string));
  650. } else {
  651. return $dir . '/' . iconv('UTF-8', $fix_utf8, remove_sort_prefix($string));
  652. }
  653. }
  654. function remove_sort_prefix($string) {
  655. global $sort_files_by_date;
  656. if ($sort_files_by_date) {
  657. return substr($string, 10);
  658. } else {
  659. return $string;
  660. }
  661. }
  662. function getRootUrl() {
  663. if (isset($_SERVER)) {
  664. $GLOBALS['__SERVER'] = &$_SERVER;
  665. } elseif (isset($HTTP_SERVER_VARS)) {
  666. $GLOBALS['__SERVER'] = &$HTTP_SERVER_VARS;
  667. }
  668. $dirn = dirname ($GLOBALS['__SERVER']['PHP_SELF']);
  669. if ($dirn == '\\' || $dirn == '/') $dirn = '';
  670. return 'http' . (isset($GLOBALS['__SERVER']['HTTPS']) ? 's' : '') . '://' . $GLOBALS['__SERVER']['HTTP_HOST'] . $dirn . '/';
  671. }
  672. function tfu_checkSession()
  673. {
  674. }
  675. if (isset($_SESSION['TF' . 'U_RN'])) {
  676. $s = $_SESSION['TF' . 'U_RN'];
  677. $t = substr($s, 0, 3) . substr($s, 21, 3) . substr($s, 10, 4);
  678. if (time() > ($t + (6 * 12 * 2 * 1000))) $_SESSION['TF' . 'U_RN'] = '0';
  679. }
  680. /**
  681. * * removes ../ in a pathname!
  682. */
  683. function fixUrl($url)
  684. {
  685. $pos = strpos ($url, '../');
  686. while ($pos !== false && $pos != 0) {
  687. $before = substr($url, 0, $pos-1);
  688. $after = substr($url, $pos + 3);
  689. $before = substr($before, 0, strrpos($before, '/') + 1);
  690. $url = $before . $after;
  691. $pos = strpos ($url, '../');
  692. }
  693. return $url;
  694. }
  695. function runsNotAsCgi()
  696. {
  697. $no_cgi = true;
  698. if (isset($_SERVER['SERVER_SOFTWARE'])) {
  699. $mystring = $_SERVER['SERVER_SOFTWARE'];
  700. $pos = strpos ($mystring, 'CGI');
  701. if ($pos === false) {
  702. // nicht gefunden...
  703. } else {
  704. $no_cgi = false;
  705. }
  706. $mystring = $_SERVER['SERVER_SOFTWARE'];
  707. $pos = strpos ($mystring, 'cgi');
  708. if ($pos === false) {
  709. // nicht gefunden...
  710. } else {
  711. $no_cgi = false;
  712. }
  713. }
  714. return $no_cgi;
  715. }
  716. function has_safemode_problem_global()
  717. {
  718. $isWindows = substr(PHP_OS, 0, 3) == 'WIN';
  719. $no_cgi = runsNotAsCgi();
  720. if (function_exists('posix_getpwuid') && function_exists('posix_getpwuid')) {
  721. if (!isset($_SESSION['tfu_posix_geteuid_works'])) {
  722. $_SESSION['tfu_posix_geteuid_works'] = 'check';
  723. $userid = @posix_geteuid();
  724. $userinfo = @posix_getpwuid($userid);
  725. $def_user = array ('apache', 'nobody', 'www');
  726. if (in_array ($userinfo['name'], $def_user)) {
  727. $no_cgi = true;
  728. }
  729. unset($_SESSION['tfu_posix_geteuid_works']);
  730. }
  731. }
  732. if (ini_get('safe_mode') == 1 && $no_cgi && !$isWindows) {
  733. return true;
  734. }
  735. return false;
  736. }
  737. // set a umask that makes the files deletable again!
  738. if ($check_safemode && (has_safemode_problem_global() || runsNotAsCgi())) {
  739. umask(0000); // otherwise you cannot delete files anymore with ftp if you are no the owner!
  740. } else {
  741. umask(0022); // Added to make created files/dirs group writable
  742. }
  743. function gd_version()
  744. {
  745. static $gd_version_number = null;
  746. if ($gd_version_number === null) {
  747. if (function_exists('gd_info')) {
  748. $info = gd_info();
  749. $module_info = $info['GD Version'];
  750. if (preg_match("/[^\d\n\r]*?([\d\.]+)/i",
  751. $module_info, $matches)) {
  752. $gd_version_number = $matches[1];
  753. } else {
  754. $gd_version_number = 0;
  755. }
  756. } else { // needed before 4.3 !
  757. ob_start();
  758. phpinfo(8);
  759. $module_info = ob_get_contents();
  760. @ob_end_clean();
  761. if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
  762. $module_info, $matches)) {
  763. $gd_version_number = $matches[1];
  764. } else {
  765. $gd_version_number = 0;
  766. }
  767. }
  768. }
  769. return $gd_version_number;
  770. }
  771. function is_gd_version_min_20()
  772. {
  773. if (gd_version() >= 2) {
  774. return 'true';
  775. } else {
  776. return 'false';
  777. }
  778. }
  779. function restore_split_files($items)
  780. {
  781. $split_array = array();
  782. // first we check if files are split and group he splited files
  783. foreach ($items as $filename) {
  784. if (is_part($filename)) {
  785. $split_array[removeExtension($filename)][] = $filename;
  786. }
  787. }
  788. foreach ($split_array as $restore => $parts) {
  789. $totsize = 0;
  790. // sorting of parts is important!
  791. usort($parts, 'mycmp');
  792. // we open the destination
  793. $dest_file = fopen($restore, 'wb');
  794. foreach ($parts as $parts_name) {
  795. $totsize += filesize($parts_name);
  796. $fp = fopen($parts_name, 'rb');
  797. while ($content = fread($fp, 8192)) {
  798. fputs($dest_file, $content);
  799. flush();
  800. ob_flush();
  801. }
  802. fclose($fp);
  803. }
  804. fclose($dest_file);
  805. // if o.k. we delete the .part files! - check the filesize maybe?
  806. if (filesize($restore) == $totsize) {
  807. array_map('unlink', $parts);
  808. }
  809. }
  810. }
  811. function resize_merged_files($items, $size)
  812. {
  813. global $compression;
  814. $split_array = array();
  815. // first we check if files are split and group the splited files
  816. foreach ($items as $filename) {
  817. if (is_part($filename)) {
  818. $split_array[removeExtension($filename)][] = $filename;
  819. }
  820. }
  821. foreach ($split_array as $restore => $parts) {
  822. if (is_supported_tfu_image(my_basename($restore), $restore) && $size < 100000) {
  823. resize_file($restore, $size, $compression, my_basename($restore));
  824. }
  825. }
  826. }
  827. function is_part($str)
  828. {
  829. global $split_extension;
  830. $ex = substr (strrchr ($str, '.'), 1);
  831. $pos = strpos ($ex, $split_extension);
  832. if ($pos === false) {
  833. return false;
  834. } else if ($pos == 0) {
  835. return true;
  836. } else {
  837. return false;
  838. }
  839. }
  840. function is_supported_tfu_image($image,$current)
  841. {
  842. global $scan_images;
  843. $image = strtolower ($image);
  844. $isimage = preg_match('/.*\.(jp)(e){0,1}(g)$/', $image) ||
  845. preg_match('/.*\.(gif)$/', $image) ||
  846. preg_match('/.*\.(png)$/', $image) ;
  847. if ($isimage) {
  848. // we check if this is really an image - if we cannot read the size we assume it could be a php fake
  849. set_error_handler('on_error_no_output');
  850. if (file_exists($current)) {
  851. $size = @getimagesize ($current);
  852. if ($size === false || $scan_images) {
  853. // seems not to be an image - now we we replace the <?php with <_php
  854. $data = file_get_contents($current);
  855. $data2 = str_replace("<?php","<_php",$data);
  856. if ($data2 != $data) {
  857. file_put_contents($current, $data2);
  858. tfu_debug("SECURITY WARNING: Please check the file ".$image.". It was uploaded with an image extensions but included php code. The php start of this file was changed because of security issues!" );
  859. }
  860. }
  861. }
  862. set_error_handler('on_error');
  863. }
  864. return $isimage;
  865. }
  866. if (!isset($skip_error_handling)) {
  867. set_error_handler("on_error_no_output"); // 4.x gives depreciated errors here but if I change it it does only work with 5.x - therefore I don't show any errors here !
  868. }
  869. if (file_exists('tfu_exifReader.php')) {
  870. include 'tfu_exifReader.php';
  871. }
  872. if (!isset($skip_error_handling)) {
  873. set_error_handler("on_error");
  874. }
  875. function get_exif_size($filename, $image_name)
  876. {
  877. set_error_handler('on_error_no_output'); // is needed because error are most likly but we don't care about fields we don't even know
  878. $er = new phpExifReader($filename);
  879. $er->processFile();
  880. $exif_info = $er->getImageInfo();
  881. set_error_handler('on_error');
  882. $size_array = array();
  883. $size_array[2] = 2;
  884. if (isset($er->ImageInfo[TAG_EXIF_IMAGEWIDTH])) {
  885. $size_array[0] = $er->ImageInfo[TAG_EXIF_IMAGEWIDTH];
  886. } else {
  887. $size_array[0] = 1024;
  888. tfu_debug('Size of image ' . $image_name . ' cannot be detected using 1024x768.');
  889. }
  890. if (isset($er->ImageInfo[TAG_EXIF_IMAGELENGTH])) {
  891. $size_array[1] = $er->ImageInfo[TAG_EXIF_IMAGELENGTH];
  892. } else {
  893. $size_array[1] = 768;
  894. }
  895. return $size_array;
  896. }
  897. function removeCacheThumb($filename)
  898. {
  899. $thumbsdir = dirname(__FILE__) . '/thumbs';
  900. if (file_exists($thumbsdir) && is_writable($thumbsdir)) { // is a caching dir available and writeable?
  901. $cachename = $thumbsdir . '/' . sha1($filename . '160') . '.jpg'; // small
  902. if (file_exists($cachename)) {
  903. @unlink($cachename);
  904. }
  905. $cachename = $thumbsdir . '/' . sha1($filename . '400') . '.jpg'; // big
  906. if (file_exists($cachename)) {
  907. @unlink($cachename);
  908. }
  909. }
  910. cleanup_thumbs_cache();
  911. }
  912. function cleanup_thumbs_cache()
  913. {
  914. if (isset($_SESSION['checkcache'])) { // we only check once per session!
  915. return;
  916. }
  917. $_SESSION['checkcache'] = 'TRUE';
  918. $cache_time = 10; // in days !!
  919. $thumbsdir = dirname(__FILE__) . '/thumbs';
  920. $cache_time = $cache_time * 86400;
  921. $del_time = time() - $cache_time;
  922. if (file_exists($thumbsdir) && is_writable($thumbsdir)) {
  923. $d = opendir($thumbsdir);
  924. $i = 0;
  925. while (false !== ($entry = readdir($d))) {
  926. if ($entry != '.' && $entry != '..') {
  927. $atime = fileatime($thumbsdir . '/' . $entry);
  928. if ($atime < $del_time) {
  929. @unlink($thumbsdir . '/' . $entry);
  930. }
  931. }
  932. }
  933. closedir($d);
  934. }
  935. }
  936. function removeExtension($name)
  937. {
  938. return substr($name, 0, strrpos ($name, '.'));
  939. }
  940. /**
  941. * * create a unique directory - 1 st is year, 2 and 3 rd is month - rest is unique up to length
  942. */
  943. function createUniqueDir($basedir, $length = 10)
  944. {
  945. $dir = '';
  946. $prefix = substr(date('Ym'), 3);
  947. while ($dir == '') {
  948. $start = pow (10, $length-3);
  949. $stop = pow (10, $length-2)-1;
  950. $value = rand($start, $stop);
  951. $tempdir = $basedir . $prefix . $value;
  952. if (!file_exists($tempdir)) {
  953. mkdir($tempdir);
  954. $dir = $tempdir;
  955. break;
  956. }
  957. }
  958. return $dir;
  959. }
  960. /**
  961. * Finds the destination folder depending on the id - the id has the format 1,2,0
  962. * means folder 2 in level 1, 3 rd folder in level 2, 1st folder in level 3.....
  963. * empty means root!
  964. */
  965. function getDestinationFolder($id_list)
  966. {
  967. global $exclude_directories, $hide_hidden_files;
  968. $base_dir = $_SESSION['TFU_ROOT_DIR'];
  969. if ($id_list == '') return $base_dir;
  970. $ids = explode(',', $id_list);
  971. $dir = $base_dir;
  972. foreach ($ids as $id) {
  973. // read the dir - get the directory and set the base to the new level.
  974. $dirhandle = opendir($dir);
  975. $myDirs = array();
  976. while (false !== ($filed = readdir($dirhandle))) {
  977. if ($filed != '.' && $filed != '..' && !in_array($filed, $exclude_directories) && (!($hide_hidden_files && (strpos($filed, '.') === 0)))) {
  978. if (is_dir($dir . '/' . $filed)) {
  979. array_push($myDirs, $filed);
  980. }
  981. }
  982. }
  983. usort ($myDirs, 'mycmp');
  984. $dir = $dir . '/' . $myDirs[$id];
  985. }
  986. return $dir;
  987. }
  988. function get_tree_xml()
  989. {
  990. if (isset($_SESSION["TREE_" . $_SESSION['TFU_ROOT_DIR']])) {
  991. return $_SESSION["TREE_" . $_SESSION['TFU_ROOT_DIR']];
  992. } else {
  993. $tree = '<node><node label="/" id="">' . show_dir_xml($_SESSION['TFU_ROOT_DIR']) . '</node></node>';
  994. $_SESSION["TREE_" . $_SESSION['TFU_ROOT_DIR']] = $tree;
  995. return $tree;
  996. }
  997. }
  998. function show_dir_xml($myDir = '.', $indent = 0, $levelStr = '')
  999. {
  1000. global $exclude_directories, $hide_hidden_files;
  1001. $dir = opendir($myDir);
  1002. $einrueckung = str_repeat(' ', $indent * 4);
  1003. if ($levelStr != '') {
  1004. $levelStr .= ',';
  1005. }
  1006. $foo = '';
  1007. $counter = 0;
  1008. $dirlist = array();
  1009. while ($file = readdir($dir)) {
  1010. $dirlist[] = $file;
  1011. }
  1012. usort ($dirlist, 'mycmp');
  1013. foreach ($dirlist as $file) {
  1014. $newDir = $myDir . '/' . $file;
  1015. if ($file == '.' || $file == '..' || in_array($file, $exclude_directories)&& (!($hide_hidden_files && (strpos($file, '.') === 0))))
  1016. continue;
  1017. if (is_dir($newDir)) {
  1018. $curLevelStr = $levelStr . '' . $counter++;
  1019. $foo .= '<node id="' . $curLevelStr . '" label="' . $file . '">' . "\n" . show_dir_xml($newDir . '/', 1, $curLevelStr) . "</node>\n";
  1020. }
  1021. }
  1022. return $foo;
  1023. }
  1024. function get_unique_filename($dir, $image)
  1025. {
  1026. $i = 1;
  1027. $probeer = $image;
  1028. while (file_exists($dir . $probeer)) {
  1029. $punt = strrpos($image, '.');
  1030. if (substr($image, ($punt-3), 1) !== ('(') && substr($image, ($punt-1), 1) !== (')')) {
  1031. $probeer = substr($image, 0, $punt) . '(' . $i . ')' .
  1032. substr($image, ($punt), strlen($image) - $punt);
  1033. } else {
  1034. $probeer = substr($image, 0, ($punt-3)) . '(' . $i . ')' .
  1035. substr($image, ($punt), strlen($image) - $punt);
  1036. }
  1037. $i++;
  1038. }
  1039. return $probeer;
  1040. }
  1041. /**
  1042. * Needed for loading saving text files
  1043. */
  1044. $cp1252_map = array(
  1045. '\xc2\x80' => '\xe2\x82\xac', /* EURO SIGN */
  1046. '\xc2\x82' => '\xe2\x80\x9a', /* SINGLE LOW-9 QUOTATION MARK */
  1047. '\xc2\x83' => '\xc6\x92', /* LATIN SMALL LETTER F WITH HOOK */
  1048. '\xc2\x84' => '\xe2\x80\x9e', /* DOUBLE LOW-9 QUOTATION MARK */
  1049. '\xc2\x85' => '\xe2\x80\xa6', /* HORIZONTAL ELLIPSIS */
  1050. '\xc2\x86' => '\xe2\x80\xa0', /* DAGGER */
  1051. '\xc2\x87' => '\xe2\x80\xa1', /* DOUBLE DAGGER */
  1052. '\xc2\x88' => '\xcb\x86', /* MODIFIER LETTER CIRCUMFLEX ACCENT */
  1053. '\xc2\x89' => '\xe2\x80\xb0', /* PER MILLE SIGN */
  1054. '\xc2\x8a' => '\xc5\xa0', /* LATIN CAPITAL LETTER S WITH CARON */
  1055. '\xc2\x8b' => '\xe2\x80\xb9', /* SINGLE LEFT-POINTING ANGLE QUOTATION */
  1056. '\xc2\x8c' => '\xc5\x92', /* LATIN CAPITAL LIGATURE OE */
  1057. '\xc2\x8e' => '\xc5\xbd', /* LATIN CAPITAL LETTER Z WITH CARON */
  1058. '\xc2\x91' => '\xe2\x80\x98', /* LEFT SINGLE QUOTATION MARK */
  1059. '\xc2\x92' => '\xe2\x80\x99', /* RIGHT SINGLE QUOTATION MARK */
  1060. '\xc2\x93' => '\xe2\x80\x9c', /* LEFT DOUBLE QUOTATION MARK */
  1061. '\xc2\x94' => '\xe2\x80\x9d', /* RIGHT DOUBLE QUOTATION MARK */
  1062. '\xc2\x95' => '\xe2\x80\xa2', /* BULLET */
  1063. '\xc2\x96' => '\xe2\x80\x93', /* EN DASH */
  1064. '\xc2\x97' => '\xe2\x80\x94', /* EM DASH */
  1065. '\xc2\x98' => '\xcb\x9c', /* SMALL TILDE */
  1066. '\xc2\x99' => '\xe2\x84\xa2', /* TRADE MARK SIGN */
  1067. '\xc2\x9a' => '\xc5\xa1', /* LATIN SMALL LETTER S WITH CARON */
  1068. '\xc2\x9b' => '\xe2\x80\xba', /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
  1069. '\xc2\x9c' => '\xc5\x93', /* LATIN SMALL LIGATURE OE */
  1070. '\xc2\x9e' => '\xc5\xbe', /* LATIN SMALL LETTER Z WITH CARON */
  1071. '\xc2\x9f' => '\xc5\xb8' /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
  1072. );
  1073. function tfu_seems_utf8($Str)
  1074. {
  1075. for ($i = 0; $i < strlen($Str); $i++) {
  1076. if (ord($Str[$i]) < 0x80) $n = 0; # 0bbbbbbb
  1077. elseif ((ord($Str[$i]) &0xE0) == 0xC0) $n = 1; # 110bbbbb
  1078. elseif ((ord($Str[$i]) &0xF0) == 0xE0) $n = 2; # 1110bbbb
  1079. elseif ((ord($Str[$i]) &0xF0) == 0xF0) $n = 3; # 1111bbbb
  1080. else return false; # Does not match any model
  1081. for ($j = 0; $j < $n; $j++) { // n octets that match 10bbbbbb follow ?
  1082. if ((++$i == strlen($Str)) || ((ord($Str[$i]) &0xC0) != 0x80)) return false;
  1083. }
  1084. }
  1085. return true;
  1086. }
  1087. function cp1252_to_utf8($str)
  1088. {
  1089. global $cp1252_map;
  1090. return strtr(utf8_encode($str), $cp1252_map);
  1091. }
  1092. function utf8_to_cp1252($str)
  1093. {
  1094. global $cp1252_map;
  1095. return utf8_decode(strtr($str, array_flip($cp1252_map)));
  1096. }
  1097. function getExtension($name)
  1098. {
  1099. $name = rtrim($name, ".,; \t\n\r\0\x0B");
  1100. return substr (strrchr ($name, '.'), 1);
  1101. }
  1102. function space_enc($string) {
  1103. global $description_mode;
  1104. if ($description_mode == 'true') { // - description is added at the end - we don't encode ' : ' and the rest.
  1105. $teile = explode(" : ", $string,2);
  1106. $teile[0] = str_replace(" ", "%20", $teile[0]);
  1107. $string = implode(" : ", $teile);
  1108. } else {
  1109. $string = str_replace(" ", "%20", $string);
  1110. }
  1111. return $string;
  1112. }
  1113. /**
  1114. * This does a nice character exchange with a random crypt key!
  1115. * If you need a 100% secure connection please use https!
  1116. */
  1117. function tfu_enc($str, $id, $length = false)
  1118. {
  1119. if ($length) {
  1120. $str = substr($str, 0, $length);
  1121. }
  1122. for ($i = 0; $i < strlen($id); $i++) {
  1123. if (ord($id{$i}) > 127) {
  1124. tfu_debug('The crypt key at position ' . $i . ' is not valid - please change the implementation.');
  1125. return $str;
  1126. }
  1127. }
  1128. $code = '';
  1129. $keylen = strlen($id);
  1130. for ($i = 0; $i < strlen($str); $i++) {
  1131. $code .= chr(ord($str{$i}) + ord($id{$i%$keylen}));
  1132. }
  1133. return utf8_encode($code);
  1134. }
  1135. function setSessionVariables()
  1136. {
  1137. global $folder, $user, $login;
  1138. // this settings are needed in the other php files too!
  1139. if ($login == 'true') {
  1140. $_SESSION['TFU_LOGIN'] = 'true';
  1141. if (!isset($_SESSION['TFU_USER'])) { // can be set by the Joomla wrapper and we don't overwrite it with a dummy value!
  1142. $_SESSION['TFU_USER'] = ($user != '' && $user != '__empty__') ? $user : $_SERVER['REMOTE_ADDR'];
  1143. }
  1144. } else {
  1145. unset($_SESSION['TFU_USER']);
  1146. }
  1147. $_SESSION['TFU_RN'] = parseInputParameter($_POST['twg_rn']);
  1148. $_SESSION['TFU_ROOT_DIR'] = $_SESSION['TFU_DIR'] = $folder;
  1149. store_temp_session();
  1150. }
  1151. /**
  1152. * All parameters a sent to the flash
  1153. * First I wanted to introduce a Config class but this is the only place where they
  1154. * have to be passed globaly - therefore no class is used now.
  1155. */
  1156. function sendConfigData()
  1157. {
  1158. global $login, $rn, $maxfilesize, $resize_show, $resize_data, $resize_label, $resize_default, $allowed_file_extensions;
  1159. global $forbidden_file_extensions, $show_delete, $enable_folder_browsing, $enable_folder_creation;
  1160. global $enable_folder_deletion, $enable_file_download, $keep_file_extension, $show_preview, $show_big_preview;
  1161. global $enable_file_rename, $enable_folder_rename, $enable_folder_move, $enable_file_copymove, $language_dropdown;
  1162. global $preview_textfile_extensions, $edit_textfile_extensions;
  1163. //, $maxfilesize_split;
  1164. // optional settings
  1165. global $reg_infos, $login_text, $relogin_text, $upload_file, $base_dir, $titel;
  1166. global $warning_setting, $hide_remote_view, $directory_file_limit, $remote_label;
  1167. global $preview_label, $show_full_url_for_selected_file, $upload_finished_js_url;
  1168. global $preview_select_js_url, $delete_js_url, $js_change_folder, $js_create_folder;
  1169. global $js_rename_folder, $js_delete_folder, $js_copymove, $queue_file_limit, $show_size;
  1170. global $queue_file_limit_size, $split_extension, $hide_help_button, $direct_download;
  1171. global $description_mode_show_default, $description_mode, $download_multiple_files_as_zip;
  1172. global $overwrite_files, $description_mode_mandatory, $post_upload_panel, $form_fields;
  1173. global $big_progressbar,$img_progressbar,$img_progressbar_back,$img_progressbar_anim, $big_server_view;
  1174. global $zip_file_pattern, $is_jfu_plugin, $has_post_processing, $directory_file_limit_size;
  1175. global $show_server_date_instead_size, $enable_file_creation, $enable_file_creation_extensions;
  1176. // the sessionid is mandatory because upload in flash and Firefox would create a new session otherwise - sessionhandled login would fail then!
  1177. $output = '&login=' . $login . '&maxfilesize=' . '' . $maxfilesize;
  1178. // $output .= '&maxfilesize_split=' . tfu_enc('' . $maxfilesize_split, $rn);
  1179. // $output .= '&maxfilesize_php=' . getMaximumUploadSize();
  1180. $output .= '&resize_show=' . $resize_show . '&resize_data=' . $resize_data;
  1181. $output .= '&resize_label=' . urlencode($resize_label) . '&resize_default=' . $resize_default;
  1182. $output .= '&allowed_file_extensions=' . $allowed_file_extensions . '&forbidden_file_extensions=' . $forbidden_file_extensions;
  1183. $output .= '&show_delete=' . $show_delete . '&enable_folder_browsing=' . $enable_folder_browsing;
  1184. $output .= '&enable_folder_creation=' . $enable_folder_creation . '&enable_folder_deletion=' . $enable_folder_deletion ;
  1185. $output .= '&enable_file_download=' . $enable_file_download . '&keep_file_extension=' . $keep_file_extension;
  1186. $output .= '&show_preview=' . $show_preview . '&show_big_preview=' . $show_big_preview ;
  1187. $output .= '&enable_file_rename=' . $enable_file_rename . '&enable_folder_rename=' . $enable_folder_rename;
  1188. $output .= '&enable_folder_copy=' . $enable_folder_move . '&enable_file_copy=' . $enable_file_copymove;
  1189. $output .= '&language_dropdown=' . $language_dropdown;
  1190. $output .= '&preview_textfile_extensions=' . $preview_textfile_extensions . '&edit_textfile_extensions=' . $edit_textfile_extensions;
  1191. // optional settings
  1192. $output .= $reg_infos . '&login_text=' . $login_text;
  1193. $output .= '&relogin_text=' . $relogin_text . '&upload_file=' . $upload_file;
  1194. $output .= '&base_dir=' . $base_dir . '&titel=' . urlencode($titel);
  1195. $output .= '&warning_setting=' . $warning_setting . '&hide_remote_view=' . $hide_remote_view;
  1196. $output .= '&directory_file_limit=' . $directory_file_limit;
  1197. $output .= '&remote_label=' . urlencode($remote_label) . '&preview_label=' . $preview_label;
  1198. $output .= '&show_full_url_for_selected_file=' . $show_full_url_for_selected_file;
  1199. $output .= '&upload_finished_js_url=' . urlencode($upload_finished_js_url) . '&preview_select_js_url=' . urlencode($preview_select_js_url);
  1200. $output .= '&delete_js_url=' . urlencode($delete_js_url) . '&js_change_folder=' . urlencode($js_change_folder);
  1201. $output .= '&js_create_folder=' . urlencode($js_create_folder) . '&js_rename_folder=' . urlencode($js_rename_folder);
  1202. $output .= '&js_delete_folder=' . urlencode($js_delete_folder) . '&js_copymove=' . urlencode($js_copymove);
  1203. $output .= '&queue_file_limit=' . $queue_file_limit . '&queue_file_limit_size=' . $queue_file_limit_size;
  1204. $output .= '&split_extension=' . $split_extension . '&hide_help_button=' . $hide_help_button;
  1205. $output .= '&direct_download=' . $direct_download . '&show_size=' . $show_size;
  1206. $output .= '&description_mode=' . $description_mode . '&description_mode_show_default=' . $description_mode_show_default;
  1207. $output .= '&multiple_zip_download=' . $download_multiple_files_as_zip;
  1208. $output .= '&overwrite_files=' . $overwrite_files . '&description_mode_mandatory=' . $description_mode_mandatory;
  1209. $output .= '&post_upload_panel=' . $post_upload_panel . '&form_fields=' .$form_fields;
  1210. $output .= '&big_progressbar=' . $big_progressbar . '&img_progressbar=' .$img_progressbar;
  1211. $output .= '&img_progressbar_back=' . $img_progressbar_back . '&img_progressbar_anim=' .$img_progressbar_anim;
  1212. $output .= '&big_server_view=' . $big_server_view . '&zip_file_pattern=' . $zip_file_pattern;
  1213. $output .= '&is_jfu_plugin=' . $is_jfu_plugin . '&has_post_processing=' . $has_post_processing;
  1214. $output .= '&directory_file_limit_size=' . $directory_file_limit_size . '&show_server_date_instead_size=' . $show_server_date_instead_size;
  1215. $output .= '&enable_file_creation=' . $enable_file_creation . '&enable_file_creation_extensions=' . $enable_file_creation_extensions;
  1216. // all parameters are sent encrypted to the client.
  1217. $parameters = "&parameters=" . urlencode(tfu_enc($output, $rn));
  1218. // we generate a nonce for this request
  1219. // last=true is added for such websites who add their own code to each page!
  1220. echo '&tfu_nonce=' . create_tfu_nonce() . $parameters . "&last=true";
  1221. }
  1222. /**
  1223. * This stores all data in a session in a temporary folder as well if it does exist.
  1224. * This is a workaround if a session is lost and empty in the tfu_upload.php and restored there!
  1225. */
  1226. function store_temp_session()
  1227. {
  1228. global $session_double_fix;
  1229. clearstatcache();
  1230. if (file_exists(dirname(__FILE__) . '/session_cache') && session_id() != "") { // we do your own small session handling
  1231. $cachename = dirname(__FILE__) . '/session_cache/' . session_id();
  1232. $ser_file = fopen($cachename, 'w');
  1233. fwrite($ser_file, serialize($_SESSION));
  1234. fclose($ser_file);
  1235. if ($session_double_fix) {
  1236. $ser_file = fopen($cachename . '2', 'w');
  1237. fwrite($ser_file, serialize($_SESSION));
  1238. fclose($ser_file);
  1239. }
  1240. }
  1241. }
  1242. function checkSessionTempDir($type = 0)
  1243. {
  1244. global $keep_internal_session_handling;
  1245. if (isset($_FILES) && (count ($_FILES) > 0)) {
  1246. $filen = array_shift($_FILES);
  1247. $filename = $filen['name'];
  1248. tfu_debug('It can be possible that someone tried to upload something without permissions! If you think this is the case the IP of this user is logged: ' . $_SERVER['REMOTE_ADDR'] . '. He tried to upload the following file: ' . $filename);
  1249. }
  1250. if (!file_exists(dirname(__FILE__) . '/session_cache')) {
  1251. tfu_debug('Or it is possible that the session handling of the server is not o.k. Therefore TFU simulates a basic session handling and uses the session_cache folder for that.');
  1252. if (!mkdir(dirname(__FILE__) . '/session_cache')) {
  1253. tfu_debug('Directory session_cache could not be created! Please create the sub directoy session_cache and set the permissions of it to 777.');
  1254. } else {
  1255. tfu_debug('Directory session_cache could be created! TFU does now an internal session handling. Delete the directory session_cache to turn the internal handling off.');
  1256. @chmod(dirname(__FILE__) . '/session_cache', 0777);
  1257. // we create an index.htm to prevent listings!
  1258. $datei = fopen(dirname(__FILE__) . '/session_cache/index.htm', 'w');
  1259. fclose($datei);
  1260. }
  1261. } else if ($type == 5) { // the upload check has to fail because the whole session data is gone.
  1262. echo 'int_session_handling=true';
  1263. } else {
  1264. tfu_debug('It seems that the session handling of the server is not o.k. TFU already tried a workaround that does not seem to work. TFU deleted the session_cache folder. Maybe it was created because of a wrong request! Please go to http://www.tinywebgallery.com/de/tfu/tfu_faq_12.php. If this does not help please report this in the forum to find a solution!');
  1265. if (!$keep_internal_session_handling) {
  1266. remove(dirname(__FILE__) . '/session_cache');
  1267. }
  1268. echo 'int_session_handling=false';
  1269. }
  1270. }
  1271. $check_server_file_extensions = $m;
  1272. function restore_temp_session($checkrn = false)
  1273. {
  1274. global $session_double_fix;
  1275. clearstatcache();
  1276. if (file_exists(dirname(__FILE__) . '/session_cache')) { // we do your own small session handling
  1277. $cachename = dirname(__FILE__) . '/session_cache/' . session_id();
  1278. if (file_exists($cachename)) {
  1279. $data = file_get_contents($cachename);
  1280. set_error_handler('on_error_no_output'); // is needed because error are most likly but we don't care about fields we don't even know
  1281. $sdata = unserialize($data);
  1282. set_error_handler('on_error');
  1283. if (isset($sdata) && (isset($sdata['TFU_RN']) || $checkrn)) {
  1284. $_SESSION = $sdata;
  1285. } else { // we try again
  1286. sleep(1);
  1287. if ($session_double_fix) {
  1288. $cachename .= '2';
  1289. }
  1290. $data = file_get_contents ($cachename);
  1291. set_error_handler('on_error_no_output'); // is needed because error are most likly but we don't care about fields we don't even know
  1292. $sdata = unserialize($data);
  1293. set_error_handler('on_error');
  1294. if (isset($sdata) && (isset($sdata['TFU_RN'])|| $checkrn)) {
  1295. $_SESSION = $sdata;
  1296. } else {
  1297. tfu_debug('Session data could no be restored :' . $data);
  1298. }
  1299. }
  1300. }
  1301. // now we have to clean old temp sessions! - we do this once a day only!
  1302. // first we check if we have done this already!
  1303. $today = dirname(__FILE__) . '/session_cache/_cache_day_' . date('Y_m_d') . '.tmp';
  1304. if (file_exists($today)) {
  1305. return;
  1306. }
  1307. // not done - we delete all files on this folder older than 1 day + the _cache_day_*.tmp files
  1308. $d = opendir(dirname(__FILE__) . '/session_cache');
  1309. $i = 0;
  1310. $del_time = time() - 86000; // we delete file older then 24 hours
  1311. while (false !== ($entry = readdir($d))) {
  1312. if ($entry != '.' && $entry != '..') {
  1313. $atime = fileatime(dirname(__FILE__) . '/session_cache/' . $entry);
  1314. if ($atime < $del_time) {
  1315. @unlink(dirname(__FILE__) . '/session_cache/' . $entry);
  1316. }
  1317. }
  1318. }
  1319. $tmp_files = glob(dirname(__FILE__) . '/session_cache/*.tmp');
  1320. if ($tmp_files) {
  1321. foreach($tmp_files as $fn) {
  1322. if ($fn != '/session_cache/.' && $fn != '/session_cache/..') {
  1323. @unlink($fn);
  1324. }
  1325. }
  1326. }
  1327. // now we write the flag
  1328. $fh = fopen($today, 'w');
  1329. fclose($fh);
  1330. }
  1331. // Joomla session update!
  1332. if (isset($_SESSION['__default']['session.counter'])) {
  1333. $_SESSION['__default']['session.counter'] = $_SESSION['__default']['session.counter'] + 1;
  1334. $_SESSION['__default']['session.timer.now'] = time();
  1335. $_SESSION['__default']['session.timer.last'] = $_SESSION['__default']['session.timer.now'];
  1336. }
  1337. }
  1338. // creates a nonce see http://en.wikipedia.org/wiki/Cryptographic_nonce
  1339. // just some random parts and then a hash of it.
  1340. function create_tfu_nonce() {
  1341. return nhash(date("is") . session_id() . rand());
  1342. }
  1343. // checks if the extension is allowed to be viewed!
  1344. function check_view_extension($name)
  1345. {
  1346. global $check_server_file_extensions, $allowed_view_file_extensions, $forbidden_view_file_extensions, $forbidden_view_file_filter;
  1347. $allowed_view_file_extensions = str_replace(' ', '', strtolower($allowed_view_file_extensions));
  1348. $forbidden_view_file_extensions = str_replace(' ', '', strtolower($forbidden_view_file_extensions));
  1349. $forbidden_view_file_filter = str_replace(' ', '', strtolower($forbidden_view_file_filter));
  1350. $isAllowed = true;
  1351. if ($check_server_file_extensions == 'v') {
  1352. if ($allowed_view_file_extensions != 'all' || $forbidden_view_file_extensions != '') {
  1353. if ($allowed_view_file_extensions != 'all' && strpos($name, '.') === false) {
  1354. $isAllowed = false;
  1355. } else {
  1356. $ext = strtolower(getExtension($name));
  1357. if ($allowed_view_file_extensions == 'all') { // we check the not allowed extensions
  1358. $isAllowed = !in_array($ext, explode(',', $forbidden_view_file_extensions));
  1359. } else { // we only allow the allowed extension
  1360. $isAllowed = in_array($ext, explode(',', $allowed_view_file_extensions));
  1361. }
  1362. }
  1363. } else {
  1364. $isAllowed = true;
  1365. }
  1366. // now we check the filter on non windows systems!
  1367. if (function_exists('fnmatch')) {
  1368. if ($forbidden_view_file_filter != '') {
  1369. $filters =explode(',', $forbidden_view_file_filter);
  1370. foreach ($filters as $filter) {
  1371. if (fnmatch ($filter, $name)) {
  1372. $isAllowed = false;
  1373. break;
  1374. }
  1375. }
  1376. }
  1377. }
  1378. }
  1379. return $isAllowed;
  1380. }
  1381. function t($l, $s)
  1382. {
  1383. $n = '';
  1384. $m = explode(';', $l);
  1385. foreach($m as $v) {
  1386. $nrp = substr_count($v, '.');
  1387. if ($nrp == 1 && (strpos($v,'*')=== false)) { $nrp++; $v.="*."; }
  1388. $el = explode('.', $s);
  1389. if ($el !== false) {
  1390. $r = array_slice($el, 0, -$nrp);
  1391. $n .= ';' . str_replace('*', 'ww'.'w'. ((count($r) >0) ? ('.'.array_pop($r)) : ''), $v);
  1392. }
  1393. }
  1394. return $n;
  1395. }
  1396. // Checks if the uploaded extension is o.k. on the server side!
  1397. // Trailing . are removed because of security issues.
  1398. function check_valid_extension($name, $die_if_invalid = true)
  1399. {
  1400. global $forbidden_file_extensions, $allowed_file_extensions;
  1401. $afe = str_replace(' ', '', strtolower($allowed_file_extensions));
  1402. $name = rtrim($name, ".,; \t\n\r\0\x0B");
  1403. $path_info = pathinfo($name);
  1404. if (isset($path_info['extension'])) {
  1405. $file_extension = strtolower($path_info['extension']);
  1406. } else {
  1407. $file_extension = '';
  1408. }
  1409. if ($afe == '') { // this can be useful if you don't allow to upload - only to download!
  1410. return false;
  1411. }
  1412. if ($afe != 'all') {
  1413. $extension_whitelist = explode(',', $afe); // Allowed file extensions
  1414. // $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'; // Characters allowed in the file name (in a Regular Expression format)
  1415. $is_valid_extension = false;
  1416. foreach ($extension_whitelist as $extension) {
  1417. if ($file_extension == $extension) {
  1418. $is_valid_extension = true;
  1419. break;
  1420. }
  1421. }
  1422. } else { // not allowed extensions
  1423. $nafe = str_replace(' ', '', strtolower($forbidden_file_extensions));
  1424. $is_valid_extension = true;
  1425. if ($nafe != '') {
  1426. $extension_blacklist = explode(',', $nafe);
  1427. foreach ($extension_blacklist as $extension) {
  1428. if (strpos($file_extension, $extension) !== false) {
  1429. $is_valid_extension = false;
  1430. break;
  1431. }
  1432. }
  1433. }
  1434. }
  1435. if (!$is_valid_extension && $die_if_invalid) {
  1436. header('HTTP/1.1 500 Internal Server Error');
  1437. echo 'No valid extension - upload not permitted.';
  1438. exit(0);
  1439. }
  1440. return $is_valid_extension;
  1441. }
  1442. // Validate the file size (Warning the largest files supported by this code is 2GB)
  1443. function check_valid_filesize($name)
  1444. {
  1445. global $maxfilesize;
  1446. $file_size = sprintf("%u", @filesize($name));
  1447. if (!$file_size || $file_size > ($maxfilesize * 1024)) {
  1448. @unlink($name);
  1449. header('HTTP/1.1 500 Internal Server Error');
  1450. echo 'File size too big - upload not permitted.';
  1451. exit(0);
  1452. }
  1453. }
  1454. /**
  1455. * Right now the parameters are only checked very basic because they are not
  1456. * returned back to a frontend or passed somewhere else.
  1457. * Therefore only a basic regular expression is used!
  1458. * You can pass a different regex if you want to restrict something more (e.g a file name)
  1459. * The are 2 functions
  1460. * - parseInputParameter check for valid caracters because there I know the proper values
  1461. * - parseInputParameterFile is an exclude - there I only check for chars that are not allowed in file names!
  1462. */
  1463. function parseInputParameter($value, $def = '', $valid_chars_regex = '.\w_,-')
  1464. {
  1465. return (isset($value)) ? preg_replace('/[^' . $valid_chars_regex . ']|\.+$/i', '_', $value) : $def;
  1466. }
  1467. function parseInputParameterFile($value, $def = '')
  1468. {
  1469. if (isset($value)) {
  1470. $reserved = preg_quote("\/:*?'<>", "/");
  1471. return preg_replace("/([\\x00-\\x1f{$reserved}])/", '_', $value);
  1472. } else {
  1473. return $def;
  1474. }
  1475. }
  1476. function printServerInfo()
  1477. {
  1478. global $check_image_magic; global $m;
  1479. echo '
  1480. <style type="text/css">
  1481. body { font-family : Arial, Helvetica, sans-serif; font-size: 12px; background-color:#ffffff; }
  1482. td { vertical-align: top; font-size: 12px; }
  1483. .install { margin-left: auto; margin-right: auto; margin-top: 3em; margin-bottom: 3em; padding: 10px; border: 1px solid #cccccc; width: 650px; background: #F1F1F1; }
  1484. </style>
  1485. ';
  1486. $limit = return_kbytes(ini_get('memory_limit'));
  1487. echo '<br><p><center>Some info\'s about your server. This limits are not TFU limits. You have to change this in the php.ini.</center></p>';
  1488. echo '<div class="install">';
  1489. echo '<table><tr><td>';
  1490. echo '<tr><td width="400">TFU version:</td><td width="250">2.14&nbsp;';
  1491. // simply output the license type by checking the strings in the license. No real check like in the flash is done here.
  1492. if ($m != "" && $m != "s" && $m !="w" ) {
  1493. ob_start();
  1494. $ff = dirname(__FILE__) . "/twg.lic.php";
  1495. if (!file_exists($ff)) { // we are in TWG
  1496. $ff = dirname(__FILE__) . "/../../twg.lic.php";
  1497. }
  1498. include $ff;
  1499. ob_end_clean();
  1500. if ($l == $d) {
  1501. echo " (Enterprise Edition License)";
  1502. } else if (strpos($d, "TWG_PROFESSIONAL") !== false) {
  1503. echo " (Professional Edition License)";
  1504. } else if (strpos($d, "TWG_SOURCE") !== false) {
  1505. echo " (Source code Edition License)";
  1506. } else {
  1507. echo " (Standart Edition License)";
  1508. }
  1509. } else {
  1510. echo " (Freeware Edition)";
  1511. }
  1512. echo '</td></tr>';
  1513. echo '<tr><td width="400">Server name:</td><td width="250">' . get_server_name() . '</td></tr>';
  1514. echo '<tr><td>PHP upload limit (in KB): </td><td>' . getMaximumUploadSize() . '</td></tr>';
  1515. echo '<tr><td>PHP memory limit (in KB):&nbsp;&nbsp;&nbsp;</td><td>' . $limit . '</td></tr>';
  1516. echo '<tr><td>Safe mode:</td><td>';
  1517. echo (ini_get('safe_mode') == 1) ? 'ON<br>You maybe have some limitations creating folders or uploading<br>if the permissions are not set properly.<br>Please check the TWG FAQ 30 if you want to know more about<br>safe mode and the problems that comes with this setting.' : 'OFF';
  1518. echo '</td></tr><tr><td>GD lib:</td><td>';
  1519. echo (!function_exists('imagecreatetruecolor')) ? '<font color="red">GDlib is not installed properly.<br>TFU Preview does not work!</font>' : 'Available';
  1520. echo '</td></tr>';
  1521. echo '<tr><td>Max resize resolution (GDlib):</td><td>';
  1522. if (!$limit) {
  1523. echo '<font color="green">No limit</font>';
  1524. } else {
  1525. $xy = $limit * 1024 / 6.6; // 10 % overhead.
  1526. $x = floor(sqrt ($xy / 0.75));
  1527. $y = floor(sqrt($xy / 1.33));
  1528. if ($x > 4000) {
  1529. echo '<font color="green">~ ' . $x . ' x ' . $y . '</font>';
  1530. } else if ($x > 2000) {
  1531. echo '<font color="orange">~ ' . $x . ' x ' . $y . '</font>';
  1532. } else {
  1533. echo '<font color="red">~ ' . $x . ' x ' . $y . '</font>';
  1534. }
  1535. }
  1536. echo '</td></tr>';
  1537. $test = check_image_magic("",$check_image_magic);
  1538. echo '<tr><td>Image magick support:&nbsp;&nbsp;&nbsp;</td><td>' . (($test == '1') ? '<font color="green">Available</font>' : (($test == '0') ? '<b><font color="red">Not available</b><br>(or test could not be performed!)</font>': '<font color="red">Test disabled</font>')) . '</td></tr>';
  1539. echo '<tr><td>The times below have to be longer than the maximum<br>upload duration! Otherwise the upload will fail.</td><td>&nbsp;</td></tr>';
  1540. echo '<tr><td>PHP maximum execution time: </td><td>' . ini_get('max_execution_time') . ' s</td></tr>';
  1541. echo '<tr><td>PHP maximum input time: </td><td>' . ini_get('max_input_time') . ' s</td></tr>';
  1542. echo '<tr><td>PHP default socket timeout: </td><td>' . ini_get('default_socket_timeout') . ' s</td></tr>';
  1543. echo '</table>';
  1544. echo '</div>';
  1545. }
  1546. /*
  1547. We check if we can create a image with image magick
  1548. The check is only done once per session because in JFU this function is called every time we access
  1549. a profile page. If this function has a problem because of the execute you would never get to the config page.
  1550. */
  1551. function check_image_magic($path = "", $check_image_magic = true) {
  1552. global $folder, $image_magic_path;
  1553. if ($check_image_magic) {
  1554. if (isset($_SESSION['IM_CHECK'])) {
  1555. return ($_SESSION['IM_CHECK']);
  1556. }
  1557. $inputimage = dirname(__FILE__) . "/lang/de.gif";
  1558. set_error_handler('on_error_no_output'); // is needed because the cache folder could be not reachable because of base_dir restrictions
  1559. if (!file_exists($folder)) {
  1560. $folder = dirname(__FILE__) . "/../../../../cache"; // if the tfu folder is in the administration
  1561. if (!file_exists($folder) && (!is_writeable($folder))) {
  1562. $folder = dirname(__FILE__) . "/../../../cache"; // if the tfu folder is in the frontend
  1563. if (!file_exists($folder) && (!is_writeable($folder))) {
  1564. // now we check if we can do the test in the local directoy
  1565. $folder = dirname(__FILE__);
  1566. if (!is_writeable($folder)) {
  1567. set_error_handler('on_error');
  1568. return '0';
  1569. }
  1570. }
  1571. }
  1572. }
  1573. set_error_handler('on_error');
  1574. if ($path != "") {
  1575. $image_magic_path = $path;
  1576. }
  1577. $outputcachetest = $folder . "/_image_magick_test.jpg";
  1578. $fh=fopen($outputcachetest,'w'); // fix for a but in some php - versions - thanks to Anders
  1579. fclose($fh);
  1580. $command = $image_magic_path. " \"" . realpath($inputimage) . "\" -quality 80 -resize 120x81 \"" . realpath($outputcachetest) . "\"";
  1581. @unlink($outputcachetest);
  1582. $_SESSION['IM_CHECK'] = '0';
  1583. execute_command($command);
  1584. if (file_exists($outputcachetest)) {
  1585. $ok = '1';
  1586. @unlink($outputcachetest);
  1587. $_SESSION['IM_CHECK'] = '1';
  1588. } else {
  1589. $ok = '0';
  1590. }
  1591. return $ok;
  1592. } else {
  1593. return '-1';
  1594. }
  1595. }
  1596. /**
  1597. * Normalizes the file names - fix_encoding has to be called before this function is used.
  1598. * This isn't done here because normalize filenames is an optional step while fix_encoding
  1599. * is always done.
  1600. **/
  1601. function normalizeFileNames($imageName){
  1602. global $normalizeSpaces;
  1603. // it's needed to decode first because str_replace does not handle str_replace in utf-8
  1604. $imageName = utf8_decode($imageName);
  1605. // we make the file name lowercase ÄÖÜ as well.
  1606. $imageName = mb_strtolower($imageName);
  1607. if ($normalizeSpaces == 'true') {
  1608. $imageName=str_replace(' ','_',$imageName);
  1609. }
  1610. // Some characters I know how to fix ;).
  1611. $imageName=str_replace(array('ä','ö','ü','ß'),array('ae','oe','ue','ss'),$imageName);
  1612. // and some others might need
  1613. $imageName=str_replace(array('á','ŕ','ă','â','ç','˘','é','ę','č','ë','í','î','ď','ě','ń','ô','ó','ő','ň','š','ú','ů','ű','ü','ý','˙','ž'),
  1614. array('a','a','a','a','c','c','e','e','e','e','i','i','i','i','n','o','o','o','o','s','u','u','u','u','y','y','z'),$imageName);
  1615. // we remove the rest of unwanted chars
  1616. $patterns[] = '/[\x7b-\xff]/'; // remove all characters above the letter z. This will eliminate some non-English language letters
  1617. $patterns[] = '/[\x21-\x2c]/'; // remove range of shifted characters on keyboard - !"#$%&'()*+
  1618. $patterns[] = '/[\x5b-\x60]/'; // remove range including brackets - []\^_`
  1619. // we remove all kind of special characters for utf8 encoding as well
  1620. $patterns[] = '/[\x7b-\xff]/u'; // remove all characters above the letter z. This will eliminate some non-English language letters
  1621. $patterns[] = '/[\x21-\x2c]/u'; // remove range of shifted characters on keyboard - !"#$%&'()*+
  1622. $patterns[] = '/[\x5b-\x60]/u'; // remove range including brackets - []\^_`
  1623. $replacement ="_";
  1624. return utf8_encode(preg_replace($patterns, $replacement, $imageName));
  1625. }
  1626. function execute_command ($command) {
  1627. $use_shell_exec = true;;
  1628. ob_start();
  1629. set_error_handler('on_error_no_output');
  1630. if (substr(@php_uname(), 0, 7) == "Windows"){
  1631. // Make a new instance of the COM object
  1632. $WshShell = new COM("WScript.Shell");
  1633. // Make the command window but dont show it.
  1634. $oExec = $WshShell->Run("cmd /C " . $command, 0, true);
  1635. } else {
  1636. if ($use_shell_exec) {
  1637. shell_exec($command);
  1638. } else {
  1639. exec($command . " > /dev/null");
  1640. }
  1641. }
  1642. set_error_handler('on_error');
  1643. ob_end_clean();
  1644. }
  1645. /*
  1646. Functions used for file handling
  1647. */
  1648. function tfu_rename_file($dir, $file, $enable_file_rename, $keep_file_extension, $fix_utf8) {
  1649. global $normalise_file_names;
  1650. if ($enable_file_rename != 'true') {
  1651. echo 'This action is not enabled!';
  1652. exit(0);
  1653. }
  1654. $newName = parseInputParameterFile(trim(my_basename(' ' . $_GET['newfilename']))); // fixes that file can be renamed to an upper dir.
  1655. if ($normalise_file_names) {
  1656. $newName = normalizeFileNames($newName);
  1657. }
  1658. $newName = fix_decoding($newName, $fix_utf8);
  1659. if ($keep_file_extension == 'true') {
  1660. $newNameEx = getExtension($newName);
  1661. $fileEx = getExtension($file);
  1662. if (strtolower($newNameEx) != strtolower($fileEx)) {
  1663. echo 'This action is not allowed. Changing file extensions is disabled because of security issues!';
  1664. exit(0);
  1665. }
  1666. }
  1667. $newName = $dir . '/' . $newName;
  1668. if (!file_exists($newName) || ($file != $newName && strtolower($file) == strtolower($newName) )) { // file_exists does not check case sensitive on windows
  1669. if (is_writeable($file)) {
  1670. $result = @rename($file, $newName);
  1671. if ($result) {
  1672. echo '&result=true';
  1673. } else {
  1674. echo '&result=false';
  1675. }
  1676. } else {
  1677. echo '&result=perm';
  1678. }
  1679. } else {
  1680. echo '&result=exists';
  1681. }
  1682. }
  1683. function tfu_delete_file($file, $show_delete) {
  1684. // first we check if delete is enabled!
  1685. if ($show_delete != 'true') {
  1686. echo 'This action is not enabled!';
  1687. exit(0);
  1688. }
  1689. if (is_tfu_deletable($file)) {
  1690. set_error_handler('on_error_no_output');
  1691. @chmod($file , 0777);
  1692. set_error_handler('on_error');
  1693. $result = @unlink($file);
  1694. if ($result) {
  1695. echo '&result=true';
  1696. } else {
  1697. echo '&result=false';
  1698. }
  1699. } else {
  1700. echo '&result=perm';
  1701. }
  1702. }
  1703. function tfu_delete_files($file, $show_delete) {
  1704. // first we check if delete is enabled!
  1705. if ($show_delete != 'true') {
  1706. echo 'This action is not enabled!';
  1707. exit(0);
  1708. }
  1709. $deleted = 0;
  1710. $perm = 0;
  1711. $notdel = 0;
  1712. foreach ($file as $ff) {
  1713. if (is_tfu_deletable($ff)) {
  1714. set_error_handler('on_error_no_output');
  1715. @chmod($ff , 0777);
  1716. set_error_handler('on_error');
  1717. $result = @unlink($ff);
  1718. if ($result) {
  1719. $deleted++;
  1720. } else {
  1721. $notdel++;
  1722. }
  1723. } else {
  1724. $perm++;
  1725. }
  1726. }
  1727. echo '&result=multiple&nr_del=' . $deleted . '&nr_perm=' . $perm . '&nr_not_del=' . $notdel;
  1728. }
  1729. function tfu_copy_move($dir, $file, $enable_file_copymove, $enable_folder_copymove ) {
  1730. // first we check if delete is enabled!
  1731. if ($enable_file_copymove != 'true' && $enable_folder_copymove != 'true') {
  1732. echo 'This action is not enabled!';
  1733. exit(0);
  1734. }
  1735. $done = 0;
  1736. $total = 0;
  1737. $error = 0;
  1738. $exists = 0;
  1739. resetSessionTree();
  1740. $overwrite = parseInputParameter($_GET['overwrite']);
  1741. $folder = getDestinationFolder(parseInputParameter($_GET['target']));
  1742. $dest_folder = $folder . '/' . my_basename($dir);
  1743. if ($_GET['copyfolder'] == 'true') {
  1744. if ($folder == $dir) {
  1745. $error = 1;
  1746. } else if (strpos ($folder, $dir) !== false) {
  1747. $error = 2;
  1748. } else if ($overwrite == 'false' && file_exists($dest_folder)) {
  1749. $error = 3;
  1750. } else {
  1751. if (@rename($dir, $dest_folder)) {
  1752. $done = 1;
  1753. $upperdir = substr($dir, 0, strrpos ($dir, "/"));
  1754. $_SESSION['TFU_DIR'] = $upperdir;
  1755. } else {
  1756. $error = 4;
  1757. }
  1758. }
  1759. } else {
  1760. foreach ($file as $ff) {
  1761. $total++;
  1762. $dest = $folder . '/' . my_basename($ff);
  1763. if ($_GET['type'] == 'c') {
  1764. if ($folder == $dir) {
  1765. $u_file = get_unique_filename($folder, my_basename($ff));
  1766. $dest = $folder . "/" . $u_file;
  1767. }
  1768. if (file_exists($dest) && $overwrite == 'false') { // if file exists and not overwrite = error
  1769. $exists++;
  1770. } else {
  1771. if ($ff == $dest) {
  1772. $nr = 2;
  1773. $dest = $folder . '/Copy of ' . my_basename($ff);
  1774. while (file_exists($dest)) {
  1775. $dest = $folder . '/Copy (' . $nr++ . ') of ' . my_basename($ff);
  1776. }
  1777. }
  1778. if (@copy($ff, $dest)) {
  1779. $done++;
  1780. } else {
  1781. $error++;
  1782. }
  1783. }
  1784. } else {
  1785. if ($ff != $dest) {
  1786. if (file_exists($dest) && $overwrite) {
  1787. @unlink($dest);
  1788. }
  1789. if (!file_exists($dest)) {
  1790. if (@rename($ff, $dest)) {
  1791. $done++;
  1792. } else {
  1793. $error++;
  1794. }
  1795. }
  1796. }
  1797. }
  1798. }
  1799. }
  1800. echo '&total=' . $total . '&ok=' . $done . '&error=' . $error . '&exists=' . $exists ;
  1801. }
  1802. function tfu_preview($file) {
  1803. global $use_image_magic, $image_magic_path, $pdf_thumb_format;
  1804. $pdf_preview = false;
  1805. if (file_exists(dirname(__FILE__) . '/thumbs') && is_writable(dirname(__FILE__) . '/thumbs')) { // is a caching dir available and writeable?
  1806. $pdf_preview = true;
  1807. }
  1808. // we store the url of the last preview image in the session - use it if you need it ;).
  1809. // we generate thumbs for jpge,png and gif!
  1810. if (preg_match("/.*\.(j|J)(p|P)(e|E){0,1}(g|G)$/", $file) ||
  1811. preg_match("/.*\.(p|P)(n|N)(g|G)$/", $file) ||
  1812. preg_match("/.*\.(g|G)(i|I)(f|F)$/", $file)) {
  1813. if (isset($_GET['big'])) {
  1814. send_thumb($file, 90, 440, 280); // big preview 4x bigger!
  1815. } else {
  1816. send_thumb($file, 90, 80, 55); // small preview
  1817. }
  1818. } else if (preg_match("/.*\.(p|P)(d|D)(f|F)$/", $file) && $use_image_magic && $pdf_preview) {
  1819. $cachename = dirname(__FILE__) . '/thumbs/' . sha1($file) . '.' . $pdf_thumb_format;
  1820. if (!file_exists($cachename)) {
  1821. $ima = realpath($file);
  1822. $resize = '1000x1000';
  1823. $command = $image_magic_path . ' -colorspace rgb "' . $ima . '[0]" -border 1x1 -quality 80 -thumbnail ' . $resize . ' "' . $cachename . '"';
  1824. execute_command ($command);
  1825. }
  1826. if (isset($_GET['big'])) {
  1827. send_thumb($cachename, 90, 440, 280); // big preview 4x bigger!
  1828. } else {
  1829. send_thumb($cachename, 90, 80, 55); // small preview
  1830. }
  1831. // the cleanup is done in the thumbs folder which is cleaned up regularly
  1832. // @unlink($cachename);
  1833. return;
  1834. } else {
  1835. return; // we return nothing if no image.
  1836. }
  1837. }
  1838. function tfu_createThumb($file) {
  1839. global $compression, $use_image_magic, $image_magic_path, $pdf_thumb_format;
  1840. if (!(preg_match("/.*\.(p|P)(d|D)(f|F)$/", $file) && $use_image_magic)) {
  1841. $name = removeExtension($file) . "-" . $_GET['tfu_width'] . 'x' . $_GET['tfu_height'] . "." . getExtension($file);
  1842. resize_file($file, $_GET['tfu_width'] . 'x' . $_GET['tfu_height'], $compression, basename($file), $name);
  1843. } else {
  1844. $name = dirname(__FILE__) . '/' . removeExtension($file) . "-" . $_GET['tfu_width'] . '.' . $pdf_thumb_format;
  1845. // create a pdf thumbnail
  1846. $ima = realpath($file);
  1847. if (!file_exists($name)) {
  1848. $ima = realpath($file);
  1849. $resize = $_GET['tfu_width'] . 'x' . $_GET['tfu_height'];
  1850. $command = $image_magic_path . ' -colorspace rgb "' . $ima . '[0]" -border 1x1 -quality 80 -thumbnail ' . $resize . ' "' . $name . '"';
  1851. execute_command ($command);
  1852. }
  1853. }
  1854. }
  1855. function tfu_info($file) {
  1856. global $use_image_magic;
  1857. unset($_SESSION['TFU_LAST_UPLOADS']);
  1858. $_SESSION['TFU_LAST_PREVIEW'] = fixUrl(getRootUrl() . $file);
  1859. echo '&size=' . sprintf("%u", @filesize($file));
  1860. // we check if the image can be resized
  1861. if (is_supported_tfu_image($file,$file)) {
  1862. set_error_handler('on_error_no_output'); // is needed because error are most likly but we don't care about fields we don't even know
  1863. $oldsize = @getimagesize($file);
  1864. set_error_handler('on_error');
  1865. if ($oldsize) {
  1866. if (isMemoryOk($oldsize, 400, "")) {
  1867. echo '&hasPreview=true&tfu_x=' . $oldsize[0] . '&tfu_y=' . $oldsize[1] ; // has preview!
  1868. } else {
  1869. echo '&hasPreview=error&tfu_x=0&tfu_y=0'; // too big! - same error massage as hasPreview=false
  1870. }
  1871. return;
  1872. }
  1873. echo '&hasPreview=false'; // no image!
  1874. }
  1875. if (preg_match("/.*\.(p|P)(d|D)(f|F)$/", $file) && $use_image_magic &&
  1876. file_exists(dirname(__FILE__) . '/thumbs') && is_writable(dirname(__FILE__) . '/thumbs')) { // check if pdf
  1877. echo '&hasPreview=true&tfu_x=1000&tfu_y=1000'; // has preview! - pdfs are max 1000x1000';
  1878. return;
  1879. }
  1880. echo '&hasPreview=false&tfu_x=0&tfu_y=0';
  1881. }
  1882. function tfu_text($file) {
  1883. if (is_writable($file)) {
  1884. echo '&writeable=true';
  1885. } else {
  1886. echo '&writeable=false';
  1887. }
  1888. echo '&data=';
  1889. $enc = 'UTF-8';
  1890. $format = 'UNIX';
  1891. $fp = fopen($file, 'rb');
  1892. $content = '';
  1893. if (filesize ($file) > 0) {
  1894. $content = fread ($fp, filesize ($file));
  1895. }
  1896. // we replace \r with nothing
  1897. $content_new = str_replace("\r", "", $content);
  1898. if ($content_new != $content) {
  1899. $format = 'DOS';
  1900. }
  1901. if (!tfu_seems_utf8($content_new)) {
  1902. $content_new = cp1252_to_utf8($content_new);
  1903. $enc = 'ANSI';
  1904. }
  1905. echo urlencode($content_new);
  1906. echo '&encoding=' . $enc;
  1907. echo '&format=' . $format;
  1908. fclose($fp);
  1909. }
  1910. function tfu_savetext($file, $overwrite=true) {
  1911. if (file_exists($file) && !$overwrite) {
  1912. echo "&create_file=exists";
  1913. } else {
  1914. $content = urldecode($_POST['data']);
  1915. if ($_POST['encoding'] == 'ANSI') {
  1916. $content = utf8_to_cp1252($content);
  1917. }
  1918. if ($_POST['format'] == 'DOS') {
  1919. $content = preg_replace("/\r\n|\r|\n/", chr(13) . chr(10), $content);
  1920. } else {
  1921. $content = preg_replace("/\r\n|\r|\n/", chr(10), $content);
  1922. }
  1923. // now we write the file again
  1924. $file_local = fopen($file, 'w');
  1925. if (getExtension($file) == 'php') { // we remove leading and trailing spaces returns if it is a php file!
  1926. $content = trim($content);
  1927. }
  1928. fputs($file_local, $content);
  1929. fclose($file_local);
  1930. if (file_exists($file)) {
  1931. echo "&create_file=true";
  1932. } else {
  1933. echo "&create_file=false";
  1934. }
  1935. }
  1936. }
  1937. function tfu_download($file, $enable_file_download) {
  1938. if ($enable_file_download == 'false' && !isset($_GET['fullscreen'])) {
  1939. echo 'This action is not enabled!';
  1940. exit(0);
  1941. }
  1942. if (isset($_GET['fullscreen'])) { // we check if we have an image in the cache folder!
  1943. $cachename = dirname(__FILE__) . '/thumbs/' . sha1($file) . '.jpg';
  1944. if (file_exists($cachename)) {
  1945. $file = $cachename;
  1946. }
  1947. }
  1948. ini_set('zlib.output_compression','Off');
  1949. header("Content-Transfer-Encoding: binary");
  1950. header('Content-type: application/octet-stream');
  1951. header('Content-Length: ' . filesize($file));
  1952. // small chunk size is used for IE! 1024 would be better but has only half the dl speed - 2048 seems to be the best trade off.
  1953. $fp = fopen($file, 'rb');
  1954. while ($content = fread($fp, 2048)) {
  1955. echo $content;
  1956. set_error_handler('on_error_no_output');
  1957. @set_time_limit(20);
  1958. @flush();
  1959. @ob_flush(); // some server need this althou on some server this throws a warning
  1960. set_error_handler('on_error');
  1961. }
  1962. fclose($fp);
  1963. }
  1964. function tfu_zip_download($files, $enable_file_download) {
  1965. global $zip_folder, $zip_file_pattern; // The folder is used to create the temp download files!
  1966. if ($enable_file_download == 'false' && !isset($_GET['fullscreen'])) {
  1967. echo 'This action is not enabled!';
  1968. exit(0);
  1969. }
  1970. /*
  1971. $createZip = new createZip;
  1972. $nrfiles = count($files);
  1973. for ($i = 0; $i < $nrfiles; $i++) {
  1974. $createZip -> addFile(file_get_contents($files[$i]), my_basename($files[$i]));
  1975. }
  1976. $fileName = $zip_folder . '/' . $_GET['zipname'];
  1977. $fd = fopen ($fileName, "wb");
  1978. $out = fwrite ($fd, $createZip -> getZippedfile());
  1979. fclose ($fd);
  1980. */
  1981. $nrfiles = count($files);
  1982. if ($zip_file_pattern == '') {
  1983. $zipName = parseInputParameterFile(trim(my_basename(' ' . $_GET['zipname']))); // fixes that file can be renamed to an upper dir.
  1984. $fileName = $zip_folder . '/' . $zipName;
  1985. } else {
  1986. // zip file pattern can have the following patterns {folder}, {number}, {date} e.g. "download-{number}-files_{date}.zip"
  1987. // but here I only use {number} and {date} because this is enough to be unique. The filename itself is build in the flash.
  1988. $newName = str_replace('{number}', $nrfiles, $zip_file_pattern);
  1989. $newName = str_replace('{date}', date("Y-m-d"), $newName);
  1990. $fileName = $zip_folder . '/' . $newName;
  1991. }
  1992. if (!is_writeable($zip_folder)) {
  1993. tfu_debug("ERROR: The folder '" . $zip_folder . "' is not writeable. Please set the permissions properly to enable the download of multiple files.");
  1994. }
  1995. $fd = @fopen ($fileName, "wb");
  1996. if ($fd) {
  1997. $createZip = new TFUZipFile($fd);
  1998. for ($i = 0; $i < $nrfiles; $i++) {
  1999. $createZip -> addFile($files[$i], my_basename($files[$i]));
  2000. }
  2001. $createZip -> close();
  2002. tfu_download($fileName, $enable_file_download);
  2003. @unlink($fileName);
  2004. } else {
  2005. tfu_debug("ERROR: The file '" . $fileName . "' could not be created. Please set the permissions properly to enable the download of multiple files.");
  2006. }
  2007. }
  2008. /*
  2009. Functions used for directory handling
  2010. */
  2011. function create_dir($dir, $enable_folder_creation, $fix_utf8) {
  2012. global $normalise_directory_names, $dir_chmod;
  2013. global $ftp_enable, $ftp_host, $ftp_port, $ftp_user, $ftp_pass, $ftp_root, $master_profile;
  2014. if ($enable_folder_creation != 'true') {
  2015. echo 'This action is not enabled!';
  2016. exit(0);
  2017. }
  2018. resetSessionTree();
  2019. $newdir = parseInputParameterFile(trim(my_basename(' ' . $_GET['newdir'])));
  2020. if ($normalise_directory_names) {
  2021. $newdir = normalizeFileNames($newdir);
  2022. }
  2023. $newdir = fix_decoding($newdir, $fix_utf8);
  2024. $createdir = $dir . "/" . $newdir;
  2025. if (file_exists($createdir)) {
  2026. $status = '&create_dir=exists';
  2027. } else {
  2028. if (isset($ftp_enable) && $ftp_enable) {
  2029. if ($master_profile) {
  2030. // we have to remove one level from the TFU_ROOT_DIR that was added automatically by the jfu wrapper
  2031. $parent_root = dirname($_SESSION['TFU_ROOT_DIR']);
  2032. $ftp_createdir = substr($createdir,strlen($parent_root)+1);
  2033. } else {
  2034. $ftp_createdir = substr($createdir,strlen($_SESSION['TFU_ROOT_DIR'])+1);
  2035. }
  2036. $conn_id = ftp_connect($ftp_host, $ftp_port);
  2037. $login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
  2038. ftp_chdir($conn_id, $ftp_root);
  2039. $result = ftp_mkdir ($conn_id , $ftp_createdir);
  2040. if ($result && $dir_chmod != 0) {
  2041. @ftp_chmod($conn_id, $dir_chmod, $ftp_createdir);
  2042. }
  2043. ftp_close($conn_id);
  2044. } else {
  2045. $result = mkdir ($createdir);
  2046. if ($result && $dir_chmod != 0) {
  2047. @chmod($createdir, $dir_chmod);
  2048. }
  2049. }
  2050. $status = ($result) ? '&create_dir=true':'&create_dir=false';
  2051. }
  2052. return $status;
  2053. }
  2054. function rename_dir( &$dir, $enable_folder_rename, $fix_utf8) {
  2055. global $normalise_directory_names;
  2056. if ($enable_folder_rename != 'true') {
  2057. echo 'This action is not enabled!';
  2058. exit(0);
  2059. }
  2060. resetSessionTree();
  2061. $upperdir = substr($dir, 0, strrpos ($dir, "/"));
  2062. $newdir = parseInputParameterFile(trim(my_basename(' ' . $_GET['newdir'])));
  2063. if ($normalise_directory_names) {
  2064. $newdir = normalizeFileNames($newdir);
  2065. }
  2066. $newdir = fix_decoding($newdir, $fix_utf8);
  2067. if ($dir == $_SESSION["TFU_ROOT_DIR"]) {
  2068. $status = "&rename_dir=main";
  2069. } else {
  2070. $createdir = $upperdir . "/" . $newdir;
  2071. if (file_exists($createdir)) {
  2072. $status = "&rename_dir=exists";
  2073. } else {
  2074. $result = rename ($dir, $upperdir . "/" . $newdir);
  2075. if ($result) {
  2076. $dir = $createdir;
  2077. $_SESSION["TFU_DIR"] = $dir;
  2078. $status = "&rename_dir=true";
  2079. } else {
  2080. $status = "&rename_dir=false";
  2081. }
  2082. }
  2083. }
  2084. return $status;
  2085. }
  2086. function delete_folder(&$dir, $enable_folder_deletion, $fix_utf8) {
  2087. global $folder; // the root folder!
  2088. if ($enable_folder_deletion != 'true') {
  2089. echo 'This action is not enabled!';
  2090. exit(0);
  2091. }
  2092. // we check if this is the root dir. We don't allow this even when the request was faked!
  2093. if ($dir == $folder) {
  2094. echo 'Deleting the root folder is not allowed!';
  2095. exit(0);
  2096. }
  2097. resetSessionTree();
  2098. $upperdir = substr($dir, 0, strrpos ($dir, "/"));
  2099. $result = remove($dir);
  2100. if ($result) {
  2101. $status = "&delete_dir=true";
  2102. $dir = $upperdir;
  2103. $_SESSION["TFU_DIR"] = $dir;
  2104. } else {
  2105. $status = "&delete_dir=false";
  2106. }
  2107. return $status;
  2108. }
  2109. function change_folder($dir, $show_root, $enable_folder_browsing, $exclude_directories, $sort_directores_by_date) {
  2110. global $hide_hidden_files;
  2111. if ($enable_folder_browsing != 'true') {
  2112. echo 'This action is not enabled!';
  2113. exit(0);
  2114. }
  2115. $index = parseInputParameter($_GET['index']);
  2116. if ($index == 0 && $show_root) { // we go up!
  2117. $dir = substr($_SESSION["TFU_DIR"], 0, strrpos ($_SESSION["TFU_DIR"], "/"));
  2118. } else { // we go deeper
  2119. if ($show_root) {
  2120. $index--;
  2121. }
  2122. $dirhandle = opendir($dir);
  2123. $myDirs = array();
  2124. while (false !== ($filed = readdir($dirhandle))) {
  2125. if ($filed != "." && $filed != ".." && !in_array($filed, $exclude_directories) && (!($hide_hidden_files && (strpos($filed, '.') === 0)))) {
  2126. if (is_dir($dir . '/' . $filed)) {
  2127. if ($sort_directores_by_date) {
  2128. $fdate = filemtime($dir . '/' . $filed);
  2129. $filed = $fdate . $filed;
  2130. }
  2131. array_push($myDirs, $filed);
  2132. }
  2133. }
  2134. }
  2135. if ($sort_directores_by_date) {
  2136. usort ($myDirs, "cmp_date_dec");
  2137. $i = 0;
  2138. foreach ($myDirs as $fieldName) {
  2139. $myDirs[$i++] = substr($fieldName, 10);
  2140. }
  2141. } else {
  2142. usort ($myDirs, "cmp_dir_dec");
  2143. }
  2144. $dir = $dir . "/" . $myDirs[$index];
  2145. }
  2146. $_SESSION["TFU_DIR"] = $dir;
  2147. return $dir;
  2148. }
  2149. function create_directory_title($dir, $hide_directory_in_title, $truncate_dir_in_title, $fix_utf8) {
  2150. if ($hide_directory_in_title == 'true') {
  2151. $dirsub = " ";
  2152. } else if ($truncate_dir_in_title == 'true') {
  2153. $root = isset($_SESSION["TFU_ROOT_DIR"]) ? $_SESSION["TFU_ROOT_DIR"] : '';
  2154. $folder = substr($dir, strlen($root) + 1);
  2155. $dirsub = " - Upload Folder: " . $folder;
  2156. } else {
  2157. // we only show the path - relative path is not shown! Therefore I replace some things.
  2158. $dirsub = ($fix_utf8 == "") ? utf8_encode(str_replace("../", "", $dir)) : str_replace("../", "", $dir);
  2159. $dirsub = str_replace("..", "", str_replace("//", "/", $dirsub)); // display fixes
  2160. $dirsub = " - Upload Folder: " . $dirsub;
  2161. }
  2162. return $dirsub;
  2163. }
  2164. function read_dir($dir, &$myFiles, &$myDirs, $fix_utf8, $exclude_directories, $sort_files_by_date, $sort_directores_by_date) {
  2165. global $hide_hidden_files, $show_server_date_instead_size;
  2166. $size = 0;
  2167. if (!file_exists($dir)) {
  2168. return;
  2169. }
  2170. $dirhandle = opendir($dir);
  2171. while (false !== ($file = readdir($dirhandle))) {
  2172. if ($file != "." && $file != ".." && !in_array($file, $exclude_directories) && (!($hide_hidden_files && (strpos($file, '.') === 0)))) {
  2173. $filepath = $dir . '/' . $file;
  2174. if (is_dir($filepath)) {
  2175. $dirname = fix_encoding($file, $fix_utf8);
  2176. if ($sort_directores_by_date) {
  2177. $dirname = filemtime($filepath) . $dirname;
  2178. }
  2179. array_push($myDirs, urlencode($dirname));
  2180. } else if (check_view_extension($file)) {
  2181. set_error_handler("on_error_no_output");
  2182. $current_size = sprintf("%u", @filesize($dir . '/' . $file));
  2183. $size += $current_size;
  2184. if ($show_server_date_instead_size=='true' || $sort_files_by_date) {
  2185. $fdate = filemtime($filepath);
  2186. }
  2187. if ($show_server_date_instead_size=='true') {
  2188. $current_size = $fdate;
  2189. }
  2190. // size or date is added.
  2191. $file = $file . "**" . $current_size;
  2192. if ($sort_files_by_date) {
  2193. $file = $fdate . $file;
  2194. }
  2195. set_error_handler("on_error");
  2196. array_push($myFiles, urlencode(fix_encoding($file, $fix_utf8)));
  2197. }
  2198. }
  2199. }
  2200. closedir ($dirhandle);
  2201. return $size;
  2202. }
  2203. function sort_data (&$myFiles, &$myDirs, $sort_files_by_date, $sort_directores_by_date) {
  2204. if ($sort_files_by_date) {
  2205. usort ($myFiles, "cmp_date_dec");
  2206. $i = 0;
  2207. foreach ($myFiles as $fieldName) {
  2208. $myFiles[$i] = substr($myFiles[$i], 10);
  2209. $i++;
  2210. }
  2211. } else {
  2212. usort ($myFiles, "cmp_dec");
  2213. }
  2214. reset($myFiles);
  2215. if ($sort_directores_by_date) {
  2216. usort ($myDirs, "cmp_date_dec");
  2217. $i = 0;
  2218. foreach ($myDirs as $fieldName) {
  2219. $myDirs[$i] = substr($myDirs[$i], 10);
  2220. $i++;
  2221. }
  2222. } else {
  2223. usort ($myDirs, "cmp_dir_dec");
  2224. }
  2225. reset($myDirs);
  2226. }
  2227. function check_restrictions($dir, $show_root, &$myFiles, $fix_utf8, $status) {
  2228. global $enable_dir_create_detection, $check_safemode;
  2229. // this is a check if the dir exists - this is a configuration error!
  2230. if (file_exists($dir)) {
  2231. $status .= "&dir_exists=true";
  2232. } else {
  2233. $status .= "&dir_exists=false";
  2234. // no other checks are made because the directory is not available!
  2235. return $status;
  2236. }
  2237. // now we check if we can delete the current folder - root folder cannot be deleted!
  2238. $status .= (is_tfu_deletable($dir) && $show_root) ? "&dir_delete=true" : "&dir_delete=false";
  2239. // new we check if we can create folders - we have to check safemode too!
  2240. set_error_handler("on_error_no_output");
  2241. $sm_prob = $check_safemode && has_safemode_problem_global() && runsNotAsCgi();
  2242. if (is_writeable($dir)) {
  2243. if ($enable_dir_create_detection) { // the detection of the safemode does not work on all systems - therefore it can be disabled.
  2244. $status .= ($sm_prob) ? "&dir_create=subdir" : "&dir_create=true";
  2245. } else {
  2246. $status .= "&dir_create=true";
  2247. }
  2248. } else {
  2249. $status .= ($sm_prob) ? "&dir_create=safemode" : "&dir_create=false";
  2250. }
  2251. set_error_handler("on_error");
  2252. $nrFiles = count($myFiles);
  2253. // now we check if can delete files - we only check the 1st file!
  2254. if ($nrFiles > 0) {
  2255. $delfile = fix_decoding(urldecode($myFiles[0]), $fix_utf8);
  2256. // we have to remove the ** before checking
  2257. $delfile = substr($delfile, 0, strpos($delfile, "**"));
  2258. $status .= (is_tfu_deletable($dir . "/" . $delfile)) ? "&file_delete=true" : "&file_delete=false";
  2259. }
  2260. return $status;
  2261. }
  2262. function get_server_name() {
  2263. if(isset($_SERVER['HTTP_HOST'])) {
  2264. $domain = $_SERVER['HTTP_HOST'];
  2265. } else if(isset($_SERVER['SERVER_NAME'])) {
  2266. $domain = $_SERVER['SERVER_NAME'];
  2267. } else {
  2268. $domain = '';
  2269. }
  2270. $port = strpos($domain, ':');
  2271. if ( $port !== false ) $domain = substr($domain, 0, $port);
  2272. return $domain;
  2273. }
  2274. /*
  2275. encodes only the part without the /
  2276. */
  2277. function tfu_urlencode($data)
  2278. {
  2279. $data = str_replace("/", "__TWG__", $data);
  2280. $data = str_replace(":", "__QT__", $data);
  2281. $parts = explode (" - ", $data); // descripton should not be encoded
  2282. if (count($parts) > 1) {
  2283. $parts[0] = rawurlencode ($parts[0]);
  2284. $data = implode(" - ", $parts);
  2285. } else {
  2286. $data = rawurlencode ($data);
  2287. }
  2288. $data = str_replace("__QT__", ":", $data);
  2289. return str_replace("__TWG__", "/", $data);
  2290. }
  2291. // only executes basename if a / or \ is in the filename.
  2292. // Fixes the problem that basename e.g. destroys chinese filename encoded in utf-8
  2293. function my_basename($name) {
  2294. if ((strpos($name, '\\') === false) && (strpos($name, '/') === false)) {
  2295. return $name;
  2296. } else {
  2297. $sep = ((strpos($name, '/') === false)) ? '\\' : '/';
  2298. return ltrim(substr($name, strrpos($name, $sep) ), $sep);
  2299. }
  2300. }
  2301. /**
  2302. * Fixes the encoding of the file names we get from the flash. They come utf-8 encoded
  2303. * from the flash and writing this directly to the filesystem produces depending on the
  2304. * system unreadable file names. Especially if special characters like öäü or even
  2305. * chinese Characters are used.
  2306. */
  2307. function fix_decoding($encoded_filename, $fix_utf8) {
  2308. if ($fix_utf8 == 'none') {
  2309. return $encoded_filename;
  2310. } else {
  2311. $temp = str_replace("\\'", "'", $encoded_filename ); // we change escaped ' to normal '
  2312. return ($fix_utf8 == '') ? utf8_decode($temp ) : iconv('UTF-8', $fix_utf8, $temp);
  2313. }
  2314. }
  2315. function fix_encoding($decoded_filename, $fix_utf8) {
  2316. if ($fix_utf8 == 'none') {
  2317. return $decoded_filename;
  2318. } else {
  2319. return ($fix_utf8 == '') ? utf8_encode($decoded_filename) : iconv($fix_utf8, 'UTF-8', $decoded_filename);
  2320. }
  2321. }
  2322. // Specifiy the file_put_contents() function for PHP version 4
  2323. if (function_exists('file_put_contents') == false) {
  2324. function file_put_contents($file, $string) {
  2325. $f=fopen($file, 'w');
  2326. fwrite($f, $string);
  2327. fclose($f);
  2328. }
  2329. }
  2330. function formatSize($size) {
  2331. if ($size>=1048576*1000) {
  2332. // > 1000 MB - no komma - display e.g. 1421 MB
  2333. $strSize = floor($size/1048576)." MB";
  2334. } else if ($size>1048576*100) {
  2335. // > 100 MB - 1 digit - e.g. 71.5 MB
  2336. $num = floor($size/1048576.0);
  2337. $strSize = $num . "." . floor(($size-($num*1048576))/104857.6) . " MB";
  2338. } else if ($size>1048576) {
  2339. // > 1 MB - 2 digit - e.g. 2.53 MB
  2340. $num = floor($size/1048576.0);
  2341. $komma = floor(($size-($num*1048576.0))/1048.576);
  2342. $pad = "";
  2343. if ($komma<100) { $pad = "0"; }
  2344. if ($komma<10) { $pad = "00"; }
  2345. $strSize = $num . "." . $pad. $komma ." KB";
  2346. } else if ($size == 0) {
  2347. $strSize = "0 KB";
  2348. } else {
  2349. $strSize = ceil($size/1024)." KB";
  2350. }
  2351. return $strSize;
  2352. }
  2353. function resetSessionTree() {
  2354. unset($_SESSION["TREE_" . $_SESSION['TFU_ROOT_DIR']]);
  2355. }
  2356. function check_multiple_extensions($image, $remove_multiple_php_extension) {
  2357. if ($remove_multiple_php_extension) {
  2358. $ext = getExtension($image);
  2359. if (substr($ext,0,2) != "php") {
  2360. $image2 = str_replace(".php", "", $image);
  2361. if ($image != $image2) {
  2362. tfu_debug("SECURITY WARNING: Please check the file ".$image2.". It was uploaded with an image extensions and also a nested php extension. On some server this is a security problem (multiple extensions) and therefore the .php part of the file name was removed!" );
  2363. $image = $image2;
  2364. }
  2365. }
  2366. }
  2367. return $image;
  2368. }
  2369. function getFolderSizeCached($path) {
  2370. $md = md5($path);
  2371. if (isset($_SESSION['TFU_TMP']) && isset($_SESSION['TFU_TMP']['FS' . $md] )) {
  2372. echo "c";
  2373. return $_SESSION['TFU_TMP']['FS' . $md];
  2374. } else {
  2375. echo "b";
  2376. if (!isset($_SESSION['TFU_TMP'])) {
  2377. $_SESSION['TFU_TMP'] = array();
  2378. }
  2379. $size = getFoldersize($path);
  2380. $_SESSION['TFU_TMP']['FS' . $md] = $size;
  2381. return $size;
  2382. }
  2383. }
  2384. /**
  2385. * Optimized way to read the the size of a directoy.
  2386. *
  2387. * First the windows or Unix way is tried. If this fails
  2388. * the php internal stuff is used.
  2389. *
  2390. * if you select legacy = false only the pure php
  2391. * version is used.
  2392. */
  2393. function getFoldersize($path, $legacy = true) {
  2394. $size = -1;
  2395. ob_start();
  2396. set_error_handler('on_error_no_output');
  2397. if ($legacy) {
  2398. if (substr(@php_uname(), 0, 7) == "Windows"){
  2399. // we have to make the path absolute !
  2400. $path_ab = realpath($path);
  2401. $obj = new COM ( 'scripting.filesystemobject' );
  2402. if ( is_object ( $obj ) ) {
  2403. $ref = $obj->getfolder ( $path_ab );
  2404. $size = $ref->size;
  2405. $obj = null;
  2406. }
  2407. } else { // hopefully unix - du has to be in the path. If it is not you have to adjust the path.
  2408. $io = popen ( 'du -sb ' . $path, 'r' );
  2409. $usize = trim(fgets ( $io, 4096));
  2410. $split = preg_split('/\s+/', $usize);
  2411. $usize = $split[0];
  2412. pclose ( $io );
  2413. if (is_numeric($usize)) {
  2414. $size = $usize;
  2415. }
  2416. }
  2417. }
  2418. set_error_handler('on_error');
  2419. @ob_end_clean();
  2420. // backup if both ways fail. It is ~ 18 times slower (tested on windows) than one of the solutions above.
  2421. if ($size == -1) {
  2422. $size = foldersize($path);
  2423. }
  2424. return $size;
  2425. }
  2426. /**
  2427. * The basic php way to go through all directories and adding the file sizes.
  2428. * It does also check the parameters $exclude_directories and $hide_hidden_files
  2429. */
  2430. function foldersize($p) {
  2431. global $exclude_directories, $hide_hidden_files;
  2432. $size = 0;
  2433. $fs = scandir($p);
  2434. foreach($fs as $f) {
  2435. if (is_dir(rtrim($p, '/') . '/' . $f)) {
  2436. if ($f!='.' && $f!='..') {
  2437. $size += foldersize(rtrim($p, '/') . '/' . $f);
  2438. }
  2439. } else {
  2440. if ($f != '.' && $f != '..' && !in_array($f, $exclude_directories)&&
  2441. (!($hide_hidden_files && (strpos($f, '.') === 0)))) {
  2442. $size += filesize(rtrim($p, '/') . '/' . $f);
  2443. }
  2444. }
  2445. }
  2446. return $size;
  2447. }
  2448. function check_syntax($file)
  2449. {
  2450. // load file
  2451. $code = file_get_contents($file);
  2452. // remove non php blocks
  2453. $code = preg_replace('/(^|\?>).*?(<\?php|$)/i', '', $code);
  2454. // create lambda function
  2455. $f = @create_function('', $code);
  2456. // return function error status
  2457. return !empty($f);
  2458. }
  2459. function file_upload_error_message($error_code) {
  2460. switch ($error_code) {
  2461. case UPLOAD_ERR_INI_SIZE:
  2462. return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
  2463. case UPLOAD_ERR_FORM_SIZE:
  2464. return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
  2465. case UPLOAD_ERR_PARTIAL:
  2466. return 'The uploaded file was only partially uploaded. Please check your timeouts.';
  2467. case UPLOAD_ERR_NO_FILE:
  2468. return 'No file was uploaded';
  2469. case UPLOAD_ERR_NO_TMP_DIR:
  2470. return 'Missing a temporary folder';
  2471. case UPLOAD_ERR_CANT_WRITE:
  2472. return 'Failed to write file to disk';
  2473. case UPLOAD_ERR_EXTENSION:
  2474. return 'File upload stopped by extension';
  2475. default:
  2476. return 'Unknown upload error';
  2477. }
  2478. }
  2479. @ob_end_clean();
  2480. ?>