/*
Have to register custom interceptor to
set  "x-li-format: "json" header as
otherwise we appear to get error from linkedin
which suggests its expecting xml rather than json.
API appears to ignore Content-Type header
7346
private void registerJsonFormatInterceptor() {		
		RestTemplate restTemplate = getRestTemplate();
		if (interceptorsSupported) {
			List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
			interceptors.add(new JsonFormatInterceptor());
		} else {
			// for Spring 3.0.x where interceptors aren't supported
			ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory();
			JsonFormatHeaderRequestFactory newRequestFactory = new JsonFormatHeaderRequestFactory(originalRequestFactory);
			restTemplate.setRequestFactory(newRequestFactory);
		}
	}
1294226
function &parseResponseHeaders(&$data, $headers_processed=false)
		{
				// Support "web-proxy-tunelling" connections for https through proxies
				if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data))
				{
					// Look for CR/LF or simple LF as line separator,
					// (even though it is not valid http)
					$pos = strpos($data,"\r\n\r\n");
					if($pos || is_int($pos))
					{
						$bd = $pos+4;
					}
					else
					{
						$pos = strpos($data,"\n\n");
						if($pos || is_int($pos))
						{
							$bd = $pos+2;
						}
						else
						{
							// No separation between response headers and body: fault?
							$bd = 0;
						}
					}
					if ($bd)
					{
						// this filters out all http headers from proxy.
						// maybe we could take them into account, too?
						$data = substr($data, $bd);
					}
					else
					{
						error_log('XML-RPC: '.__METHOD__.': HTTPS via proxy error, tunnel connection possibly failed');
						$r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (HTTPS via proxy error, tunnel connection possibly failed)');
						return $r;
					}
				}

				// Strip HTTP 1.1 100 Continue header if present
				while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data))
				{
					$pos = strpos($data, 'HTTP', 12);
					// server sent a Continue header without any (valid) content following...
					// give the client a chance to know it
					if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
					{
						break;
					}
					$data = substr($data, $pos);
				}
				if(!preg_match('/^HTTP\/[0-9.]+ 200 /', $data))
				{
					$errstr= substr($data, 0, strpos($data, "\n")-1);
					error_log('XML-RPC: '.__METHOD__.': HTTP error, got response: ' .$errstr);
					$r=new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['http_error'], $GLOBALS['xmlrpcstr']['http_error']. ' (' . $errstr . ')');
					return $r;
				}

				$GLOBALS['_xh']['headers'] = array();
				$GLOBALS['_xh']['cookies'] = array();

				// be tolerant to usage of \n instead of \r\n to separate headers and data
				// (even though it is not valid http)
				$pos = strpos($data,"\r\n\r\n");
				if($pos || is_int($pos))
				{
					$bd = $pos+4;
				}
				else
				{
					$pos = strpos($data,"\n\n");
					if($pos || is_int($pos))
					{
						$bd = $pos+2;
					}
					else
					{
						// No separation between response headers and body: fault?
						// we could take some action here instead of going on...
						$bd = 0;
					}
				}
				// be tolerant to line endings, and extra empty lines
				$ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
				while(list(,$line) = @each($ar))
				{
					// take care of multi-line headers and cookies
					$arr = explode(':',$line,2);
					if(count($arr) > 1)
					{
						$header_name = strtolower(trim($arr[0]));
						/// @todo some other headers (the ones that allow a CSV list of values)
						/// do allow many values to be passed using multiple header lines.
						/// We should add content to $GLOBALS['_xh']['headers'][$header_name]
						/// instead of replacing it for those...
						if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
						{
							if ($header_name == 'set-cookie2')
							{
								// version 2 cookies:
								// there could be many cookies on one line, comma separated
								$cookies = explode(',', $arr[1]);
							}
							else
							{
								$cookies = array($arr[1]);
							}
							foreach ($cookies as $cookie)
							{
								// glue together all received cookies, using a comma to separate them
								// (same as php does with getallheaders())
								if (isset($GLOBALS['_xh']['headers'][$header_name]))
									$GLOBALS['_xh']['headers'][$header_name] .= ', ' . trim($cookie);
								else
									$GLOBALS['_xh']['headers'][$header_name] = trim($cookie);
								// parse cookie attributes, in case user wants to correctly honour them
								// feature creep: only allow rfc-compliant cookie attributes?
								// @todo support for server sending multiple time cookie with same name, but using different PATHs
								$cookie = explode(';', $cookie);
								foreach ($cookie as $pos => $val)
								{
									$val = explode('=', $val, 2);
									$tag = trim($val[0]);
									$val = trim(@$val[1]);
									/// @todo with version 1 cookies, we should strip leading and trailing " chars
									if ($pos == 0)
									{
										$cookiename = $tag;
										$GLOBALS['_xh']['cookies'][$tag] = array();
										$GLOBALS['_xh']['cookies'][$cookiename]['value'] = urldecode($val);
									}
									else
									{
										if ($tag != 'value')
										{
										  $GLOBALS['_xh']['cookies'][$cookiename][$tag] = $val;
										}
									}
								}
							}
						}
						else
						{
							$GLOBALS['_xh']['headers'][$header_name] = trim($arr[1]);
						}
					}
					elseif(isset($header_name))
					{
						///	@todo version1 cookies might span multiple lines, thus breaking the parsing above
						$GLOBALS['_xh']['headers'][$header_name] .= ' ' . trim($line);
					}
				}

				$data = substr($data, $bd);

				if($this->debug && count($GLOBALS['_xh']['headers']))
				{
					print '<PRE>';
					foreach($GLOBALS['_xh']['headers'] as $header => $value)
					{
						print htmlentities("HEADER: $header: $value\n");
					}
					foreach($GLOBALS['_xh']['cookies'] as $header => $value)
					{
						print htmlentities("COOKIE: $header={$value['value']}\n");
					}
					print "</PRE>\n";
				}

				// if CURL was used for the call, http headers have been processed,
				// and dechunking + reinflating have been carried out
				if(!$headers_processed)
				{
					// Decode chunked encoding sent by http 1.1 servers
					if(isset($GLOBALS['_xh']['headers']['transfer-encoding']) && $GLOBALS['_xh']['headers']['transfer-encoding'] == 'chunked')
					{
						if(!$data = decode_chunked($data))
						{
							error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to rebuild the chunked data received from server');
							$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['dechunk_fail'], $GLOBALS['xmlrpcstr']['dechunk_fail']);
							return $r;
						}
					}

					// Decode gzip-compressed stuff
					// code shamelessly inspired from nusoap library by Dietrich Ayala
					if(isset($GLOBALS['_xh']['headers']['content-encoding']))
					{
						$GLOBALS['_xh']['headers']['content-encoding'] = str_replace('x-', '', $GLOBALS['_xh']['headers']['content-encoding']);
						if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'] == 'gzip')
						{
							// if decoding works, use it. else assume data wasn't gzencoded
							if(function_exists('gzinflate'))
							{
								if($GLOBALS['_xh']['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data))
								{
									$data = $degzdata;
									if($this->debug)
									print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
								}
								elseif($GLOBALS['_xh']['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
								{
									$data = $degzdata;
									if($this->debug)
									print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" . htmlentities($data) . "\n---END---</PRE>";
								}
								else
								{
									error_log('XML-RPC: '.__METHOD__.': errors occurred when trying to decode the deflated data received from server');
									$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['decompress_fail'], $GLOBALS['xmlrpcstr']['decompress_fail']);
									return $r;
								}
							}
							else
							{
								error_log('XML-RPC: '.__METHOD__.': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
								$r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['cannot_decompress'], $GLOBALS['xmlrpcstr']['cannot_decompress']);
								return $r;
							}
						}
					}
				} // end of 'if needed, de-chunk, re-inflate response'

				// real stupid hack to avoid PHP complaining about returning NULL by ref
				$r = null;
				$r =& $r;
				return $r;
		}
687601
public static Builder setContentTypeHeaders(boolean isBinaryTransportEnabled, Builder requestBuilder)
    {
        if (isBinaryTransportEnabled) {
            return requestBuilder
                    .setHeader(CONTENT_TYPE, APPLICATION_JACKSON_SMILE)
                    .setHeader(ACCEPT, APPLICATION_JACKSON_SMILE);
        }
        return requestBuilder
                .setHeader(CONTENT_TYPE, JSON_UTF_8.toString())
                .setHeader(ACCEPT, JSON_UTF_8.toString());
    }
790591
function (xhr) {
        this.xhr = xhr;
        this.status = xhr.status;
        this.$nativeResponseHeaders = xhr.getAllResponseHeaders();
        this.responses = {};

        var xml = xhr.responseXML;

        // Construct response list
        if (xml && xml.documentElement) {
            this.responses.xml = xml;
        }
        this.responses.text = xhr.responseText;

        try {
            this.statusText = xhr.statusText;
        } catch (e) {
            this.statusText = "";
        }
    }
422819
function json (request) {

    var type = request.headers.get('Content-Type') || '';

    if (isObject(request.body) && type.indexOf('application/json') === 0) {
        request.body = JSON.stringify(request.body);
    }

    return function (response) {

        return response.bodyText ? when(response.text(), function (text) {

            var type = response.headers.get('Content-Type') || '';

            if (type.indexOf('application/json') === 0 || isJson(text)) {

                try {
                    response.body = JSON.parse(text);
                } catch (e) {
                    response.body = null;
                }

            } else {
                response.body = text;
            }

            return response;

        }) : response;

    };
}
566005
function setAuthType(auth_type) {
    var headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    };

    if (auth_type == 'AccessToken') {
        headers['Authorization'] = _config.access_token;
    }
    else if (auth_type == 'AppCredentials') {
        headers['x-accela-appid'] = _config.app_id
        headers['x-accela-appsecret'] = _config.app_secret;
    }
    else {
        headers['x-accela-appid'] = _config.app_id
        headers['x-accela-agency'] = _config.agency;
        headers['x-accela-environment'] = _config.environment;
    }
    return headers;
}
232652
public static HandlerChainInfo buildHandlerChainInfoFromXML(HandlerChain hChain) {
        HandlerChainInfo hcInfo = new HandlerChainInfo();
        // set Service QName
        if (hChain.getServiceNamePattern() != null) {
            hcInfo.setServiceNamePattern(new QName(hChain.getServiceNamePattern().getNamespaceURI(),
                            hChain.getServiceNamePattern().getLocalPart()));
        } else {
            hcInfo.setServiceNamePattern(new QName("*"));
        }
        // set Port QName
        if (hChain.getPortNamePattern() != null) {

            hcInfo.setPortNamePattern(new QName(hChain.getPortNamePattern().getNamespaceURI(),
                            hChain.getPortNamePattern().getLocalPart()));
        } else {
            hcInfo.setPortNamePattern(new QName("*"));
        }
        // add protocol bindings
        hcInfo.addProtocolBindings(hChain.getProtocolBindings());

        for (com.ibm.ws.javaee.dd.common.wsclient.Handler handler : hChain.getHandlers()) {
            hcInfo.addHandlerInfo(buildHandlerInfoFromXML(handler));
        }
        return hcInfo;
    }
1341237
function initialize({ url, cdnUrl, certificateAuthority, proxyUrl }) {
  if (!is.string(url)) {
    throw new Error("WebAPI.initialize: Invalid server url");
  }
  if (!is.string(cdnUrl)) {
    throw new Error("WebAPI.initialize: Invalid cdnUrl");
  }
  if (!is.string(certificateAuthority)) {
    throw new Error("WebAPI.initialize: Invalid certificateAuthority");
  }

  // Thanks to function-hoisting, we can put this return statement before all of the
  //   below function definitions.
  return {
    connect
  };

  // Then we connect to the server with user-specific information. This is the only API
  //   exposed to the browser context, ensuring that it can't connect to arbitrary
  //   locations.
  function connect({ username: initialUsername, password: initialPassword }) {
    let username = initialUsername;
    let password = initialPassword;

    // Thanks, function hoisting!
    return {
      confirmCode,
      getAttachment,
      getAvatar,
      getDevices,
      getKeysForNumber,
      getMessageSocket,
      getMyKeys,
      getProfile,
      getProvisioningSocket,
      putAttachment,
      registerKeys,
      requestVerificationSMS,
      requestVerificationVoice,
      sendMessages,
      setSignedPreKey
    };

    function _ajax(param) {
      if (!param.urlParameters) {
        // eslint-disable-next-line no-param-reassign
        param.urlParameters = "";
      }
      return _outerAjax(null, {
        certificateAuthority,
        contentType: "application/json; charset=utf-8",
        data: param.jsonData && _jsonThing(param.jsonData),
        host: url,
        password,
        path: URL_CALLS[param.call] + param.urlParameters,
        proxyUrl,
        responseType: param.responseType,
        timeout: param.timeout,
        type: param.httpType,
        user: username,
        validateResponse: param.validateResponse
      }).catch(e => {
        const { code } = e;
        if (code === 200) {
          // happens sometimes when we get no response
          // (TODO: Fix server to return 204? instead)
          return null;
        }
        let message;
        switch (code) {
          case -1:
            message =
              "Failed to connect to the server, please check your network connection.";
            break;
          case 413:
            message = "Rate limit exceeded, please try again later.";
            break;
          case 403:
            message = "Invalid code, please try again.";
            break;
          case 417:
            // TODO: This shouldn't be a thing?, but its in the API doc?
            message = "Number already registered.";
            break;
          case 401:
            message =
              "Invalid authentication, most likely someone re-registered and invalidated our registration.";
            break;
          case 404:
            message = "Number is not registered.";
            break;
          default:
            message =
              "The server rejected our query, please file a bug report.";
        }
        e.message = message;
        throw e;
      });
    }

    function getProfile(number) {
      return _ajax({
        call: "profile",
        httpType: "GET",
        urlParameters: `/${number}`,
        responseType: "json"
      });
    }

    function getAvatar(path) {
      // Using _outerAJAX, since it's not hardcoded to the Signal Server. Unlike our
      //   attachment CDN, it uses our self-signed certificate, so we pass it in.
      return _outerAjax(`${cdnUrl}/${path}`, {
        certificateAuthority,
        contentType: "application/octet-stream",
        proxyUrl,
        responseType: "arraybuffer",
        timeout: 0,
        type: "GET"
      });
    }

    function requestVerificationSMS(number) {
      return _ajax({
        call: "accounts",
        httpType: "GET",
        urlParameters: `/sms/code/${number}`
      });
    }

    function requestVerificationVoice(number) {
      return _ajax({
        call: "accounts",
        httpType: "GET",
        urlParameters: `/voice/code/${number}`
      });
    }

    async function confirmCode(
      number,
      code,
      newPassword,
      signalingKey,
      registrationId,
      deviceName
    ) {
      const jsonData = {
        signalingKey: _btoa(_getString(signalingKey)),
        supportsSms: false,
        fetchesMessages: true,
        registrationId
      };

      let call;
      let urlPrefix;
      let schema;
      let responseType;

      if (deviceName) {
        jsonData.name = deviceName;
        call = "devices";
        urlPrefix = "/";
        schema = { deviceId: "number" };
        responseType = "json";
      } else {
        call = "accounts";
        urlPrefix = "/code/";
      }

      // We update our saved username and password, since we're creating a new account
      username = number;
      password = newPassword;

      const response = await _ajax({
        call,
        httpType: "PUT",
        urlParameters: urlPrefix + code,
        jsonData,
        responseType,
        validateResponse: schema
      });

      // From here on out, our username will be our phone number combined with device
      username = `${number}.${response.deviceId || 1}`;

      return response;
    }

    function getDevices() {
      return _ajax({
        call: "devices",
        httpType: "GET"
      });
    }

    function registerKeys(genKeys) {
      const keys = {};
      keys.identityKey = _btoa(_getString(genKeys.identityKey));
      keys.signedPreKey = {
        keyId: genKeys.signedPreKey.keyId,
        publicKey: _btoa(_getString(genKeys.signedPreKey.publicKey)),
        signature: _btoa(_getString(genKeys.signedPreKey.signature))
      };

      keys.preKeys = [];
      let j = 0;
      // eslint-disable-next-line guard-for-in, no-restricted-syntax
      for (const i in genKeys.preKeys) {
        keys.preKeys[j] = {
          keyId: genKeys.preKeys[i].keyId,
          publicKey: _btoa(_getString(genKeys.preKeys[i].publicKey))
        };
        j += 1;
      }

      // This is just to make the server happy
      // (v2 clients should choke on publicKey)
      keys.lastResortKey = { keyId: 0x7fffffff, publicKey: _btoa("42") };

      return _ajax({
        call: "keys",
        httpType: "PUT",
        jsonData: keys
      });
    }

    function setSignedPreKey(signedPreKey) {
      return _ajax({
        call: "signed",
        httpType: "PUT",
        jsonData: {
          keyId: signedPreKey.keyId,
          publicKey: _btoa(_getString(signedPreKey.publicKey)),
          signature: _btoa(_getString(signedPreKey.signature))
        }
      });
    }

    function getMyKeys() {
      return _ajax({
        call: "keys",
        httpType: "GET",
        responseType: "json",
        validateResponse: { count: "number" }
      }).then(res => res.count);
    }

    function getKeysForNumber(number, deviceId = "*") {
      return _ajax({
        call: "keys",
        httpType: "GET",
        urlParameters: `/${number}/${deviceId}`,
        responseType: "json",
        validateResponse: { identityKey: "string", devices: "object" }
      }).then(res => {
        if (res.devices.constructor !== Array) {
          throw new Error("Invalid response");
        }
        res.identityKey = _base64ToBytes(res.identityKey);
        res.devices.forEach(device => {
          if (
            !_validateResponse(device, { signedPreKey: "object" }) ||
            !_validateResponse(device.signedPreKey, {
              publicKey: "string",
              signature: "string"
            })
          ) {
            throw new Error("Invalid signedPreKey");
          }
          if (device.preKey) {
            if (
              !_validateResponse(device, { preKey: "object" }) ||
              !_validateResponse(device.preKey, { publicKey: "string" })
            ) {
              throw new Error("Invalid preKey");
            }
            // eslint-disable-next-line no-param-reassign
            device.preKey.publicKey = _base64ToBytes(device.preKey.publicKey);
          }
          // eslint-disable-next-line no-param-reassign
          device.signedPreKey.publicKey = _base64ToBytes(
            device.signedPreKey.publicKey
          );
          // eslint-disable-next-line no-param-reassign
          device.signedPreKey.signature = _base64ToBytes(
            device.signedPreKey.signature
          );
        });
        return res;
      });
    }

    function sendMessages(destination, messageArray, timestamp, silent) {
      const jsonData = { messages: messageArray, timestamp };

      if (silent) {
        jsonData.silent = true;
      }

      return _ajax({
        call: "messages",
        httpType: "PUT",
        urlParameters: `/${destination}`,
        jsonData,
        responseType: "json"
      });
    }

    function getAttachment(id) {
      return _ajax({
        call: "attachment",
        httpType: "GET",
        urlParameters: `/${id}`,
        responseType: "json",
        validateResponse: { location: "string" }
      }).then(response =>
        // Using _outerAJAX, since it's not hardcoded to the Signal Server
        _outerAjax(response.location, {
          contentType: "application/octet-stream",
          proxyUrl,
          responseType: "arraybuffer",
          timeout: 0,
          type: "GET"
        })
      );
    }

    function putAttachment(encryptedBin) {
      return _ajax({
        call: "attachment",
        httpType: "GET",
        responseType: "json"
      }).then(response =>
        // Using _outerAJAX, since it's not hardcoded to the Signal Server
        _outerAjax(response.location, {
          contentType: "application/octet-stream",
          data: encryptedBin,
          processData: false,
          proxyUrl,
          timeout: 0,
          type: "PUT"
        }).then(() => response.idString)
      );
    }

    function getMessageSocket() {
      console.info("opening message socket", url);
      const fixedScheme = url
        .replace("https://", "wss://")
        .replace("http://", "ws://");
      const login = encodeURIComponent(username);
      const pass = encodeURIComponent(password);

      return _createSocket(
        `${fixedScheme}/v1/websocket/?login=${login}&password=${pass}&agent=OWD`,
        { certificateAuthority, proxyUrl }
      );
    }

    function getProvisioningSocket() {
      console.info("opening provisioning socket", url);
      const fixedScheme = url
        .replace("https://", "wss://")
        .replace("http://", "ws://");

      return _createSocket(
        `${fixedScheme}/v1/websocket/provisioning/?agent=OWD`,
        { certificateAuthority, proxyUrl }
      );
    }
  }
}
806155
function () {
                // ##### END: MODIFIED BY SAP
                    if (done || xhr === null || xhr.readyState !== 4) {
                        return;
                    }

                    // Workaround for XHR behavior on IE.
                    var statusText = xhr.statusText;
                    var statusCode = xhr.status;
                    if (statusCode === 1223) {
                        statusCode = 204;
                        statusText = "No Content";
                    }

                    var headers = [];
                    readResponseHeaders(xhr, headers);

                    // 
                    var xml = null;
                    if (datajs._sap && xhr.responseXML) {
                    	xml = xhr.responseXML;
                    }
                   	// ##### END: MODIFIED BY SAP

                    var response = { requestUri: url, statusCode: statusCode, statusText: statusText, headers: headers, body: xhr.responseText };

                    done = true;
                    xhr = null;
                    if (statusCode >= 200 && statusCode <= 299) {
                        success(response);
                    } else {
                    	// 
                    	// normalize response headers here which is also done in the success function call above
                      	normalizeHeaders(response.headers);
                      	// ##### END: MODIFIED BY SAP
                        error({ message: "HTTP request failed", request: request, response: response });
                    }
                    // 
                    if (datajs._sap && response.requestUri.indexOf("$metadata") > -1) {

                    	var mSettings = {
                      	   supportXML: xml,
                      	   response: response
                      	};
                    	datajs._sap._supportInfo({context: xml, env: {caller:'datajs', settings: mSettings, type:"metadata"}});
                    }
                    // ##### END: MODIFIED BY SAP
                }
394411
function(method, data, callback) {
      xhr.open(method, url, true, user, password);
      if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
      if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
      if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
      if (responseType != null) xhr.responseType = responseType;
      if (timeout > 0) xhr.timeout = timeout;
      if (callback == null && typeof data === "function") callback = data, data = null;
      if (callback != null && callback.length === 1) callback = fixCallback(callback);
      if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
      event.call("beforesend", request, xhr);
      xhr.send(data == null ? null : data);
      return request;
    }
431309
function(hljs) {
  var XML_IDENT_RE = '[A-Za-z0-9\\._:-]+';
  var PHP = {
    begin: /<\?(php)?(?!\w)/, end: /\?>/,
    subLanguage: 'php', subLanguageMode: 'continuous'
  };
  var TAG_INTERNALS = {
    endsWithParent: true,
    illegal: /</,
    relevance: 0,
    contains: [
      PHP,
      {
        className: 'attribute',
        begin: XML_IDENT_RE,
        relevance: 0
      },
      {
        begin: '=',
        relevance: 0,
        contains: [
          {
            className: 'value',
            variants: [
              {begin: /"/, end: /"/},
              {begin: /'/, end: /'/},
              {begin: /[^\s\/>]+/}
            ]
          }
        ]
      }
    ]
  };
  return {
    aliases: ['html', 'xhtml', 'rss', 'atom', 'xsl', 'plist'],
    case_insensitive: true,
    contains: [
      {
        className: 'doctype',
        begin: '<!DOCTYPE', end: '>',
        relevance: 10,
        contains: [{begin: '\\[', end: '\\]'}]
      },
      {
        className: 'comment',
        begin: '<!--', end: '-->',
        relevance: 10
      },
      {
        className: 'cdata',
        begin: '<\\!\\[CDATA\\[', end: '\\]\\]>',
        relevance: 10
      },
      {
        className: 'tag',
        /*
        The lookahead pattern (?=...) ensures that 'begin' only matches
        '<style' as a single word, followed by a whitespace or an
        ending braket. The '$' is needed for the lexeme to be recognized
        by hljs.subMode() that tests lexemes outside the stream.
        */
        begin: '<style(?=\\s|>|$)', end: '>',
        keywords: {title: 'style'},
        contains: [TAG_INTERNALS],
        starts: {
          end: '</style>', returnEnd: true,
          subLanguage: 'css'
        }
      },
      {
        className: 'tag',
        // See the comment in the <style tag about the lookahead pattern
        begin: '<script(?=\\s|>|$)', end: '>',
        keywords: {title: 'script'},
        contains: [TAG_INTERNALS],
        starts: {
          end: '</script>', returnEnd: true,
          subLanguage: 'javascript'
        }
      },
      {
        begin: '<%', end: '%>',
        subLanguage: 'vbscript'
      },
      PHP,
      {
        className: 'pi',
        begin: /<\?\w+/, end: /\?>/,
        relevance: 10
      },
      {
        className: 'tag',
        begin: '</?', end: '/?>',
        contains: [
          {
            className: 'title', begin: '[^ /><]+', relevance: 0
          },
          TAG_INTERNALS
        ]
      }
    ]
  };
}
905369
function ( xhr, type ) {
		type = type || "";
		var result, obj;

		if ( ( regex.json_maybe.test( type ) || string.isEmpty( type ) ) && ( regex.json_wrap.test( xhr.responseText ) && Boolean( obj = json.decode( xhr.responseText, true ) ) ) ) {
			result = obj;
		}
		else if ( regex.xml.test( type ) ) {
			if ( type !== "text/xml" ) {
				xhr.overrideMimeType( "text/xml" );
			}

			result = xhr.responseXML;
		}
		else if ( type === "text/plain" && regex.is_xml.test( xhr.responseText) && xml.valid( xhr.responseText ) ) {
			result = xml.decode( xhr.responseText );
		}
		else {
			result = xhr.responseText;
		}

		return result;
	}
958911
function requestJson(method, url, successCallback, failureCallback) {
    successCallback = successCallback || console.log;
    failureCallback = failureCallback || console.error || console.warn || console.log;
    var xhr = (typeof XDomainRequest !== 'undefined') ?
      (new XDomainRequest()) :
      (new XMLHttpRequest());
    xhr.onreadystatechange = function (event) {
      if (event.target.readyState === 4) {
        /* parse response as JSON */
        var responseJson;
        try { responseJson = window.JSON.parse(event.target.response); }
        catch (exception) { return failureCallback(event.target.response, exception); }
        /* perform callback according to HTTP status code */
        if (xhr.status > 0 && xhr.status < 400) {
          return successCallback(responseJson);
        } else {
          return failureCallback(responseJson);
        }
      }
    };
    xhr.open(method, url, true);
    xhr.send();
  }
1086909
function _createXhr(method, url, options) {
    var xhr = new XMLHttpRequest();

    xhr.open(method, url);

    // Setup headers, including the *Authorization* that holds the Api Key.
    for (var header in options.headers) {
      if (options.headers.hasOwnProperty(header)) {
        xhr.setRequestHeader(header, options.headers[header]);
      }
    }

    // Set timeout.
    if (options.timeout > 0) {
      xhr.timeout = options.timeout;
    }

    return xhr;
  }
1065094
function(httpMethod, xhrURL){
			var cookie = headers["cookie"] || "";

			// Monkey patch URL onto xhr for cookie origin checking in the send method.
			var reqURL = url.parse(xhrURL);
			this.__url = reqURL;

			if (options.auth && cookie) {
				var domainIsApproved = options.auth.domains.reduce(function(prev, domain){
					return prev || reqURL.host.indexOf(domain) >= 0;
				}, false);
			}

			// fix: if proxy is specified, use proxy-hostname instead of request-hostname for xhrURL
			var args = Array.prototype.slice.call(arguments);
			if (
				options &&
				options.proxy &&
				options.proxyTo &&
				(xhrURL.indexOf(options.proxyTo) === 0)
			) {
				args[1] = url.resolve(options.proxy, xhrURL);
			}
			var res = oldOpen.apply(this, args);

			// If on an approved domain copy the jwt from a cookie to the request headers.
			if (domainIsApproved) {
				var jwtCookie = cookieReg.exec(cookie);
				if(jwtCookie && !this.getRequestHeader('authorization')){
					this.setRequestHeader('authorization', 'Bearer ' + jwtCookie[1]);
				}
			}

			return res;
		}
131472
function resourceToXml (resource, rel, currentIndent, nextIndent) {
    // Do not add line feeds if no indentation is asked
    var LF = (currentIndent || nextIndent) ? '\n' : '';

    // Resource tag
    var xml = currentIndent + '<resource';

    // Resource attributes: rel, href, name
    if (rel) xml += ' rel="' + escapeXml(rel) + '"';
    if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"';
    if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"';
    xml += '>' + LF;

    // Add <link> tags
    for (var rel in resource._links) {
      if (!resource.href && rel === 'self') continue;
      xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF;
    }

    // Add embedded
    for (var embed in resource._embedded) {
      // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF)
      var rel = embed.replace(/s$/, '');
      resource._embedded[embed].forEach(function (res) {
        xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF;
      });
    }

    // Add properties as tags
    for (var prop in resource) {
      if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') {
        xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF;
      }
    }

    // Close tag and return the shit
    xml += currentIndent + '</resource>';

    return xml;
  }
1359991
function xdrClient (request) {
    return new PromiseObj(function (resolve) {

        var xdr = new XDomainRequest(), handler = function (ref) {
                var type = ref.type;


                var status = 0;

                if (type === 'load') {
                    status = 200;
                } else if (type === 'error') {
                    status = 500;
                }

                resolve(request.respondWith(xdr.responseText, {status: status}));
            };

        request.abort = function () { return xdr.abort(); };

        xdr.open(request.method, request.getUrl());

        if (request.timeout) {
            xdr.timeout = request.timeout;
        }

        xdr.onload = handler;
        xdr.onabort = handler;
        xdr.onerror = handler;
        xdr.ontimeout = handler;
        xdr.onprogress = function () {};
        xdr.send(request.getBody());
    });
}