Completed
Push — master ( 781eb1...9b2920 )
by Daniel
02:35
created

CommonCode::getContentFromUrlThroughCurlRawArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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