Completed
Push — master ( d07412...cd27fe )
by Daniel
02:58 queued 10s
created

CommonCode::buildArrayForCurlInterogation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 2
eloc 8
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 CommonBasic,
40
        CommonPermissions,
41
        DomComponentsByDanielGP,
42
        MySQLiByDanielGPqueries,
43
        MySQLiByDanielGP;
44
45
    protected function arrayDiffAssocRecursive($array1, $array2)
46
    {
47
        $difference = [];
48
        foreach ($array1 as $key => $value) {
49
            if (is_array($value)) {
50
                if (!isset($array2[$key]) || !is_array($array2[$key])) {
51
                    $difference[$key] = $value;
52
                } else {
53
                    $workingDiff = $this->arrayDiffAssocRecursive($value, $array2[$key]);
54
                    if (!empty($workingDiff)) {
55
                        $difference[$key] = $workingDiff;
56
                    }
57
                }
58
            } elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
59
                $difference[$key] = $value;
60
            }
61
        }
62
        return $difference;
63
    }
64
65
    private function buildArrayForCurlInterogation($chanel)
66
    {
67
        if (curl_errno($chanel)) {
68
            return [
69
                'info'     => $this->setArrayToJson(['#' => curl_errno($chanel), 'description' => curl_error($chanel)]),
70
                'response' => '',
71
            ];
72
        }
73
        return [
74
            'info'     => $this->setArrayToJson(curl_getinfo($chanel)),
75
            'response' => $rspJsonFromClient,
0 ignored issues
show
Bug introduced by
The variable $rspJsonFromClient does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
76
        ];
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 getContentFromUrlThroughCurl($fullURL, $features = null)
87
    {
88
        if (!function_exists('curl_init')) {
89
            $aReturn = [
90
                'info'     => $this->lclMsgCmn('i18n_Error_ExtensionNotLoaded'),
91
                'response' => '',
92
            ];
93
            return $this->setArrayToJson($aReturn);
94
        }
95
        if (!filter_var($fullURL, FILTER_VALIDATE_URL)) {
96
            $aReturn = [
97
                'info'     => $this->lclMsgCmn('i18n_Error_GivenUrlIsNotValid'),
98
                'response' => '',
99
            ];
100
            return $this->setArrayToJson($aReturn);
101
        }
102
        $aReturn = $this->getContentFromUrlThroughCurlRawArray($fullURL, $features);
103
        return '{ ' . $this->packIntoJson($aReturn, 'info') . ', ' . $this->packIntoJson($aReturn, 'response') . ' }';
104
    }
105
106
    /**
107
     * Reads the content of a remote file through CURL extension
108
     *
109
     * @param string $fullURL
110
     * @param array $features
111
     * @return blob
112
     */
113
    protected function getContentFromUrlThroughCurlAsArrayIfJson($fullURL, $features = null)
114
    {
115
        $result = $this->setJsonToArray($this->getContentFromUrlThroughCurl($fullURL, $features));
116
        if (is_array($result['info'])) {
117
            ksort($result['info']);
118
        }
119
        if (is_array($result['response'])) {
120
            ksort($result['response']);
121
        }
122
        return $result;
123
    }
124
125
    protected function getContentFromUrlThroughCurlRawArray($fullURL, $features = null)
126
    {
127
        $chanel = curl_init();
128
        curl_setopt($chanel, CURLOPT_USERAGENT, $this->getUserAgentByCommonLib());
129
        if ((strpos($fullURL, 'https') !== false) || (isset($features['forceSSLverification']))) {
130
            curl_setopt($chanel, CURLOPT_SSL_VERIFYHOST, false);
131
            curl_setopt($chanel, CURLOPT_SSL_VERIFYPEER, false);
132
        }
133
        curl_setopt($chanel, CURLOPT_URL, $fullURL);
134
        curl_setopt($chanel, CURLOPT_HEADER, false);
135
        curl_setopt($chanel, CURLOPT_RETURNTRANSFER, true);
136
        curl_setopt($chanel, CURLOPT_FRESH_CONNECT, true); //avoid a cached response
137
        curl_setopt($chanel, CURLOPT_FAILONERROR, true);
138
        $rspJsonFromClient = curl_exec($chanel);
0 ignored issues
show
Unused Code introduced by
$rspJsonFromClient is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
139
        $aReturn           = $this->buildArrayForCurlInterogation($chanel);
140
        curl_close($chanel);
141
        return $aReturn;
142
    }
143
144
    protected function getFeedbackMySQLAffectedRecords()
145
    {
146
        if (is_null($this->mySQLconnection)) {
147
            $message = 'No MySQL';
148
        } else {
149
            $afRows  = $this->mySQLconnection->affected_rows;
150
            $message = sprintf($this->lclMsgCmnNumber('i18n_Record', 'i18n_Records', $afRows), $afRows);
151
        }
152
        return '<div>' . $message . '</div>';
153
    }
154
155
    /**
156
     * returns the details about Communicator (current) file
157
     *
158
     * @param string $fileGiven
159
     * @return array
160
     */
161
    protected function getFileDetails($fileGiven)
162
    {
163
        if (!file_exists($fileGiven)) {
164
            return ['error' => sprintf($this->lclMsgCmn('i18n_Error_GivenFileDoesNotExist'), $fileGiven)];
165
        }
166
        $info = new \SplFileInfo($fileGiven);
167
        return [
168
            'File Extension'         => $info->getExtension(),
169
            'File Group'             => $info->getGroup(),
170
            'File Inode'             => $info->getInode(),
171
            'File Link Target'       => ($info->isLink() ? $info->getLinkTarget() : '-'),
172
            'File is Dir'            => $info->isDir(),
173
            'File is Executable'     => $info->isExecutable(),
174
            'File is File'           => $info->isFile(),
175
            'File is Link'           => $info->isLink(),
176
            'File is Readable'       => $info->isReadable(),
177
            'File is Writable'       => $info->isWritable(),
178
            'File Name'              => $info->getBasename('.' . $info->getExtension()),
179
            'File Name w. Extension' => $info->getFilename(),
180
            'File Owner'             => $info->getOwner(),
181
            'File Path'              => $info->getPath(),
182
            'File Permissions'       => $this->explainPerms($info->getPerms()),
183
            'Name'                   => $info->getRealPath(),
184
            'Size'                   => $info->getSize(),
185
            'Sha1'                   => sha1_file($fileGiven),
186
            'Timestamp Accessed'     => [
187
                'PHP number' => $info->getATime(),
188
                'SQL format' => date('Y-m-d H:i:s', $info->getATime()),
189
            ],
190
            'Timestamp Changed'      => [
191
                'PHP number' => $info->getCTime(),
192
                'SQL format' => date('Y-m-d H:i:s', $info->getCTime()),
193
            ],
194
            'Timestamp Modified'     => [
195
                'PHP number' => $info->getMTime(),
196
                'SQL format' => date('Y-m-d H:i:s', $info->getMTime()),
197
            ],
198
            'Type'                   => $info->getType(),
199
        ];
200
    }
201
202
    /**
203
     * returns a multi-dimensional array with list of file details within a given path
204
     * (by using Symfony/Finder package)
205
     *
206
     * @param  string $pathAnalised
207
     * @return array
208
     */
209
    protected function getListOfFiles($pathAnalised)
210
    {
211
        if (realpath($pathAnalised) === false) {
212
            return ['error' => sprintf($this->lclMsgCmn('i18n_Error_GivenPathIsNotValid'), $pathAnalised)];
213
        } elseif (!is_dir($pathAnalised)) {
214
            return ['error' => $this->lclMsgCmn('i18n_Error_GivenPathIsNotFolder')];
215
        }
216
        $aFiles   = null;
217
        $finder   = new \Symfony\Component\Finder\Finder();
218
        $iterator = $finder->files()->sortByName()->in($pathAnalised);
219
        foreach ($iterator as $file) {
220
            $aFiles[$file->getRealPath()] = $this->getFileDetails($file);
221
        }
222
        return $aFiles;
223
    }
224
225
    /**
226
     * Returns server Timestamp into various formats
227
     *
228
     * @param string $returnType
229
     * @return string
230
     */
231
    protected function getTimestamp($returnType = 'string')
232
    {
233
        $crtTime          = gettimeofday();
234
        $knownReturnTypes = ['array', 'float', 'string'];
235
        if (in_array($returnType, $knownReturnTypes)) {
236
            return call_user_func([$this, 'getTimestamp' . ucfirst($returnType)], $crtTime);
237
        }
238
        return sprintf($this->lclMsgCmn('i18n_Error_UnknownReturnType'), $returnType);
239
    }
240
241
    private function getTimestampArray($crtTime)
242
    {
243
        return [
244
            'float'  => $this->getTimestampFloat($crtTime),
245
            'string' => $this->getTimestampString($crtTime),
246
        ];
247
    }
248
249
    private function getTimestampFloat($crtTime)
250
    {
251
        return ($crtTime['sec'] + $crtTime['usec'] / pow(10, 6));
252
    }
253
254
    private function getTimestampString($crtTime)
255
    {
256
        return implode('', [
257
            '<span style="color:black!important;font-weight:bold;">[',
258
            date('Y-m-d H:i:s.', $crtTime['sec']),
259
            substr(round($crtTime['usec'], -3), 0, 3),
260
            ']</span> '
261
        ]);
262
    }
263
264
    /**
265
     * Tests if given string has a valid Json format
266
     *
267
     * @param string $inputJson
268
     * @return boolean|string
269
     */
270
    protected function isJsonByDanielGP($inputJson)
271
    {
272
        if (is_string($inputJson)) {
273
            json_decode($inputJson);
274
            return (json_last_error() == JSON_ERROR_NONE);
275
        }
276
        return $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson');
277
    }
278
279
    private function packIntoJson($aReturn, $keyToWorkWith)
280
    {
281
        if ($this->isJsonByDanielGP($aReturn[$keyToWorkWith])) {
282
            return '"' . $keyToWorkWith . '": ' . $aReturn[$keyToWorkWith];
283
        }
284
        return '"' . $keyToWorkWith . '": {' . $aReturn[$keyToWorkWith] . ' }';
285
    }
286
287
    /**
288
     * Send an array of parameters like a form through a POST action
289
     *
290
     * @param string $urlToSendTo
291
     * @param array $params
292
     * @throws \Exception
293
     * @throws \UnexpectedValueException
294
     */
295
    protected function sendBackgroundEncodedFormElementsByPost($urlToSendTo, $params = [])
296
    {
297
        try {
298
            $postingUrl = filter_var($urlToSendTo, FILTER_VALIDATE_URL);
299
            if ($postingUrl === false) {
300
                throw new \Exception($exc);
301
            } else {
302
                if (is_array($params)) {
303
                    $postingString = $this->setArrayToStringForUrl('&', $params);
304
                    $pUrlParts     = parse_url($postingUrl);
305
                    $postingPort   = (isset($pUrlParts['port']) ? $pUrlParts['port'] : 80);
306
                    $flPointer     = fsockopen($pUrlParts['host'], $postingPort, $errNo, $errorMessage, 30);
307
                    if ($flPointer === false) {
308
                        throw new \UnexpectedValueException($this->lclMsgCmn('i18n_Error_FailedToConnect') . ': '
309
                        . $errNo . ' (' . $errorMessage . ')');
310
                    } else {
311
                        fwrite($flPointer, $this->sendBackgroundPrepareData($pUrlParts, $postingString));
312
                        fclose($flPointer);
313
                    }
314
                } else {
315
                    throw new \UnexpectedValueException($this->lclMsgCmn('i18n_Error_GivenParameterIsNotAnArray'));
316
                }
317
            }
318
        } catch (\Exception $exc) {
319
            echo '<pre style="color:#f00">' . $exc->getTraceAsString() . '</pre>';
320
        }
321
    }
322
323
    protected function sendBackgroundPrepareData($pUrlParts, $postingString)
324
    {
325
        $this->initializeSprGlbAndSession();
326
        $out   = [];
327
        $out[] = 'POST ' . $pUrlParts['path'] . ' ' . $this->tCmnSuperGlobals->server->get['SERVER_PROTOCOL'];
328
        $out[] = 'Host: ' . $pUrlParts['host'];
329
        if (is_null($this->tCmnSuperGlobals->server->get('HTTP_USER_AGENT'))) {
330
            $out[] = 'User-Agent: ' . $this->tCmnSuperGlobals->server->get('HTTP_USER_AGENT');
331
        }
332
        $out[] = 'Content-Type: application/x-www-form-urlencoded';
333
        $out[] = 'Content-Length: ' . strlen($postingString);
334
        $out[] = 'Connection: Close' . "\r\n";
335
        $out[] = $postingString;
336
        return implode("\r\n", $out);
337
    }
338
339
    /**
340
     * Returns proper result from a mathematical division in order to avoid Zero division erorr or Infinite results
341
     *
342
     * @param float $fAbove
343
     * @param float $fBelow
344
     * @param mixed $mArguments
345
     * @return decimal
346
     */
347
    protected function setDividedResult($fAbove, $fBelow, $mArguments = 0)
348
    {
349
        if (($fAbove == 0) || ($fBelow == 0)) { // prevent infinite result AND division by 0
350
            return 0;
351
        }
352
        if (is_array($mArguments)) {
353
            $frMinMax = [
354
                'MinFractionDigits' => $mArguments[1],
355
                'MaxFractionDigits' => $mArguments[1],
356
            ];
357
            return $this->setNumberFormat(($fAbove / $fBelow), $frMinMax);
358
        }
359
        return $this->setNumberFormat(round(($fAbove / $fBelow), $mArguments));
360
    }
361
362
    /**
363
     * Converts a JSON string into an Array
364
     *
365
     * @param string $inputJson
366
     * @return array
367
     */
368
    protected function setJsonToArray($inputJson)
369
    {
370
        if (!$this->isJsonByDanielGP($inputJson)) {
371
            return ['error' => $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson')];
372
        }
373
        $sReturn   = (json_decode($inputJson, true));
374
        $jsonError = $this->setJsonErrorInPlainEnglish();
375
        if (is_null($jsonError)) {
376
            return $sReturn;
377
        } else {
378
            return ['error' => $jsonError];
379
        }
380
    }
381
}
382