Passed
Push — develop ( 339f21...34e8b6 )
by Pieter van der
14:45
created
library/tiqr/Tiqr/OcraService/OathServiceClient.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@
 block discarded – undo
81 81
                     'verifyResponse for user "%s" failed',
82 82
                     $userId
83 83
                 ),
84
-                array( 'exception' => $e)
84
+                array('exception' => $e)
85 85
             );
86 86
             return false;
87 87
         }
Please login to merge, or discard this patch.
library/tiqr/Tiqr/Random.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@
 block discarded – undo
42 42
     public static function randomBytes(int $length): string
43 43
     {
44 44
         // Get $length cryptographically secure pseudo-random bytes
45
-        $rnd=\random_bytes($length);
45
+        $rnd = \random_bytes($length);
46 46
 
47 47
         if (strlen($rnd) !== $length) {
48 48
             throw new Exception("random_bytes did not return the requested number of bytes");
Please login to merge, or discard this patch.
library/tiqr/Tiqr/Exception/ReadWriteException.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -22,6 +22,6 @@
 block discarded – undo
22 22
     {
23 23
         // $code must be int, otherwise this throws with Error("Wrong parameters for ReadWriteException")
24 24
         // PDOException::getCode() can return a sting
25
-        return new self($e->getMessage(), (int)$e->getCode(), $e );
25
+        return new self($e->getMessage(), (int) $e->getCode(), $e);
26 26
     }
27 27
 }
Please login to merge, or discard this patch.
library/tiqr/Tiqr/Service.php 3 patches
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -571,17 +571,17 @@  discard block
 block discarded – undo
571 571
         }
572 572
 
573 573
         $metadata = array("service"=>
574
-                               array("displayName"       => $this->_name,
575
-                                     "identifier"        => $this->_identifier,
576
-                                     "logoUrl"           => $this->_logoUrl,
577
-                                     "infoUrl"           => $this->_infoUrl,
578
-                                     "authenticationUrl" => $authenticationUrl,
579
-                                     "ocraSuite"         => $this->_ocraSuite,
580
-                                     "enrollmentUrl"     => $enrollmentUrl
581
-                               ),
582
-                          "identity"=>
583
-                               array("identifier" =>$data["userId"],
584
-                                     "displayName"=>$data["displayName"]));
574
+                                array("displayName"       => $this->_name,
575
+                                        "identifier"        => $this->_identifier,
576
+                                        "logoUrl"           => $this->_logoUrl,
577
+                                        "infoUrl"           => $this->_infoUrl,
578
+                                        "authenticationUrl" => $authenticationUrl,
579
+                                        "ocraSuite"         => $this->_ocraSuite,
580
+                                        "enrollmentUrl"     => $enrollmentUrl
581
+                                ),
582
+                            "identity"=>
583
+                                array("identifier" =>$data["userId"],
584
+                                        "displayName"=>$data["displayName"]));
585 585
 
586 586
         $this->_unsetStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
587 587
 
@@ -611,28 +611,28 @@  discard block
 block discarded – undo
611 611
      */
612 612
     public function getEnrollmentSecret(string $enrollmentKey): string
613 613
     {
614
-         $data = $this->_getStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
615
-         if (!is_array($data)) {
616
-             $this->logger->error('getEnrollmentSecret: enrollment key not found');
617
-             throw new RuntimeException('enrollment key not found');
618
-         }
619
-         $userId = $data["userId"] ?? NULL;
620
-         $sessionId = $data["sessionId"] ?? NULL;
621
-         if (!is_string($userId) || !(is_string($sessionId))) {
622
-             throw new RuntimeException('getEnrollmentSecret: invalid enrollment data');
623
-         }
624
-         $enrollmentData = [
625
-             "userId" => $userId,
626
-             "sessionId" => $sessionId
627
-         ];
628
-         $enrollmentSecret = $this->_uniqueSessionKey();
629
-         $this->_setStateValue(
630
-             self::PREFIX_ENROLLMENT_SECRET,
631
-             $enrollmentSecret,
632
-             $enrollmentData,
633
-             self::ENROLLMENT_EXPIRE
634
-         );
635
-         return $enrollmentSecret;
614
+            $data = $this->_getStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
615
+            if (!is_array($data)) {
616
+                $this->logger->error('getEnrollmentSecret: enrollment key not found');
617
+                throw new RuntimeException('enrollment key not found');
618
+            }
619
+            $userId = $data["userId"] ?? NULL;
620
+            $sessionId = $data["sessionId"] ?? NULL;
621
+            if (!is_string($userId) || !(is_string($sessionId))) {
622
+                throw new RuntimeException('getEnrollmentSecret: invalid enrollment data');
623
+            }
624
+            $enrollmentData = [
625
+                "userId" => $userId,
626
+                "sessionId" => $sessionId
627
+            ];
628
+            $enrollmentSecret = $this->_uniqueSessionKey();
629
+            $this->_setStateValue(
630
+                self::PREFIX_ENROLLMENT_SECRET,
631
+                $enrollmentSecret,
632
+                $enrollmentData,
633
+                self::ENROLLMENT_EXPIRE
634
+            );
635
+            return $enrollmentSecret;
636 636
     }
637 637
 
638 638
     /**
Please login to merge, or discard this patch.
Braces   +8 added lines, -7 removed lines patch added patch discarded remove patch
@@ -287,8 +287,7 @@  discard block
 block discarded – undo
287 287
         if (isset($options['ocraservice']) && $options['ocraservice']['type'] != 'tiqr') {
288 288
             $options['ocraservice']['ocra.suite'] = $this->_ocraSuite;
289 289
             $this->_ocraService = Tiqr_OcraService::getOcraService($options['ocraservice']['type'], $options['ocraservice'], $logger);
290
-        }
291
-        else { // Create default ocraservice
290
+        } else { // Create default ocraservice
292 291
             $this->_ocraService = Tiqr_OcraService::getOcraService('tiqr', array('ocra.suite' => $this->_ocraSuite), $logger);
293 292
         }
294 293
     }
@@ -347,8 +346,9 @@  discard block
 block discarded – undo
347 346
                 case 'APNS':
348 347
                 case 'APNS_DIRECT':
349 348
                     $apns_version = $this->_options['apns.version'] ?? 2;
350
-                    if ($apns_version !=2)
351
-                        throw new InvalidArgumentException("Unsupported APNS version '$apns_version'");
349
+                    if ($apns_version !=2) {
350
+                                            throw new InvalidArgumentException("Unsupported APNS version '$apns_version'");
351
+                    }
352 352
                     $message = new Tiqr_Message_APNS2($this->_options, $this->logger);
353 353
                     break;
354 354
 
@@ -514,7 +514,9 @@  discard block
 block discarded – undo
514 514
             $sessionId = session_id(); 
515 515
         }
516 516
         $status = $this->_getStateValue(self::PREFIX_ENROLLMENT_STATUS, $sessionId);
517
-        if (is_null($status)) return self::ENROLLMENT_STATUS_IDLE;
517
+        if (is_null($status)) {
518
+            return self::ENROLLMENT_STATUS_IDLE;
519
+        }
518 520
         return $status;
519 521
     }
520 522
         
@@ -871,8 +873,7 @@  discard block
 block discarded – undo
871 873
         
872 874
         try {
873 875
             return $this->_getStateValue("authenticated_", $sessionId);
874
-        }
875
-        catch (Exception $e) {
876
+        } catch (Exception $e) {
876 877
             $this->logger->error('getAuthenticatedUser failed', array('exception'=>$e));
877 878
             return NULL;
878 879
         }
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
     // INVALID_USERID: The client authenticated a different user than the server expected. This error is returned when
112 112
     // the application stated an authentication session specifying the userId and later during the authentication
113 113
     // provides a different userId
114
-    const AUTH_RESULT_INVALID_USERID    = 5;
114
+    const AUTH_RESULT_INVALID_USERID = 5;
115 115
     
116 116
     /**
117 117
      * The default OCRA Suite (RFC 6287) to use for authentication in Tiqr
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
      * @param int $version The tiqr protocol version to use (defaults to the latest)
221 221
      * @throws Exception
222 222
      */
223
-    public function __construct(LoggerInterface $logger, array $options=array(), int $version = 2)
223
+    public function __construct(LoggerInterface $logger, array $options = array(), int $version = 2)
224 224
     {
225 225
         $this->_options = $options; // Used to later get settings for Tiqr_Message_*
226 226
         $this->logger = $logger;
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
                 case 'APNS':
343 343
                 case 'APNS_DIRECT':
344 344
                     $apns_version = $this->_options['apns.version'] ?? 2;
345
-                    if ($apns_version !=2)
345
+                    if ($apns_version != 2)
346 346
                         throw new InvalidArgumentException("Unsupported APNS version '$apns_version'");
347 347
                     $message = new Tiqr_Message_APNS2($this->_options, $this->logger);
348 348
                     break;
@@ -361,11 +361,11 @@  discard block
 block discarded – undo
361 361
             // can use this value to stop offering the authentication to the user.
362 362
             // Use CHALLENGE_EXPIRE - 30 seconds as the maximum timeout to send to the client. This gives the user 30 seconds
363 363
             // before the authentication session expires at the server. Never send an authenticationTimeout of less than 30 seconds.
364
-            $authenticationTimeout = max( 30, self::CHALLENGE_EXPIRE - 30);
364
+            $authenticationTimeout = max(30, self::CHALLENGE_EXPIRE - 30);
365 365
 
366 366
             $this->logger->info(sprintf('Creating and sending a %s push notification', $notificationType));
367 367
             $message->setId(time());
368
-            $message->setText("Please authenticate for " . $this->_name);
368
+            $message->setText("Please authenticate for ".$this->_name);
369 369
             $message->setAddress($notificationAddress);
370 370
             $message->setCustomProperty('challenge', $this->_getChallengeUrl($sessionKey));
371 371
             $message->setCustomProperty('authenticationTimeout', $authenticationTimeout);
@@ -422,13 +422,13 @@  discard block
 block discarded – undo
422 422
      * @return string The authentication sessionKey
423 423
      * @throws Exception when starting the authentication session failed
424 424
      */
425
-    public function startAuthenticationSession(string $userId="", string $sessionId="", string $spIdentifier=""): string
425
+    public function startAuthenticationSession(string $userId = "", string $sessionId = "", string $spIdentifier = ""): string
426 426
     {
427
-        if ($sessionId=="") {
427
+        if ($sessionId == "") {
428 428
             $sessionId = session_id();
429 429
         }
430 430
 
431
-        if ($spIdentifier=="") {
431
+        if ($spIdentifier == "") {
432 432
             $spIdentifier = $this->_identifier;
433 433
         }
434 434
 
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
         
438 438
         $data = array("sessionId"=>$sessionId, "challenge"=>$challenge, "spIdentifier" => $spIdentifier);
439 439
         
440
-        if ($userId!="") {
440
+        if ($userId != "") {
441 441
             $data["userId"] = $userId;
442 442
         }
443 443
         
@@ -461,9 +461,9 @@  discard block
 block discarded – undo
461 461
      * @return String The enrollment key
462 462
      * @throws Exception when start the enrollement session failed
463 463
      */
464
-    public function startEnrollmentSession(string $userId, string $displayName, string $sessionId=""): string
464
+    public function startEnrollmentSession(string $userId, string $displayName, string $sessionId = ""): string
465 465
     {
466
-        if ($sessionId=="") {
466
+        if ($sessionId == "") {
467 467
             $sessionId = session_id();
468 468
         }
469 469
         $enrollmentKey = $this->_uniqueSessionKey();
@@ -483,9 +483,9 @@  discard block
 block discarded – undo
483 483
      * @param string $sessionId The application's session identifier (defaults to php session)
484 484
      * @throws Exception when resetting the session failed
485 485
      */
486
-    public function resetEnrollmentSession(string $sessionId=""): void
486
+    public function resetEnrollmentSession(string $sessionId = ""): void
487 487
     {
488
-        if ($sessionId=="") {
488
+        if ($sessionId == "") {
489 489
             $sessionId = session_id();
490 490
         }
491 491
 
@@ -520,9 +520,9 @@  discard block
 block discarded – undo
520 520
      *
521 521
      * @throws Exception when an error communicating with the state storage backend was detected
522 522
      */
523
-    public function getEnrollmentStatus(string $sessionId=""): int
523
+    public function getEnrollmentStatus(string $sessionId = ""): int
524 524
     { 
525
-        if ($sessionId=="") {
525
+        if ($sessionId == "") {
526 526
             $sessionId = session_id(); 
527 527
         }
528 528
         $status = $this->_getStateValue(self::PREFIX_ENROLLMENT_STATUS, $sessionId);
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
             if (NULL === $data) {
697 697
                 throw new RuntimeException('Enrollment secret not found');
698 698
             }
699
-            if ( !is_array($data) || !is_string($data["userId"] ?? NULL)) {
699
+            if (!is_array($data) || !is_string($data["userId"] ?? NULL)) {
700 700
                 throw new RuntimeException('Invalid enrollment data');
701 701
             }
702 702
 
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
                 $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_FINALIZED);
737 737
             } else {
738 738
                 $this->logger->error(
739
-                    'Enrollment status is not finalized, enrollmentsecret was not found in state storage. ' .
739
+                    'Enrollment status is not finalized, enrollmentsecret was not found in state storage. '.
740 740
                     'Warning! the method will still return "true" as a result.'
741 741
                 );
742 742
             }
@@ -805,9 +805,9 @@  discard block
 block discarded – undo
805 805
             throw $e;
806 806
         }
807 807
 
808
-        $sessionId = $state["sessionId"] ?? NULL;   // Application's sessionId
809
-        $challenge = $state["challenge"] ?? NULL;   // The challenge we sent to the Tiqr client
810
-        if (!is_string($sessionId) || (!is_string($challenge)) ) {
808
+        $sessionId = $state["sessionId"] ?? NULL; // Application's sessionId
809
+        $challenge = $state["challenge"] ?? NULL; // The challenge we sent to the Tiqr client
810
+        if (!is_string($sessionId) || (!is_string($challenge))) {
811 811
             throw new RuntimeException('Invalid state for state storage');
812 812
         }
813 813
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
         $challengeUserId = $state["userId"] ?? NULL;
817 817
 
818 818
         // If the application requested a specific userId, verify that that is that userId that we're now authenticating
819
-        if ($challengeUserId!==NULL && ($userId !== $challengeUserId)) {
819
+        if ($challengeUserId !== NULL && ($userId !== $challengeUserId)) {
820 820
             $this->logger->error(
821 821
                 sprintf('Authentication failed: the requested userId "%s" does not match userId "%s" that is being authenticated',
822 822
                 $challengeUserId, $userId)
@@ -864,9 +864,9 @@  discard block
 block discarded – undo
864 864
      *
865 865
      * @throws Exception when there was an error communicating with the storage backed
866 866
      */
867
-    public function logout(string $sessionId=""): void
867
+    public function logout(string $sessionId = ""): void
868 868
     {
869
-        if ($sessionId=="") {
869
+        if ($sessionId == "") {
870 870
             $sessionId = session_id(); 
871 871
         }
872 872
         
@@ -906,9 +906,9 @@  discard block
 block discarded – undo
906 906
      *
907 907
      * Does not throw
908 908
      */
909
-    public function getAuthenticatedUser(string $sessionId=""): ?string
909
+    public function getAuthenticatedUser(string $sessionId = ""): ?string
910 910
     {
911
-        if ($sessionId=="") {
911
+        if ($sessionId == "") {
912 912
             $this->logger->debug('Using the PHP session id, as no session id was provided');
913 913
             $sessionId = session_id(); 
914 914
         }
@@ -952,22 +952,22 @@  discard block
 block discarded – undo
952 952
         $challenge = $state["challenge"] ?? '';
953 953
         $spIdentifier = $state["spIdentifier"] ?? '';
954 954
 
955
-        if ( (strpos($this->_protocolAuth, 'https://') === 0) || (strpos($this->_protocolAuth, 'http://') === 0) ) {
955
+        if ((strpos($this->_protocolAuth, 'https://') === 0) || (strpos($this->_protocolAuth, 'http://') === 0)) {
956 956
             // Create universal Link
957
-            $parameters=array();
957
+            $parameters = array();
958 958
             if (!is_null($userId)) {
959
-                $parameters[]='u='.urlencode($userId);
959
+                $parameters[] = 'u='.urlencode($userId);
960 960
             }
961
-            $parameters[]='s='.urlencode($sessionKey);
962
-            $parameters[]='q='.urlencode($challenge);
963
-            $parameters[]='i='.urlencode($this->getIdentifier());
964
-            $parameters[]='v='.urlencode($this->_protocolVersion);
961
+            $parameters[] = 's='.urlencode($sessionKey);
962
+            $parameters[] = 'q='.urlencode($challenge);
963
+            $parameters[] = 'i='.urlencode($this->getIdentifier());
964
+            $parameters[] = 'v='.urlencode($this->_protocolVersion);
965 965
             return $this->_protocolAuth.'?'.implode('&', $parameters);
966 966
         }
967 967
 
968 968
         // Create custom URL scheme
969 969
         // Last bit is the spIdentifier
970
-        return $this->_protocolAuth."://".(!is_null($userId)?urlencode($userId).'@':'').$this->getIdentifier()."/".$sessionKey."/".$challenge."/".urlencode($spIdentifier)."/".$this->_protocolVersion;
970
+        return $this->_protocolAuth."://".(!is_null($userId) ?urlencode($userId).'@' : '').$this->getIdentifier()."/".$sessionKey."/".$challenge."/".urlencode($spIdentifier)."/".$this->_protocolVersion;
971 971
     }
972 972
 
973 973
     /**
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
     {
979 979
         // The are two formats see: https://tiqr.org/technical/protocol/
980 980
 
981
-        if ( (strpos($this->_protocolEnroll, 'https://') === 0) || (strpos($this->_protocolEnroll, 'http://') === 0) ) {
981
+        if ((strpos($this->_protocolEnroll, 'https://') === 0) || (strpos($this->_protocolEnroll, 'http://') === 0)) {
982 982
             // Create universal Link
983 983
             return $this->_protocolEnroll.'?metadata='.urlencode($metadataUrl);
984 984
         }
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
     protected function _uniqueSessionKey(): string
998 998
     {
999 999
 
1000
-        return bin2hex( Tiqr_Random::randomBytes(self::SESSION_KEY_LENGTH_BYTES) );
1000
+        return bin2hex(Tiqr_Random::randomBytes(self::SESSION_KEY_LENGTH_BYTES));
1001 1001
     }
1002 1002
     
1003 1003
     /**
@@ -1028,7 +1028,7 @@  discard block
 block discarded – undo
1028 1028
      */
1029 1029
     protected function _setStateValue(string $key_prefix, string $key, $value, int $expire): void {
1030 1030
         $this->_stateStorage->setValue(
1031
-            $key_prefix . $this->_hashKey($key),
1031
+            $key_prefix.$this->_hashKey($key),
1032 1032
             $value,
1033 1033
             $expire
1034 1034
         );
@@ -1045,7 +1045,7 @@  discard block
 block discarded – undo
1045 1045
 
1046 1046
     protected function _getStateValue(string $key_prefix, string $key) {
1047 1047
         return $this->_stateStorage->getValue(
1048
-            $key_prefix . $this->_hashKey($key)
1048
+            $key_prefix.$this->_hashKey($key)
1049 1049
         );
1050 1050
     }
1051 1051
 
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
      */
1060 1060
     protected function _unsetStateValue(string $key_prefix, string $key): void {
1061 1061
         $this->_stateStorage->unsetValue(
1062
-            $key_prefix . $this->_hashKey($key)
1062
+            $key_prefix.$this->_hashKey($key)
1063 1063
         );
1064 1064
     }
1065 1065
 
Please login to merge, or discard this patch.
library/tiqr/Tiqr/Message/APNS2.php 2 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -28,8 +28,7 @@
 block discarded – undo
28 28
             // Use HTTP/1.1 instead of HTTP/2
29 29
             $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
30 30
             $this->logger->notice(sprintf('Using HTTP/1.1 CURL Proxy URL: "%s" and port "%s"',  $curl_options[CURLOPT_URL], $curl_options[CURLOPT_URL]));
31
-        }
32
-        else {
31
+        } else {
33 32
             $version_info = curl_version();
34 33
             if ($version_info['features'] & CURL_VERSION_HTTP2 == 0) {
35 34
                 throw new RuntimeException('APNS2 requires HTTP/2 support in curl');
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -20,11 +20,11 @@  discard block
 block discarded – undo
20 20
         $options = $this->getOptions();
21 21
         if (isset($options['apns.proxy_host_url'])) {
22 22
             // Override CURL options to connect to a HTTP/1.1 to HTTP/2 proxy
23
-            $curl_options[CURLOPT_URL] = $options['apns.proxy_host_url'] . '/3/device/' . $this->getAddress();
23
+            $curl_options[CURLOPT_URL] = $options['apns.proxy_host_url'].'/3/device/'.$this->getAddress();
24 24
             $curl_options[CURLOPT_PORT] = $options['apns.proxy_host_port'] ?? 443;
25 25
             // Use HTTP/1.1 instead of HTTP/2
26 26
             $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
27
-            $this->logger->notice(sprintf('Using HTTP/1.1 CURL Proxy URL: "%s" and port "%s"',  $curl_options[CURLOPT_URL], $curl_options[CURLOPT_URL]));
27
+            $this->logger->notice(sprintf('Using HTTP/1.1 CURL Proxy URL: "%s" and port "%s"', $curl_options[CURLOPT_URL], $curl_options[CURLOPT_URL]));
28 28
         }
29 29
         else {
30 30
             $version_info = curl_version();
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 
36 36
         // Get the UID from the client certificate we use for authentication, this
37 37
         // is set to the bundle ID.
38
-        $options=$this->getOptions();
38
+        $options = $this->getOptions();
39 39
         $cert_filename = $options['apns.certificate'];
40 40
         if (strlen($cert_filename) == 0) {
41 41
             throw new RuntimeException('apns.certificate option not set');
@@ -47,11 +47,11 @@  discard block
 block discarded – undo
47 47
             );
48 48
         }
49 49
 
50
-        $cert=openssl_x509_parse( $cert_file_contents );
50
+        $cert = openssl_x509_parse($cert_file_contents);
51 51
         if (false === $cert) {
52 52
             // Log openssl error information
53 53
             while ($msg = openssl_error_string()) {
54
-                $this->logger->error('openssl_x509_parse(): ' . $msg);
54
+                $this->logger->error('openssl_x509_parse(): '.$msg);
55 55
             }
56 56
             throw new RuntimeException('Error parsing APNS client certificate');
57 57
         }
@@ -76,11 +76,11 @@  discard block
 block discarded – undo
76 76
         $authProvider = AuthProvider\Certificate::create($authProviderOptions);
77 77
 
78 78
         // Create the push message
79
-        $alert=Alert::create();
79
+        $alert = Alert::create();
80 80
         $alert->setBody($this->getText());
81 81
         // Note: It is possible to specify a title and a subtitle: $alert->setTitle() && $alert->setSubtitle()
82 82
         //       The tiqr service currently does not implement this.
83
-        $payload=Payload::create()->setAlert($alert);
83
+        $payload = Payload::create()->setAlert($alert);
84 84
         $payload->setSound('default');
85 85
         foreach ($this->getCustomProperties() as $name => $value) {
86 86
             $payload->setCustomValue($name, $value);
@@ -91,32 +91,32 @@  discard block
 block discarded – undo
91 91
         $payload->setMutableContent(true);
92 92
 
93 93
         $this->logger->debug(sprintf('JSON Payload: %s', $payload->toJson()));
94
-        $notification=new Notification($payload, $this->getAddress());
94
+        $notification = new Notification($payload, $this->getAddress());
95 95
         // Set expiration to 30 seconds from now, same as Message_APNS
96 96
         $now = new DateTime();
97
-        $expirationInstant=$now->add(new DateInterval('PT30S'));
97
+        $expirationInstant = $now->add(new DateInterval('PT30S'));
98 98
         $notification->setExpirationAt($expirationInstant);
99 99
 
100 100
         // Send the push message
101 101
         $client = new Client($authProvider, $options['apns.environment'] == 'production', $curl_options);
102 102
         $client->addNotification($notification);
103
-        $responses=$client->push();
104
-        if ( sizeof($responses) != 1) {
105
-            $this->logger->warning(sprintf('Unexpected number responses. Expected 1, got %d', sizeof($responses)) );
103
+        $responses = $client->push();
104
+        if (sizeof($responses) != 1) {
105
+            $this->logger->warning(sprintf('Unexpected number responses. Expected 1, got %d', sizeof($responses)));
106 106
             if (sizeof($responses) == 0) {
107 107
                 $this->logger->warning('Could not determine whether the notification was sent');
108 108
                 return;
109 109
             }
110 110
         }
111 111
         /** @var \Pushok\Response $response */
112
-        $response = reset($responses);  // Get first response from the array
113
-        $deviceToken=$response->getDeviceToken() ?? '';
112
+        $response = reset($responses); // Get first response from the array
113
+        $deviceToken = $response->getDeviceToken() ?? '';
114 114
         // A canonical UUID that is the unique ID for the notification. E.g. 123e4567-e89b-12d3-a456-4266554400a0
115
-        $apnsId=$response->getApnsId() ?? '';
115
+        $apnsId = $response->getApnsId() ?? '';
116 116
         // Status code. E.g. 200 (Success), 410 (The device token is no longer active for the topic.)
117
-        $statusCode=$response->getStatusCode();
117
+        $statusCode = $response->getStatusCode();
118 118
         $this->logger->info(sprintf('Got response with ApnsId "%s", status %s for deviceToken "%s"', $apnsId, $statusCode, $deviceToken));
119
-        if ( strcasecmp($deviceToken, $this->getAddress()) ) {
119
+        if (strcasecmp($deviceToken, $this->getAddress())) {
120 120
         $this->logger->warning(sprintf('Unexpected deviceToken in response. Expected: "%s"; got: "%s"', $this->getAddress(), $deviceToken));
121 121
         }
122 122
         if ($statusCode == 200) {
@@ -124,9 +124,9 @@  discard block
 block discarded – undo
124 124
             return;
125 125
         }
126 126
 
127
-        $reasonPhrase=$response->getReasonPhrase(); // E.g. The device token is no longer active for the topic.
128
-        $errorReason=$response->getErrorReason(); // E.g. Unregistered
129
-        $errorDescription=$response->getErrorDescription(); // E.g. The device token is inactive for the specified topic.
127
+        $reasonPhrase = $response->getReasonPhrase(); // E.g. The device token is no longer active for the topic.
128
+        $errorReason = $response->getErrorReason(); // E.g. Unregistered
129
+        $errorDescription = $response->getErrorDescription(); // E.g. The device token is inactive for the specified topic.
130 130
 
131 131
         $this->logger->error(sprintf('Error sending APNS2 push notification. APNS ID: "%s"; deviceToken: "%s"; Error: "%s" "%s" "%s"', $apnsId, $deviceToken, $reasonPhrase, $errorReason, $errorDescription));
132 132
         throw new RuntimeException(
Please login to merge, or discard this patch.
library/tiqr/Tiqr/UserSecretStorage.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@
 block discarded – undo
74 74
                 $password = $options['password'];
75 75
 
76 76
                 try {
77
-                    $handle = new PDO($dsn, $userName, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
77
+                    $handle = new PDO($dsn, $userName, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
78 78
                 } catch (PDOException $e) {
79 79
                     $logger->error(
80 80
                         sprintf('Unable to establish a PDO connection. Error message from PDO: %s', $e->getMessage())
Please login to merge, or discard this patch.
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@
 block discarded – undo
97 97
      *         ),
98 98
      *     )
99 99
      * );
100
- *
100
+     *
101 101
      *
102 102
      * @return Tiqr_UserSecretStorage_Interface
103 103
      * @throws RuntimeException If an unknown type is requested.
Please login to merge, or discard this patch.
library/tiqr/Tiqr/OcraService.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -39,10 +39,10 @@
 block discarded – undo
39 39
      * @return Tiqr_OcraService_Interface
40 40
      * @throws Exception An exception if an unknown orca service type is requested.
41 41
      */
42
-    public static function getOcraService(string $type="tiqr", array $options=array(), LoggerInterface $logger=null)
42
+    public static function getOcraService(string $type = "tiqr", array $options = array(), LoggerInterface $logger = null)
43 43
     {
44 44
         if (!$logger)
45
-            $logger=new \Psr\Log\NullLogger();
45
+            $logger = new \Psr\Log\NullLogger();
46 46
 
47 47
         switch ($type) {
48 48
             case "tiqr":
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -41,8 +41,9 @@
 block discarded – undo
41 41
      */
42 42
     public static function getOcraService(string $type="tiqr", array $options=array(), LoggerInterface $logger=null)
43 43
     {
44
-        if (!$logger)
45
-            $logger=new \Psr\Log\NullLogger();
44
+        if (!$logger) {
45
+                    $logger=new \Psr\Log\NullLogger();
46
+        }
46 47
 
47 48
         switch ($type) {
48 49
             case "tiqr":
Please login to merge, or discard this patch.
library/tiqr/Tiqr/OATH/OCRAParser.php 2 patches
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 	 */
46 46
 	private function parseOCRASuite($ocraSuite) {
47 47
 		if (!is_string($ocraSuite)) {
48
-			throw new Exception('OCRASuite not in string format: ' . var_export($ocraSuite, TRUE));
48
+			throw new Exception('OCRASuite not in string format: '.var_export($ocraSuite, TRUE));
49 49
 		}
50 50
 
51 51
 		$ocraSuite = strtoupper($ocraSuite);
@@ -53,54 +53,54 @@  discard block
 block discarded – undo
53 53
 
54 54
 		$s = explode(':', $ocraSuite);
55 55
 		if (count($s) != 3) {
56
-			throw new Exception('Invalid OCRASuite format: ' . var_export($ocraSuite, TRUE));
56
+			throw new Exception('Invalid OCRASuite format: '.var_export($ocraSuite, TRUE));
57 57
 		}
58 58
 
59 59
 		$algo = explode('-', $s[0]);
60 60
 		if (count($algo) != 2) {
61
-			throw new Exception('Invalid OCRA version: ' . var_export($s[0], TRUE));
61
+			throw new Exception('Invalid OCRA version: '.var_export($s[0], TRUE));
62 62
 		}
63 63
 
64 64
 		if ($algo[0] !== 'OCRA') {
65
-			throw new Exception('Unsupported OCRA algorithm: ' . var_export($algo[0], TRUE));
65
+			throw new Exception('Unsupported OCRA algorithm: '.var_export($algo[0], TRUE));
66 66
 		}
67 67
 
68 68
 		if ($algo[1] !== '1') {
69
-			throw new Exception('Unsupported OCRA version: ' . var_export($algo[1], TRUE));
69
+			throw new Exception('Unsupported OCRA version: '.var_export($algo[1], TRUE));
70 70
 		}
71 71
 		$this->OCRAVersion = $algo[1];
72 72
 
73 73
 		$cf = explode('-', $s[1]);
74 74
 		if (count($cf) != 3) {
75
-			throw new Exception('Invalid OCRA suite crypto function: ' . var_export($s[1], TRUE));
75
+			throw new Exception('Invalid OCRA suite crypto function: '.var_export($s[1], TRUE));
76 76
 		}
77 77
 
78 78
 		if ($cf[0] !== 'HOTP') {
79
-			throw new Exception('Unsupported OCRA suite crypto function: ' . var_export($cf[0], TRUE));
79
+			throw new Exception('Unsupported OCRA suite crypto function: '.var_export($cf[0], TRUE));
80 80
 		}
81 81
 		$this->CryptoFunctionType = $cf[0];
82 82
 
83 83
 		if (!array_key_exists($cf[1], $this->supportedHashFunctions)) {
84
-			throw new Exception('Unsupported hash function in OCRA suite crypto function: ' . var_export($cf[1], TRUE));
84
+			throw new Exception('Unsupported hash function in OCRA suite crypto function: '.var_export($cf[1], TRUE));
85 85
 		}
86 86
 		$this->CryptoFunctionHash = $cf[1];
87 87
 		$this->CryptoFunctionHashLength = $this->supportedHashFunctions[$cf[1]];
88 88
 
89 89
 		if (!preg_match('/^\d+$/', $cf[2]) || (($cf[2] < 4 || $cf[2] > 10) && $cf[2] != 0)) {
90
-			throw new Exception('Invalid OCRA suite crypto function truncation length: ' . var_export($cf[2], TRUE));
90
+			throw new Exception('Invalid OCRA suite crypto function truncation length: '.var_export($cf[2], TRUE));
91 91
 		}
92 92
 		$this->CryptoFunctionTruncation = intval($cf[2]);
93 93
 
94 94
 		$di = explode('-', $s[2]);
95 95
 		if (count($cf) == 0) {
96
-			throw new Exception('Invalid OCRA suite data input: ' . var_export($s[2], TRUE));
96
+			throw new Exception('Invalid OCRA suite data input: '.var_export($s[2], TRUE));
97 97
 		}
98 98
 
99 99
 		$data_input = array();
100
-		foreach($di as $elem) {
100
+		foreach ($di as $elem) {
101 101
 			$letter = $elem[0];
102 102
 			if (array_key_exists($letter, $data_input)) {
103
-				throw new Exception('Duplicate field in OCRA suite data input: ' . var_export($elem, TRUE));
103
+				throw new Exception('Duplicate field in OCRA suite data input: '.var_export($elem, TRUE));
104 104
 			}
105 105
 			$data_input[$letter] = 1;
106 106
 
@@ -112,13 +112,13 @@  discard block
 block discarded – undo
112 112
 				} elseif (preg_match('/^Q([AHN])(\d+)$/', $elem, $match)) {
113 113
 					$q_len = intval($match[2]);
114 114
 					if ($q_len < 4 || $q_len > 64) {
115
-						throw new Exception('Invalid OCRA suite data input question length: ' . var_export($q_len, TRUE));
115
+						throw new Exception('Invalid OCRA suite data input question length: '.var_export($q_len, TRUE));
116 116
 					}
117 117
 					$this->Q = TRUE;
118 118
 					$this->QType = $match[1];
119 119
 					$this->QLength = $q_len;
120 120
 				} else {
121
-					throw new Exception('Invalid OCRA suite data input question: ' . var_export($elem, TRUE));
121
+					throw new Exception('Invalid OCRA suite data input question: '.var_export($elem, TRUE));
122 122
 				}
123 123
 			} elseif ($letter === 'P') {
124 124
 				if (strlen($elem) == 1) {
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 				} else {
127 127
 					$p_algo = substr($elem, 1);
128 128
 					if (!array_key_exists($p_algo, $this->supportedHashFunctions)) {
129
-						throw new Exception('Unsupported OCRA suite PIN hash function: ' . var_export($elem, TRUE));
129
+						throw new Exception('Unsupported OCRA suite PIN hash function: '.var_export($elem, TRUE));
130 130
 					}
131 131
 					$this->P = TRUE;
132 132
 					$this->PType = $p_algo;
@@ -138,13 +138,13 @@  discard block
 block discarded – undo
138 138
 				} elseif (preg_match('/^S(\d+)$/', $elem, $match)) {
139 139
 					$s_len = intval($match[1]);
140 140
 					if ($s_len <= 0 || $s_len > 512) {
141
-						throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($s_len, TRUE));
141
+						throw new Exception('Invalid OCRA suite data input session information length: '.var_export($s_len, TRUE));
142 142
 					}
143 143
 
144 144
 					$this->S = TRUE;
145 145
 					$this->SLength = $s_len;
146 146
 				} else {
147
-					throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($elem, TRUE));
147
+					throw new Exception('Invalid OCRA suite data input session information length: '.var_export($elem, TRUE));
148 148
 				}
149 149
 			} elseif ($letter === 'T') {
150 150
 				if (strlen($elem) == 1) {
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 					preg_match_all('/(\d+)([HMS])/', $elem, $match);
154 154
 
155 155
 					if (count($match[1]) !== count(array_unique($match[2]))) {
156
-						throw new Exception('Duplicate definitions in OCRA suite data input timestamp: ' . var_export($elem, TRUE));
156
+						throw new Exception('Duplicate definitions in OCRA suite data input timestamp: '.var_export($elem, TRUE));
157 157
 					}
158 158
 
159 159
 					$length = 0;
@@ -161,21 +161,21 @@  discard block
 block discarded – undo
161 161
 						$length += intval($match[1][$i]) * $this->TPeriods[$match[2][$i]];
162 162
 					}
163 163
 					if ($length <= 0) {
164
-						throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
164
+						throw new Exception('Invalid OCRA suite data input timestamp: '.var_export($elem, TRUE));
165 165
 					}
166 166
 
167 167
 					$this->T = TRUE;
168 168
 					$this->TLength = $length;
169 169
 				} else {
170
-					throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
170
+					throw new Exception('Invalid OCRA suite data input timestamp: '.var_export($elem, TRUE));
171 171
 				}
172 172
 			} else {
173
-				throw new Exception('Unsupported OCRA suite data input field: ' . var_export($elem, TRUE));
173
+				throw new Exception('Unsupported OCRA suite data input field: '.var_export($elem, TRUE));
174 174
 			}
175 175
 		}
176 176
 
177 177
 		if (!$this->Q) {
178
-			throw new Exception('OCRA suite data input question not defined: ' . var_export($s[2], TRUE));
178
+			throw new Exception('OCRA suite data input question not defined: '.var_export($s[2], TRUE));
179 179
 		}
180 180
 	}
181 181
 
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 
197 197
         $bytes = Tiqr_Random::randomBytes($q_length);
198 198
 
199
-		switch($q_type) {
199
+		switch ($q_type) {
200 200
 			case 'A':
201 201
 				$challenge = base64_encode($bytes);
202 202
 				$tr = implode("", unpack('H*', $bytes));
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 				$challenge = implode("", unpack('N*', $bytes));
210 210
 				break;
211 211
 			default:
212
-				throw new Exception('Unsupported OCRASuite challenge type: ' . var_export($q_type, TRUE));
212
+				throw new Exception('Unsupported OCRASuite challenge type: '.var_export($q_type, TRUE));
213 213
 				break;
214 214
 		}
215 215
 
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 			$result &= ($s1[$i] == $s2[$i]);
234 234
 		}
235 235
 
236
-		return (boolean)$result;
236
+		return (boolean) $result;
237 237
 	}
238 238
 
239 239
 }
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -2,32 +2,32 @@  discard block
 block discarded – undo
2 2
 
3 3
 class OATH_OCRAParser {
4 4
 
5
-	private $OCRASuite = NULL;
5
+    private $OCRASuite = NULL;
6 6
 
7
-	private $OCRAVersion = NULL;
7
+    private $OCRAVersion = NULL;
8 8
 
9
-	private $CryptoFunctionType = NULL;
10
-	private $CryptoFunctionHash = NULL;
11
-	private $CryptoFunctionHashLength = NULL;
12
-	private $CryptoFunctionTruncation = NULL;
9
+    private $CryptoFunctionType = NULL;
10
+    private $CryptoFunctionHash = NULL;
11
+    private $CryptoFunctionHashLength = NULL;
12
+    private $CryptoFunctionTruncation = NULL;
13 13
 
14
-	private $C = FALSE;
15
-	private $Q = FALSE;
16
-	private $QType = 'N';
17
-	private $QLength = 8;
14
+    private $C = FALSE;
15
+    private $Q = FALSE;
16
+    private $QType = 'N';
17
+    private $QLength = 8;
18 18
 
19
-	private $P = FALSE;
20
-	private $PType = 'SHA1';
21
-	private $PLength = 20;
19
+    private $P = FALSE;
20
+    private $PType = 'SHA1';
21
+    private $PLength = 20;
22 22
 
23
-	private $S = FALSE;
24
-	private $SLength = 64;
23
+    private $S = FALSE;
24
+    private $SLength = 64;
25 25
 
26
-	private $T = FALSE;
27
-	private $TLength = 60; // 1M
28
-	private $TPeriods = array('H' => 3600, 'M' => 60, 'S' => 1);
26
+    private $T = FALSE;
27
+    private $TLength = 60; // 1M
28
+    private $TPeriods = array('H' => 3600, 'M' => 60, 'S' => 1);
29 29
 
30
-	private $supportedHashFunctions = array('SHA1' => 20, 'SHA256' => 32, 'SHA512' => 64);
30
+    private $supportedHashFunctions = array('SHA1' => 20, 'SHA256' => 32, 'SHA512' => 64);
31 31
 
32 32
 
33 33
     /**
@@ -35,149 +35,149 @@  discard block
 block discarded – undo
35 35
      * @throws Exception
36 36
      */
37 37
     public function __construct(String $ocraSuite) {
38
-		$this->parseOCRASuite($ocraSuite);
39
-	}
38
+        $this->parseOCRASuite($ocraSuite);
39
+    }
40 40
 
41
-	/**
42
-	 * Inspired by https://github.com/bdauvergne/python-oath
41
+    /**
42
+     * Inspired by https://github.com/bdauvergne/python-oath
43 43
      *
44 44
      * @throws Exception
45
-	 */
46
-	private function parseOCRASuite($ocraSuite) {
47
-		if (!is_string($ocraSuite)) {
48
-			throw new Exception('OCRASuite not in string format: ' . var_export($ocraSuite, TRUE));
49
-		}
50
-
51
-		$ocraSuite = strtoupper($ocraSuite);
52
-		$this->OCRASuite = $ocraSuite;
53
-
54
-		$s = explode(':', $ocraSuite);
55
-		if (count($s) != 3) {
56
-			throw new Exception('Invalid OCRASuite format: ' . var_export($ocraSuite, TRUE));
57
-		}
58
-
59
-		$algo = explode('-', $s[0]);
60
-		if (count($algo) != 2) {
61
-			throw new Exception('Invalid OCRA version: ' . var_export($s[0], TRUE));
62
-		}
63
-
64
-		if ($algo[0] !== 'OCRA') {
65
-			throw new Exception('Unsupported OCRA algorithm: ' . var_export($algo[0], TRUE));
66
-		}
67
-
68
-		if ($algo[1] !== '1') {
69
-			throw new Exception('Unsupported OCRA version: ' . var_export($algo[1], TRUE));
70
-		}
71
-		$this->OCRAVersion = $algo[1];
72
-
73
-		$cf = explode('-', $s[1]);
74
-		if (count($cf) != 3) {
75
-			throw new Exception('Invalid OCRA suite crypto function: ' . var_export($s[1], TRUE));
76
-		}
77
-
78
-		if ($cf[0] !== 'HOTP') {
79
-			throw new Exception('Unsupported OCRA suite crypto function: ' . var_export($cf[0], TRUE));
80
-		}
81
-		$this->CryptoFunctionType = $cf[0];
82
-
83
-		if (!array_key_exists($cf[1], $this->supportedHashFunctions)) {
84
-			throw new Exception('Unsupported hash function in OCRA suite crypto function: ' . var_export($cf[1], TRUE));
85
-		}
86
-		$this->CryptoFunctionHash = $cf[1];
87
-		$this->CryptoFunctionHashLength = $this->supportedHashFunctions[$cf[1]];
88
-
89
-		if (!preg_match('/^\d+$/', $cf[2]) || (($cf[2] < 4 || $cf[2] > 10) && $cf[2] != 0)) {
90
-			throw new Exception('Invalid OCRA suite crypto function truncation length: ' . var_export($cf[2], TRUE));
91
-		}
92
-		$this->CryptoFunctionTruncation = intval($cf[2]);
93
-
94
-		$di = explode('-', $s[2]);
95
-		if (count($cf) == 0) {
96
-			throw new Exception('Invalid OCRA suite data input: ' . var_export($s[2], TRUE));
97
-		}
98
-
99
-		$data_input = array();
100
-		foreach($di as $elem) {
101
-			$letter = $elem[0];
102
-			if (array_key_exists($letter, $data_input)) {
103
-				throw new Exception('Duplicate field in OCRA suite data input: ' . var_export($elem, TRUE));
104
-			}
105
-			$data_input[$letter] = 1;
106
-
107
-			if ($letter === 'C' && strlen($elem) == 1) {
108
-				$this->C = TRUE;
109
-			} elseif ($letter === 'Q') {
110
-				if (strlen($elem) == 1) {
111
-					$this->Q = TRUE;
112
-				} elseif (preg_match('/^Q([AHN])(\d+)$/', $elem, $match)) {
113
-					$q_len = intval($match[2]);
114
-					if ($q_len < 4 || $q_len > 64) {
115
-						throw new Exception('Invalid OCRA suite data input question length: ' . var_export($q_len, TRUE));
116
-					}
117
-					$this->Q = TRUE;
118
-					$this->QType = $match[1];
119
-					$this->QLength = $q_len;
120
-				} else {
121
-					throw new Exception('Invalid OCRA suite data input question: ' . var_export($elem, TRUE));
122
-				}
123
-			} elseif ($letter === 'P') {
124
-				if (strlen($elem) == 1) {
125
-					$this->P = TRUE;
126
-				} else {
127
-					$p_algo = substr($elem, 1);
128
-					if (!array_key_exists($p_algo, $this->supportedHashFunctions)) {
129
-						throw new Exception('Unsupported OCRA suite PIN hash function: ' . var_export($elem, TRUE));
130
-					}
131
-					$this->P = TRUE;
132
-					$this->PType = $p_algo;
133
-					$this->PLength = $this->supportedHashFunctions[$p_algo];
134
-				}
135
-			} elseif ($letter === 'S') {
136
-				if (strlen($elem) == 1) {
137
-					$this->S = TRUE;
138
-				} elseif (preg_match('/^S(\d+)$/', $elem, $match)) {
139
-					$s_len = intval($match[1]);
140
-					if ($s_len <= 0 || $s_len > 512) {
141
-						throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($s_len, TRUE));
142
-					}
143
-
144
-					$this->S = TRUE;
145
-					$this->SLength = $s_len;
146
-				} else {
147
-					throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($elem, TRUE));
148
-				}
149
-			} elseif ($letter === 'T') {
150
-				if (strlen($elem) == 1) {
151
-					$this->T = TRUE;
152
-				} elseif (preg_match('/^T(\d+[HMS])+$/', $elem)) {
153
-					preg_match_all('/(\d+)([HMS])/', $elem, $match);
154
-
155
-					if (count($match[1]) !== count(array_unique($match[2]))) {
156
-						throw new Exception('Duplicate definitions in OCRA suite data input timestamp: ' . var_export($elem, TRUE));
157
-					}
158
-
159
-					$length = 0;
160
-					for ($i = 0; $i < count($match[1]); $i++) {
161
-						$length += intval($match[1][$i]) * $this->TPeriods[$match[2][$i]];
162
-					}
163
-					if ($length <= 0) {
164
-						throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
165
-					}
166
-
167
-					$this->T = TRUE;
168
-					$this->TLength = $length;
169
-				} else {
170
-					throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
171
-				}
172
-			} else {
173
-				throw new Exception('Unsupported OCRA suite data input field: ' . var_export($elem, TRUE));
174
-			}
175
-		}
176
-
177
-		if (!$this->Q) {
178
-			throw new Exception('OCRA suite data input question not defined: ' . var_export($s[2], TRUE));
179
-		}
180
-	}
45
+     */
46
+    private function parseOCRASuite($ocraSuite) {
47
+        if (!is_string($ocraSuite)) {
48
+            throw new Exception('OCRASuite not in string format: ' . var_export($ocraSuite, TRUE));
49
+        }
50
+
51
+        $ocraSuite = strtoupper($ocraSuite);
52
+        $this->OCRASuite = $ocraSuite;
53
+
54
+        $s = explode(':', $ocraSuite);
55
+        if (count($s) != 3) {
56
+            throw new Exception('Invalid OCRASuite format: ' . var_export($ocraSuite, TRUE));
57
+        }
58
+
59
+        $algo = explode('-', $s[0]);
60
+        if (count($algo) != 2) {
61
+            throw new Exception('Invalid OCRA version: ' . var_export($s[0], TRUE));
62
+        }
63
+
64
+        if ($algo[0] !== 'OCRA') {
65
+            throw new Exception('Unsupported OCRA algorithm: ' . var_export($algo[0], TRUE));
66
+        }
67
+
68
+        if ($algo[1] !== '1') {
69
+            throw new Exception('Unsupported OCRA version: ' . var_export($algo[1], TRUE));
70
+        }
71
+        $this->OCRAVersion = $algo[1];
72
+
73
+        $cf = explode('-', $s[1]);
74
+        if (count($cf) != 3) {
75
+            throw new Exception('Invalid OCRA suite crypto function: ' . var_export($s[1], TRUE));
76
+        }
77
+
78
+        if ($cf[0] !== 'HOTP') {
79
+            throw new Exception('Unsupported OCRA suite crypto function: ' . var_export($cf[0], TRUE));
80
+        }
81
+        $this->CryptoFunctionType = $cf[0];
82
+
83
+        if (!array_key_exists($cf[1], $this->supportedHashFunctions)) {
84
+            throw new Exception('Unsupported hash function in OCRA suite crypto function: ' . var_export($cf[1], TRUE));
85
+        }
86
+        $this->CryptoFunctionHash = $cf[1];
87
+        $this->CryptoFunctionHashLength = $this->supportedHashFunctions[$cf[1]];
88
+
89
+        if (!preg_match('/^\d+$/', $cf[2]) || (($cf[2] < 4 || $cf[2] > 10) && $cf[2] != 0)) {
90
+            throw new Exception('Invalid OCRA suite crypto function truncation length: ' . var_export($cf[2], TRUE));
91
+        }
92
+        $this->CryptoFunctionTruncation = intval($cf[2]);
93
+
94
+        $di = explode('-', $s[2]);
95
+        if (count($cf) == 0) {
96
+            throw new Exception('Invalid OCRA suite data input: ' . var_export($s[2], TRUE));
97
+        }
98
+
99
+        $data_input = array();
100
+        foreach($di as $elem) {
101
+            $letter = $elem[0];
102
+            if (array_key_exists($letter, $data_input)) {
103
+                throw new Exception('Duplicate field in OCRA suite data input: ' . var_export($elem, TRUE));
104
+            }
105
+            $data_input[$letter] = 1;
106
+
107
+            if ($letter === 'C' && strlen($elem) == 1) {
108
+                $this->C = TRUE;
109
+            } elseif ($letter === 'Q') {
110
+                if (strlen($elem) == 1) {
111
+                    $this->Q = TRUE;
112
+                } elseif (preg_match('/^Q([AHN])(\d+)$/', $elem, $match)) {
113
+                    $q_len = intval($match[2]);
114
+                    if ($q_len < 4 || $q_len > 64) {
115
+                        throw new Exception('Invalid OCRA suite data input question length: ' . var_export($q_len, TRUE));
116
+                    }
117
+                    $this->Q = TRUE;
118
+                    $this->QType = $match[1];
119
+                    $this->QLength = $q_len;
120
+                } else {
121
+                    throw new Exception('Invalid OCRA suite data input question: ' . var_export($elem, TRUE));
122
+                }
123
+            } elseif ($letter === 'P') {
124
+                if (strlen($elem) == 1) {
125
+                    $this->P = TRUE;
126
+                } else {
127
+                    $p_algo = substr($elem, 1);
128
+                    if (!array_key_exists($p_algo, $this->supportedHashFunctions)) {
129
+                        throw new Exception('Unsupported OCRA suite PIN hash function: ' . var_export($elem, TRUE));
130
+                    }
131
+                    $this->P = TRUE;
132
+                    $this->PType = $p_algo;
133
+                    $this->PLength = $this->supportedHashFunctions[$p_algo];
134
+                }
135
+            } elseif ($letter === 'S') {
136
+                if (strlen($elem) == 1) {
137
+                    $this->S = TRUE;
138
+                } elseif (preg_match('/^S(\d+)$/', $elem, $match)) {
139
+                    $s_len = intval($match[1]);
140
+                    if ($s_len <= 0 || $s_len > 512) {
141
+                        throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($s_len, TRUE));
142
+                    }
143
+
144
+                    $this->S = TRUE;
145
+                    $this->SLength = $s_len;
146
+                } else {
147
+                    throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($elem, TRUE));
148
+                }
149
+            } elseif ($letter === 'T') {
150
+                if (strlen($elem) == 1) {
151
+                    $this->T = TRUE;
152
+                } elseif (preg_match('/^T(\d+[HMS])+$/', $elem)) {
153
+                    preg_match_all('/(\d+)([HMS])/', $elem, $match);
154
+
155
+                    if (count($match[1]) !== count(array_unique($match[2]))) {
156
+                        throw new Exception('Duplicate definitions in OCRA suite data input timestamp: ' . var_export($elem, TRUE));
157
+                    }
158
+
159
+                    $length = 0;
160
+                    for ($i = 0; $i < count($match[1]); $i++) {
161
+                        $length += intval($match[1][$i]) * $this->TPeriods[$match[2][$i]];
162
+                    }
163
+                    if ($length <= 0) {
164
+                        throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
165
+                    }
166
+
167
+                    $this->T = TRUE;
168
+                    $this->TLength = $length;
169
+                } else {
170
+                    throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
171
+                }
172
+            } else {
173
+                throw new Exception('Unsupported OCRA suite data input field: ' . var_export($elem, TRUE));
174
+            }
175
+        }
176
+
177
+        if (!$this->Q) {
178
+            throw new Exception('OCRA suite data input question not defined: ' . var_export($s[2], TRUE));
179
+        }
180
+    }
181 181
 
182 182
     /** Generate an OCRA challenge question according to the ocra suite specified in the constructor
183 183
      * @return String: The randomly generated OCRA question
@@ -190,50 +190,50 @@  discard block
 block discarded – undo
190 190
      * Note that the question string is the exact question string a specified in the OCRA strandard (RFC 6287)
191 191
      * The challenge is not yet hex encoded as expected by OCRA::generateOCRA()
192 192
      */
193
-	public function generateChallenge() : String {
194
-		$q_length = $this->QLength;
195
-		$q_type = $this->QType;
193
+    public function generateChallenge() : String {
194
+        $q_length = $this->QLength;
195
+        $q_type = $this->QType;
196 196
 
197 197
         $bytes = Tiqr_Random::randomBytes($q_length);
198 198
 
199
-		switch($q_type) {
200
-			case 'A':
201
-				$challenge = base64_encode($bytes);
202
-				$tr = implode("", unpack('H*', $bytes));
203
-				$challenge = rtrim(strtr($challenge, '+/', $tr), '=');
204
-				break;
205
-			case 'H':
206
-				$challenge = implode("", unpack('H*', $bytes));
207
-				break;
208
-			case 'N':
209
-				$challenge = implode("", unpack('N*', $bytes));
210
-				break;
211
-			default:
212
-				throw new Exception('Unsupported OCRASuite challenge type: ' . var_export($q_type, TRUE));
213
-				break;
214
-		}
215
-
216
-		$challenge = substr($challenge, 0, $q_length);
217
-
218
-		return $challenge;
219
-	}
220
-
221
-
222
-	/**
223
-	 * Constant time string comparison, see http://codahale.com/a-lesson-in-timing-attacks/
224
-	 */
225
-	public static function constEqual(string $s1, string $s2): bool {
226
-		if (strlen($s1) != strlen($s2)) {
227
-			return FALSE;
228
-		}
229
-
230
-		$result = TRUE;
231
-		$length = strlen($s1);
232
-		for ($i = 0; $i < $length; $i++) {
233
-			$result &= ($s1[$i] == $s2[$i]);
234
-		}
235
-
236
-		return (boolean)$result;
237
-	}
199
+        switch($q_type) {
200
+            case 'A':
201
+                $challenge = base64_encode($bytes);
202
+                $tr = implode("", unpack('H*', $bytes));
203
+                $challenge = rtrim(strtr($challenge, '+/', $tr), '=');
204
+                break;
205
+            case 'H':
206
+                $challenge = implode("", unpack('H*', $bytes));
207
+                break;
208
+            case 'N':
209
+                $challenge = implode("", unpack('N*', $bytes));
210
+                break;
211
+            default:
212
+                throw new Exception('Unsupported OCRASuite challenge type: ' . var_export($q_type, TRUE));
213
+                break;
214
+        }
215
+
216
+        $challenge = substr($challenge, 0, $q_length);
217
+
218
+        return $challenge;
219
+    }
220
+
221
+
222
+    /**
223
+     * Constant time string comparison, see http://codahale.com/a-lesson-in-timing-attacks/
224
+     */
225
+    public static function constEqual(string $s1, string $s2): bool {
226
+        if (strlen($s1) != strlen($s2)) {
227
+            return FALSE;
228
+        }
229
+
230
+        $result = TRUE;
231
+        $length = strlen($s1);
232
+        for ($i = 0; $i < $length; $i++) {
233
+            $result &= ($s1[$i] == $s2[$i]);
234
+        }
235
+
236
+        return (boolean)$result;
237
+    }
238 238
 
239 239
 }
Please login to merge, or discard this patch.
library/tiqr/Tiqr/OcraService/Abstract.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@
 block discarded – undo
35 35
         $this->logger = $logger;
36 36
 
37 37
         // Set the OCRA suite
38
-        $this->_ocraSuite = $config['ocra.suite'] ?? 'OCRA-1:HOTP-SHA1-6:QH10-S';   // Use tiqr server default suite
38
+        $this->_ocraSuite = $config['ocra.suite'] ?? 'OCRA-1:HOTP-SHA1-6:QH10-S'; // Use tiqr server default suite
39 39
         $this->_ocraParser = new OATH_OCRAParser($this->_ocraSuite);
40 40
     }
41 41
 
Please login to merge, or discard this patch.