CommonCode   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 229
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 100
dl 0
loc 229
rs 9.6
c 0
b 0
f 0
wmc 35

14 Methods

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