source: branches/version-2_12-dev/data/class/helper/SC_Helper_FileManager.php @ 21684

Revision 21684, 15.3 KB checked in by Seasoft, 12 years ago (diff)

#1613 (typo修正・ソース整形・ソースコメントの改善)

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
  • Property svn:mime-type set to text/x-httpd-php; charset=UTF-8
Line 
1<?php
2/*
3 * This file is part of EC-CUBE
4 *
5 * Copyright(c) 2000-2011 LOCKON CO.,LTD. All Rights Reserved.
6 *
7 * http://www.lockon.co.jp/
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 */
23
24/**
25 * ファイル管理 のヘルパークラス.
26 *
27 * @package Page
28 * @author LOCKON CO.,LTD.
29 * @version $Id$
30 */
31class SC_Helper_FileManager {
32
33    /**
34     * 指定パス配下のディレクトリ取得する.
35     *
36     * @param string $dir 取得するディレクトリパス
37     * @return void
38     */
39    function sfGetFileList($dir) {
40        $arrFileList = array();
41        $arrDirList = array();
42
43        if (is_dir($dir)) {
44            if ($dh = opendir($dir)) {
45                $cnt = 0;
46                // 行末の/を取り除く
47                while (($file = readdir($dh)) !== false) $arrDir[] = $file;
48                $dir = ereg_replace("/$", '', $dir);
49                // アルファベットと数字でソート
50                natcasesort($arrDir);
51                foreach ($arrDir as $file) {
52                    // ./ と ../を除くファイルのみを取得
53                    if ($file != '.' && $file != '..') {
54
55                        $path = $dir.'/'.$file;
56                        // SELECT内の見た目を整えるため指定文字数で切る
57                        $file_name = SC_Utils_Ex::sfCutString($file, FILE_NAME_LEN);
58                        $file_size = SC_Utils_Ex::sfCutString($this->sfGetDirSize($path), FILE_NAME_LEN);
59                        $file_time = date('Y/m/d', filemtime($path));
60
61                        // ディレクトリとファイルで格納配列を変える
62                        if (is_dir($path)) {
63                            $arrDirList[$cnt]['file_name'] = $file;
64                            $arrDirList[$cnt]['file_path'] = $path;
65                            $arrDirList[$cnt]['file_size'] = $file_size;
66                            $arrDirList[$cnt]['file_time'] = $file_time;
67                            $arrDirList[$cnt]['is_dir'] = true;
68                        } else {
69                            $arrFileList[$cnt]['file_name'] = $file;
70                            $arrFileList[$cnt]['file_path'] = $path;
71                            $arrFileList[$cnt]['file_size'] = $file_size;
72                            $arrFileList[$cnt]['file_time'] = $file_time;
73                            $arrFileList[$cnt]['is_dir'] = false;
74                        }
75                        $cnt++;
76                    }
77                }
78                closedir($dh);
79            }
80        }
81
82        // フォルダを先頭にしてマージ
83        return array_merge($arrDirList, $arrFileList);
84    }
85
86    /**
87     * 指定したディレクトリのバイト数を取得する.
88     *
89     * @param string $dir ディレクトリ
90     * @return void
91     */
92    function sfGetDirSize($dir) {
93        $bytes = 0;
94        if (file_exists($dir)) {
95            // ディレクトリの場合下層ファイルの総量を取得
96            if (is_dir($dir)) {
97                $handle = opendir($dir);
98                while ($file = readdir($handle)) {
99                    // 行末の/を取り除く
100                    $dir = ereg_replace("/$", '', $dir);
101                    $path = $dir.'/'.$file;
102                    if ($file != '..' && $file != '.' && !is_dir($path)) {
103                        $bytes += filesize($path);
104                    } else if (is_dir($path) && $file != '..' && $file != '.') {
105                        // 下層ファイルのバイト数を取得する為、再帰的に呼び出す。
106                        $bytes += $this->sfGetDirSize($path);
107                    }
108                }
109            } else {
110                // ファイルの場合
111                $bytes = filesize($dir);
112            }
113        }
114        // ディレクトリ(ファイル)が存在しない場合は0byteを返す
115        if ($bytes == '') {
116            $bytes = 0;
117        }
118
119        return $bytes;
120    }
121
122    /**
123     * 指定したディレクトリ又はファイルを削除する.
124     *
125     * @param string $dir 削除するディレクトリ又はファイル
126     * @return void
127     */
128    function sfDeleteDir($dir) {
129        $arrResult = array();
130        if (file_exists($dir)) {
131            // ディレクトリかチェック
132            if (is_dir($dir)) {
133                if ($handle = opendir("$dir")) {
134                    $cnt = 0;
135                    while (false !== ($item = readdir($handle))) {
136                        if ($item != '.' && $item != '..') {
137                            if (is_dir("$dir/$item")) {
138                                $this->sfDeleteDir("$dir/$item");
139                            } else {
140                                $arrResult[$cnt]['result'] = @unlink("$dir/$item");
141                                $arrResult[$cnt]['file_name'] = "$dir/$item";
142                            }
143                        }
144                        $cnt++;
145                    }
146                }
147                closedir($handle);
148                $arrResult[$cnt]['result'] = @rmdir($dir);
149                $arrResult[$cnt]['file_name'] = "$dir/$item";
150            } else {
151                // ファイル削除
152                $arrResult[0]['result'] = @unlink("$dir");
153                $arrResult[0]['file_name'] = "$dir";
154            }
155        }
156
157        return $arrResult;
158    }
159
160    /**
161     * ツリー生成用配列取得(javascriptに渡す用).
162     *
163     * @param string $dir ディレクトリ
164     * @param string $tree_status 現在のツリーの状態開いているフォルダのパスを
165     *                            | 区切りで格納
166     * @return array ツリー生成用の配列
167     */
168    function sfGetFileTree($dir, $tree_status) {
169
170        $cnt = 0;
171        $arrTree = array();
172        $default_rank = count(explode('/', $dir));
173
174        // 文末の/を取り除く
175        $dir = ereg_replace("/$", '', $dir);
176        // 最上位層を格納(user_data/)
177        if ($this->sfDirChildExists($dir)) {
178            $arrTree[$cnt]['type'] = '_parent';
179        } else {
180            $arrTree[$cnt]['type'] = '_child';
181        }
182        $arrTree[$cnt]['path'] = $dir;
183        $arrTree[$cnt]['rank'] = 0;
184        $arrTree[$cnt]['count'] = $cnt;
185        // 初期表示はオープン
186        if ($_POST['mode'] != '') {
187            $arrTree[$cnt]['open'] = $this->lfIsFileOpen($dir, $tree_status);
188        } else {
189            $arrTree[$cnt]['open'] = true;
190        }
191        $cnt++;
192
193        $this->sfGetFileTreeSub($dir, $default_rank, $cnt, $arrTree, $tree_status);
194
195        return $arrTree;
196    }
197
198    /**
199     * ツリー生成用配列取得(javascriptに渡す用).
200     *
201     * @param string $dir ディレクトリ
202     * @param string $default_rank デフォルトの階層
203     *                             (/区切りで 0,1,2・・・とカウント)
204     * @param integer $cnt 連番
205     * @param string $tree_status 現在のツリーの状態開いているフォルダのパスが
206     *                            | 区切りで格納
207     * @return array ツリー生成用の配列
208     */
209    function sfGetFileTreeSub($dir, $default_rank, &$cnt, &$arrTree, $tree_status) {
210
211        if (file_exists($dir)) {
212            if ($handle = opendir("$dir")) {
213                while (false !== ($item = readdir($handle))) $arrDir[] = $item;
214                // アルファベットと数字でソート
215                natcasesort($arrDir);
216                foreach ($arrDir as $item) {
217                    if ($item != '.' && $item != '..') {
218                        // 文末の/を取り除く
219                        $dir = ereg_replace("/$", '', $dir);
220                        $path = $dir.'/'.$item;
221                        // ディレクトリのみ取得
222                        if (is_dir($path)) {
223                            $arrTree[$cnt]['path'] = $path;
224                            if ($this->sfDirChildExists($path)) {
225                                $arrTree[$cnt]['type'] = '_parent';
226                            } else {
227                                $arrTree[$cnt]['type'] = '_child';
228                            }
229
230                            // 階層を割り出す
231                            $arrCnt = explode('/', $path);
232                            $rank = count($arrCnt);
233                            $arrTree[$cnt]['rank'] = $rank - $default_rank + 1;
234                            $arrTree[$cnt]['count'] = $cnt;
235                            // フォルダが開いているか
236                            $arrTree[$cnt]['open'] = $this->lfIsFileOpen($path, $tree_status);
237                            $cnt++;
238                            // 下層ディレクトリ取得の為、再帰的に呼び出す
239                            $this->sfGetFileTreeSub($path, $default_rank, $cnt, $arrTree, $tree_status);
240                        }
241                    }
242                }
243            }
244            closedir($handle);
245        }
246    }
247
248    /**
249     * 指定したディレクトリ配下にファイルがあるかチェックする.
250     *
251     * @param string ディレクトリ
252     * @return bool ファイルが存在する場合 true
253     */
254    function sfDirChildExists($dir) {
255        if (file_exists($dir)) {
256            if (is_dir($dir)) {
257                $handle = opendir($dir);
258                while ($file = readdir($handle)) {
259                    // 行末の/を取り除く
260                    $dir = ereg_replace("/$", '', $dir);
261                    $path = $dir.'/'.$file;
262                    if ($file != '..' && $file != '.' && is_dir($path)) {
263                        return true;
264                    }
265                }
266            }
267        }
268
269        return false;
270    }
271
272    /**
273     * 指定したファイルが前回開かれた状態にあったかチェックする.
274     *
275     * @param string $dir ディレクトリ
276     * @param string $tree_status 現在のツリーの状態開いているフォルダのパスが
277     *                            | 区切りで格納
278     * @return bool 前回開かれた状態の場合 true
279     */
280    function lfIsFileOpen($dir, $tree_status) {
281        $arrTreeStatus = explode('|', $tree_status);
282        if (in_array($dir, $arrTreeStatus)) {
283            return true;
284        }
285
286        return false;
287    }
288
289    /**
290     * ファイルのダウンロードを行う.
291     *
292     * @param string $file ファイルパス
293     * @return void
294     */
295    function sfDownloadFile($file) {
296        // ファイルの場合はダウンロードさせる
297        Header('Content-disposition: attachment; filename='.basename($file));
298        Header('Content-type: application/octet-stream; name='.basename($file));
299        Header('Cache-Control: ');
300        Header('Pragma: ');
301        echo ($this->sfReadFile($file));
302    }
303
304    /**
305     * ファイル作成を行う.
306     *
307     * @param string $file ファイルパス
308     * @param integer $mode パーミッション
309     * @return bool ファイル作成に成功した場合 true
310     */
311    function sfCreateFile($file, $mode = '') {
312        // 行末の/を取り除く
313        if ($mode != '') {
314            $ret = @mkdir($file, $mode);
315        } else {
316            $ret = @mkdir($file);
317        }
318
319        return $ret;
320    }
321
322    /**
323     * ファイル読込を行う.
324     *
325     * @param string ファイルパス
326     * @return string ファイルの内容
327     */
328    function sfReadFile($filename) {
329        $str = '';
330        // バイナリモードでオープン
331        $fp = @fopen($filename, 'rb');
332        //ファイル内容を全て変数に読み込む
333        if ($fp) {
334            $str = @fread($fp, filesize($filename)+1);
335        }
336        @fclose($fp);
337
338        return $str;
339    }
340
341    /**
342     * ファイル書込を行う.
343     *
344     * @param string $filename ファイルパス
345     * @param string $value 書き込み内容
346     * @return boolean ファイルの書き込みに成功した場合 true
347     */
348    function sfWriteFile($filename, $value) {
349        if (!is_dir(dirname($filename))) {
350            SC_Utils_Ex::recursiveMkdir(dirname($filename), 0777);
351        }
352        $fp = fopen($filename,'w');
353        if ($fp === false) {
354            return false;
355        }
356        if (fwrite($fp, $value) === false) {
357            return false;
358        }
359        return fclose($fp);;
360    }
361
362    /**
363     * ユーザが作成したファイルをアーカイブしダウンロードさせる
364     * TODO 要リファクタリング
365     * @param string $dir アーカイブを行なうディレクトリ
366     * @param string $template_code テンプレートコード
367     * @return boolean 成功した場合 true; 失敗した場合 false
368     */
369    function downloadArchiveFiles($dir, $template_code) {
370        // ダウンロードされるファイル名
371        $dlFileName = 'tpl_package_' . $template_code . '_' . date('YmdHis') . '.tar.gz';
372
373        $debug_message = $dir . ' から ' . $dlFileName . " を作成します...\n";
374        // ファイル一覧取得
375        $arrFileHash = SC_Utils_Ex::sfGetFileList($dir);
376        foreach ($arrFileHash as $val) {
377            $arrFileList[] = $val['file_name'];
378            $debug_message.= '圧縮:'.$val['file_name']."\n";
379        }
380        GC_Utils_Ex::gfPrintLog($debug_message);
381
382        // ディレクトリを移動
383        chdir($dir);
384        // 圧縮をおこなう
385        $tar = new Archive_Tar($dlFileName, true);
386        if ($tar->create($arrFileList)) {
387            // ダウンロード用HTTPヘッダ出力
388            header("Content-disposition: attachment; filename=${dlFileName}");
389            header("Content-type: application/octet-stream; name=${dlFileName}");
390            header('Cache-Control: ');
391            header('Pragma: ');
392            readfile($dlFileName);
393            unlink($dir . '/' . $dlFileName);
394            return true;
395        } else {
396            return false;
397        }
398    }
399
400    /**
401     * tarアーカイブを解凍する.
402     *
403     * @param string $path アーカイブパス
404     * @return boolean Archive_Tar::extractModify()のエラー
405     */
406    function unpackFile($path) {
407        // 圧縮フラグTRUEはgzip解凍をおこなう
408        $tar = new Archive_Tar($path, true);
409
410        $dir = dirname($path);
411        $file_name = basename($path);
412
413        // 拡張子を切り取る
414        $unpacking_name = preg_replace("/(\.tar|\.tar\.gz)$/", '', $file_name);
415
416        // 指定されたフォルダ内に解凍する
417        $result = $tar->extractModify($dir. '/', $unpacking_name);
418        GC_Utils_Ex::gfPrintLog('解凍:' . $dir.'/'.$file_name.'->'.$dir.'/'.$unpacking_name);
419
420        // フォルダ削除
421        SC_Utils_Ex::sfDelFile($dir . '/' . $unpacking_name);
422        // 圧縮ファイル削除
423        unlink($path);
424        return $result;
425    }
426}
Note: See TracBrowser for help on using the repository browser.