Elgg  Version 3.0
UrlSigner.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Security;
4 
10 class UrlSigner {
11 
12  const KEY_MAC = '__elgg_mac';
13  const KEY_EXPIRES = '__elgg_exp';
14 
27  public function sign($url, $expires = false) {
29 
30  $parts = parse_url($url);
31 
32  if (isset($parts['query'])) {
33  $query = elgg_parse_str($parts['query']);
34  } else {
35  $query = [];
36  }
37 
38  if (isset($query[self::KEY_MAC])) {
39  throw new \InvalidArgumentException('URL has already been signed');
40  }
41 
42  if ($expires) {
43  $query[self::KEY_EXPIRES] = strtotime($expires);
44  }
45 
46  ksort($query);
47 
48  $parts['query'] = http_build_query($query);
49 
50  $url = elgg_http_build_url($parts, false);
51 
52  $token = elgg_build_hmac($url)->getToken();
53 
55  self::KEY_MAC => $token,
56  ]);
57  }
58 
65  public function isValid($url) {
66 
67  $parts = parse_url($url);
68 
69  if (isset($parts['query'])) {
70  $query = elgg_parse_str($parts['query']);
71  } else {
72  $query = [];
73  }
74 
75  if (!isset($query[self::KEY_MAC])) {
76  // No signature found
77  return false;
78  }
79 
80  $token = $query[self::KEY_MAC];
81  unset($query[self::KEY_MAC]);
82 
83  if (isset($query[self::KEY_EXPIRES]) && $query[self::KEY_EXPIRES] < time()) {
84  // Signature has expired
85  return false;
86  }
87 
88  ksort($query);
89 
90  $parts['query'] = http_build_query($query);
91 
92  $url = elgg_http_build_url($parts, false);
93 
94  return elgg_build_hmac($url)->matchesToken($token);
95 
96  }
97 }
elgg_http_add_url_query_elements($url, array $elements)
Sets elements in a URL&#39;s query string.
Definition: elgglib.php:942
elgg_parse_str($str)
Parses a string using mb_parse_str() if available.
Definition: mb_wrapper.php:19
$query
Definition: groups.php:8
elgg_normalize_url($url)
Definition: output.php:186
elgg parse_url
Parse a URL into its parts.
Definition: elgglib.js:442
$url
Definition: default.php:33
$token
Component for creating signed URLs.
Definition: UrlSigner.php:10
elgg_http_build_url(array $parts, $html_encode=true)
Builds a URL from the a parts array like one returned by parse_url().
Definition: elgglib.php:859
isValid($url)
Validates HMAC signature.
Definition: UrlSigner.php:65
elgg_build_hmac($data)
Get an HMAC token builder/validator object.
Definition: actions.php:62
sign($url, $expires=false)
Normalizes and signs the URL with SHA256 HMAC key.
Definition: UrlSigner.php:27