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

Revision 23124, 15.8 KB checked in by kimoto, 11 years ago (diff)

#2043 typo修正・ソース整形・ソースコメントの改善 for 2.13.0
PHP4的な書き方の修正

  • 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        Header('Content-disposition: attachment; filename='.basename($file));
267        Header('Content-type: application/octet-stream; name='.basename($file));
268        Header('Cache-Control: ');
269        Header('Pragma: ');
270        echo ($this->sfReadFile($file));
271    }
272
273    /**
274     * ファイル作成を行う.
275     *
276     * @param  string  $file ファイルパス
277     * @param  integer $mode パーミッション
278     * @return bool    ファイル作成に成功した場合 true
279     */
280    public function sfCreateFile($file, $mode = '')
281    {
282        // 行末の/を取り除く
283        if ($mode != '') {
284            $ret = @mkdir($file, $mode);
285        } else {
286            $ret = @mkdir($file);
287        }
288
289        return $ret;
290    }
291
292    /**
293     * ファイル読込を行う.
294     *
295     * @param string ファイルパス
296     * @return string ファイルの内容
297     */
298    public function sfReadFile($filename)
299    {
300        $str = '';
301        // バイナリモードでオープン
302        $fp = @fopen($filename, 'rb');
303        //ファイル内容を全て変数に読み込む
304        if ($fp) {
305            $str = @fread($fp, filesize($filename)+1);
306        }
307        @fclose($fp);
308
309        return $str;
310    }
311
312    /**
313     * ファイル書込を行う.
314     *
315     * @param  string  $filename ファイルパス
316     * @param  string  $value    書き込み内容
317     * @return boolean ファイルの書き込みに成功した場合 true
318     */
319    public function sfWriteFile($filename, $value)
320    {
321        if (!is_dir(dirname($filename))) {
322            SC_Utils_Ex::recursiveMkdir(dirname($filename), 0777);
323        }
324        $fp = fopen($filename,'w');
325        if ($fp === false) {
326            return false;
327        }
328        if (fwrite($fp, $value) === false) {
329            return false;
330        }
331
332        return fclose($fp);;
333    }
334
335    /**
336     * ユーザが作成したファイルをアーカイブしダウンロードさせる
337     * TODO 要リファクタリング
338     * @param  string  $dir           アーカイブを行なうディレクトリ
339     * @param  string  $template_code テンプレートコード
340     * @return boolean 成功した場合 true; 失敗した場合 false
341     */
342    public function downloadArchiveFiles($dir, $template_code)
343    {
344        // ダウンロードされるファイル名
345        $dlFileName = 'tpl_package_' . $template_code . '_' . date('YmdHis') . '.tar.gz';
346
347        $debug_message = $dir . ' から ' . $dlFileName . " を作成します...\n";
348        // ファイル一覧取得
349        $arrFileHash = SC_Helper_FileManager_Ex::sfGetFileList($dir);
350        $arrFileList = array();
351        foreach ($arrFileHash as $val) {
352            $arrFileList[] = $val['file_name'];
353            $debug_message.= '圧縮:'.$val['file_name']."\n";
354        }
355        GC_Utils_Ex::gfPrintLog($debug_message);
356
357        // ディレクトリを移動
358        chdir($dir);
359        // 圧縮をおこなう
360        $tar = new Archive_Tar($dlFileName, true);
361        if ($tar->create($arrFileList)) {
362            // ダウンロード用HTTPヘッダ出力
363            header("Content-disposition: attachment; filename=${dlFileName}");
364            header("Content-type: application/octet-stream; name=${dlFileName}");
365            header('Cache-Control: ');
366            header('Pragma: ');
367            readfile($dlFileName);
368            unlink($dir . '/' . $dlFileName);
369
370            return true;
371        } else {
372            return false;
373        }
374    }
375
376    /**
377     * tarアーカイブを解凍する.
378     *
379     * @param  string  $path アーカイブパス
380     * @return boolean Archive_Tar::extractModify()のエラー
381     */
382    public function unpackFile($path)
383    {
384        // 圧縮フラグTRUEはgzip解凍をおこなう
385        $tar = new Archive_Tar($path, true);
386
387        $dir = dirname($path);
388        $file_name = basename($path);
389
390        // 拡張子を切り取る
391        $unpacking_name = preg_replace("/(\.tar|\.tar\.gz)$/", '', $file_name);
392
393        // 指定されたフォルダ内に解凍する
394        $result = $tar->extractModify($dir. '/', $unpacking_name);
395        GC_Utils_Ex::gfPrintLog('解凍:' . $dir.'/'.$file_name.'->'.$dir.'/'.$unpacking_name);
396
397        // フォルダ削除
398        SC_Helper_FileManager_Ex::deleteFile($dir . '/' . $unpacking_name);
399        // 圧縮ファイル削除
400        unlink($path);
401
402        return $result;
403    }
404
405    /**
406     * 指定されたパスの配下を再帰的に削除.
407     *
408     * @param  string  $path       削除対象のディレクトリまたはファイルのパス
409     * @param  boolean $del_myself $pathそのものを削除するか. true なら削除する.
410     * @return void
411     */
412    public function deleteFile($path, $del_myself = true)
413    {
414        $flg = false;
415        // 対象が存在するかを検証.
416        if (file_exists($path) === false) {
417            GC_Utils_Ex::gfPrintLog($path . ' が存在しません.');
418        } elseif (is_dir($path)) {
419            // ディレクトリが指定された場合
420            $handle = opendir($path);
421            if (!$handle) {
422                GC_Utils_Ex::gfPrintLog($path . ' が開けませんでした.');
423            }
424            while (($item = readdir($handle)) !== false) {
425                if ($item === '.' || $item === '..') continue;
426                $cur_path = $path . '/' . $item;
427                if (is_dir($cur_path)) {
428                    // ディレクトリの場合、再帰処理
429                    $flg = SC_Helper_FileManager_Ex::deleteFile($cur_path);
430                } else {
431                    // ファイルの場合、unlink
432                    $flg = @unlink($cur_path);
433                }
434            }
435            closedir($handle);
436            // ディレクトリを削除
437            GC_Utils_Ex::gfPrintLog($path . ' を削除します.');
438            if ($del_myself) {
439                $flg = @rmdir($path);
440            }
441        } else {
442            // ファイルが指定された場合.
443            GC_Utils_Ex::gfPrintLog($path . ' を削除します.');
444            $flg = @unlink($path);
445        }
446
447        return $flg;
448    }
449}
Note: See TracBrowser for help on using the repository browser.