Completed
Branch dev (1ad2e5)
by
unknown
04:33
created

AdminPageFramework_WPUtility_File::download()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 25
nc 7
nop 2
dl 0
loc 41
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * Admin Page Framework
4
 * 
5
 * http://en.michaeluno.jp/admin-page-framework/
6
 * Copyright (c) 2013-2016 Michael Uno; Licensed MIT
7
 * 
8
 */
9
10
/**
11
 * Provides utility methods regarding reading file which use WordPress built-in functions and classes.
12
 *
13
 * @since       2.0.0
14
 * @extends     AdminPageFramework_Utility
15
 * @package     AdminPageFramework
16
 * @subpackage  Utility
17
 * @internal
18
 */
19
class AdminPageFramework_WPUtility_File extends AdminPageFramework_WPUtility_Hook {
20
    
21
    /**
22
     * Returns an array of plugin data from the given path.     
23
     * 
24
     * An alternative to get_plugin_data() as some users change the location of the wp-admin directory.
25
     * 
26
     * @since   2.0.0
27
     * @since   3.0.0       Changed the scope to public and become static.
28
     * @since   3.6.2       Supported a text content to be passed to the first parameter.
29
     * @access  public
30
     */ 
31
    static public function getScriptData( $sPathOrContent, $sType='plugin', $aDefaultHeaderKeys=array() ) {
1 ignored issue
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
32
        
33
        $_aHeaderKeys = $aDefaultHeaderKeys + array(
34
            // storing array key =>    the comment entry header label
35
            'sName'         => 'Name',
36
            'sURI'          => 'URI',
37
            'sScriptName'   => 'Script Name',
38
            'sLibraryName'  => 'Library Name',
39
            'sLibraryURI'   => 'Library URI',
40
            'sPluginName'   => 'Plugin Name',
41
            'sPluginURI'    => 'Plugin URI',
42
            'sThemeName'    => 'Theme Name',
43
            'sThemeURI'     => 'Theme URI',
44
            'sVersion'      => 'Version',
45
            'sDescription'  => 'Description',
46
            'sAuthor'       => 'Author',
47
            'sAuthorURI'    => 'Author URI',
48
            'sTextDomain'   => 'Text Domain',
49
            'sDomainPath'   => 'Domain Path',
50
            'sNetwork'      => 'Network',
51
            // Site Wide Only is deprecated in favour of Network.
52
            '_sitewide'     => 'Site Wide Only',
53
        );
54
        
55
        $aData = file_exists( $sPathOrContent )
56
            ? get_file_data( 
57
                $sPathOrContent,
58
                $_aHeaderKeys,
59
                $sType // context
60
            ) 
61
            : self::getScriptDataFromContents(
62
                $sPathOrContent,
63
                $sType,
64
                $_aHeaderKeys
65
            );
66
67
        switch ( trim( $sType ) ) {
68
            case 'theme':    
69
                $aData['sName'] = $aData['sThemeName'];
70
                $aData['sURI'] = $aData['sThemeURI'];
71
                break;
72
            case 'library':    
73
                $aData['sName'] = $aData['sLibraryName'];
74
                $aData['sURI'] = $aData['sLibraryURI'];
75
                break;
76
            case 'script':    
77
                $aData['sName'] = $aData['sScriptName'];
78
                break;     
79
            case 'plugin':    
80
                $aData['sName'] = $aData['sPluginName'];
81
                $aData['sURI'] = $aData['sPluginURI'];
82
                break;
83
            default:    
84
                break;     
85
        }     
86
87
        return $aData;
88
        
89
    }
90
    
91
    /**
92
     * Returns an array of plugin data from the given text content.     
93
     * @since       3.6.2
94
     * @return      array       The script data
95
     */
96
    static public function getScriptDataFromContents( $sContent, $sType='plugin', $aDefaultHeaderKeys=array() ) {
1 ignored issue
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
97
        
98
        // Make sure we catch CR-only line endings.
99
        $sContent = str_replace( "\r", "\n", $sContent );
100
        
101
        $_aHeaders      = $aDefaultHeaderKeys;
102
        if ( $sType ) {
103
            $_aExtraHeaders = apply_filters( "extra_{$sType}_headers", array() );
104
            if ( ! empty( $_aExtraHeaders ) ) {
105
                $_aExtraHeaders = array_combine( $_aExtraHeaders, $_aExtraHeaders ); // keys equal values
106
                $_aHeaders      = array_merge( $_aExtraHeaders, ( array ) $aDefaultHeaderKeys );
107
            }
108
        } 
109
110
        foreach ( $_aHeaders as $_sHeaderKey => $_sRegex ) {
111
            $_bFound = preg_match( '/^[ \t\/*#@]*' . preg_quote( $_sRegex, '/' ) . ':(.*)$/mi', $sContent, $_aMatch );
112
            $_aHeaders[ $_sHeaderKey ] = $_bFound && $_aMatch[ 1 ]
113
                ? _cleanup_header_comment( $_aMatch[ 1 ] )
114
                : '';        
115
        }
116
117
        return $_aHeaders;
118
        
119
    }
120
    
121
    /**
122
     * Downloads a file by the given URL.
123
     * 
124
     * @remark      The downloaded file should be unlinked(deleted) after it is ued as this function does not do it.
125
     * @since       3.4.2
126
     * @see         download_url() in file.php in core.
127
     */
128
    static public function download( $sURL, $iTimeOut=300 ) {
1 ignored issue
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
129
        
130
        if ( false === filter_var( $sURL, FILTER_VALIDATE_URL ) ) {
131
            return false;
132
        }
133
134
        $_sTmpFileName = self::setTempPath( self::getBaseNameOfURL( $sURL ) );
135
        if ( ! $_sTmpFileName ) {
136
            return false;
137
        }
138
139
        $_aoResponse = wp_safe_remote_get( 
140
            $sURL, 
141
            array( 
142
                'timeout'   => $iTimeOut, 
143
                'stream'    => true, 
144
                'filename'  => $_sTmpFileName
145
            )
146
        );
147
148
        if ( is_wp_error( $_aoResponse ) ) {
149
            unlink( $_sTmpFileName );
150
            return false;
151
        }
152
153
        if ( 200 != wp_remote_retrieve_response_code( $_aoResponse ) ){
154
            unlink( $_sTmpFileName );
155
            return false;
156
        }
157
158
        $_sContent_md5 = wp_remote_retrieve_header( $_aoResponse, 'content-md5' );
159
        if ( $_sContent_md5 ) {
160
            $_boIsMD5 = verify_file_md5( $_sTmpFileName, $_sContent_md5 );
161
            if ( is_wp_error( $_boIsMD5 ) ) {
162
                unlink( $_sTmpFileName );
163
                return false;
164
            }
165
        }
166
167
        return $_sTmpFileName;
168
    }    
169
    
170
    /**
171
     * Sets a temporary file in the system temporary directory and return the file path.
172
     * 
173
     * This function respects the file name passed to the parameter.
174
     * 
175
     * @since       3.4.2
176
     * @return      string      The set file path.
177
     */
178
    static public function setTempPath( $sFilePath='' ) {
1 ignored issue
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
179
        
180
        $_sDir = get_temp_dir();
181
        
182
        $sFilePath = basename( $sFilePath );
183
        if ( empty( $sFilePath ) ) {            
184
            $sFilePath = time() . '.tmp';
185
        }
186
187
        $sFilePath = $_sDir . wp_unique_filename( $_sDir, $sFilePath );
188
        touch( $sFilePath );
189
        return $sFilePath;
190
        
191
    }    
192
    
193
    /**
194
     * Returns the base name of a URL.
195
     * 
196
     * @since       3.4.2
197
     */
198
    static public function getBaseNameOfURL( $sURL ) {
1 ignored issue
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
199
        
200
        $_sPath         = parse_url( $sURL, PHP_URL_PATH) ; 
201
        $_sFileBaseName = basename( $_sPath );
202
        return $_sFileBaseName;
203
        
204
    }
205
    
206
}
207