Browse Source

Add existence check url https detection

mscherer 2 years ago
parent
commit
fb59506dcc

+ 0 - 68
src/Utility/GitterLog.php

@@ -1,68 +0,0 @@
-<?php
-
-namespace Tools\Utility;
-
-use Cake\Core\Configure;
-use Cake\Http\Client;
-use InvalidArgumentException;
-use Psr\Log\LogLevel;
-
-/**
- * Wrapper class to log data into Gitter API.
- *
- * e.g simple post: curl -d message=hello your_url
- * e.g error levels: curl -d message=oops -d level=error your_url
- * e.g markdown: curl --data-urlencode "message=_markdown_ is fun" your_url
- *
- * Uses {@link \Cake\Http\Client} to make the API call.
- */
-class GitterLog {
-
-	/**
-	 * @var string
-	 */
-	protected const URL = 'https://webhooks.gitter.im/e/%s';
-
-	/**
-	 * @param string $message
-	 * @param string|null $level
-	 *
-	 * @return void
-	 */
-	public function write(string $message, ?string $level = null): void {
-		$url = sprintf(static::URL, Configure::readOrFail('Gitter.key'));
-
-		$data = [
-			'message' => $message,
-		];
-		if ($level !== null) {
-			$levelString = $this->levelString($level);
-			$data['level'] = $levelString;
-		}
-
-		$options = [];
-		$client = $this->getClient();
-		$client->post($url, $data, $options);
-	}
-
-	/**
-	 * @return \Cake\Http\Client
-	 */
-	protected function getClient(): Client {
-		return new Client();
-	}
-
-	/**
-	 * @param string $level
-	 *
-	 * @return string
-	 */
-	protected function levelString(string $level): string {
-		if (!in_array($level, [LogLevel::ERROR, LogLevel::INFO], true)) {
-			throw new InvalidArgumentException('Only levels `info` and `error`are allowed.');
-		}
-
-		return $level;
-	}
-
-}

+ 36 - 9
src/Utility/Utility.php

@@ -2,6 +2,7 @@
 
 namespace Tools\Utility;
 
+use Cake\Core\Configure;
 use Cake\Log\Log;
 use Cake\Routing\Router;
 use Cake\Utility\Hash;
@@ -193,18 +194,18 @@ class Utility {
 	}
 
 	/**
-	 * Remove unnessary stuff + add http:// for external urls
-	 * TODO: protocol to lower!
+	 * Remove unnecessary stuff + add http:// for external urls
 	 *
 	 * @param string $url
 	 * @param bool $headerRedirect
+	 * @param bool|null $detectHttps
 	 * @return string Cleaned Url
 	 */
-	public static function cleanUrl($url, $headerRedirect = false) {
+	public static function cleanUrl($url, $headerRedirect = false, $detectHttps = null) {
 		if ($url === '' || $url === 'http://' || $url === 'http://www' || $url === 'http://www.') {
 			$url = '';
 		} else {
-			$url = static::autoPrefixUrl($url, 'http://');
+			$url = static::autoPrefixUrl($url, 'http://', $detectHttps);
 		}
 
 		if ($headerRedirect && !empty($url)) {
@@ -274,10 +275,27 @@ class Utility {
 	 * So if you check on strpos(http) === 0 you can use this
 	 * to check for URLs instead.
 	 *
-	 * @param string $url Absolute URL
+	 * @param string $url Absolute URL.
+	 * @param array $statusCodes List of accepted status codes. Defaults to 200 OK.
 	 * @return bool Success
 	 */
-	public static function urlExists($url) {
+	public static function urlExists($url, array $statusCodes = []) {
+		if (function_exists('curl_init')) {
+			$curl = curl_init($url);
+			curl_setopt($curl, CURLOPT_NOBODY, true);
+			$result = curl_exec($curl);
+			if ($result === false) {
+				return false;
+			}
+
+			$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
+			if ($statusCodes === []) {
+				$statusCodes = [200];
+			}
+
+			return in_array($statusCode, $statusCodes, true);
+		}
+
 		// @codingStandardsIgnoreStart
 		$headers = @get_headers($url);
 		// @codingStandardsIgnoreEnd
@@ -344,21 +362,30 @@ class Utility {
 	 *
 	 * @param string $url
 	 * @param string|null $prefix
+	 * @param bool|null $detectHttps
 	 * @return string
 	 */
-	public static function autoPrefixUrl($url, $prefix = null) {
+	public static function autoPrefixUrl($url, $prefix = null, $detectHttps = null) {
 		if ($prefix === null) {
 			$prefix = 'http://';
 		}
 
+		$modifiedUrl = $url;
 		$pos = strpos($url, '.');
 		if ($pos !== false) {
 			if (strpos(substr($url, 0, $pos), '//') === false) {
-				$url = $prefix . $url;
+				$modifiedUrl = $prefix . $url;
+			}
+
+			if ($detectHttps === null) {
+				$detectHttps = !Configure::read('debug');
+			}
+			if ($prefix === 'http://' && $detectHttps && static::urlExists('https://' . $url)) {
+				$modifiedUrl = 'https://' . $url;
 			}
 		}
 
-		return $url;
+		return $modifiedUrl;
 	}
 
 	/**

+ 0 - 55
tests/TestCase/Utility/GitterLogTest.php

@@ -1,55 +0,0 @@
-<?php
-
-namespace Tools\Test\TestCase\Utility;
-
-use Cake\Core\Configure;
-use Cake\Http\Client;
-use Cake\Http\Client\Request;
-use Psr\Log\LogLevel;
-use Shim\TestSuite\TestCase;
-use Tools\Utility\GitterLog;
-
-/**
- * GitterLogTest class
- */
-class GitterLogTest extends TestCase {
-
-	/**
-	 * @return void
-	 */
-	public function setUp(): void {
-		parent::setUp();
-
-		$key = env('GITTER_KEY') ?: '123';
-		Configure::write('Gitter.key', $key);
-	}
-
-	/**
-	 * @return void
-	 */
-	public function tearDown(): void {
-		parent::tearDown();
-
-		Configure::delete('Gitter.key');
-	}
-
-	/**
-	 * testLogsIntoDefaultFile method
-	 *
-	 * @return void
-	 */
-	public function testLogsIntoDefaultFile(): void {
-		$mockClient = $this->getMockBuilder(Client::class)->onlyMethods(['send'])->getMock();
-
-		$callback = function(Request $value) {
-			return (string)$value->getBody() === 'message=Test%3A+It+%2Aworks%2A+with+some+error+%5Bmarkup%5D%28https%3A%2F%2Fmy-url.com%29%21&level=error';
-		};
-		$mockClient->expects($this->once())->method('send')->with($this->callback($callback));
-
-		$gitterLog = $this->getMockBuilder(GitterLog::class)->onlyMethods(['getClient'])->getMock();
-		$gitterLog->expects($this->once())->method('getClient')->willReturn($mockClient);
-
-		$gitterLog->write('Test: It *works* with some error [markup](https://my-url.com)!', LogLevel::ERROR);
-	}
-
-}

+ 9 - 0
tests/TestCase/Utility/UtilityTest.php

@@ -264,6 +264,15 @@ class UtilityTest extends TestCase {
 	}
 
 	/**
+	 * @covers ::autoPrefixUrl
+	 * @return void
+	 */
+	public function testAutoPrefixUrlWithDetection() {
+		$res = Utility::autoPrefixUrl('www.spiegel.de', null, true);
+		$this->assertSame('https://www.spiegel.de', $res);
+	}
+
+	/**
 	 * @covers ::cleanUrl
 	 * @return void
 	 */