source: branches/version-2_13-dev/data/class/helper/SC_Helper_FileManager.php @ 23389

Revision 23389, 15.9 KB checked in by shutta, 10 years ago (diff)

#2448 (typo修正・ソース整形・ソースコメントの改善 for 2.13.2)
コーディング規約に則した修正。

  • "." 演算子の前後にスペースを付加。
  • 1行の長さが80文字以下になるよう調整。
  • 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-2013 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    public function sfGetFileList($dir)
40    {
41        $arrFileList = array();
42        $arrDirList = array();
43
44        if (is_dir($dir)) {
45            $dh = opendir($dir);
46            if ($dh) {
47                $cnt = 0;
48                $arrDir = array();
49                // 行末の/を取り除く
50                while (($file = readdir($dh)) !== false) $arrDir[] = $file;
51                $dir = rtrim($dir, '/');
52                // アルファベットと数字でソート
53                natcasesort($arrDir);
54                foreach ($arrDir as $file) {
55                    // ./ と ../を除くファイルのみを取得
56                    if ($file != '.' && $file != '..') {
57                        $path = $dir.'/'.$file;
58                        // SELECT内の見た目を整えるため指定文字数で切る
59                        $file_size = SC_Utils_Ex::sfCutString(SC_Helper_FileManager::sfGetDirSize($path), FILE_NAME_LEN);
60                        $file_time = date('Y/m/d', filemtime($path));
61
62                        // ディレクトリとファイルで格納配列を変える
63                        if (is_dir($path)) {
64                            $arrDirList[$cnt]['file_name'] = $file;
65                            $arrDirList[$cnt]['file_path'] = $path;
66                            $arrDirList[$cnt]['file_size'] = $file_size;
67                            $arrDirList[$cnt]['file_time'] = $file_time;
68                            $arrDirList[$cnt]['is_dir'] = true;
69                        } else {
70                            $arrFileList[$cnt]['file_name'] = $file;
71                            $arrFileList[$cnt]['file_path'] = $path;
72                            $arrFileList[$cnt]['file_size'] = $file_size;
73                            $arrFileList[$cnt]['file_time'] = $file_time;
74                            $arrFileList[$cnt]['is_dir'] = false;
75                        }
76                        $cnt++;
77                    }
78                }
79                closedir($dh);
80            }
81        }
82
83        // フォルダを先頭にしてマージ
84        return array_merge($arrDirList, $arrFileList);
85    }
86
87    /**
88     * 指定したディレクトリのバイト数を取得する.
89     *
90     * @param  string $dir ディレクトリ
91     * @return void
92     */
93    public function sfGetDirSize($dir)
94    {
95        $bytes = 0;
96        if (file_exists($dir)) {
97            // ディレクトリの場合下層ファイルの総量を取得
98            if (is_dir($dir)) {
99                $handle = opendir($dir);
100                while ($file = readdir($handle)) {
101                    // 行末の/を取り除く
102                    $dir = rtrim($dir, '/');
103                    $path = $dir.'/'.$file;
104                    if ($file != '..' && $file != '.' && !is_dir($path)) {
105                        $bytes += filesize($path);
106                    } elseif (is_dir($path) && $file != '..' && $file != '.') {
107                        // 下層ファイルのバイト数を取得する為、再帰的に呼び出す。
108                        $bytes += SC_Helper_FileManager::sfGetDirSize($path);
109                    }
110                }
111            } else {
112                // ファイルの場合
113                $bytes = filesize($dir);
114            }
115        }
116        // ディレクトリ(ファイル)が存在しない場合は0byteを返す
117        if ($bytes == '') {
118            $bytes = 0;
119        }
120
121        return $bytes;
122    }
123
124    /**
125     * ツリー生成用配列取得(javascriptに渡す用).
126     *
127     * @param string $dir         ディレクトリ
128     * @param string $tree_status 現在のツリーの状態開いているフォルダのパスを
129     *                            | 区切りで格納
130     * @return array ツリー生成用の配列
131     */
132    public function sfGetFileTree($dir, $tree_status)
133    {
134        $cnt = 0;
135        $arrTree = array();
136        $default_rank = count(explode('/', $dir));
137
138        // 文末の/を取り除く
139        $dir = rtrim($dir, '/');
140        // 最上位層を格納(user_data/)
141        if ($this->sfDirChildExists($dir)) {
142            $arrTree[$cnt]['type'] = '_parent';
143        } else {
144            $arrTree[$cnt]['type'] = '_child';
145        }
146        $arrTree[$cnt]['path'] = $dir;
147        $arrTree[$cnt]['rank'] = 0;
148        $arrTree[$cnt]['count'] = $cnt;
149        // 初期表示はオープン
150        if ($_POST['mode'] != '') {
151            $arrTree[$cnt]['open'] = $this->lfIsFileOpen($dir, $tree_status);
152        } else {
153            $arrTree[$cnt]['open'] = true;
154        }
155        $cnt++;
156
157        $this->sfGetFileTreeSub($dir, $default_rank, $cnt, $arrTree, $tree_status);
158
159        return $arrTree;
160    }
161
162    /**
163     * ツリー生成用配列取得(javascriptに渡す用).
164     *
165     * @param string $dir          ディレクトリ
166     * @param string $default_rank デフォルトの階層
167     *                             (/区切りで 0,1,2・・・とカウント)
168     * @param integer $cnt         連番
169     * @param string  $tree_status 現在のツリーの状態開いているフォルダのパスが
170     *                            | 区切りで格納
171     * @return array ツリー生成用の配列
172     */
173    public function sfGetFileTreeSub($dir, $default_rank, &$cnt, &$arrTree, $tree_status)
174    {
175        if (file_exists($dir)) {
176            $handle = opendir($dir);
177            if ($handle) {
178                $arrDir = array();
179                while (false !== ($item = readdir($handle))) $arrDir[] = $item;
180                // アルファベットと数字でソート
181                natcasesort($arrDir);
182                foreach ($arrDir as $item) {
183                    if ($item != '.' && $item != '..') {
184                        // 文末の/を取り除く
185                        $dir = rtrim($dir, '/');
186                        $path = $dir.'/'.$item;
187                        // ディレクトリのみ取得
188                        if (is_dir($path)) {
189                            $arrTree[$cnt]['path'] = $path;
190                            if ($this->sfDirChildExists($path)) {
191                                $arrTree[$cnt]['type'] = '_parent';
192                            } else {
193                                $arrTree[$cnt]['type'] = '_child';
194                            }
195
196                            // 階層を割り出す
197                            $arrCnt = explode('/', $path);
198                            $rank = count($arrCnt);
199                            $arrTree[$cnt]['rank'] = $rank - $default_rank + 1;
200                            $arrTree[$cnt]['count'] = $cnt;
201                            // フォルダが開いているか
202                            $arrTree[$cnt]['open'] = $this->lfIsFileOpen($path, $tree_status);
203                            $cnt++;
204                            // 下層ディレクトリ取得の為、再帰的に呼び出す
205                            $this->sfGetFileTreeSub($path, $default_rank, $cnt, $arrTree, $tree_status);
206                        }
207                    }
208                }
209            }
210            closedir($handle);
211        }
212    }
213
214    /**
215     * 指定したディレクトリ配下にファイルがあるかチェックする.
216     *
217     * @param string ディレクトリ
218     * @return bool ファイルが存在する場合 true
219     */
220    public function sfDirChildExists($dir)
221    {
222        if (file_exists($dir)) {
223            if (is_dir($dir)) {
224                $handle = opendir($dir);
225                while ($file = readdir($handle)) {
226                    // 行末の/を取り除く
227                    $dir = rtrim($dir, '/');
228                    $path = $dir.'/'.$file;
229                    if ($file != '..' && $file != '.' && is_dir($path)) {
230                        return true;
231                    }
232                }
233            }
234        }
235
236        return false;
237    }
238
239    /**
240     * 指定したファイルが前回開かれた状態にあったかチェックする.
241     *
242     * @param string $dir         ディレクトリ
243     * @param string $tree_status 現在のツリーの状態開いているフォルダのパスが
244     *                            | 区切りで格納
245     * @return bool 前回開かれた状態の場合 true
246     */
247    public function lfIsFileOpen($dir, $tree_status)
248    {
249        $arrTreeStatus = explode('|', $tree_status);
250        if (in_array($dir, $arrTreeStatus)) {
251            return true;
252        }
253
254        return false;
255    }
256
257    /**
258     * ファイルのダウンロードを行う.
259     *
260     * @param  string $file ファイルパス
261     * @return void
262     */
263    public function sfDownloadFile($file)
264    {
265        // ファイルの場合はダウンロードさせる
266        $file_name = basename($file);
267        header('Content-disposition: attachment; filename=' . $file_name);
268        header('Content-type: application/octet-stream; name=' . $file_name);
269        header('Cache-Control: ');
270        header('Pragma: ');
271        echo ($this->sfReadFile($file));
272    }
273
274    /**
275     * ファイル作成を行う.
276     *
277     * @param  string  $file ファイルパス
278     * @param  integer $mode パーミッション
279     * @return bool    ファイル作成に成功した場合 true
280     */
281    public function sfCreateFile($file, $mode = '')
282    {
283        // 行末の/を取り除く
284        if ($mode != '') {
285            $ret = @mkdir($file, $mode);
286        } else {
287            $ret = @mkdir($file);
288        }
289
290        return $ret;
291    }
292
293    /**
294     * ファイル読込を行う.
295     *
296     * @param string ファイルパス
297     * @return string ファイルの内容
298     */
299    public function sfReadFile($filename)
300    {
301        $str = '';
302        // バイナリモードでオープン
303        $fp = @fopen($filename, 'rb');
304        //ファイル内容を全て変数に読み込む
305        if ($fp) {
306            $str = @fread($fp, filesize($filename)+1);
307        }
308        @fclose($fp);
309
310        return $str;
311    }
312
313    /**
314     * ファイル書込を行う.
315     *
316     * @param  string  $filename ファイルパス
317     * @param  string  $value    書き込み内容
318     * @return boolean ファイルの書き込みに成功した場合 true
319     */
320    public function sfWriteFile($filename, $value)
321    {
322        if (!is_dir(dirname($filename))) {
323            SC_Utils_Ex::recursiveMkdir(dirname($filename), 0777);
324        }
325        $fp = fopen($filename,'w');
326        if ($fp === false) {
327            return false;
328        }
329        if (fwrite($fp, $value) === false) {
330            return false;
331        }
332
333        return fclose($fp);;
334    }
335
336    /**
337     * ユーザが作成したファイルをアーカイブしダウンロードさせる
338     * TODO 要リファクタリング
339     * @param  string  $dir           アーカイブを行なうディレクトリ
340     * @param  string  $template_code テンプレートコード
341     * @return boolean 成功した場合 true; 失敗した場合 false
342     */
343    public function downloadArchiveFiles($dir, $template_code)
344    {
345        // ダウンロードされるファイル名
346        $dlFileName = 'tpl_package_' . $template_code . '_' . date('YmdHis') . '.tar.gz';
347
348        $debug_message = $dir . ' から ' . $dlFileName . " を作成します...\n";
349        // ファイル一覧取得
350        $arrFileHash = SC_Helper_FileManager_Ex::sfGetFileList($dir);
351        $arrFileList = array();
352        foreach ($arrFileHash as $val) {
353            $arrFileList[] = $val['file_name'];
354            $debug_message.= '圧縮:'.$val['file_name']."\n";
355        }
356        GC_Utils_Ex::gfPrintLog($debug_message);
357
358        // ディレクトリを移動
359        chdir($dir);
360        // 圧縮をおこなう
361        $tar = new Archive_Tar($dlFileName, true);
362        if ($tar->create($arrFileList)) {
363            // ダウンロード用HTTPヘッダ出力
364            header("Content-disposition: attachment; filename=${dlFileName}");
365            header("Content-type: application/octet-stream; name=${dlFileName}");
366            header('Cache-Control: ');
367            header('Pragma: ');
368            readfile($dlFileName);
369            unlink($dir . '/' . $dlFileName);
370
371            return true;
372        } else {
373            return false;
374        }
375    }
376
377    /**
378     * tarアーカイブを解凍する.
379     *
380     * @param  string  $path アーカイブパス
381     * @return boolean Archive_Tar::extractModify()のエラー
382     */
383    public function unpackFile($path)
384    {
385        // 圧縮フラグTRUEはgzip解凍をおこなう
386        $tar = new Archive_Tar($path, true);
387
388        $dir = dirname($path);
389        $file_name = basename($path);
390
391        // 拡張子を切り取る
392        $unpacking_name = preg_replace("/(\.tar|\.tar\.gz)$/", '', $file_name);
393
394        // 指定されたフォルダ内に解凍する
395        $result = $tar->extractModify($dir. '/', $unpacking_name);
396        GC_Utils_Ex::gfPrintLog('解凍:' . $dir.'/'.$file_name.'->'.$dir.'/'.$unpacking_name);
397
398        // フォルダ削除
399        SC_Helper_FileManager_Ex::deleteFile($dir . '/' . $unpacking_name);
400        // 圧縮ファイル削除
401        unlink($path);
402
403        return $result;
404    }
405
406    /**
407     * 指定されたパスの配下を再帰的に削除.
408     *
409     * @param  string  $path       削除対象のディレクトリまたはファイルのパス
410     * @param  boolean $del_myself $pathそのものを削除するか. true なら削除する.
411     * @return void
412     */
413    public function deleteFile($path, $del_myself = true)
414    {
415        $flg = false;
416        // 対象が存在するかを検証.
417        if (file_exists($path) === false) {
418            GC_Utils_Ex::gfPrintLog($path . ' が存在しません.');
419        } elseif (is_dir($path)) {
420            // ディレクトリが指定された場合
421            $handle = opendir($path);
422            if (!$handle) {
423                GC_Utils_Ex::gfPrintLog($path . ' が開けませんでした.');
424            }
425            while (($item = readdir($handle)) !== false) {
426                if ($item === '.' || $item === '..') continue;
427                $cur_path = $path . '/' . $item;
428                if (is_dir($cur_path)) {
429                    // ディレクトリの場合、再帰処理
430                    $flg = SC_Helper_FileManager_Ex::deleteFile($cur_path);
431                } else {
432                    // ファイルの場合、unlink
433                    $flg = @unlink($cur_path);
434                }
435            }
436            closedir($handle);
437            // ディレクトリを削除
438            GC_Utils_Ex::gfPrintLog($path . ' を削除します.');
439            if ($del_myself) {
440                $flg = @rmdir($path);
441            }
442        } else {
443            // ファイルが指定された場合.
444            GC_Utils_Ex::gfPrintLog($path . ' を削除します.');
445            $flg = @unlink($path);
446        }
447
448        return $flg;
449    }
450}
Note: See TracBrowser for help on using the repository browser.