Moodle authentication plugin for Macaroons

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Macaroons;
  3. class Packet
  4. {
  5. const PACKET_PREFIX_LENGTH = 4;
  6. private $key;
  7. private $data;
  8. public function __construct($key = NULL, $data = NULL)
  9. {
  10. $this->key = $key;
  11. $this->data = $data;
  12. }
  13. public function packetize(Array $packets)
  14. {
  15. // PHP 5.3 workaround
  16. // $this isn't bound in anonymous functions
  17. return join('',
  18. array_map(
  19. array($this, 'mapPacketsCallback'),
  20. array_keys($packets),
  21. $packets
  22. )
  23. );
  24. }
  25. public function getKey()
  26. {
  27. return $this->key;
  28. }
  29. public function getData()
  30. {
  31. return $this->data;
  32. }
  33. private function mapPacketsCallback($key, $data)
  34. {
  35. return $this->encode($key, $data);
  36. }
  37. private function encode($key, $data)
  38. {
  39. $packetSize = self::PACKET_PREFIX_LENGTH + 2 + strlen($key) + strlen($data);
  40. // packetSize can't be larger than 0xFFFF
  41. if ($packetSize > pow(16, 4))
  42. throw new \InvalidArgumentException('Data is too long for a binary packet.');
  43. // hexadecimal representation with lowercase letters
  44. $packetSizeHex = sprintf("%x", $packetSize);
  45. $header = str_pad($packetSizeHex, 4, '0', STR_PAD_LEFT);
  46. $packetContent = "$key $data\n";
  47. $packet = $header . $packetContent;
  48. return $packet;
  49. }
  50. public function decode($packet)
  51. {
  52. $packets = explode(' ', $packet);
  53. $key = array_shift($packets);
  54. $data = substr($packet, strlen($key) + 1);
  55. return new Packet($key, $data);
  56. }
  57. }