Skip to content

Commit 2fc9201

Browse files
committed
Separate out requests code.
Changelog excerpt: - Separated the code for performing outbound requests through cURL out to its own independent class.
1 parent 811e4c0 commit 2fc9201

File tree

4 files changed

+35
-208
lines changed

4 files changed

+35
-208
lines changed

Changelog.md

+4
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,7 @@ __*Why "v3.0.0" instead of "v1.0.0?"*__ Prior to phpMussel v3, the "phpMussel Co
3131
[2020.11.27; Maikuolan]: Some minor code-style cleanup.
3232

3333
[2020.12.04; Maikuolan]: Maintenance release (dependencies update, repository cleanup, etc).
34+
35+
### v3.1.1
36+
37+
[2021.01.10; Maikuolan]: Separated the code for performing outbound requests through cURL out to its own independent class.

README.md

+7-7
Original file line numberDiff line numberDiff line change
@@ -56,17 +56,17 @@ composer require phpmussel/core
5656

5757
### Current major version development status:
5858

59-
⬇Stage reached⬇ ➡Major version➡ | v0 | v1 | v2 | v3
60-
:--|:-:|:-:|:-:|:-:
61-
Pre-Alpha<em><br />- Exploring early concepts/ideas. No code written/available yet.</em> | ✔ | ✔ | ✔ | ✔
62-
Alpha<em><br />- Branched, but unstable. Not production-ready (high risk if used).</em> | ✔ | ✔ | ✔ | ✔
63-
Beta<em><br />- Branched, but unstable. Not production-ready (low risk if used).</em> | ✔ | ✔ | ✔ | ✔
64-
Stable<em><br />- First production-ready version has been tagged/released.</em> | ✔ | ✔ | ✔ | ✔
59+
⬇Stage reached⬇ ➡Major version➡ | v0 | v1 | v2~v3
60+
:--|:-:|:-:|:-:
61+
Pre-Alpha<em><br />- Exploring early concepts/ideas. No code written/available yet.</em> | ✔ | ✔ | ✔
62+
Alpha<em><br />- Branched, but unstable. Not production-ready (high risk if used).</em> | ✔ | ✔ | ✔
63+
Beta<em><br />- Branched, but unstable. Not production-ready (low risk if used).</em> | ✔ | ✔ | ✔
64+
Stable<em><br />- First production-ready version has been tagged/released.</em> | ✔ | ✔ | ✔
6565
Mature<em><br />- Multiple stable versions/releases exist.</em> | ✔ | ✔ | ✔
6666
Locked<em><br />- Still maintained, but new features won't be implemented anymore.</em> | ✔ | ✔
6767
EoL/Dead<em><br />- Not maintained anymore. If possible, stop using, and update ASAP.</em> | ✔
6868

6969
---
7070

7171

72-
Last Updated: 16 October 2020 (2020.10.16).
72+
Last Updated: 12 December 2020 (2020.12.12).

src/Loader.php

+20-197
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* License: GNU/GPLv2
99
* @see LICENSE.txt
1010
*
11-
* This file: The loader (last modified: 2020.11.27).
11+
* This file: The loader (last modified: 2021.01.10).
1212
*/
1313

1414
namespace phpMussel\Core;
@@ -60,6 +60,11 @@ class Loader
6060
*/
6161
public $Events;
6262

63+
/**
64+
* @var \Maikuolan\Common\Request An object for sending cURL requests.
65+
*/
66+
public $Request;
67+
6368
/**
6469
* @var \Maikuolan\Common\L10N An object for handling configuration-defined L10N data.
6570
*/
@@ -83,7 +88,7 @@ class Loader
8388
/**
8489
* @var string phpMussel version number (SemVer).
8590
*/
86-
public $ScriptVersion = '3.1.0';
91+
public $ScriptVersion = '3.1.1';
8792

8893
/**
8994
* @var string phpMussel version identifier (complete notation).
@@ -138,11 +143,6 @@ class Loader
138143
*/
139144
public $HashReference = '';
140145

141-
/**
142-
* @var bool Set as true at the implementation to enable debug messages.
143-
*/
144-
public $EnableDebugMessages = false;
145-
146146
/**
147147
* @var int Populated by the request method.
148148
*/
@@ -158,11 +158,6 @@ class Loader
158158
*/
159159
private $L10NPath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'l10n' . DIRECTORY_SEPARATOR;
160160

161-
/**
162-
* @var int The default timeout for request.
163-
*/
164-
private $Timeout = 12;
165-
166161
/**
167162
* @var array Channels information for request.
168163
*/
@@ -331,8 +326,16 @@ public function __construct(
331326
date_default_timezone_set($this->Configuration['core']['timezone']);
332327
}
333328

334-
/** Calculate instantiation time. */
335-
$this->Time = time() + ($this->Configuration['core']['time_offset'] * 60);
329+
/** Instantiate request class. */
330+
$this->Request = new \Maikuolan\Common\Request();
331+
$this->Request->Channels = (
332+
$Channels = $this->readFileBlocks($this->AssetsPath . 'channels.yaml')
333+
) ? (new \Maikuolan\Common\YAML($Channels))->Data : [];
334+
if (!isset($this->Request->Channels['Triggers'])) {
335+
$this->Request->Channels['Triggers'] = [];
336+
}
337+
$this->Request->Disabled = $this->Configuration['core']['disabled_channels'];
338+
$this->Request->UserAgent = $this->ScriptUA;
336339

337340
/** If the language directive is empty, default to English. */
338341
if (empty($this->Configuration['core']['lang'])) {
@@ -342,6 +345,9 @@ public function __construct(
342345
/** Load phpMussel core L10N data. */
343346
$this->loadL10N($this->L10NPath);
344347

348+
/** Calculate instantiation time. */
349+
$this->Time = time() + ($this->Configuration['core']['time_offset'] * 60);
350+
345351
/** Initialise the cache. */
346352
$this->initialiseCache();
347353

@@ -908,148 +914,6 @@ public function readFileAsArray(string $Filename, int $Flags = 0, $Context = nul
908914
return is_array($Output) ? $Output : [];
909915
}
910916

911-
/**
912-
* Used to send cURL requests.
913-
*
914-
* @param string $URI The resource to request.
915-
* @param mixed $Params If empty or omitted, CURLOPT_POST is false. Otherwise,
916-
* CURLOPT_POST is true, and the parameter is used to supply
917-
* CURLOPT_POSTFIELDS. Normally an associative array of key-value pairs,
918-
* but can be any kind of value supported by CURLOPT_POSTFIELDS. Optional.
919-
* @param int $Timeout An optional timeout limit.
920-
* @param array $Headers An optional array of headers to send with the request.
921-
* @param int $Depth Recursion depth of the current closure instance.
922-
* @return string The results of the request, or an empty string upon failure.
923-
*/
924-
public function request(string $URI, $Params = [], int $Timeout = -1, array $Headers = [], int $Depth = 0): string
925-
{
926-
/** Fetch channel information. */
927-
if (empty($this->Channels)) {
928-
$this->Channels = (
929-
$Channels = $this->readFileBlocks($this->AssetsPath . 'channels.yaml')
930-
) ? (new \Maikuolan\Common\YAML($Channels))->Data : [];
931-
if (!isset($this->Channels['Triggers'])) {
932-
$this->Channels['Triggers'] = [];
933-
}
934-
}
935-
936-
/** Test channel triggers. */
937-
foreach ($this->Channels['Triggers'] as $TriggerName => $TriggerURI) {
938-
if (
939-
!isset($this->Channels[$TriggerName]) ||
940-
!is_array($this->Channels[$TriggerName]) ||
941-
substr($URI, 0, strlen($TriggerURI)) !== $TriggerURI
942-
) {
943-
continue;
944-
}
945-
foreach ($this->Channels[$TriggerName] as $Channel => $Options) {
946-
if (!is_array($Options) || !isset($Options[$TriggerName])) {
947-
continue;
948-
}
949-
$Len = strlen($Options[$TriggerName]);
950-
if (substr($URI, 0, $Len) !== $Options[$TriggerName]) {
951-
continue;
952-
}
953-
unset($Options[$TriggerName]);
954-
if (empty($Options) || $this->inCsv(key($Options), $this->Configuration['core']['disabled_channels'])) {
955-
continue;
956-
}
957-
$AlternateURI = current($Options) . substr($URI, $Len);
958-
break;
959-
}
960-
if ($this->inCsv($TriggerName, $this->Configuration['core']['disabled_channels'])) {
961-
if (isset($AlternateURI)) {
962-
return $this->request($AlternateURI, $Params, $Timeout, $Headers, $Depth);
963-
}
964-
return '';
965-
}
966-
if (isset($this->Channels['Overrides'], $this->Channels['Overrides'][$TriggerName])) {
967-
$Overrides = $this->Channels['cURL Overrides'][$TriggerName];
968-
}
969-
break;
970-
}
971-
972-
/** Empty overrides in case none declared. */
973-
$Overrides = [];
974-
975-
/** Initialise the cURL session. */
976-
$Request = curl_init($URI);
977-
978-
$LCURI = strtolower($URI);
979-
$SSL = (substr($LCURI, 0, 6) === 'https:');
980-
981-
curl_setopt($Request, CURLOPT_FRESH_CONNECT, true);
982-
curl_setopt($Request, CURLOPT_HEADER, false);
983-
if (empty($Params)) {
984-
curl_setopt($Request, CURLOPT_POST, false);
985-
$Post = false;
986-
} else {
987-
curl_setopt($Request, CURLOPT_POST, true);
988-
curl_setopt($Request, CURLOPT_POSTFIELDS, $Params);
989-
$Post = true;
990-
}
991-
if ($SSL) {
992-
curl_setopt($Request, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
993-
curl_setopt($Request, CURLOPT_SSL_VERIFYPEER, (
994-
isset($Overrides['CURLOPT_SSL_VERIFYPEER']) ? !empty($Overrides['CURLOPT_SSL_VERIFYPEER']) : false
995-
));
996-
}
997-
curl_setopt($Request, CURLOPT_FOLLOWLOCATION, true);
998-
curl_setopt($Request, CURLOPT_MAXREDIRS, 1);
999-
curl_setopt($Request, CURLOPT_RETURNTRANSFER, true);
1000-
curl_setopt($Request, CURLOPT_TIMEOUT, ($Timeout > 0 ? $Timeout : $this->Timeout));
1001-
curl_setopt($Request, CURLOPT_USERAGENT, $this->ScriptUA);
1002-
curl_setopt($Request, CURLOPT_HTTPHEADER, $Headers ?: []);
1003-
$Time = microtime(true);
1004-
1005-
/** Execute and get the response. */
1006-
$Response = curl_exec($Request);
1007-
1008-
/** Used for debugging. */
1009-
$Time = microtime(true) - $Time;
1010-
1011-
/** Check for problems (e.g., resource not found, server errors, etc). */
1012-
if (($Info = curl_getinfo($Request)) && is_array($Info) && isset($Info['http_code'])) {
1013-
1014-
/** Used for debugging. */
1015-
$this->debugMessage(sprintf(
1016-
"\r%s - %s - %s - %s\n",
1017-
$Post ? 'POST' : 'GET',
1018-
$URI,
1019-
$Info['http_code'],
1020-
(floor($Time * 100) / 100) . 's'
1021-
));
1022-
1023-
/** Most recent HTTP code flag. */
1024-
$this->MostRecentHttpCode = $Info['http_code'];
1025-
1026-
/** Request failed. Try again using an alternative address. */
1027-
if ($Info['http_code'] >= 400 && isset($AlternateURI) && $Depth < 3) {
1028-
curl_close($Request);
1029-
return $this->request($AlternateURI, $Params, $Timeout, $Headers, $Depth + 1);
1030-
}
1031-
} else {
1032-
1033-
/** Used for debugging. */
1034-
$this->debugMessage(sprintf(
1035-
"\r%s - %s - %s - %s\n",
1036-
$Post ? 'POST' : 'GET',
1037-
$URI,
1038-
200,
1039-
(floor($Time * 100) / 100) . 's'
1040-
));
1041-
1042-
/** Most recent HTTP code flag. */
1043-
$this->MostRecentHttpCode = 200;
1044-
}
1045-
1046-
/** Close the cURL session. */
1047-
curl_close($Request);
1048-
1049-
/** Return the results of the request. */
1050-
return $Response;
1051-
}
1052-
1053917
/**
1054918
* A simple safety wrapper for unpack.
1055919
*
@@ -1274,47 +1138,6 @@ private function initialiseCache()
12741138
}
12751139
}
12761140

1277-
/**
1278-
* Checks for a value within CSV.
1279-
*
1280-
* @param string $Value The value to look for.
1281-
* @param string $CSV The CSV to look in.
1282-
* @return bool True when found; False when not found.
1283-
*/
1284-
public function inCsv(string $Value, string $CSV): bool
1285-
{
1286-
if (!$Value || !$CSV) {
1287-
return false;
1288-
}
1289-
$Arr = explode(',', $CSV);
1290-
if (strpos($CSV, '"') !== false) {
1291-
foreach ($Arr as &$Item) {
1292-
if (substr($Item, 0, 1) === '"' && substr($Item, -1) === '"') {
1293-
$Item = substr($Item, 1, -1);
1294-
}
1295-
}
1296-
}
1297-
return in_array($Value, $Arr, true);
1298-
}
1299-
1300-
/**
1301-
* Prints debug messages (used in dev; not needed for production).
1302-
*
1303-
* @param string $Message The debug message to send.
1304-
*/
1305-
public function debugMessage(string $Message)
1306-
{
1307-
if ($this->EnableDebugMessages !== true) {
1308-
return;
1309-
}
1310-
$Handle = fopen('php://stdout', 'wb');
1311-
if (!is_resource($Handle)) {
1312-
return;
1313-
}
1314-
fwrite($Handle, $Message);
1315-
fclose($Handle);
1316-
}
1317-
13181141
/**
13191142
* Fetch favicon.
13201143
*

src/Scanner.php

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* License: GNU/GPLv2
99
* @see LICENSE.txt
1010
*
11-
* This file: The scanner (last modified: 2020.11.27).
11+
* This file: The scanner (last modified: 2021.01.10).
1212
*/
1313

1414
namespace phpMussel\Core;
@@ -2232,7 +2232,7 @@ private function dataHandler(string $str = '', int $Depth = 0, string $OriginalF
22322232
'apikey' => $this->Loader->Configuration['virustotal']['vt_public_api_key'],
22332233
'resource' => $md5
22342234
];
2235-
$VTRequest = $this->Loader->request(
2235+
$VTRequest = $this->Loader->Request->request(
22362236
'https://www.virustotal.com/vtapi/v2/file/report?apikey=' .
22372237
urlencode($this->Loader->Configuration['virustotal']['vt_public_api_key']) .
22382238
'&resource=' . $md5,
@@ -3501,10 +3501,10 @@ private function safeBrowseLookup(array $URLs, array $URLsNoLookup = [], array $
35013501
}
35023502

35033503
/** Perform lookup. */
3504-
$Response = $this->Loader->request(
3504+
$Response = $this->Loader->Request->request(
35053505
'https://safebrowsing.googleapis.com/v4/threatMatches:find?key=' . $this->Loader->Configuration['urlscanner']['google_api_key'],
35063506
$Arr,
3507-
$this->Loader->Timeout,
3507+
$this->Loader->Request->Timeout,
35083508
['Content-type: application/json']
35093509
);
35103510
$this->Loader->InstanceCache['LookupCount']++;

0 commit comments

Comments
 (0)