Completed
Push — master ( 9b2920...4ebe21 )
by Daniel
02:25
created

CommonCode::getListOfFiles()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 15
rs 9.2
cc 4
eloc 11
nc 4
nop 1
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * usefull functions to get quick results
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait CommonCode
37
{
38
39
    use CommonViews;
40
41
    /**
42
     * Reads the content of a remote file through CURL extension
43
     *
44
     * @param string $fullURL
45
     * @param array $features
46
     * @return blob
47
     */
48
    protected function getContentFromUrlThroughCurl($fullURL, $features = null)
49
    {
50
        if (!function_exists('curl_init')) {
51
            $aReturn = ['info' => $this->lclMsgCmn('i18n_Error_ExtensionNotLoaded'), 'response' => ''];
52
            return $this->setArrayToJson($aReturn);
53
        }
54
        if (!filter_var($fullURL, FILTER_VALIDATE_URL)) {
55
            $aReturn = ['info' => $this->lclMsgCmn('i18n_Error_GivenUrlIsNotValid'), 'response' => ''];
56
            return $this->setArrayToJson($aReturn);
57
        }
58
        $aReturn = $this->getContentFromUrlThroughCurlRawArray($fullURL, $features);
59
        return '{ ' . $this->packIntoJson($aReturn, 'info') . ', ' . $this->packIntoJson($aReturn, 'response') . ' }';
60
    }
61
62
    /**
63
     * Reads the content of a remote file through CURL extension
64
     *
65
     * @param string $fullURL
66
     * @param array $features
67
     * @return blob
68
     */
69
    protected function getContentFromUrlThroughCurlAsArrayIfJson($fullURL, $features = null)
70
    {
71
        $result = $this->setJsonToArray($this->getContentFromUrlThroughCurl($fullURL, $features));
72
        if (is_array($result['info'])) {
73
            ksort($result['info']);
74
        }
75
        if (is_array($result['response'])) {
76
            ksort($result['response']);
77
        }
78
        return $result;
79
    }
80
81
    protected function getContentFromUrlThroughCurlRaw($fullURL, $features = null)
82
    {
83
        $chanel = curl_init();
84
        curl_setopt($chanel, CURLOPT_USERAGENT, $this->getUserAgentByCommonLib());
85
        if ((strpos($fullURL, 'https') !== false)) {
86
            $chk = false;
87
            if (isset($features['forceSSLverification'])) {
88
                $chk = true;
89
            }
90
            curl_setopt($chanel, CURLOPT_SSL_VERIFYHOST, $chk);
91
            curl_setopt($chanel, CURLOPT_SSL_VERIFYPEER, $chk);
92
        }
93
        curl_setopt($chanel, CURLOPT_URL, $fullURL);
94
        curl_setopt($chanel, CURLOPT_HEADER, false);
95
        curl_setopt($chanel, CURLOPT_RETURNTRANSFER, true);
96
        curl_setopt($chanel, CURLOPT_FRESH_CONNECT, true); //avoid a cached response
97
        curl_setopt($chanel, CURLOPT_FAILONERROR, true);
98
        $aReturn = [curl_exec($chanel), curl_getinfo($chanel), curl_errno($chanel), curl_error($chanel)];
99
        curl_close($chanel);
100
        return ['response' => $aReturn[0], 'info' => $aReturn[1], 'errNo' => $aReturn[2], 'errMsg' => $aReturn[3]];
101
    }
102
103
    protected function getContentFromUrlThroughCurlRawArray($fullURL, $features = null)
104
    {
105
        $curlFeedback = $this->getContentFromUrlThroughCurlRaw($fullURL, $features);
106
        if ($curlFeedback['errNo'] !== 0) {
107
            $info = $this->setArrayToJson(['#' => $curlFeedback['errNo'], 'description' => $curlFeedback['errMsg']]);
108
            return ['info' => $info, 'response' => ''];
109
        }
110
        return ['info' => $this->setArrayToJson($curlFeedback['info']), 'response' => $curlFeedback['response']];
111
    }
112
113
    protected function getFeedbackMySQLAffectedRecords()
114
    {
115
        if (is_null($this->mySQLconnection)) {
116
            return '<div>No MySQL connection detected</div>';
117
        }
118
        $afRows = $this->mySQLconnection->affected_rows;
119
        return '<div>' . sprintf($this->lclMsgCmnNumber('i18n_Record', 'i18n_Records', $afRows), $afRows) . '</div>';
120
    }
121
122
    /**
123
     * returns the details about Communicator (current) file
124
     *
125
     * @param string $fileGiven
126
     * @return array
127
     */
128
    protected function getFileDetails($fileGiven)
129
    {
130
        if (!file_exists($fileGiven)) {
131
            return ['error' => sprintf($this->lclMsgCmn('i18n_Error_GivenFileDoesNotExist'), $fileGiven)];
132
        }
133
        return $this->getFileDetailsRaw($fileGiven);
134
    }
135
136
    /**
137
     * returns a multi-dimensional array with list of file details within a given path
138
     * (by using Symfony/Finder package)
139
     *
140
     * @param  string $pathAnalised
141
     * @return array
142
     */
143
    protected function getListOfFiles($pathAnalised)
144
    {
145
        if (realpath($pathAnalised) === false) {
146
            return ['error' => sprintf($this->lclMsgCmn('i18n_Error_GivenPathIsNotValid'), $pathAnalised)];
147
        } elseif (!is_dir($pathAnalised)) {
148
            return ['error' => $this->lclMsgCmn('i18n_Error_GivenPathIsNotFolder')];
149
        }
150
        $finder   = new \Symfony\Component\Finder\Finder();
151
        $iterator = $finder->files()->sortByName()->in($pathAnalised);
152
        $aFiles   = null;
153
        foreach ($iterator as $file) {
154
            $aFiles[$file->getRealPath()] = $this->getFileDetails($file);
155
        }
156
        return $aFiles;
157
    }
158
159
    /**
160
     * Returns server Timestamp into various formats
161
     *
162
     * @param string $returnType
163
     * @return string
164
     */
165
    protected function getTimestamp($returnType = 'string')
166
    {
167
        if (in_array($returnType, ['array', 'float', 'string'])) {
168
            return $this->getTimestampRaw($returnType);
169
        }
170
        return sprintf($this->lclMsgCmn('i18n_Error_UnknownReturnType'), $returnType);
171
    }
172
173
    /**
174
     * Tests if given string has a valid Json format
175
     *
176
     * @param string $inputJson
177
     * @return boolean|string
178
     */
179
    protected function isJsonByDanielGP($inputJson)
180
    {
181
        if (is_string($inputJson)) {
182
            json_decode($inputJson);
183
            return (json_last_error() == JSON_ERROR_NONE);
184
        }
185
        return $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson');
186
    }
187
188
    private function packIntoJson($aReturn, $keyToWorkWith)
189
    {
190
        if ($this->isJsonByDanielGP($aReturn[$keyToWorkWith])) {
191
            return '"' . $keyToWorkWith . '": ' . $aReturn[$keyToWorkWith];
192
        }
193
        return '"' . $keyToWorkWith . '": {' . $aReturn[$keyToWorkWith] . ' }';
194
    }
195
196
    /**
197
     * Send an array of parameters like a form through a POST action
198
     *
199
     * @param string $urlToSendTo
200
     * @param array $params
201
     * @throws \Exception
202
     */
203
    protected function sendBackgroundEncodedFormElementsByPost($urlToSendTo, $params = [])
204
    {
205
        $postingUrl = filter_var($urlToSendTo, FILTER_VALIDATE_URL);
206
        if ($postingUrl === false) {
207
            throw new \Exception('Invalid URL in ' . __FUNCTION__);
208
        }
209
        if (is_array($params)) {
210
            $cntFailErrMsg = $this->lclMsgCmn('i18n_Error_FailedToConnect');
211
            $this->sendBackgroundPostData($postingUrl, $params, $cntFailErrMsg);
212
            return '';
213
        }
214
        throw new \Exception($this->lclMsgCmn('i18n_Error_GivenParameterIsNotAnArray'));
215
    }
216
217
    private function sendBackgroundPostData($postingUrl, $params, $cntFailErrMsg)
218
    {
219
        $postingString = $this->setArrayToStringForUrl('&', $params);
220
        $pUrlParts     = parse_url($postingUrl);
221
        $postingPort   = 80;
222
        if (isset($pUrlParts['port'])) {
223
            $postingPort = $pUrlParts['port'];
224
        }
225
        $flPointer = fsockopen($pUrlParts['host'], $postingPort, $erN, $erM, 30);
226
        if ($flPointer === false) {
227
            throw new \Exception($cntFailErrMsg . ': ' . $erN . ' (' . $erM . ')');
228
        }
229
        fwrite($flPointer, $this->sendBackgroundPrepareData($pUrlParts, $postingString));
230
        fclose($flPointer);
231
    }
232
233
    private function sendBackgroundPrepareData($pUrlParts, $postingString)
234
    {
235
        $this->initializeSprGlbAndSession();
236
        $out   = [];
237
        $out[] = 'POST ' . $pUrlParts['path'] . ' ' . $this->tCmnSuperGlobals->server->get['SERVER_PROTOCOL'];
238
        $out[] = 'Host: ' . $pUrlParts['host'];
239
        $out[] = 'User-Agent: ' . $this->getUserAgentByCommonLib();
240
        $out[] = 'Content-Type: application/x-www-form-urlencoded';
241
        $out[] = 'Content-Length: ' . strlen($postingString);
242
        $out[] = 'Connection: Close' . "\r\n";
243
        $out[] = $postingString;
244
        return implode("\r\n", $out);
245
    }
246
247
    /**
248
     * Converts a JSON string into an Array
249
     *
250
     * @param string $inputJson
251
     * @return array
252
     */
253
    protected function setJsonToArray($inputJson)
254
    {
255
        if (!$this->isJsonByDanielGP($inputJson)) {
256
            return ['error' => $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson')];
257
        }
258
        $sReturn   = (json_decode($inputJson, true));
259
        $jsonError = $this->setJsonErrorInPlainEnglish();
260
        if (is_null($jsonError)) {
261
            return $sReturn;
262
        }
263
        return ['error' => $jsonError];
264
    }
265
}
266