Projet

Général

Profil

class.ftpCasAccessDriver.php

Gérald Schwartzmann, 09/01/2012 14:22

Télécharger (44,2 ko)

 
1
<?php
2
/**
3
 * @package info.ajaxplorer.plugins
4
 *
5
 *
6
 * Description : The most used and standard plugin : FileSystem access
7
 */
8
include_once('CAS/eoleCAS.php');
9
include('configCAS/cas.inc.php');
10
include(INSTALL_PATH.'/plugins/auth.cas/config.php');
11
EolephpCAS::proxy(__CAS_VERSION, __CAS_SERVER, __CAS_PORT, __CAS_URL, false);
12
if (method_exists(phpCAS, "setNoCasServerValidation")){
13
        EolephpCAS::setNoCasServerValidation();
14
}
15

    
16
class ftpCasAccessDriver extends  AbstractAccessDriver
17
{
18
        /**
19
         * @var Repository
20
         */
21
        var $connect;
22
        /** The user to connect to */
23
        var $user;
24
        /** The password to use */
25
        var $password;
26
        var $path;
27
        var $logger;
28

    
29
        function  ftpCasAccessDriver($driverName, $filePath, $repository, $optOptions = NULL){
30
                //CAS eole
31
                //Corrige bug basename
32
                setlocale(LC_ALL, 'en_US.UTF8');
33
                $this->user = $optOptions ? $optOptions["user"] : $_SESSION['username'];
34
                $this->password = $optOptions ? $optOptions["password"] : $_SESSION['password'];
35
                parent::AbstractAccessDriver($driverName, INSTALL_PATH."/plugins/access.fs/fsActions.xml", $repository);
36
                unset($this->actions["upload"]);
37
                $this->initXmlActionsFile(INSTALL_PATH."/plugins/access.ftpCas/additionalActions.xml");
38
                $this->xmlFilePath = INSTALL_PATH."/plugins/access.fs/fsActions.xml";
39
        }
40

    
41
        function get_cas_pt(){
42
                if (EolephpCAS::isAuthenticated()){
43
                        $CAS = $GLOBALS['PHPCAS_CLIENT'];
44
                        //$CAS->setPGT($_SESSION['phpCAS']['pgt']);
45
                        $PT = $CAS->retrievePT(__FTP_SERVICE, $err_code, $output);
46
                        $USER = EolephpCAS::getUser();
47
                        return $PT;
48
                }else{
49
                        return '';
50
                }
51
        }
52

    
53
        function initRepository(){
54
                $this->connect = $this->createFTPLink();
55
                // Try to detect the charset encoding
56
                global $_SESSION;
57
                if (!isset($_SESSION["ftpCharset"]) || !strlen($_SESSION["ftpCharset"]))
58
                {
59
                        $features = $this->getServerFeatures();
60
                        if(!isSet($_SESSION["AJXP_CHARSET"])) $_SESSION["AJXP_CHARSET"] = "";
61
                        if ($_SESSION["AJXP_CHARSET"] == "") $_SESSION["AJXP_CHARSET"] = $features["charset"];
62
                        $_SESSION["ftpCharset"] = $_SESSION["AJXP_CHARSET"];
63
                }
64
                $recycle = $this->repository->getOption("RECYCLE_BIN");
65
                if(class_exists("RecycleBinManager") && $recycle != "" && $this->repository->detectStreamWrapper(true)){
66
                        RecycleBinManager::init("ajxp.ftp://".$this->repository->getUniqueId(), "/".$recycle);
67
                }
68

    
69
        }
70

    
71
        function getUserName($repository){
72
                $logUser = AuthService::getLoggedUser();
73
                $wallet = $logUser->getPref("AJXP_WALLET");
74
                return is_array($wallet) ? $wallet[$repository->getUniqueId()]["FTP_USER"] : "";
75
        }
76

    
77
        function getPassword($repository){
78
                $logUser = AuthService::getLoggedUser();
79
                $wallet = $logUser->getPref("AJXP_WALLET");
80
                return is_array($wallet) ? $logUser->decodeUserPassword($wallet[$repository->getUniqueId()]["FTP_PASS"]) : "";
81
        }
82

    
83
        /** This method retrieves the FTP server features as described in RFC2389
84
            A decent FTP server support MLST command to list file using UTF-8 encoding
85
        @return an array of features (see code) */
86
        function getServerFeatures(){
87
                $features = @ftp_raw($this->connect, "FEAT");
88
                // Check the answer code
89
                if (!$this->checkCode($features)) return array("list"=>"LIST", "charset"=>$this->repository->getOption("CHARSET"));
90
                $retArray = array("list"=>"LIST", "charset"=>$this->repository->getOption("CHARSET"));
91
                // Ok, find out the encoding used
92
                foreach($features as $feature)
93
                {
94
                        if (strstr($feature, "UTF8") !== FALSE)
95
                        {   // See http://wiki.filezilla-project.org/Character_Set for an explaination
96
                                @ftp_raw($this->connect, "OPTS UTF-8 ON");
97
                                $retArray['charset'] = "UTF-8";
98
                                return $retArray;
99
                        }
100
                }
101
                // In the future version, we should also use MLST as it standardize the listing format
102
                return $retArray;
103
        }
104

    
105
        function checkCode($array)
106
        {   // Good output is 2xx value
107
                if ($array[0] && $array[0][0] != "2") return FALSE;
108
                return TRUE;
109
        }
110

    
111
        function createFTPLink($registerClose = true){
112
                $link = FALSE;
113
                //Connects to the FTP.
114
                $host = $this->repository->getOption("FTP_HOST");
115
                #                $this->path = $this->repository->getOption("PATH");
116
                $this->path = $this->createRepository();
117
                $this->repository->options = array('PATH'=>$this->path);
118
                $link = @ftp_connect($host);
119
                if(!$link) {
120
                        $ajxpExp = new AJXP_Exception("Cannot connect to FTP server!");
121
                        AJXP_Exception::errorToXml($ajxpExp);
122

    
123
                }
124
                if($registerClose){
125
                        register_shutdown_function('ftp_close', $link);
126
                }
127
                @ftp_set_option($link, FTP_TIMEOUT_SEC, 10);
128
                $password = $this->get_cas_pt();
129
                if(!@ftp_login($link,$this->user,$password)){
130
                        $ajxpExp = new AJXP_Exception("Cannot login to FTP server with user $this->user");
131
                        AJXP_Exception::errorToXml($ajxpExp);
132
                }
133
                if ($this->repository->getOption("FTP_DIRECT") != "TRUE")
134
                {
135
                        @ftp_pasv($link, true);
136
                        global $_SESSION;
137
                        $_SESSION["ftpPasv"]="true";
138
                }
139
                return $link;
140
        }
141

    
142
        function switchAction($action, $httpVars, $fileVars){
143
                if(!isSet($this->actions[$action])) return;
144
                $xmlBuffer = "";
145
                foreach($httpVars as $getName=>$getValue){
146
                        $$getName = Utils::securePath(SystemTextEncoding::magicDequote($getValue));
147
                }
148
                $selection = new UserSelection();
149
                $selection->initFromHttpVars($httpVars);
150
                if(isSet($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); }
151
                if(isSet($dest)) $dest = SystemTextEncoding::fromUTF8($dest);
152
                $mess = ConfService::getMessages();
153
                if(class_exists("RecycleBinManager")){
154
                        $newArgs = RecycleBinManager::filterActions($action, $selection, $dir);
155
                        foreach ($newArgs as $argName => $argValue){
156
                                $$argName = $argValue;
157
                        }
158
                }
159

    
160
                switch($action)
161
                {
162
                        //------------------------------------
163
                        //        DOWNLOAD, IMAGE & MP3 PROXYS
164
                        //------------------------------------
165
                case "download":
166
                case "image_proxy":
167
                case "mp3_proxy":
168
                        if($selection->isUnique()){
169
                                AJXP_Logger::logAction("Download", array("files"=>$selection));
170
                                $this->sendRemoteFile($selection->files[0], $action == "download");
171
                        }else{
172
                                $zip = true;
173
                        }
174
                        if($zip){
175
                                $file = "files/tmpDownload.zip";
176
                                $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
177
                                $this->readFile($file, "force-download");
178
                                $this->deleteMakeZip($selection->getFiles(), $file);
179
                        }
180
                        exit(0);
181
                        break;
182

    
183
                        //------------------------------------
184
                        //        ONLINE EDIT
185
                        //------------------------------------
186
                        case "edit";
187
                        $file_name = basename($file);
188
                        $this->ftp_get_contents($file);
189
                        if(isset($save) && $save==1 && isSet($code))
190
                        {
191
                                // Reload "code" variable directly from POST array, do not "securePath"...
192
                                $code = $_POST["code"];
193
                                AJXP_Logger::logAction("Online Edition", array("file"=>SystemTextEncoding::fromUTF8($file_name)));
194
                                $code=stripslashes($code);
195
                                $code=str_replace("&lt;","<",$code);
196
                                $fp=fopen("files/".SystemTextEncoding::fromUTF8("$file_name"),"w");
197
                                fputs ($fp,$code);
198
                                fclose($fp);
199
                                echo $mess[115];
200
                                ftp_put($this->connect,$this->secureFtpPath($this->getPath().$file),"files/".SystemTextEncoding::fromUTF8($file_name), FTP_BINARY);
201
                                $this->ftpRemoveFileTmp("files/".SystemTextEncoding::fromUTF8("$file_name"));
202
                                $reload_current_node = true;
203

    
204
                        }
205
                        else
206
                        {
207
                                $this->readFile("files/".SystemTextEncoding::fromUTF8($file_name), "plain");
208
                        }
209

    
210
                        exit(0);
211
                        break;
212

    
213
                case "compress" :
214
                        // Make a temp zip and send it as download
215
                        if(isSet($archive_name)){
216
                                $localName = SystemTextEncoding::fromUTF8($archive_name);
217
                        }else{
218
                                $localName = (basename($dir)==""?"Files":basename($dir)).".zip";
219
                        }
220
                        $file = $this->secureFtpPath("files/".$localName);
221
                        $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
222
                        if(!$zipFile) AJXP_Exception::errorToXml("Error while compressing file $localName");
223
                        ftp_put($this->connect,$this->secureFtpPath($this->getPath().$dir."/".basename($file)),"files/".SystemTextEncoding::fromUTF8(basename($file)), FTP_BINARY);
224
                        $this->deleteMakeZip($selection->getFiles(), $file);
225
                        $reload_current_node = true;
226
                        $reload_file_list = $localName;
227

    
228
                        break;
229

    
230

    
231
                        //------------------------------------
232
                        //        SUPPRIMER / DELETE
233
                        //------------------------------------
234
                        case "delete";
235

    
236
                        if($selection->isEmpty())
237
                        {
238
                                $errorMessage = $mess[113];
239
                                break;
240
                        }
241
                        $logMessages = array();
242
                        $errorMessage = $this->delete($selection->getFiles(), $logMessages,$dir);
243
                        if(count($logMessages))
244
                        {
245
                                $logMessage = join("\n", $logMessages);
246
                        }
247
                        AJXP_Logger::logAction("Delete", array("files"=>$selection));
248
                        $reload_current_node = true;
249
                        $reload_file_list = true;
250

    
251
                        break;
252

    
253
                        //------------------------------------
254
                        //        RENOMMER / RENAME
255
                        //------------------------------------
256
                        case "rename";
257

    
258
                        $file = SystemTextEncoding::fromUTF8($file);
259
                        $filename_new = SystemTextEncoding::fromUTF8($filename_new);
260
                        $error = $this->rename($file, $filename_new);
261
                        if($error != null) {
262
                                $errorMessage  = $error;
263
                                break;
264
                        }
265
                        $logMessage= SystemTextEncoding::toUTF8($file)." $mess[41] ".SystemTextEncoding::toUTF8($filename_new);
266
                        $reload_current_node = true;
267
                        $reload_file_list = basename($filename_new);
268
                        AJXP_Logger::logAction("Rename", array("original"=>$file, "new"=>$filename_new));
269

    
270
                        break;
271

    
272
                        //------------------------------------
273
                        //        CREER UN REPERTOIRE / CREATE DIR
274
                        //------------------------------------
275
                        case "mkdir";
276

    
277
                        $messtmp="";
278
                        $dirname=Utils::processFileName(SystemTextEncoding::fromUTF8($dirname));
279
                        $error = $this->mkDir($dir, $dirname);
280
                        if(isSet($error)){
281
                                $errorMessage = $error; break;
282
                        }
283
                        $reload_file_list = $dirname;
284
                        $messtmp.="$mess[38] ".SystemTextEncoding::toUTF8($dirname)." $mess[39] ";
285
                        if($dir=="") {$messtmp.="/";} else {$messtmp.= SystemTextEncoding::toUTF8($dir);}
286
                        $logMessage = $messtmp;
287
                        $reload_current_node = true;
288
                        AJXP_Logger::logAction("Create Dir", array("dir"=>$dir."/".$dirname));
289

    
290
                        break;
291

    
292
                        //------------------------------------
293
                        //        CREER UN FICHIER / CREATE FILE
294
                        //------------------------------------
295
                        case "mkfile";
296

    
297
                        $messtmp="";
298
                        $filename=Utils::processFileName(SystemTextEncoding::fromUTF8($filename));
299
                        $error = $this->createEmptyFile($dir, $filename);
300
                        if(isSet($error)){
301
                                $errorMessage = $error; break;
302
                        }
303
                        $messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] ";
304
                        if($dir=="") {$messtmp.="/";} else {$messtmp.=SystemTextEncoding::toUTF8($dir);}
305
                        $logMessage = $messtmp;
306
                        $reload_file_list = $filename;
307
                        AJXP_Logger::logAction("Create File", array("file"=>$dir."/".$filename));
308

    
309
                        break;
310

    
311
                        //------------------------------------
312
                        //        CHANGE FILE PERMISSION
313
                        //------------------------------------
314
                        case "chmod";
315

    
316
                        $files = $selection->getFiles();
317
                        if(@ftp_chmod($this->connect,$chmod_value, $this->getPath().$files[0])===false)
318
                        {
319
                                $error = "Error chmod";
320
                        }
321
                        if(isSet($error)){
322
                                $errorMessage = $error; break;
323
                        }
324
                        $logMessage="Successfully changed permission to ".$chmod_value." for ".$files[0];
325
                        $reload_file_list = $dir;
326
                        AJXP_Logger::logAction("Chmod", array("dir"=>$dir, "file"=>$files[0]));
327

    
328

    
329
                        break;
330

    
331
                        //------------------------------------
332
                        //        UPLOAD
333
                        //------------------------------------
334
                case "upload":
335

    
336
                        break;
337

    
338
                        //------------------------------------
339
                        //        COPY / MOVE
340
                        //------------------------------------
341

    
342
                        case "copy";
343
                        case "move";
344
                                
345
                                if($selection->isEmpty())
346
                                {
347
                                        $errorMessage = $mess[113];
348
                                        break;
349
                                }
350
                                if($selection->inZip()){
351
                                        $tmpDir = dirname($selection->getZipPath())."/.tmpExtractDownload";
352
                                        @mkdir($this->getPath()."/".$tmpDir);                                        
353
                                        $this->convertSelectionToTmpFiles($tmpDir, $selection);
354
                                        if(is_dir($tmpDir))        $this->deldir($this->getPath()."/".$tmpDir);                                        
355
                                }
356
                                $success = $error = array();
357
                                
358
                                $this->copyOrMove($dest, $selection->getFiles(), $error, $success, ($action=="move"?true:false));
359
                                
360
                                if(count($error)){
361
                                        $errorMessage = join("\n", $error);
362
                                }
363
                                else {
364
                                        $logMessage = join("\n", $success);
365
                                        AJXP_Logger::logAction(($action=="move"?"Move":"Copy"), array("files"=>$selection, "destination"=>$dest));
366
                                }
367
                                $reload_current_node = true;
368
                                if(isSet($dest_node)) $reload_dest_node = $dest_node;
369
                                $reload_file_list = true;
370
                                
371
                        break;
372

    
373
                        //------------------------------------
374
                        // Public URL
375
                        //------------------------------------
376

    
377
                case "public_url":
378
                        $file = SystemTextEncoding::fromUTF8($file);
379
                        $url = $this->makePubliclet($file, $password, $expiration);
380
                        header("Content-type:text/plain");
381
                        echo $url;
382
                        exit(1);
383
                        break;
384
                        //------------------------------------
385
                        //        XML LISTING
386
                        //------------------------------------
387
                case "ls":
388
                        if(!isSet($dir) || $dir == "/") $dir = "";
389
                        $searchMode = $fileListMode = $completeMode = false;
390
                        if(isSet($mode)){
391
                                if($mode == "search") $searchMode = true;
392
                                else if($mode == "file_list") $fileListMode = true;
393
                                else if($mode == "complete") $completeMode = true;
394
                        }
395
                        if(isSet($skipZip) && $skipZip == "true"){
396
                                $skipZip = true;
397
                        }else{
398
                                $skipZip = false;
399
                        }
400
                        if($test = UserSelection::detectZip($dir)){
401
                                $liste = array();
402
                                $zip = $this->zipListing($test[0], $test[1], $liste);
403
                                AJXP_XMLWriter::header();
404
                                $tmpDir = $this->getPath().dirname($test[0]).".tmpZipExtract";
405
                                foreach ($liste as $zipEntry){
406
                                        $atts = array();
407
                                        if(!$fileListMode && !$zipEntry["folder"]) continue;
408
                                        $atts[] = "is_file=\"".($zipEntry["folder"]?"false":"true")."\"";
409
                                        $atts[] = "text=\"".str_replace("&", "&amp;", basename(SystemTextEncoding::toUTF8($zipEntry["stored_filename"])))."\"";
410
                                        $atts[] = "filename=\"".str_replace("&", "&amp;", SystemTextEncoding::toUTF8($zipEntry["filename"]))."\"";
411
                                        if($fileListMode){
412
                                                $atts[] = "filesize=\"".Utils::roundSize($zipEntry["size"])."\"";
413
                                                $atts[] = "bytesize=\"".$zipEntry["size"]."\"";
414
                                                $atts[] = "ajxp_modiftime=\"".$zipEntry["mtime"]."\"";
415
                                                $atts[] = "mimestring=\"".Utils::mimetype($zipEntry["stored_filename"], "mime", $zipEntry["folder"])."\"";
416
                                                $atts[] = "icon=\"".Utils::mimetype($zipEntry["stored_filename"], "image", $zipEntry["folder"])."\"";
417
                                                $is_image = Utils::is_image(basename($zipEntry["stored_filename"]));
418
                                                $atts[] = "is_image=\"".$is_image."\"";
419
                                                if($is_image){
420
                                                        if(!is_dir($tmpDir)) mkdir($tmpDir);
421
                                                        $currentFile = $tmpDir."/".basename($zipEntry["stored_filename"]);
422
                                                        $data = $zip->extract(PCLZIP_OPT_BY_NAME, $zipEntry["stored_filename"], PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $tmpDir);
423
                                                        list($width, $height, $type, $attr) = @getimagesize($currentFile);
424
                                                        $atts[] = "image_type=\"".image_type_to_mime_type($type)."\"";
425
                                                        $atts[] = "image_width=\"$width\"";
426
                                                        $atts[] = "image_height=\"$height\"";
427
                                                        unlink($currentFile);
428
                                                }
429
                                        }else{
430
                                                $atts[] = "icon=\"client/images/foldericon.png\"";
431
                                                $atts[] = "openicon=\"client/images/foldericon.png\"";
432
                                                $atts[] = "src=\"content.php?dir=".urlencode(SystemTextEncoding::toUTF8($zipEntry["filename"]))."\"";
433
                                        }
434
                                        print("<tree ".join(" ", $atts)."/>");
435
                                        if(is_dir($tmpDir)){
436
                                                rmdir($tmpDir);
437
                                        }
438
                                }
439
                                AJXP_XMLWriter::close();
440
                                exit(0);
441
                        }
442
                        $nom_rep = $this->initName($dir);
443
                        AJXP_Exception::errorToXml($nom_rep);
444
                        $result = $this->listing($nom_rep, !($searchMode || $fileListMode));
445
                        $this->fileListData = $result[0];
446
                        $reps = $result[0];
447
                        AJXP_XMLWriter::header();
448
                        if (!is_array($reps))
449
                        {
450
                                AJXP_XMLWriter::close();
451
                                exit(1);
452
                        }
453
                        foreach ($reps as $repIndex => $repName)
454
                        {
455
                                if(is_string($repName) && (preg_match("/\.zip$/",$repName) && $skipZip)) continue;
456
                                $attributes = "";
457
                                if($searchMode)
458
                                {
459
                                        if(is_file($nom_rep."/".$repIndex)) {$attributes = "is_file=\"true\" icon=\"$repName\""; $repName = $repIndex;}
460
                                }
461
                                else if($fileListMode)
462
                                {
463
                                        $currentFile = $nom_rep."/".$repName['name'];
464
                                        $atts = array();
465
                                        $atts[] = "is_file=\"".($repName['isDir']?"0":"1")."\"";
466

    
467
                                        $atts[] = "is_image=\"".Utils::is_image($currentFile)."\"";
468
                                        $atts[] = "file_group=\"".$repName['group']."\"";
469
                                        $atts[] = "file_owner=\"".$repName['owner']."\"";
470
                                        $atts[] = "file_perms=\"".$repName['chmod1']."\"";
471
                                        if(Utils::is_image($currentFile))
472
                                        {
473
                                                list($width, $height, $type, $attr) = $this->getimagesize($currentFile);
474
                                                $atts[] = "image_type=\"".image_type_to_mime_type($type)."\"";
475
                                                $atts[] = "image_width=\"$width\"";
476
                                                $atts[] = "image_height=\"$height\"";
477
                                        }
478
                                        $atts[] = "mimestring=\"".$repName['type']."\"";
479
                                        $datemodif = $repName['modifTime'];
480
                                        $atts[] = "ajxp_modiftime=\"".($datemodif ? $datemodif : "0")."\"";
481
                                        $bytesize = $repName['size'] or 0;
482
                                        if($bytesize < 0) $bytesize = sprintf("%u", $bytesize);
483
                                        $atts[] = "filesize=\"".Utils::roundSize($bytesize)."\"";
484
                                        $atts[] = "bytesize=\"".$bytesize."\"";
485
                                        $atts[] = "filename=\"".str_replace("&", "&amp;", SystemTextEncoding::toUTF8($dir."/".$repIndex))."\"";
486
                                        $atts[] = "icon=\"".$repName['icon']."\"";
487
                                        $attributes = join(" ", $atts);
488
                                        $repName = $repIndex;
489
                                }
490
                                else
491
                                {
492
                                        //Menu treeview repertoire
493
                                        $folderBaseName = str_replace("&", "&amp;", $repName['name']);
494
                                        $link = SystemTextEncoding::toUTF8(SERVER_ACCESS."?dir=".$dir."/".$folderBaseName);
495
                                        $link = urlencode($link);
496
                                        $folderFullName = str_replace("&", "&amp;", $dir)."/".$folderBaseName;
497
                                        $parentFolderName = $dir;
498
                                        $repName = $repIndex;
499
                                        if(!$completeMode){
500
                                                $icon = CLIENT_RESOURCES_FOLDER."/images/foldericon.png";
501
                                                $openicon = CLIENT_RESOURCES_FOLDER."/images/openfoldericon.png";
502
                                                if(preg_match("/\.zip$/",$repName)){
503
                                                        $icon = $openicon = CLIENT_RESOURCES_FOLDER."/images/crystal/actions/16/accessories-archiver.png";
504
                                                }
505
                                                $attributes = "icon=\"$icon\"  openicon=\"$openicon\" filename=\"".SystemTextEncoding::toUTF8($folderFullName)."\" src=\"$link\"";
506
                                        }
507
                                }
508
                                print("<tree text=\"".str_replace("&", "&amp;", SystemTextEncoding::toUTF8($repName))."\" $attributes>");
509
                                print("</tree>");
510
                        }
511
                        // ADD RECYCLE BIN TO THE LIST
512
                        if($nom_rep == $this->repository->getOption("PATH") && RecycleBinManager::recycleEnabled() && !$completeMode && !$skipZip)
513
                        {
514
                                $recycleBinOption = $this->repository->getOption("RECYCLE_BIN");
515
                                if($fileListMode)
516
                                {
517
                                        print("<tree text=\"".Utils::xmlEntities($mess[122])."\" filesize=\"-\" is_file=\"0\" is_recycle=\"1\" mimestring=\"Trashcan\" ajxp_modiftime=\"\" filename=\"/".$recycleBinOption."\" icon=\"trashcan.png\"></tree>");
518
                                }
519
                                else
520
                                {
521
                                        print("<tree text=\"$mess[122]\" is_recycle=\"true\" icon=\"".CLIENT_RESOURCES_FOLDER."/images/crystal/mimes/16/trashcan.png\"  openIcon=\"".CLIENT_RESOURCES_FOLDER."/images/crystal/mimes/16/trashcan.png\" filename=\"/".$recycleBinOption."\"/>");
522
                                }
523
                        }
524
                        AJXP_XMLWriter::close();
525
                        exit(1);
526

    
527
                        break;
528
                }
529

    
530
                if(isset($logMessage) || isset($errorMessage))
531
                {
532
                        $xmlBuffer .= AJXP_XMLWriter::sendMessage((isSet($logMessage)?$logMessage:null), (isSet($errorMessage)?$errorMessage:null), false);
533
                }
534

    
535
                if(isset($requireAuth))
536
                {
537
                        $xmlBuffer .= AJXP_XMLWriter::requireAuth(false);
538
                }
539

    
540
                if(isset($reload_current_node) && $reload_current_node == "true")
541
                {
542
                        $xmlBuffer .= AJXP_XMLWriter::reloadCurrentNode(false);
543
                }
544

    
545
                if(isset($reload_dest_node) && $reload_dest_node != "")
546
                {
547
                        $xmlBuffer .= AJXP_XMLWriter::reloadNode($reload_dest_node, false);
548
                }
549

    
550
                if(isset($reload_file_list))
551
                {
552
                        $xmlBuffer .= AJXP_XMLWriter::reloadFileList($reload_file_list, false);
553
                }
554

    
555
                return $xmlBuffer;
556
        }
557
        /**
558
         * @return zipfile
559
         */
560
        function makeZip ($src, $dest, $basedir)
561
        {
562
                $safeMode =  (@ini_get("safe_mode") == 'On' || @ini_get("safe_mode") === 1) ? TRUE : FALSE;
563
                if(!$safeMode){
564
                        set_time_limit(60);
565
                }
566
                require_once(SERVER_RESOURCES_FOLDER."/pclzip.lib.php");
567
                $filePaths = array();
568
                $totalSize = 0;
569
                foreach ($src as $item){
570
                        $filePaths[] = array(PCLZIP_ATT_FILE_NAME => "files/". basename($item),
571
                                PCLZIP_ATT_FILE_NEW_SHORT_NAME => basename($item));
572
                        $this->ftp_get_contents($item);
573
                }
574
                $archive = new PclZip($this->secureFtpPath($dest));
575
                $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, "files/", PCLZIP_OPT_NO_COMPRESSION);
576

    
577
                if($vList == 0) return false;
578
        }
579

    
580
        function deleteMakeZip ($src, $dest){
581

    
582
                        $this->ftpRemoveFileTmp("files/".SystemTextEncoding::fromUTF8(basename($dest)));
583
                        foreach ($src as $item){
584
                                $this->ftpRemoveFileTmp("files/". basename($item));
585
                        }
586

    
587
}
588

    
589

    
590
        function uploadActions($action, $httpVars, $filesVars){
591
                switch ($action){
592
                case "trigger_remote_copy":
593
                        if(!$this->hasFilesToCopy()) break;
594
                        $toCopy = $this->getFileNameToCopy();
595
                        AJXP_XMLWriter::header();
596
                        AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file ".$toCopy." to ftp server");
597
                        AJXP_XMLWriter::close();
598
                        exit(1);
599
                        break;
600
                case "next_to_remote":
601
                        if(!$this->hasFilesToCopy()) break;
602
                        $fData = $this->getNextFileToCopy();
603
                        $nextFile = '';
604
                        if($this->hasFilesToCopy()){
605
                                $nextFile = $this->getFileNameToCopy();
606
                        }
607
                        @ftp_put($this->connect,$this->secureFtpPath($this->path.base64_decode($fData['destination'])."/".$fData['name']),$fData['tmp_name'], FTP_BINARY);
608
                        //unlink($fData["tmp_name"]);
609
                        AJXP_XMLWriter::header();
610
                        if($nextFile!=''){
611
                                AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file ".$nextFile." to remote server");
612
                        }else{
613
                                AJXP_XMLWriter::sendMessage("Done", null);
614
                        }
615
                        AJXP_XMLWriter::close();
616
                        exit(1);
617
                        break;
618
                case "upload":
619
                        $fancyLoader = false;
620
                        if(isSet($fileVars["Filedata"])){
621
                                $fancyLoader = true;
622
                                if($httpVars['dir']!="") $httpVars['dir'] = "/".base64_decode($httpVars['dir']);
623
                        }
624
                        if(isSet($httpVars['dir']) && $httpVars['dir']!=""){$rep_source=$httpVars['dir'];}
625
                        else $rep_source = "/";
626
                        $logMessage = "";
627
                        //$fancyLoader = false;
628
                        foreach ($filesVars as $boxName => $boxData)
629
                        {
630
                                if($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_")     continue;
631
                                if($boxName == "Filedata") $fancyLoader = true;
632
                                $err = Utils::parseFileDataErrors($boxData, $fancyLoader);
633
                                if($err != null)
634
                                {
635
                                        $errorMessage = $err;
636
                                        break;
637
                                }
638
                                $boxData["destination"] = $rep_source;
639
                                $destCopy = INSTALL_PATH."/tmp";
640
                                if(!is_dir($destCopy)){
641
                                        if(! @mkdir($destCopy)){
642
                                                $errorMessage = "Warning, cannot create folder for temporary copy.";
643
                                                break;
644
                                        }
645
                                }
646
                                if(!is_writeable($destCopy)){
647
                                        $errorMessage = "Warning, cannot write into temporary folder.";
648
                                        break;
649
                                }
650
                                $destName = $destCopy."/".basename($boxData["tmp_name"]);
651
                                if(move_uploaded_file($boxData["tmp_name"], $destName)){
652
                                        $boxData["tmp_name"] = $destName;
653
                                        $this->storeFileToCopy($boxData);
654
                                        if($httpVars['protocole']==="https"){
655
                                                @ftp_put($this->connect,$this->secureFtpPath($this->path.$boxData["destination"]."/".$boxData['name']),$boxData['tmp_name'], FTP_BINARY);
656
                                        }else{
657
                                                @ftp_put($this->connect,$this->secureFtpPath($this->path.base64_decode($boxData["destination"])."/".$boxData['name']),$boxData['tmp_name'], FTP_BINARY);
658
                                        }
659
                                        unlink($boxData["tmp_name"]);
660

    
661
                                }else{
662
                                        $mess = ConfService::getMessages();
663
                                        $errorMessage=($fancyLoader?"411 ":"")."$mess[33] ".$boxData["name"];
664
                                }
665
                        }
666
                        if($fancyLoader)
667
                        {
668
                                session_write_close();
669
                                if(isSet($errorMessage)){
670
                                        header('HTTP/1.0 '.$errorMessage);
671
                                        die('Error '.$errorMessage);
672
                                }else{
673
                                        header('HTTP/1.0 200 OK');
674
                                        die("200 OK");
675
                                }
676
                        }
677
                        else
678
                        {
679
                                print("<html><script language=\"javascript\">\n");
680
                                if(isSet($errorMessage)){
681
                                        print("\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('".str_replace("'", "\'", $errorMessage)."');");
682
                                }else{
683
                                        print("\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext();");
684
                                }
685
                                print("</script></html>");
686
                        }
687
                        session_write_close();
688
                        exit;
689

    
690
                        break;
691
                default:
692
                        break;
693
                }
694

    
695
        }
696

    
697
        function storeFileToCopy($fileData){
698
                $user = AuthService::getLoggedUser();
699
                $files = $user->getTemporaryData("tmp_upload");
700
                $files[] = $fileData;
701
                $user->saveTemporaryData("tmp_upload", $files);
702
        }
703

    
704
        function getFileNameToCopy(){
705
                $user = AuthService::getLoggedUser();
706
                $files = $user->getTemporaryData("tmp_upload");
707
                return $files[0]["name"];
708
        }
709

    
710
        function getNextFileToCopy(){
711
                if(!$this->hasFilesToCopy()) return "";
712
                $user = AuthService::getLoggedUser();
713
                $files = $user->getTemporaryData("tmp_upload");
714
                $fData = $files[0];
715
                array_shift($files);
716
                $user->saveTemporaryData("tmp_upload", $files);
717
                return $fData;
718
        }
719

    
720
        function hasFilesToCopy(){
721
                $user = AuthService::getLoggedUser();
722
                $files = $user->getTemporaryData("tmp_upload");
723
                return (count($files)?true:false);
724
        }
725

    
726

    
727
        function getPath(){
728
                return $this->repository->getOption("PATH");
729
        }
730

    
731

    
732
        function initName($dir)
733
        {
734
                $racine = $this->getPath();
735
                $mess = ConfService::getMessages();
736
                if(!isset($dir) || $dir=="" || $dir == "/")
737
                {
738
                        $nom_rep=$racine;
739
                }
740
                else
741
                {
742
                        $nom_rep=$this->secureFtpPath($racine."/".$dir);
743
                }
744
                return $nom_rep;
745
        }
746

    
747
        function secureFtpPath($v_in) {
748

    
749
                $v_in  = htmlspecialchars($v_in);
750
                $v_out = str_replace(array("//","///","\\"),"/",$v_in);
751
                return $v_out;
752
        }
753

    
754

    
755
        function readFile($filePathOrData, $headerType="plain", $localName="", $data=false, $gzip=GZIP_DOWNLOAD)
756
        {
757

    
758
                $size = ($data ? strlen($filePathOrData) : filesize($filePathOrData));
759

    
760

    
761
                if(!$data && $size < 0){
762
                        // fix files above 2Gb
763
                        $size = sprintf("%u", $size);
764
                }
765
                if($gzip && ($size > GZIP_LIMIT || !function_exists("gzencode") || @strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE)){
766
                        $gzip = false; // disable gzip
767
                }
768
                $localName = ($localName=="" ? basename($filePathOrData) : $localName);
769
                if($headerType == "plain")
770
                {
771
                        header("Content-type:text/plain");
772
                }
773
                else if($headerType == "image")
774
                {
775
                        header("Content-Type: ".Utils::getImageMimeType(basename($filePathOrData))."; name=\"".$localName."\"");
776
                        header("Content-Length: ".$size);
777
                        header('Cache-Control: public');
778
                }
779
                else if($headerType == "mp3")
780
                {
781
                        header("Content-Type: audio/mp3; name=\"".$localName."\"");
782
                        header("Content-Length: ".$size);
783
                }
784
                else
785
                {
786
                        if(preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT']) || preg_match('/ WebKit /',$_SERVER['HTTP_USER_AGENT'])){
787
                                $localName = str_replace("+", " ", urlencode(SystemTextEncoding::toUTF8($localName)));
788
                        }
789
                        header("Content-Type: application/force-download; name=\"".$localName."\"");
790
                        header("Content-Transfer-Encoding: binary");
791
                        if($gzip){
792
                                header("Content-Encoding: gzip");
793
                                // If gzip, recompute data size!
794
                                $gzippedData = ($data?gzencode($filePathOrData,9):gzencode(file_get_contents($filePathOrData), 9));
795
                                $size = strlen($gzippedData);
796
                        }
797
                        header("Content-Length: ".$size);
798
                        header("Content-Disposition: attachment; filename=\"".$localName."\"");
799
                        header("Expires: 0");
800
                        header("Cache-Control: no-cache, must-revalidate");
801
                        header("Pragma: no-cache");
802
                        if (preg_match('/ MSIE 6/',$_SERVER['HTTP_USER_AGENT'])){
803
                                header("Cache-Control: max_age=0");
804
                                header("Pragma: public");
805
                        }
806

    
807
                        // For SSL websites there is a bug with IE see article KB 323308
808
                        // therefore we must reset the Cache-Control and Pragma Header
809
                        if (ConfService::getConf("USE_HTTPS")==1 && preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT']))
810
                        {
811
                                header("Cache-Control:");
812
                                header("Pragma:");
813
                        }
814
                        if($gzip){
815
                                print $gzippedData;
816
                                return;
817
                        }
818
                }
819
                if($data){
820
                        print($filePathOrData);
821
                }else{
822
                        readfile($filePathOrData);
823
                }
824
        }
825

    
826
        function ftpRemoveFileTmp($file)
827
        {
828
                @unlink ($file);
829

    
830
        }
831

    
832
        function listing($nom_rep, $dir_only = false)
833
        {
834
                $mess = ConfService::getMessages();
835
                $size_unit = $mess["byte_unit_symbol"];
836
                $sens = 0;
837
                $ordre = "nom";
838
                $poidstotal=0;
839
                $contents = @ftp_rawlist($this->connect, $nom_rep);
840
                if (!is_array($contents))
841
                {
842
                        // We might have timed out, so let's go passive if not done yet
843
                        global $_SESSION;
844
                        if ($_SESSION["ftpPasv"] == "true")
845
                                return array();
846
                        @ftp_pasv($this->connect, TRUE);
847
                        $_SESSION["ftpPasv"]="true";
848
                        $contents = @ftp_rawlist($this->connect, $nom_rep);
849
                        if (!is_array($contents))
850
                                return array();
851
                }
852
                foreach($contents as $entry)
853
                {
854
                        $info = array();
855
                        $vinfo = preg_split("/[\s]+/", $entry, 9);
856
                        if ($vinfo[0] !== "total")
857
                        {
858
                                $info['chmod'] = $vinfo[0];
859
                                $info['num']   = $vinfo[1];
860
                                $info['owner'] = $vinfo[2];
861
                                $info['group'] = $vinfo[3];
862
                                $info['size']  = $vinfo[4];
863
                                $info['month'] = $vinfo[5];
864
                                $info['day']   = $vinfo[6];
865
                                $info['timeOrYear']  = $vinfo[7];
866
                                $info['name']  = $vinfo[8];
867
                        }
868
                        $file  = trim($info['name']);
869
                        $filetaille= trim($info['size']);
870
                        if(strstr($info["timeOrYear"], ":")){
871
                                $info["time"] = $info["timeOrYear"];
872
                                $info["year"] = date("Y");
873
                        }else{
874
                                $info["time"] = '09:00';
875
                                $info["year"] = $info["timeOrYear"];
876
                        }
877
                        $filedate  = trim($info['day'])." ".trim($info['month'])." ".trim($info['year'])." ".trim($info['time']);
878
                        $filedate  = strtotime($filedate);
879

    
880
                        $fileperms = trim($info['chmod']);
881
                        $info['chmod1'] = $this->convertingChmod(trim($info['chmod']));
882
                        $isDir =false;
883
                        $info['modifTime']=$filedate;
884
                        $info['isDir']=false;
885
                        //gestion des Simbolic Link pour la navigation
886
                        if (strpos($fileperms,"d")!==FALSE || strpos($fileperms,"l")!==FALSE)
887
                        {
888
                                if(strpos($fileperms,"l")!==FALSE)
889
                                {
890
                                        $test=explode(" ->", $file);
891
                                        $file=$test[0];
892
                                        $info['name']=$file;
893
                                }
894
                                $isDir=true;
895
                                $info['isDir']=true;
896
                        }
897

    
898
                        if($file!="." && $file!=".." )
899
                        {
900
                                if(RecycleBinManager::recycleEnabled()
901
                                        && $nom_rep == $this->repository->getOption("PATH")."/".$this->repository->getOption("RECYCLE_BIN")
902
                                                && $file == RecycleBinManager::getCacheFileName()){
903
                                                        continue;
904
                                                }
905

    
906
                                $poidstotal+=$filetaille;
907
                                if($isDir)
908
                                {
909
                                        if(RecycleBinManager::recycleEnabled()
910
                                                && $this->repository->getOption("PATH")."/".$this->repository->getOption("RECYCLE_BIN") == "$nom_rep/$file")
911
                                        {
912
                                                continue;
913
                                        }
914
                                        $liste_rep[$file]=$info;
915
                                        $liste_rep[$file]['icon']=Utils::mimetype("$nom_rep/$file","image", $isDir);
916
                                        $liste_rep[$file]['type']=Utils::mimetype("$nom_rep/$file","type", $isDir);
917
                                }
918
                                else
919
                                {
920
                                        if(!$dir_only)
921
                                        {
922
                                                $liste_fic[$file]=$info;
923
                                                $liste_fic[$file]['icon']=Utils::mimetype("$nom_rep/$file","image", $isDir);
924
                                                $liste_fic[$file]['type']=Utils::mimetype("$nom_rep/$file","type", $isDir);
925
                                        }
926
                                        else if(preg_match("/\.zip$/",$file) && ConfService::zipEnabled()){
927
                                                if(!isSet($liste_zip)) $liste_zip = array();
928
                                                $liste_zip[$file] = $file;
929
                                        }
930
                                }
931
                        }
932
                }
933
                if(isset($liste_fic) && is_array($liste_fic))
934
                {
935
                        if($ordre=="nom") {if($sens==0){ksort($liste_fic);}else{krsort($liste_fic);}}
936
                        else if($ordre=="mod") {if($sens==0){arsort($liste_fic);}else{asort($liste_fic);}}
937
                        else if($ordre=="taille"||$ordre=="type") {if($sens==0){asort($liste_fic);}else{arsort($liste_fic);}}
938
                        else {if($sens==0){ksort($liste_fic);}else{krsort($liste_fic);}}
939

    
940
                        if($ordre != "nom"){
941
                                foreach ($liste_fic as $index=>$value){
942
                                        $liste_fic[$index] = Utils::mimetype($index, "image", false);
943
                                }
944
                        }
945
                }
946
                else
947
                {
948
                        $liste_fic = array();
949
                }
950
                if(isset($liste_rep) && is_array($liste_rep))
951
                {
952
                        if($ordre=="mod") {if($sens==0){arsort($liste_rep);}else{asort($liste_rep);}}
953
                        else {if($sens==0){ksort($liste_rep);}else{krsort($liste_rep);}
954
                        }
955
                        if($ordre != "nom"){
956
                                foreach ($liste_rep as $index=>$value){
957
                                        $liste_rep[$index] = $index;
958
                                }
959
                        }
960
                }
961
                else ($liste_rep = array());
962

    
963
                $liste = Utils::mergeArrays($liste_rep,$liste_fic);
964
                if(isSet($liste_zip)){
965
                        $liste = Utils::mergeArrays($liste,$liste_zip);
966
                }
967
                if ($poidstotal >= 1073741824) {$poidstotal = round($poidstotal / 1073741824 * 100) / 100 . " G".$size_unit;}
968
                elseif ($poidstotal >= 1048576) {$poidstotal = round($poidstotal / 1048576 * 100) / 100 . " M".$size_unit;}
969
                elseif ($poidstotal >= 1024) {$poidstotal = round($poidstotal / 1024 * 100) / 100 . " K".$size_unit;}
970
                else {$poidstotal = $poidstotal . " ".$size_unit;}
971
                return array($liste,$poidstotal);
972
        }
973

    
974

    
975
        function renameAction($actionName, $httpVars)
976
        {
977
                $filePath = SystemTextEncoding::fromUTF8($httpVars["file"]);
978
                $newFilename = SystemTextEncoding::fromUTF8($httpVars["filename_new"]);
979
                return $this->rename($filePath, $newFilename);
980
        }
981

    
982
        function rename($filePath, $filename_new)
983
        {
984
                $nom_fic=basename($filePath);
985
                $pathFile= dirname($filePath);
986
                $mess = ConfService::getMessages();
987
                $filename_new=Utils::processFileName($filename_new);
988
                $filename_new = $this->secureFtpPath($this->getPath()."/".$pathFile."///".$filename_new);
989
                $nom_fic = $this->secureFtpPath($this->getPath()."/".$pathFile."///".$nom_fic);
990
                ftp_rename($this->connect,$nom_fic, $filename_new);
991
                return null;
992
        }
993

    
994
        function mkDir($crtDir, $newDirName)
995
        {
996
                $mess = ConfService::getMessages();
997
                if($newDirName=="")
998
                {
999
                        return "$mess[37]";
1000
                }
1001
                if(@ftp_mkdir($this->connect,$this->getPath()."/$crtDir/$newDirName")===false)
1002
                {
1003
                        return $mess[38]." $crtDir ".$mess[99];
1004
                }
1005
                return null;
1006
        }
1007

    
1008
        function createEmptyFile($crtDir, $newFileName)
1009
        {
1010
                $mess = ConfService::getMessages();
1011
                if($newFileName=="")
1012
                {
1013
                        return "$mess[37]";
1014
                }
1015
                $fp=fopen("files/".$newFileName,"x+");
1016
                if($fp)
1017
                {
1018
                        if(preg_match("/\.html$/",$newFileName)||preg_match("/\.htm$/",$newFileName))
1019
                        {
1020
                                fputs($fp,"<html>\n<head>\n<title>New Document - Created By AjaXplorer</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n</head>\n<body bgcolor=\"#FFFFFF\" text=\"#000000\">\n\n</body>\n</html>\n");
1021
                        }
1022
                        fclose($fp);
1023
                        @ftp_put($this->connect,$this->getPath()."/$crtDir/$newFileName","files/".$newFileName, FTP_BINARY);
1024
                        @unlink(utf8_decode("files/".$newFileName));
1025
                        return null;
1026
                }
1027
                else
1028
                {
1029
                        return "$mess[102] $crtDir/$newFileName (".$fp.")";
1030
                }
1031
        }
1032

    
1033
        function copyOrMove($destDir, $selectedFiles, &$error, &$success, $move = false)
1034
        {
1035
                $mess = ConfService::getMessages();
1036

    
1037
                foreach ($selectedFiles as $selectedFile)
1038
                {
1039
                        if($move){
1040
                                $this->ftpMove($destDir, $selectedFile, $error, $success);
1041
                        }else{
1042
                                $this->ftpCopy($destDir, $selectedFile, $error, $success);
1043
                        }
1044
                }
1045
        }
1046

    
1047
        function ftpMove($destDir, $srcFile, &$error, &$success){
1048
                $mess = ConfService::getMessages();
1049
                $destFile = $this->secureFtpPath($this->repository->getOption("PATH").$destDir."/".basename($srcFile));
1050
                $realSrcFile = $this->secureFtpPath($this->repository->getOption("PATH")."/$srcFile");
1051
                $recycle = $this->repository->getOption("RECYCLE_BIN");
1052

    
1053
                $test = @ftp_rename($this->connect, $realSrcFile, $destFile);
1054
                $messagePart = $mess[74]." ".SystemTextEncoding::toUTF8($destDir);
1055
                if($destDir == "/".$recycle)
1056
                {
1057
                        RecycleBinManager::fileToRecycle($srcFile);
1058
                        $messagePart = $mess[123]." ".$mess[122];
1059
                }
1060
                if($test){
1061
                        $success[] = $mess[34]." ".SystemTextEncoding::toUTF8(basename($srcFile))." ".$messagePart;
1062
                        if(RecycleBinManager::currentLocationIsRecycle(dirname($srcFile))){
1063
                                RecycleBinManager::deleteFromRecycle(basename($srcFile));
1064
                        }
1065
                }else{
1066
                        $error[] = $mess[114];
1067
                }
1068

    
1069
        }
1070

    
1071
        function ftpCopy($destDir, $srcFile, &$error, &$success){
1072
                $mess = ConfService::getMessages();
1073
                $this->repository->detectStreamWrapper(true);
1074
                $destFile = $this->repository->getOption("PATH").$destDir."/".basename($srcFile);
1075
                $realSrcFile = $this->repository->getOption("PATH")."/$srcFile";
1076
                $tmpFile = tmpfile();
1077
                if(ftp_fget($this->connect, $tmpFile, $realSrcFile, FTP_BINARY)){
1078
                        rewind($tmpFile);
1079
                        $res = ftp_fput($this->connect, $destFile, $tmpFile, FTP_BINARY);
1080
                }
1081
                $messagePart = $mess[73]." ".SystemTextEncoding::toUTF8($destDir);
1082
                if($res){
1083
                        $success[] = $mess[34]." ".SystemTextEncoding::toUTF8(basename($srcFile))." ".$messagePart;
1084
                }else{
1085
                        $error[] = $mess[114];
1086
                }
1087
        }
1088

    
1089

    
1090
        function copyOrMoveFile($destDir, $srcFile, &$error, &$success, $move = false)
1091
        {
1092
                $mess = ConfService::getMessages();
1093
                $destFile = $this->repository->getOption("PATH").$destDir."/".basename($srcFile);
1094
                $realSrcFile = $this->repository->getOption("PATH")."/$srcFile";
1095
                $recycle = $this->repository->getOption("RECYCLE_BIN");
1096
                if(!file_exists($realSrcFile))
1097
                {
1098
                        $error[] = $mess[100].$srcFile;
1099
                        return ;
1100
                }
1101
                if($realSrcFile==$destFile)
1102
                {
1103
                        $error[] = $mess[101];
1104
                        return ;
1105
                }
1106
                if(is_dir($realSrcFile))
1107
                {
1108
                        $errors = array();
1109
                        $succFiles = array();
1110
                        if($move){
1111
                                if(is_file($destFile)) unlink($destFile);
1112
                                $res = rename($realSrcFile, $destFile);
1113
                        }else{
1114
                                $dirRes = $this->dircopy($realSrcFile, $destFile, $errors, $succFiles);
1115
                        }
1116
                        if(count($errors) || (isSet($res) && $res!==true))
1117
                        {
1118
                                $error[] = $mess[114];
1119
                                return ;
1120
                        }
1121
                }
1122
                else
1123
                {
1124
                        if($move){
1125
                                if(is_file($destFile)) unlink($destFile);
1126
                                $res = rename($realSrcFile, $destFile);
1127
                        }else{
1128
                                $res = copy($realSrcFile,$destFile);
1129
                        }
1130
                        if($res != 1)
1131
                        {
1132
                                $error[] = $mess[114];
1133
                                return ;
1134
                        }
1135
                }
1136
                if($move)
1137
                {
1138
                        $messagePart = $mess[74]." ".SystemTextEncoding::toUTF8($destDir);
1139
                        if($destDir == "/".$recycle)
1140
                        {
1141
                                RecycleBinManager::fileToRecycle($srcFile);
1142
                                $messagePart = $mess[123]." ".$mess[122];
1143
                        }
1144
                        if(isset($dirRes))
1145
                        {
1146
                                $success[] = $mess[117]." ".SystemTextEncoding::toUTF8(basename($srcFile))." ".$messagePart." (".SystemTextEncoding::toUTF8($dirRes)." ".$mess[116].") ";
1147
                        }
1148
                        else
1149
                        {
1150
                                $success[] = $mess[34]." ".SystemTextEncoding::toUTF8(basename($srcFile))." ".$messagePart;
1151
                        }
1152
                }
1153
                else
1154
                {
1155
                        if($destDir == "/".$this->repository->getOption("RECYCLE_BIN"))
1156
                        {
1157
                                RecycleBinManager::fileToRecycle($srcFile);
1158
                        }
1159
                        if(isSet($dirRes))
1160
                        {
1161
                                $success[] = $mess[117]." ".SystemTextEncoding::toUTF8(basename($srcFile))." ".$mess[73]." ".SystemTextEncoding::toUTF8($destDir)." (".SystemTextEncoding::toUTF8($dirRes)." ".$mess[116].")";
1162
                        }
1163
                        else
1164
                        {
1165
                                $success[] = $mess[34]." ".SystemTextEncoding::toUTF8(basename($srcFile))." ".$mess[73]." ".SystemTextEncoding::toUTF8($destDir);
1166
                        }
1167
                }
1168

    
1169
        }
1170

    
1171

    
1172

    
1173
        function delete($selectedFiles, &$logMessages,$dir="")
1174
        {
1175
                $mess = ConfService::getMessages();
1176
                $result = $this->listing($this->secureFtpPath($this->getPath().$dir));
1177
                foreach ($selectedFiles as $selectedFile)
1178
                {
1179
                        $data ="";
1180
                        $selectedFile =  basename($selectedFile);
1181
                        if($selectedFile == "" || $selectedFile == DIRECTORY_SEPARATOR)
1182
                        {
1183
                                return $mess[120];
1184
                        }
1185

    
1186
                        if (array_key_exists($selectedFile,$result[0]))
1187
                        {
1188
                                $data = $result[0][$selectedFile];
1189

    
1190
                                $this->deldir($data['name'],$dir);
1191
                                if ($data['isDir'])
1192
                                {
1193
                                        $logMessages[]="$mess[38] ".SystemTextEncoding::toUTF8($selectedFile)." $mess[44].";
1194
                                }
1195
                                else
1196
                                {
1197
                                        $logMessages[]="$mess[34] ".SystemTextEncoding::toUTF8($selectedFile)." $mess[44].";
1198
                                }
1199
                                if(RecycleBinManager::currentLocationIsRecycle($dir)){
1200
                                        RecycleBinManager::deleteFromRecycle($selectedFile);
1201
                                }
1202
                        }
1203
                        else
1204
                        {
1205
                                $logMessages[]=$mess[100]." ".SystemTextEncoding::toUTF8($selectedFile);
1206
                                continue;
1207
                        }
1208
                }
1209
                return null;
1210
        }
1211

    
1212

    
1213
        function deldir($dir,$currentDir)
1214
        {
1215
                if (($contents = ftp_rawlist($this->connect,$this->secureFtpPath($this->getPath().$currentDir."/".$dir)))!==FALSE)
1216
                {
1217
                        foreach($contents as $file)
1218
                        {
1219
                                if (preg_match("/^[.]{2}$|^[.]{1}$/", $file)==0)
1220
                                {
1221
                                        $info = array();
1222
                                        $vinfo = preg_split("/[\s]+/", $file, 9);
1223
                                        if ($vinfo[0] !== "total")
1224
                                        {
1225
                                                $fileperms = $vinfo[0];
1226
                                                $filename  = $vinfo[8];
1227
                                        }
1228
                                        if (strpos($fileperms,"d")!==FALSE)
1229
                                        {
1230
                                                $this->deldir($dir."/".$filename,$currentDir);
1231
                                        }
1232
                                        else
1233
                                        {
1234
                                                if (strpos($filename, $this->getPath())!== false)
1235
                                                {
1236
                                                        @ftp_delete($this->connect,$this->secureFtpPath($filename));
1237
                                                }
1238
                                                else
1239
                                                {
1240
                                                        @ftp_delete($this->connect,$this->secureFtpPath($this->getPath().$currentDir."/".$dir."/".$filename));
1241
                                                }
1242
                                        }
1243
                                }
1244
                        }
1245
                        @ftp_rmdir($this->connect,$this->secureFtpPath($this->getPath().$currentDir."/".$dir."/"));
1246
                }
1247
        }
1248

    
1249
        // Distant loading
1250
        function ftp_get_contents($file)
1251
        {
1252
                if (is_array($file))
1253
                {
1254
                        $name_file= basename($this->secureFtpPath($file->files[0]));
1255
                        ftp_get($this->connect,"files/".$name_file,$this->secureFtpPath($this->getPath().$file->files[0]), FTP_BINARY);
1256
                }
1257
                else
1258
                {
1259
                        $name_file= basename($this->secureFtpPath($file));
1260
                        ftp_get($this->connect,"files/".$name_file,$this->secureFtpPath($this->getPath().$file), FTP_BINARY);
1261
                }
1262
        }
1263

    
1264
        // Instantaneous ftp loading and transferring
1265
        function sendRemoteFile($file, $forceDownload)
1266
        {
1267
                if (is_array($file)) $file = $file[0];
1268
                $localName = basename($file);
1269
                // Need to send the headers too
1270
                header("Content-type:text/plain");
1271
                if(preg_match("/\.(jpg|jpeg|png|bmp|mng|gif)$/i", $file) !== FALSE)
1272
                {
1273
                        header("Content-Type: ".Utils::getImageMimeType($localName)."; name=\"".$localName."\"");
1274
                        header('Cache-Control: public');
1275
                }
1276
                else if(substr($file, -4) ==  ".mp3")
1277
                {
1278
                        header("Content-Type: audio/mp3; name=\"".$localName."\"");
1279
                }
1280
                if ($forceDownload)
1281
                {
1282
                        if(preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT']) || preg_match('/ WebKit /',$_SERVER['HTTP_USER_AGENT'])){
1283
                                $localName = str_replace("+", " ", urlencode(SystemTextEncoding::toUTF8($localName)));
1284
                        }
1285
                        header("Content-Type: application/force-download; name=\"".$localName."\"");
1286
                        header("Content-Transfer-Encoding: binary");
1287
                        header("Content-Disposition: attachment; filename=\"".$localName."\"");
1288
                        header("Expires: 0");
1289
                        header("Cache-Control: no-cache, must-revalidate");
1290
                        header("Pragma: no-cache");
1291
                        if (preg_match('/ MSIE 6/',$_SERVER['HTTP_USER_AGENT'])){
1292
                                header("Cache-Control: max_age=0");
1293
                                header("Pragma: public");
1294
                        }
1295

    
1296
                        // For SSL websites there is a bug with IE see article KB 323308
1297
                        // therefore we must reset the Cache-Control and Pragma Header
1298
                        if (ConfService::getConf("USE_HTTPS")==1 && preg_match('/ MSIE /',$_SERVER['HTTP_USER_AGENT']))
1299
                        {
1300
                                header("Cache-Control:");
1301
                                header("Pragma:");
1302
                        }
1303
                }
1304

    
1305
                $handle = fopen('php://output', 'a');
1306
                ftp_fget($this->connect, $handle, $this->secureFtpPath($this->getPath().$file), FTP_BINARY, 0);
1307
                fclose($handle);
1308
        }
1309

    
1310

    
1311
        function getimagesize($image){
1312
                $name_file= basename($this->secureFtpPath($image));
1313
                @ftp_get($this->connect,"files/".$name_file,$image, FTP_BINARY);
1314
                $result = @getimagesize("files/".$name_file);
1315
                return $result;
1316
        }
1317

    
1318
        function convertingChmod($permissions)
1319
        {
1320
                $mode = 0;
1321

    
1322
                if ($permissions[1] == 'r') $mode += 0400;
1323
                if ($permissions[2] == 'w') $mode += 0200;
1324
                if ($permissions[3] == 'x') $mode += 0100;
1325
                else if ($permissions[3] == 's') $mode += 04100;
1326
                else if ($permissions[3] == 'S') $mode += 04000;
1327

    
1328
                if ($permissions[4] == 'r') $mode += 040;
1329
                if ($permissions[5] == 'w') $mode += 020;
1330
                if ($permissions[6] == 'x') $mode += 010;
1331
                else if ($permissions[6] == 's') $mode += 02010;
1332
                else if ($permissions[6] == 'S') $mode += 02000;
1333

    
1334
                if ($permissions[7] == 'r') $mode += 04;
1335
                if ($permissions[8] == 'w') $mode += 02;
1336
                if ($permissions[9] == 'x') $mode += 01;
1337
                else if ($permissions[9] == 't') $mode += 01001;
1338
                else if ($permissions[9] == 'T') $mode += 01000;
1339
                $mode = (string)("0".$mode);
1340
                return  $mode;
1341
        }
1342

    
1343
        /** The publiclet URL making */
1344
        function makePubliclet($filePath, $password, $expire)
1345
        {
1346
                $data = array("DRIVER"=>"ftpCas",
1347
                        "OPTIONS"=>array('user'=>$this->getUserName($this->repository), 'password'=>$this->getPassword($this->repository)), "FILE_PATH"=>$filePath, "ACTION"=>"download", "EXPIRE_TIME"=>$expire ? (time() + $expire * 86400) : 0, "PASSWORD"=>$password);
1348
                return $this->writePubliclet($data);
1349
        }
1350
        function createRepository(){
1351
                // construit le path vers le ftp de l'utilisateur
1352
                return "/home/". $this->user[0] . '/' . $this->user .'/.ftp/';
1353
        }
1354

    
1355

    
1356

    
1357
}
1358

    
1359
?>