xmlrpc (mnet) function to get the file.
reads in the file and returns it base_64 encoded
so that it can be enrypted by mnet.

@param string $token the token recieved previously during send_content_intent
553479
public static function fetch_file($token) {
        global $DB;
        $remoteclient = get_mnet_remote_client();
        try {
            if (!$transferid = $DB->get_field('portfolio_mahara_queue', 'transferid', array('token' => $token))) {
                throw new mnet_server_exception(8009, 'mnet_notoken', 'portfolio_mahara');
            }
            $exporter = portfolio_exporter::rewaken_object($transferid);
        } catch (portfolio_exception $e) {
            throw new mnet_server_exception(8010, 'mnet_noid', 'portfolio_mahara');
        }
        if ($exporter->get('instance')->get_config('mnethostid') != $remoteclient->id) {
            throw new mnet_server_exception(8011, 'mnet_wronghost', 'portfolio_mahara');
        }
        global $CFG;
        try {
            $i = $exporter->get('instance');
            $f = $i->get('file');
            if (empty($f) || !($f instanceof stored_file)) {
                throw new mnet_server_exception(8012, 'mnet_nofile', 'portfolio_mahara');
            }
            try {
                $c = $f->get_content();
            } catch (file_exception $e) {
                throw new mnet_server_exception(8013, 'mnet_nofilecontents', 'portfolio_mahara', $e->getMessage());
            }
            $contents = base64_encode($c);
        } catch (Exception $e) {
            throw new mnet_server_exception(8013, 'mnet_nofile', 'portfolio_mahara');
        }
        $exporter->log_transfer();
        $exporter->process_stage_cleanup(true);
        return $contents;
    }
975920
private function decodeToken(string $token): array
    {
        try {
            $decoded = JWT::decode(
                $token,
                $this->options["secret"],
                (array) $this->options["algorithm"]
            );
            return (array) $decoded;
        } catch (Exception $exception) {
            $this->log(LogLevel::WARNING, $exception->getMessage(), [$token]);
            throw $exception;
        }
    }
309270
public static function fromString($token)
    {
        $jwtParser = new JwtParser();
        $tokenParts = explode('.', $token);
        if (count($tokenParts) != 3) {
            throw new InvalidArgumentException("JWT parse failed: " . $token);
        }
        $tokenBase64Header = $tokenParts[0];
        $tokenBase64Body = $tokenParts[1];
        $tokenBase64Signature = $tokenParts[2];

        $urlSafeBase64Decode = function ($data) {
            return base64_decode(strtr($data, '-_', '+/'));
        };

        $tokenJsonHeader = $urlSafeBase64Decode($tokenBase64Header);
        $tokenJsonBody = $urlSafeBase64Decode($tokenBase64Body);
        $signature = $urlSafeBase64Decode($tokenBase64Signature);

        return new Jwt(
            $jwtParser->parseJwtHeaderContent($tokenJsonHeader),
            $jwtParser->parseJwtBodyContent($tokenJsonBody),
            $signature
        );
    }
972596
public function parse($token)
    {
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            throw new InvalidArgumentException('Token is invalid');
        }
        $this->token = $token;
        $this->header = json_decode(base64_decode($parts[0]), true);
        $this->payload = json_decode(base64_decode($parts[1]), true);
        $this->signature = $parts[2];
    }
1333836
public function createMdmPayload($token, $magicPushToken)
    {
        $jsonPayload = json_encode(array('mdm' => $magicPushToken));

        $payload = chr(0) . chr(0) . chr(32) . base64_decode($token) . chr(0)  . chr(strlen($jsonPayload)) . $jsonPayload;

        return $payload;
    }
471790
public function getDecodedToken(string $jwt)
    {
        try {
            /** @noinspection PhpUnusedLocalVariableInspection */
            [$headb64, $bodyb64, $cryptob64] = \explode('.', $jwt);
            $decodedToken = \json_decode(JWT::urlsafeB64Decode($bodyb64));

            /** @noinspection NullPointerExceptionInspection */
            JWT::decode($jwt, $this->findTenant($decodedToken->iss)->getSharedSecret(), ['HS256']);

            return $decodedToken;
        } catch (\Throwable $e) {
            throw new AuthenticationException($e->getMessage());
        }
    }
1000345
protected function getTokenAsEncodedWord(string $token, int $firstLineOffset = 0): string
    {
        if (null === self::$encoder) {
            self::$encoder = new QpMimeHeaderEncoder();
        }

        // Adjust $firstLineOffset to account for space needed for syntax
        $charsetDecl = $this->charset;
        if (null !== $this->lang) {
            $charsetDecl .= '*'.$this->lang;
        }
        $encodingWrapperLength = \strlen('=?'.$charsetDecl.'?'.self::$encoder->getName().'??=');

        if ($firstLineOffset >= 75) {
            //Does this logic need to be here?
            $firstLineOffset = 0;
        }

        $encodedTextLines = explode("\r\n",
            self::$encoder->encodeString($token, $this->charset, $firstLineOffset, 75 - $encodingWrapperLength)
        );

        if ('iso-2022-jp' !== strtolower($this->charset)) {
            // special encoding for iso-2022-jp using mb_encode_mimeheader
            foreach ($encodedTextLines as $lineNum => $line) {
                $encodedTextLines[$lineNum] = '=?'.$charsetDecl.'?'.self::$encoder->getName().'?'.$line.'?=';
            }
        }

        return implode("\r\n ", $encodedTextLines);
    }
1175962
public function decode($token)
    {
        try {
            $data = JWT::decode($token, $this->secretKey, $this->allowed_algs);
        } catch (\UnexpectedValueException $e) {
            throw new \UnexpectedValueException($e->getMessage());
        } catch (\DomainException $e) {
            throw new \UnexpectedValueException($e->getMessage());
        }

        if ($data->exp < time()) {
            throw new \UnexpectedValueException('token not allowed');
        }

        return $data;
    }
327917
public function Store($token)
    {
        if (!is_writable($this->GetPathToTemporaryFolder())) {
            throw new \MangoPay\Libraries\Exception('Cannot create or write to file ' . $this->GetPathToTemporaryFolder());
        }
        
        $serialized = serialize($token);
        $result = file_put_contents($this->GetPathToFile(), $this->_prefixContent . $serialized, LOCK_EX);
        if ($result === false) {
            throw new \MangoPay\Libraries\Exception('Cannot put token to file');
        }
    }
265924
public function get($data=null, $token=null)
    {
        if ($token) {
            $res = static::refresh($token, $data);
            if (isset($res['token'])) {
                return $res['token'];
            }
        }
        
        $data = static::formatData($data);
        
        if ($this->options['shared']) {
            $token = md5(serialize($data));
            $data['_token_'] = $token;
        } else {
            $token = Crypt::instance()->encrypt(uniqid());
        }
        $key = $token;
        
        $data['_expire_time_'] = time() + static::getExpire();
        
        static::getStorage()->set($key, $data);
        
        return $token;
    }
378433
public function downloadExecute(Token $token)
    {
        if (false === $list = @unserialize($token->getData())) {
            return $this->app->json([
                'success' => false,
                'message' => 'Invalid datas'
            ]);
        }

        set_time_limit(0);
        // Force the session to be saved and closed.
        /** @var Session $session */
        $session = $this->app['session'];
        $session->save();
        ignore_user_abort(true);

        if ($list['count'] > 1) {
            \set_export::build_zip(
                $this->app,
                $token,
                $list,
                sprintf('%s/%s.zip', $this->app['tmp.download.path'], $token->getValue()) // Dest file
            );
        } else {
            $list['complete'] = true;
            $token->setData(serialize($list));
            /** @var EntityManagerInterface $manager */
            $manager = $this->app['orm.em'];
            $manager->persist($token);
            $manager->flush();
        }

        return $this->app->json([
            'success' => true,
            'message' => ''
        ]);
    }
679571
public function decode($token)
    {
        try {
            $jwt = $this->parser->parse($token);
        } catch (Exception $e) {
            throw new TokenInvalidException('Could not decode token: '.$e->getMessage(), $e->getCode(), $e);
        }

        if (! $jwt->verify($this->signer, $this->getVerificationKey())) {
            throw new TokenInvalidException('Token Signature could not be verified.');
        }

        return (new Collection($jwt->getClaims()))->map(function ($claim) {
            return is_object($claim) ? $claim->getValue() : $claim;
        })->toArray();
    }
574357
public static function authenticateWithToken($token) {
    $pkeyResource = openssl_pkey_new(array(
      "digest_alg" => "sha256",
      "private_key_bits" => 2048
    ));

    openssl_pkey_export($pkeyResource, $generatedPrivateKey);

    $pkeyResourceDetails = openssl_pkey_get_details($pkeyResource);
    $generatedPublicKey = $pkeyResourceDetails["key"];

    $requestResult = Request::post("/g_business/v1/authentication_keys", array(
      "body" => array(
        "public_key" => $generatedPublicKey,
        "token" => $token
      )
    ));

    self::$privateKey = $generatedPrivateKey;
    self::$publicKey = $generatedPublicKey;
    self::$keyId = $requestResult->key_id;

    $returnClass = new ApiAuthentication();
    $returnClass->privateKey = $generatedPrivateKey;
    $returnClass->publicKey = $generatedPublicKey;
    $returnClass->keyId = $requestResult->key_id;
    return $returnClass;
  }
447705
public function decryptToken(string $token)
    {
        $tokenData = false;
        $encrypted = base64_decode($token);

        if ($encrypted) {
            $serialized = Security::decrypt($encrypted, Configure::read('Security.cryptKey'));
            $tokenData = unserialize($serialized);
        }

        return $tokenData;
    }
1331375
public static function getAsset($token)
    {
        $key = self::getJwtKey();

        $payload = JWT::decode($token, $key, array('HS256'));

        $providerClass = $payload->provider;
        $category = $payload->category;
        $data = (array) $payload->data;

        $provider = new $providerClass($category);

        return new Asset($token, $provider, $data);
    }
966415
public function readLine($token = "\n")
  {
    $this->connect();

    $line = TeamSpeak3_Helper_String::factory("");

    while(!$line->endsWith($token))
    {
      $this->waitForReadyRead();

      $data = @fgets($this->stream, 4096);

      TeamSpeak3_Helper_Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "DataRead", $data);

      if($data === FALSE)
      {
        if($line->count())
        {
          $line->append($token);
        }
        else
        {
          throw new TeamSpeak3_Transport_Exception("connection to server '" . $this->config["host"] . ":" . $this->config["port"] . "' lost");
        }
      }
      else
      {
        $line->append($data);
      }
    }

    return $line->trim();
  }
995022
public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $stream = $this->parser->getStream();

        $count = null;
        $vars = new ArrayExpression([], $lineno);
        $domain = null;
        $locale = null;
        if (!$stream->test(Token::BLOCK_END_TYPE)) {
            if ($stream->test('count')) {
                // {% trans count 5 %}
                $stream->next();
                $count = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('with')) {
                // {% trans with vars %}
                $stream->next();
                $vars = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('from')) {
                // {% trans from "messages" %}
                $stream->next();
                $domain = $this->parser->getExpressionParser()->parseExpression();
            }

            if ($stream->test('into')) {
                // {% trans into "fr" %}
                $stream->next();
                $locale = $this->parser->getExpressionParser()->parseExpression();
            } elseif (!$stream->test(Token::BLOCK_END_TYPE)) {
                throw new SyntaxError('Unexpected token. Twig was looking for the "with", "from", or "into" keyword.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
            }
        }

        // {% trans %}message{% endtrans %}
        $stream->expect(Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse([$this, 'decideTransFork'], true);

        if (!$body instanceof TextNode && !$body instanceof AbstractExpression) {
            throw new SyntaxError('A message inside a trans tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext());
        }

        $stream->expect(Token::BLOCK_END_TYPE);

        return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag());
    }