Completed
Push — master ( 465df9...781eb1 )
by Daniel
02:18
created

CommonCode::getFileDetails()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
c 8
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
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
    private function buildArrayForCurlInterogation($curlFeedback)
42
    {
43
        if ($curlFeedback['errNo'] !== 0) {
44
            $info = $this->setArrayToJson(['#' => $curlFeedback['errNo'], 'description' => $curlFeedback['errMsg']]);
45
            return ['info' => $info, 'response' => ''];
46
        }
47
        return ['info' => $this->setArrayToJson($curlFeedback['info']), 'response' => $curlFeedback['response']];
48
    }
49
50
    private function checkSecureChannelOnCurl($chanel, $fullURL, $features = null)
51
    {
52
        if ((strpos($fullURL, 'https') !== false) || (isset($features['forceSSLverification']))) {
53
            curl_setopt($chanel, CURLOPT_SSL_VERIFYHOST, false);
54
            curl_setopt($chanel, CURLOPT_SSL_VERIFYPEER, false);
55
        }
56
    }
57
58
    /**
59
     * Reads the content of a remote file through CURL extension
60
     *
61
     * @param string $fullURL
62
     * @param array $features
63
     * @return blob
64
     */
65
    protected function getContentFromUrlThroughCurl($fullURL, $features = null)
66
    {
67
        if (!function_exists('curl_init')) {
68
            $aReturn = ['info' => $this->lclMsgCmn('i18n_Error_ExtensionNotLoaded'), 'response' => ''];
69
            return $this->setArrayToJson($aReturn);
70
        }
71
        if (!filter_var($fullURL, FILTER_VALIDATE_URL)) {
72
            $aReturn = ['info' => $this->lclMsgCmn('i18n_Error_GivenUrlIsNotValid'), 'response' => ''];
73
            return $this->setArrayToJson($aReturn);
74
        }
75
        $aReturn = $this->getContentFromUrlThroughCurlRawArray($fullURL, $features);
76
        return '{ ' . $this->packIntoJson($aReturn, 'info') . ', ' . $this->packIntoJson($aReturn, 'response') . ' }';
77
    }
78
79
    /**
80
     * Reads the content of a remote file through CURL extension
81
     *
82
     * @param string $fullURL
83
     * @param array $features
84
     * @return blob
85
     */
86
    protected function getContentFromUrlThroughCurlAsArrayIfJson($fullURL, $features = null)
87
    {
88
        $result = $this->setJsonToArray($this->getContentFromUrlThroughCurl($fullURL, $features));
89
        if (is_array($result['info'])) {
90
            ksort($result['info']);
91
        }
92
        if (is_array($result['response'])) {
93
            ksort($result['response']);
94
        }
95
        return $result;
96
    }
97
98
    protected function getContentFromUrlThroughCurlRaw($fullURL, $features = null)
99
    {
100
        $chanel  = curl_init();
101
        curl_setopt($chanel, CURLOPT_USERAGENT, $this->getUserAgentByCommonLib());
102
        $this->checkSecureChannelOnCurl($chanel, $fullURL, $features);
103
        curl_setopt($chanel, CURLOPT_URL, $fullURL);
104
        curl_setopt($chanel, CURLOPT_HEADER, false);
105
        curl_setopt($chanel, CURLOPT_RETURNTRANSFER, true);
106
        curl_setopt($chanel, CURLOPT_FRESH_CONNECT, true); //avoid a cached response
107
        curl_setopt($chanel, CURLOPT_FAILONERROR, true);
108
        $aReturn = [
109
            'response' => curl_exec($chanel),
110
            'info'     => curl_getinfo($chanel),
111
            'errNo'    => curl_errno($chanel),
112
            'errMsg'   => curl_error($chanel),
113
        ];
114
        curl_close($chanel);
115
        return $aReturn;
116
    }
117
118
    protected function getContentFromUrlThroughCurlRawArray($fullURL, $features = null)
119
    {
120
        $rspJsonFromClient = $this->getContentFromUrlThroughCurlRaw($fullURL, $features);
121
        return $this->buildArrayForCurlInterogation($rspJsonFromClient);
122
    }
123
124
    protected function getFeedbackMySQLAffectedRecords()
125
    {
126
        if (is_null($this->mySQLconnection)) {
127
            return '<div>No MySQL connection detected</div>';
128
        }
129
        $afRows = $this->mySQLconnection->affected_rows;
130
        return '<div>' . sprintf($this->lclMsgCmnNumber('i18n_Record', 'i18n_Records', $afRows), $afRows) . '</div>';
131
    }
132
133
    /**
134
     * returns the details about Communicator (current) file
135
     *
136
     * @param string $fileGiven
137
     * @return array
138
     */
139
    protected function getFileDetails($fileGiven)
140
    {
141
        if (!file_exists($fileGiven)) {
142
            return ['error' => sprintf($this->lclMsgCmn('i18n_Error_GivenFileDoesNotExist'), $fileGiven)];
143
        }
144
        return $this->getFileDetailsRaw($fileGiven);
145
    }
146
147
    /**
148
     * returns a multi-dimensional array with list of file details within a given path
149
     * (by using Symfony/Finder package)
150
     *
151
     * @param  string $pathAnalised
152
     * @return array
153
     */
154
    protected function getListOfFiles($pathAnalised)
155
    {
156
        if (realpath($pathAnalised) === false) {
157
            return ['error' => sprintf($this->lclMsgCmn('i18n_Error_GivenPathIsNotValid'), $pathAnalised)];
158
        } elseif (!is_dir($pathAnalised)) {
159
            return ['error' => $this->lclMsgCmn('i18n_Error_GivenPathIsNotFolder')];
160
        }
161
        $finder   = new \Symfony\Component\Finder\Finder();
162
        $iterator = $finder->files()->sortByName()->in($pathAnalised);
163
        $aFiles   = null;
164
        foreach ($iterator as $file) {
165
            $aFiles[$file->getRealPath()] = $this->getFileDetails($file);
166
        }
167
        return $aFiles;
168
    }
169
170
    /**
171
     * Returns server Timestamp into various formats
172
     *
173
     * @param string $returnType
174
     * @return string
175
     */
176
    protected function getTimestamp($returnType = 'string')
177
    {
178
        if (in_array($returnType, ['array', 'float', 'string'])) {
179
            return $this->getTimestampRaw($returnType);
180
        }
181
        return sprintf($this->lclMsgCmn('i18n_Error_UnknownReturnType'), $returnType);
182
    }
183
184
    /**
185
     * Tests if given string has a valid Json format
186
     *
187
     * @param string $inputJson
188
     * @return boolean|string
189
     */
190
    protected function isJsonByDanielGP($inputJson)
191
    {
192
        if (is_string($inputJson)) {
193
            json_decode($inputJson);
194
            return (json_last_error() == JSON_ERROR_NONE);
195
        }
196
        return $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson');
197
    }
198
199
    private function packIntoJson($aReturn, $keyToWorkWith)
200
    {
201
        if ($this->isJsonByDanielGP($aReturn[$keyToWorkWith])) {
202
            return '"' . $keyToWorkWith . '": ' . $aReturn[$keyToWorkWith];
203
        }
204
        return '"' . $keyToWorkWith . '": {' . $aReturn[$keyToWorkWith] . ' }';
205
    }
206
207
    /**
208
     * Send an array of parameters like a form through a POST action
209
     *
210
     * @param string $urlToSendTo
211
     * @param array $params
212
     * @throws \Exception
213
     */
214
    protected function sendBackgroundEncodedFormElementsByPost($urlToSendTo, $params = [])
215
    {
216
        $postingUrl = filter_var($urlToSendTo, FILTER_VALIDATE_URL);
217
        if ($postingUrl === false) {
218
            throw new \Exception('Invalid URL in ' . __FUNCTION__);
219
        }
220
        if (is_array($params)) {
221
            $cntFailErrMsg = $this->lclMsgCmn('i18n_Error_FailedToConnect');
222
            $this->sendBackgroundPostData($postingUrl, $params, $cntFailErrMsg);
223
            return '';
224
        }
225
        throw new \Exception($this->lclMsgCmn('i18n_Error_GivenParameterIsNotAnArray'));
226
    }
227
228
    private function sendBackgroundPostData($postingUrl, $params, $cntFailErrMsg)
229
    {
230
        $postingString = $this->setArrayToStringForUrl('&', $params);
231
        $pUrlParts     = parse_url($postingUrl);
232
        $postingPort   = 80;
233
        if (isset($pUrlParts['port'])) {
234
            $postingPort = $pUrlParts['port'];
235
        }
236
        $flPointer = fsockopen($pUrlParts['host'], $postingPort, $erN, $erM, 30);
237
        if ($flPointer === false) {
238
            throw new \Exception($cntFailErrMsg . ': ' . $erN . ' (' . $erM . ')');
239
        }
240
        fwrite($flPointer, $this->sendBackgroundPrepareData($pUrlParts, $postingString));
241
        fclose($flPointer);
242
    }
243
244
    private function sendBackgroundPrepareData($pUrlParts, $postingString)
245
    {
246
        $this->initializeSprGlbAndSession();
247
        $out   = [];
248
        $out[] = 'POST ' . $pUrlParts['path'] . ' ' . $this->tCmnSuperGlobals->server->get['SERVER_PROTOCOL'];
249
        $out[] = 'Host: ' . $pUrlParts['host'];
250
        $out[] = 'User-Agent: ' . $this->getUserAgentByCommonLib();
251
        $out[] = 'Content-Type: application/x-www-form-urlencoded';
252
        $out[] = 'Content-Length: ' . strlen($postingString);
253
        $out[] = 'Connection: Close' . "\r\n";
254
        $out[] = $postingString;
255
        return implode("\r\n", $out);
256
    }
257
258
    /**
259
     * Converts a JSON string into an Array
260
     *
261
     * @param string $inputJson
262
     * @return array
263
     */
264
    protected function setJsonToArray($inputJson)
265
    {
266
        if (!$this->isJsonByDanielGP($inputJson)) {
267
            return ['error' => $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson')];
268
        }
269
        $sReturn   = (json_decode($inputJson, true));
270
        $jsonError = $this->setJsonErrorInPlainEnglish();
271
        if (is_null($jsonError)) {
272
            return $sReturn;
273
        }
274
        return ['error' => $jsonError];
275
    }
276
}
277