1<?php
2/*
3 * FCKeditor - The text editor for Internet - http://www.fckeditor.net
4 * Copyright (C) 2003-2009 Frederico Caldeira Knabben
5 *
6 * == BEGIN LICENSE ==
7 *
8 * Licensed under the terms of any of the following licenses at your
9 * choice:
10 *
11 *  - GNU General Public License Version 2 or later (the "GPL")
12 *    http://www.gnu.org/licenses/gpl.html
13 *
14 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
15 *    http://www.gnu.org/licenses/lgpl.html
16 *
17 *  - Mozilla Public License Version 1.1 or later (the "MPL")
18 *    http://www.mozilla.org/MPL/MPL-1.1.html
19 *
20 * == END LICENSE ==
21 *
22 * This is the File Manager Connector for PHP.
23 */
24
25
26require_once  'useheading.php';
27require_once 'check_acl.php';
28require_once 'input_utils.php';
29global $dwfck_conf;
30global $_FolderClass;
31
32function GetDwfckNs()
33{
34	echo $_SESSION['dwfck_ns'];
35}
36
37
38 function has_permission($folder, $resourceType, $isFolder=true) {
39   global $_FolderClass;
40   global $Dwfck_conf_values;
41        $folder = str_replace('//','/',$folder);
42
43        $sFolderPath = GetResourceTypeDirectory( $resourceType, 'GetFoldersAndFiles');
44
45       $ns_tmp = str_replace('/',':',$folder);
46       $ns_tmp=trim($ns_tmp,':');
47
48       if(preg_match('/%[a-zA-a0-9]/', $ns_tmp) && $Dwfck_conf_values['fnencode'] == 'safe') {
49          $test = dwiki_decodeFN($ns_tmp);
50       }
51       else {
52
53       $test = urldecode($ns_tmp);
54       }
55
56       if($isFolder) {
57           $test .=  ':*' ;
58       }
59       else {
60           $test=preg_replace('/\.txt$/',"",$test);
61       }
62
63       $AUTH =  auth_aclcheck($test, $_SESSION['dwfck_client'] , $_SESSION['dwfck_grps'], 1);
64
65       $_FolderClass = $AUTH;
66       if(!$isFolder) return($AUTH > 0);
67       return ($AUTH >1);
68 }
69
70
71function GetFolders( $resourceType, $currentFolder )
72{
73
74   global $_FolderClass;
75   global $Config;
76    $currentFolder=encode_dir($currentFolder);
77
78   $isInternalLink = input_strval('DWFCK_Browser', 'local') ;
79	// Map the virtual path to the local server path.
80	$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFolders' ) ;
81
82    if($Config['osWindows']) {
83        $sServerDir = normalizeWIN($sServerDir);
84    }
85
86	// Array that will hold the folders names.
87	$aFolders	= array() ;
88
89	$oCurrentFolder = @opendir( $sServerDir ) ;
90
91	if ($oCurrentFolder !== false)
92	{
93		while ( $sFile = readdir( $oCurrentFolder ) )
94		{
95			if ( $sFile != '.' && $sFile != '..' && is_dir( $sServerDir . $sFile ) ) {
96
97
98                if(has_permission(dwiki_encodeFN($currentFolder) .'/' . $sFile,  $resourceType) || has_open_access() ) {
99                        if($isInternalLink && $_FolderClass < 255) {
100                            $class = 'r';
101                       }
102                       else $class = ($_FolderClass < 8) ? 'r' : 'u';
103                       can_delete($class);
104                       if($_FolderClass) {
105 			  	           $aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) .
106                            '" class="'. $class .'" />' ;
107                       }
108
109               }
110			}
111		}
112
113
114		closedir( $oCurrentFolder ) ;
115	}
116
117	// Open the "Folders" node.
118	echo "<Folders>" ;
119
120	natcasesort( $aFolders ) ;
121
122	foreach ( $aFolders as $sFolder )
123
124		echo $sFolder ;
125
126
127	// Close the "Folders" node.
128	echo "</Folders>" ;
129
130}
131
132/**
133    seeks to determine whether user has rights to create folder
134    if the folder does not exist when file browser is opened
135    and the editor has not created it
136    This situation occurs when the file browser opened from the
137    root directory, where the file being written to is in a
138    new subdirectory that has been created for the file:
139           parent_dir:new_dir:new_file
140   Dokuwiki creates new_dir in data/pages but not in data/media.
141   Dokuwiki creates data/media/new_dir when the user opens
142   the media manager. Similarly, this directory has to be created when
143   FCKeditor's file browser is opened
144
145*/
146function has_open_access() {
147
148    $open_access = false;
149    if(isset($_REQUEST['TopLevel'])) {
150    //   list($top_level,$auth) = explode(';;',$_REQUEST['TopLevel']);
151     //  if($auth == 255 && $top_level =='/') $open_access = true;
152    }
153    $isadmin = isset($_SESSION['dwfck_conf']['isadmin']) ? $_SESSION['dwfck_conf']['isadmin'] : false;
154    $acl = isset($_SESSION['dwfck_acl']) ? $_SESSION['dwfck_acl'] : 1;
155    $openbrowser = (isset($_SESSION['dwfck_openfb']) && $_SESSION['dwfck_openfb'] == 'y') ? true : false;
156    if($open_access || $isadmin || $acl == 255 || ($openbrowser && $acl >= 8)) {
157         return true;
158    }
159
160    return false;
161}
162
163
164
165function GetFoldersAndFiles( $resourceType, $currentFolder )
166{
167	if (!isset($_GET)) {
168		global $_GET;
169	}
170     global $Config;
171
172    $isInternalLink = input_strval('DWFCK_Browser', 'local') ;
173   global $_FolderClass;
174   global $Config;
175   $currentFolder=encode_dir($currentFolder);
176
177   $sess_id = session_id();
178   if(!isset($sess_id) || $sess_id != $_COOKIE['FCK_NmSp_acl']) {
179       session_id($_COOKIE['FCK_NmSp_acl']);
180       session_start();
181   }
182    $acl_del = isset($_SESSION['dwfck_del']) ? $_SESSION['dwfck_del'] : 0;
183	// Map the virtual path to the local server path.
184	$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFoldersAndFiles' ) ;
185    if($Config['osWindows']) {
186        $sServerDir = normalizeWIN($sServerDir);
187    }
188
189    mkdir_rek($sServerDir);
190	// Arrays that will hold the folders and files names.
191	$aFolders	= array() ;
192	$aFiles		= array() ;
193
194    $sFile = '__AAAAAAAA__.AAA';
195    $temp_folder = $currentFolder;
196    $temp_folder = dwiki_encodeFN(trim($temp_folder,'/'));
197    has_permission($temp_folder, $resourceType);
198    if($isInternalLink && $_FolderClass < 16) {
199         $sfclass = 'r';
200    }
201    else {
202         if($acl_del)  {
203            $sfclass = $_FolderClass >= 16 ? 'u' : 'r';
204         }
205         else $sfclass = ($_FolderClass >= 8  || has_open_access()) ? 'u' : 'r';
206         can_delete($sfclass);
207    }
208    if(!$_FolderClass) return;
209    $aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) .
210                            '" class="'. $sfclass .'" />' ;
211
212    $sErrorNumber=0;
213
214
215     $sFolderPath = GetResourceTypeDirectory( $resourceType, 'GetFoldersAndFiles');
216
217     $absolute_path = $Config['UserFilesAbsolutePath'];
218
219
220
221
222	$oCurrentFolder = @opendir( $sServerDir ) ;
223
224	if ($oCurrentFolder !== false)
225	{
226		while ( $sFile = readdir( $oCurrentFolder ) )
227		{
228
229			if ( $sFile != '.' && $sFile != '..' )
230			{
231				if ( is_dir( $sServerDir . $sFile ) ) {
232
233                    if(has_permission(dwiki_encodeFN($currentFolder)  .$sFile,  $resourceType) || has_open_access()) {
234                        if($isInternalLink && $_FolderClass < 255) {
235                            $class = 'r';
236                       }
237                       else {
238                              $class = ($_FolderClass < 8) ? 'r' : 'u';
239                              can_delete($class);
240                       }
241                       if($_FolderClass){
242				  	       $aFolders[] = '<Folder name="' . ConvertToXmlAttribute( $sFile ) .
243                              '" class="'. $class .'" />' ;
244                       }
245
246                    }
247
248				}
249				else
250				{
251					$iFileSize = @filesize( $sServerDir . $sFile ) ;
252                    $cTime= filectime( $sServerDir . $sFile );
253					if ( !$iFileSize ) {
254						$iFileSize = 0 ;
255					}
256					if ( $iFileSize > 0 )
257					{
258						$iFileSize = round( $iFileSize / 1024 ) ;
259						if ( $iFileSize < 1 )
260							$iFileSize = 1 ;
261					}
262                    if($isInternalLink) {
263                        if(has_permission(dwiki_encodeFN($currentFolder)  .DOKU_INC,  $resourceType, false)) {
264                           $title =ckg_get_title($sFile,$currentFolder);
265                       //   $aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" time="' . $cTime .'" />' ;
266                            $aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" time="' . $cTime .'" title = "'.$title.'"/>' ;
267                        }
268                    }
269                    else {
270                       if($resourceType == 'Image') {
271                            list($width, $height, $type, $attr) = getimagesize($sServerDir . $sFile);
272                                if(isset($width) && isset($height)) {
273                                  $iFileSize .= ";;$width;;$height";
274                                }
275
276                            }
277
278
279                      //    $aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" />' ;
280                      $aFiles[] = '<File name="' . ConvertToXmlAttribute( $sFile ) . '" size="' . $iFileSize . '" time="' . $cTime .'" />' ;
281                    }
282
283				}
284			}
285		}
286		closedir( $oCurrentFolder ) ;
287	}
288
289
290
291	// Send the folders
292	natcasesort( $aFolders ) ;
293	echo '<Folders>' ;
294
295	foreach ( $aFolders as $sFolder ) {
296
297		echo $sFolder;
298	}
299
300	echo '</Folders>' ;
301
302	// Send the files
303	natcasesort( $aFiles ) ;
304	echo '<Files>' ;
305
306	foreach ( $aFiles as $sFiles )
307		echo $sFiles ;
308
309	echo '</Files>' ;
310
311
312
313}
314
315function CreateFolder( $resourceType, $currentFolder )
316{
317    global $_FolderClass;
318    global $Config;
319	if (!isset($_GET)) {
320		global $_GET;
321	}
322	$sErrorNumber	= '0' ;
323	$sErrorMsg		= '' ;
324    if(!has_permission($currentFolder, $resourceType) || $_FolderClass < 8 ) {
325         if(!has_open_access()) {
326            $sErrorNumber = 103;
327      	    echo '<Error number="' . $sErrorNumber . '" />' ;
328            return;
329         }
330    }
331
332   $sNewFolderName =  input_strval('NewFolderName');
333	if(isset($sNewFolderName))
334	{
335       $sess_id = session_id();
336       if(!isset($sess_id) || $sess_id != $_COOKIE['FCK_NmSp_acl']) {
337           session_id($_COOKIE['FCK_NmSp_acl']);
338           session_start();
339       }
340
341        global $Dwfck_conf_values;
342        global $dwfck_conf;
343        $dwfck_conf = $_SESSION['dwfck_conf'];
344        if(empty($dwfck_conf)) {
345            $dwfck_conf['deaccent'] = isset($Dwfck_conf_values['deaccent'])? $Dwfck_conf_values['deaccent'] : 1;
346            $dwfck_conf['useslash'] = isset($Dwfck_conf_values['useslash']) ? $Dwfck_conf_values['useslash'] : 0;
347            $dwfck_conf['sepchar'] = isset($Dwfck_conf_values['sepchar']) ? $Dwfck_conf_values['sepchar'] : '_';
348        }
349
350		$sNewFolderName = input_strval('NewFolderName');
351        $sNewFolderName = str_replace(' ', $dwfck_conf['sepchar'], $sNewFolderName);
352        $sNewFolderName=Dwfck_sanitize( $sNewFolderName ) ;
353
354		if ( strpos( $sNewFolderName, '..' ) !== FALSE )
355			$sErrorNumber = '102' ;		// Invalid folder name.
356		else
357		{
358			// Map the virtual path to the local server path of the current folder.
359			$sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'CreateFolder' ) ;
360
361           if($Dwfck_conf_values['fnencode'] == 'url' || ($Config['osWindows'] && !isset($Dwfck_conf_values['fnencode']))) {
362                  $sServerDir=encode_dir($sServerDir);
363           }
364            if($Config['osWindows']) {
365                $sServerDir = normalizeWIN($sServerDir);
366            }
367
368			if ( is_writable( $sServerDir ) )
369			{
370				$sServerDir .= $sNewFolderName ;
371
372				$sErrorMsg = CreateServerFolder( $sServerDir ) ;
373
374				switch ( $sErrorMsg )
375				{
376					case '' :
377						$sErrorNumber = '0' ;
378						break ;
379					case 'Invalid argument' :
380					case 'No such file or directory' :
381						$sErrorNumber = '102' ;		// Path too long.
382						break ;
383					default :
384						$sErrorNumber = '110' ;
385						break ;
386				}
387			}
388			else
389				$sErrorNumber = '103' ;
390		}
391	}
392	else
393		$sErrorNumber = '102' ;
394
395	// Create the "Error" node.
396	echo '<Error number="' . $sErrorNumber . '" />' ;
397}
398
399function Dwfck_sanitize($sFileName, $media=false) {
400  global $Dwfck_conf_values;
401
402        $sFileName = dwiki_decodeFN($sFileName);
403        $sFileName = cleanID($sFileName,false,$media);
404        return dwiki_encodeFN($sFileName);
405}
406
407
408function normalizeWIN($path) {
409  if(!$path) return "";
410  global $winChars,  $winSearch;
411  if(!isset($winSearch)) {
412      $winChars = array('/',':','(',')','{','}','{','}',' ', '\\',
413     ']','[', '$',  '+',  '@',  '!',  '#',  '%',  '*', '?');
414      $winSearch = array_map('rawurlencode', $winChars);
415  }
416
417   $path = str_replace($winSearch,$winChars,$path);
418   $path = str_replace('/','\\',$path);
419  // $path = preg_replace('#\\\\{2,}#','\\',$path);
420   $path = str_replace('.\\','\\',$path);
421
422   return str_replace('+',' ', $path);
423
424
425}
426
427function UnlinkFile($resourceType, $currentFolder, $sCommand, $filename ) {
428global $Config;
429  global $Dwfck_conf_values;
430  $move = false;
431
432    $sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFoldersAndFiles' ) ;
433    $path = $sServerDir.$filename;
434    $parts=pathinfo($path);
435
436    if(preg_match('/^(.*?)\/(.*?)$/',$filename,$matches)) {
437      $move = true;
438      $sMoveDir = $sServerDir;
439      $sMoveDir .= dwiki_encodeFN($matches[1]);
440
441      $sMoveDir = rtrim($sMoveDir, '/');
442      $filename = $matches[2];
443      mkdir_rek($sMoveDir);
444
445
446      if(preg_match('/secure$/', $sMoveDir)){
447          if(!file_exists($sMoveDir . '/' . '.htaccess')) {
448            copy( 'htaccess' , $sMoveDir . '/' . '.htaccess') ;
449          }
450      }
451      $moveFile = $sMoveDir . '/' . dwiki_encodeFN($filename );
452
453    }
454    else {
455        if($Dwfck_conf_values['fnencode'] == 'url' || ($Config['osWindows'] && !isset($Dwfck_conf_values['fnencode']))) {
456              $sServerDir=encode_dir($sServerDir);
457        }
458    }
459
460    $unlinkFile =    $sServerDir . dwiki_encodeFN($filename );
461
462    if($Config['osWindows']) {
463       $unlinkFile = normalizeWIN($unlinkFile);
464    }
465
466    if($move) {
467      if($Config['osWindows']) {
468         $moveFile = normalizeWIN($moveFile);
469       }
470
471       if(rename($unlinkFile, $moveFile)) {
472         return GetFoldersAndFiles( $resourceType, $currentFolder );
473       }
474       else {
475         $sErrorNumber = '205';
476         echo '<Error number="' . $sErrorNumber . '" />' ;
477         return;
478       }
479    }
480     return GetFoldersAndFiles( $resourceType, $currentFolder );
481    if(file_exists($unlinkFile)&& unlink($unlinkFile)) {
482          return GetFoldersAndFiles( $resourceType, $currentFolder );
483    }
484    else {
485        $sErrorNumber = '204';
486        echo '<Error number="' . $sErrorNumber . '" />' ;
487    }
488
489}
490
491function encode_dir($path) {
492
493   if(preg_match('/%25/',$path)) {
494     $path =  urldecode($path);
495     while(preg_match('/%25/',$path)) {
496       $path =  urldecode($path);
497     }
498
499     return $path;
500
501   }
502
503   if(preg_match('/%[A-F]\d/i',$path) || preg_match('/%\d[A-F]/i',$path)) {
504     return $path;
505   }
506
507
508   $dirs = explode('/',$path);
509
510   $new_path = "";
511   foreach($dirs as $dir) {
512     $new_path .= dwiki_encodeFN($dir). '/';
513   }
514
515    $new_path = rtrim($new_path,'/');
516    $new_path .= '/';
517
518    return $new_path;
519}
520
521function FileUpload( $resourceType, $currentFolder, $sCommand )
522{
523    global $dwfck_conf;
524
525	if (!isset($_FILES)) {
526		global $_FILES;
527	}
528    $f_args = array(
529    'name' => array('filter' => FILTER_SANITIZE_STRING|FILTER_SANITIZE_ENCODED,
530              'flags' => FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH),
531    'type' => "",
532    'tmp_name' => "",
533    'error' => "",
534    'size' => ""
535) ;
536    $keys = array_keys($_FILES);
537    $_FILES['NewFile']['name'] = cleanID(str_replace('&','_', $_FILES['NewFile']['name']));
538    $file_data = filter_var_array($_FILES[$keys[0]], $f_args);
539   // cmd_write_debug($_FILES);
540   // cmd_write_debug($file_data);
541	$sErrorNumber = '0' ;
542	$sFileName = '' ;
543
544    $sess_id = session_id();
545    if(!isset($sess_id) || $sess_id != $_COOKIE['FCK_NmSp_acl']) {
546       session_id($_COOKIE['FCK_NmSp_acl']);
547       session_start();
548   }
549
550    global $Dwfck_conf_values;
551    $dwfck_conf = $_SESSION['dwfck_conf'];
552    if(empty($dwfck_conf)) {
553        $dwfck_conf['deaccent'] = isset($Dwfck_conf_values['deaccent'])? $Dwfck_conf_values['deaccent'] : 1;
554        $dwfck_conf['useslash'] = isset($Dwfck_conf_values['useslash']) ? $Dwfck_conf_values['useslash'] : 0;
555        $dwfck_conf['sepchar'] = isset($Dwfck_conf_values['sepchar']) ? $Dwfck_conf_values['sepchar'] : '_';
556    }
557
558    $auth = 0;
559    if(isset($_REQUEST['TopLevel'])) {
560       list($top_level,$auth) = explode(';;',$_REQUEST['TopLevel']);
561    }
562
563
564
565  $safe = false;
566  global $Dwfck_conf_values;
567  if($Dwfck_conf_values['fnencode'] == 'safe') {
568      if(preg_match('/%[a-z]+[0-9]/',$currentFolder) || preg_match('/%[0-9][a-z]/',$currentFolder)) {
569          $safe = true;
570      }
571  }
572  $ns_tmp = dwiki_decodeFN(trim($currentFolder, '/'));
573
574  $ns_tmp = str_replace('/', ':', $ns_tmp);
575  $test = $ns_tmp . ':*' ;
576
577  if(!$safe) {
578    $test = urldecode($test);
579
580    while(preg_match('/%25/',$test)){
581          $test =  urldecode($test);
582    }
583    $test = urldecode($test);
584  }
585
586   $isadmin = isset($_SESSION['dwfck_conf']['isadmin']) ? $_SESSION['dwfck_conf']['isadmin'] : false;
587   if(!$isadmin) {
588       $AUTH = auth_aclcheck($test, $_SESSION['dwfck_client'] , $_SESSION['dwfck_grps'],1);
589
590        if($AUTH < 8) {
591            $msg="";
592        	$sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ) ;
593    	    $sFileUrl = CombinePaths( $sFileUrl, $file_data['name']);
594            SendUploadResults( '203', $sFileUrl, $file_data['name'],  $msg ) ;
595            return;
596
597         }
598   }
599    if(!$safe) {
600        $currentFolder = encode_dir($currentFolder);
601    }
602	if ( isset( $file_data ) && !is_null( $file_data['tmp_name'] ) )
603	{
604		global $Config ;
605
606        $upload_err = $file_data['error'];
607        if($upload_err ) {
608            send_ckg_UploadError($upload_err,$sFileUrl, $file_data['name']);
609            exit;
610        }
611		$oFile = $file_data ;
612
613
614		// Map the virtual path to the local server path.
615		$sServerDir = ServerMapFolder( $resourceType, $currentFolder, $sCommand ) ;
616
617		// Get the uploaded file name.
618		$sFileName = dwiki_encodeFN($oFile['name']) ;
619        $sOriginalFileName = dwiki_encodeFN($sFileName);
620
621		// Get the extension.
622		$sExtension = substr( $sFileName, ( strrpos($sFileName, '.') + 1 ) ) ;
623		$sExtension = strtolower( $sExtension ) ;
624        $image_file = false;
625
626        if(in_array($sExtension,$Config['AllowedExtensions']['Image'])) {
627            $image_file=true;
628        }
629
630		if ( isset( $Config['SecureImageUploads'] ) )
631		{
632			if ( ( $isImageValid = IsImageValid( $oFile['tmp_name'], $sExtension ) ) === false )
633			{
634				$sErrorNumber = '202' ;
635			}
636		}
637
638		if ( isset( $Config['HtmlExtensions'] ) )
639		{
640			if ( !IsHtmlExtension( $sExtension, $Config['HtmlExtensions'] ) &&
641				( $detectHtml = DetectHtml( $oFile['tmp_name'] ) ) === true )
642			{
643				$sErrorNumber = '202' ;
644			}
645		}
646
647        $sFileName = Dwfck_sanitize($sFileName, $image_file);
648
649		// Check if it is an allowed extension.
650		if ( !$sErrorNumber && IsAllowedExt( $sExtension, $resourceType ) )
651		{
652			$iCounter = 0 ;
653
654			while ( true )
655			{
656
657                //$sFileName = strtolower($sFileName);
658
659                if(!is_dir($sServerDir))
660                {
661                	if ( isset( $Config['ChmodOnFolderCreate'] ) && !$Config['ChmodOnFolderCreate'] )
662					{
663						mkdir_rek($sServerDir,$permissions);
664					}
665					else
666					{
667						$permissions = 0777 ;
668						if ( isset( $Config['ChmodOnFolderCreate'] ) )
669						{
670							$permissions = $Config['ChmodOnFolderCreate'] ;
671						}
672						// To create the folder with 0777 permissions, we need to set umask to zero.
673						$oldumask = umask(0) ;
674						mkdir_rek($sServerDir,$permissions);
675						umask( $oldumask ) ;
676					}
677
678                }
679
680				$sFilePath = $sServerDir . $sFileName ;
681
682
683				if ( is_file( $sFilePath ) )
684				{
685					$iCounter++ ;
686
687                     if($Dwfck_conf_values['fnencode'] == 'safe') {
688       			       $sFileName = RemoveExtension(dwiki_decodeFN($sOriginalFileName)) . '_' . $iCounter  . ".$sExtension" ;
689                    }
690                    else  $sFileName = RemoveExtension($sOriginalFileName) . '_' . $iCounter  . ".$sExtension" ;
691                    $sFileName = Dwfck_sanitize($sFileName, $image_file);
692					$sErrorNumber = '201' ;
693				}
694				else
695				{
696					move_uploaded_file( $oFile['tmp_name'], $sFilePath ) ;
697
698					if ( is_file( $sFilePath ) )
699					{
700						if ( isset( $Config['ChmodOnUpload'] ) && !$Config['ChmodOnUpload'] )
701						{
702							break ;
703						}
704
705						$permissions = 0777;
706
707						if ( isset( $Config['ChmodOnUpload'] ) && $Config['ChmodOnUpload'] )
708						{
709							$permissions = $Config['ChmodOnUpload'] ;
710						}
711
712						$oldumask = umask(0) ;
713						chmod( $sFilePath, $permissions ) ;
714						umask( $oldumask ) ;
715					}
716
717					break ;
718				}
719			}
720
721			if ( file_exists( $sFilePath ) )
722			{
723				//previous checks failed, try once again
724				if ( isset( $isImageValid ) && $isImageValid === -1 && IsImageValid( $sFilePath, $sExtension ) === false )
725				{
726					@unlink( $sFilePath ) ;
727					$sErrorNumber = '202' ;
728				}
729				else if ( isset( $detectHtml ) && $detectHtml === -1 && DetectHtml( $sFilePath ) === true )
730				{
731					@unlink( $sFilePath ) ;
732					$sErrorNumber = '202' ;
733				}
734			}
735		}
736		else
737			$sErrorNumber = '202' ;
738	}
739	else
740		$sErrorNumber = '202' ;
741
742
743	$sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ) ;
744	$sFileUrl = CombinePaths( $sFileUrl, $sFileName ) ;
745
746	SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ) ;
747
748	exit ;
749}
750
751function mkdir_rek($dir, $mode = 0777)
752{
753 global $Config;
754    if($Config['osWindows']) $dir=normalizeWIN($dir);
755	if (!is_dir($dir))	{
756		mkdir_rek(dirname($dir), $mode);
757		mkdir($dir, $mode);
758
759	}
760}
761
762function send_ckg_UploadError($err,$sFileUrl, $file) {
763    switch($err) {
764
765        case UPLOAD_ERR_INI_SIZE:
766            $msg = "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
767            break;
768
769        case UPLOAD_ERR_FORM_SIZE:
770        $msg = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
771        break;
772
773        case UPLOAD_ERR_PARTIAL:
774            $msg = "The uploaded file was only partially uploaded.";
775            break;
776
777        case UPLOAD_ERR_NO_FILE:
778            $msg = "No file was uploaded.";
779            break;
780
781       case 6:       //   UPLOAD_ERR_NO_TMP_DIR  Introduced in PHP 4.3.10 and PHP 5.0.3.
782            $msg = "Missing a temporary folder.";
783            break;
784
785       case 7:  //UPLOAD_ERR_CANT_WRITE  Introduced in PHP 5.1.0.
786            $msg="Failed to write file to disk.";
787            break;
788
789        case 8: //UPLOAD_ERR_EXTENSION   Introduced in PHP 5.2.0.
790            $msg="PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.";
791            break;
792
793        default:
794           $msg = "Undetermined  upload error";
795           break;
796    }
797      $upload_error = 300 + $err;
798       SendUploadResults( $upload_error, $sFileUrl, $file,  $msg ) ;
799
800}
801
802function can_delete(&$class) {
803   global $_FolderClass;
804   if($_FolderClass >=16) $class = 'd';
805}
806
807function cmd_write_debug($what) {
808return;
809if(is_array($what)) {
810   $what = print_r($what,true);
811}
812$dwfckFHandle = fopen("fbrowser_dbg.txt", "a");
813fwrite($dwfckFHandle, "$what\n");
814fclose($dwfckFHandle);
815}
816?>
817