TODO modify proxy to serve images with CORS enabled, where available
519571
function proxyGetImage(url, img, imageObj){
    var callback_name,
    scriptUrl = options.proxy,
    script;

    link.href = url;
    url = link.href; // work around for pages with base href="" set - WARNING: this may change the url

    callback_name = 'html2canvas_' + (count++);
    imageObj.callbackname = callback_name;

    if (scriptUrl.indexOf("?") > -1) {
      scriptUrl += "&";
    } else {
      scriptUrl += "?";
    }
    scriptUrl += 'url=' + encodeURIComponent(url) + '&callback=' + callback_name;
    script = doc.createElement("script");

    window[callback_name] = function(a){
      if (a.substring(0,6) === "error:"){
        imageObj.succeeded = false;
        images.numLoaded++;
        images.numFailed++;
        start();
      } else {
        setImageLoadHandlers(img, imageObj);
        img.src = a;
      }
      window[callback_name] = undefined; // to work with IE<9  // NOTE: that the undefined callback property-name still exists on the window object (for IE<9)
      try {
        delete window[callback_name];  // for all browser that support this
      } catch(ex) {}
      script.parentNode.removeChild(script);
      script = null;
      delete imageObj.script;
      delete imageObj.callbackname;
    };

    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", scriptUrl);
    imageObj.script = script;
    window.document.body.appendChild(script);

  }
995439
function proxy()
    {
        if (!UserRights(EDITOR))
            die;

        $filename = Eresus_CMS::getLegacyKernel()->request['path'] .
            Eresus_CMS::getLegacyKernel()->request['file'];
        $filename = Eresus_CMS::getLegacyKernel()->froot . substr($filename,
                strlen(Eresus_CMS::getLegacyKernel()->root));

        if (is_dir($filename))
        {
            $filename = Eresus_FS_Tool::normalize($filename . '/index.php');
        }

        if (!is_file($filename))
        {
            header('Not found', true, 404);
            die('<h1>Not found.</h1>');
        }

        $ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

        switch (true)
        {
            case in_array($ext, array('png', 'jpg', 'jpeg', 'gif')):
                $info = getimagesize($filename);
                header('Content-type: '.$info['mime']);
                echo file_get_contents($filename);
                break;

            case $ext == 'js':
                header('Content-type: text/javascript');
                $s = file_get_contents($filename);
                $s = $this->replaceMacros($s);
                echo $s;
                break;

            case $ext == 'css':
                header('Content-type: text/css');
                $s = file_get_contents($filename);
                $s = $this->replaceMacros($s);
                echo $s;
                break;

            case $ext == 'html':
            case $ext == 'htm':
                header('Content-type: text/html');
                $s = file_get_contents($filename);
                $s = $this->replaceMacros($s);
                echo $s;
                break;

            case $ext == 'php':
                Eresus_CMS::getLegacyKernel()->conf['debug']['enable'] = false;
                restore_error_handler();
                chdir(dirname($filename));
                require $filename;
                break;
        }
    }
777894
function serve(req, res) {
  var responseIsArray = Array.isArray(res.entityResponse);
  util.invariant(responseIsArray, 'Response values are required.');

  res.json({ values: res.entityResponse });
}
374510
private void configureCors(Environment environment) {
        Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filter.setInitParameter("allowCredentials", "true");
    }
59316
def __enableProxy(self):
        
        os.environ[
            "HTTP_PROXY"] = self.httpProxy()
        os.environ[
            "HTTPS_PROXY"] = self.httpsProxy()

        os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(
            os.path.dirname(
                os.path.abspath(__file__)),
            "cert.pem")
1357319
function serveSassFiles(magnet, outputDir) {
  if (!isServingSassFiles) {
    magnet.getServer()
      .getEngine()
      .use('/css', express.static(outputDir));
  }
  isServingSassFiles = true;
}
400157
function proxyHttps(){
  httpServer.on('connect', function(req, socket, upgradeHead){
    var hostname = req.url.split(':')[0];
    log.debug('Create internal https server for ' + hostname);
    createInternalHttpsServer(hostname, function (err, httpsServerPort) {
      if (err) {
        log.error('Failed to create internal https proxy');
        log.error(err);
        return;
      }
      // get proxy https server
      var netClient = net.createConnection(httpsServerPort);

      netClient.on('connect', function(){
        log.info('connect to https server successfully!');
        socket.write( "HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n");
      });

      socket.on('data', function(chunk){
        netClient.write(chunk);
      });
      socket.on('end', function(){
        netClient.end();
      });
      socket.on('close', function(){
        netClient.end();
      });
      socket.on('error', function(err){
        log.error('socket error ' + err.message);
        netClient.end();
      });

      netClient.on('data', function(chunk){
        socket.write(chunk);
      });
      netClient.on('end', function(){
        socket.end();
      });
      netClient.on('close', function(){
        socket.end();
      });
      netClient.on('error', function(err){
        log.error('netClient error ' + err.message);
        socket.end();
      });
    });
  });
}
1183894
def disable_cors(self):
        
        return self.update_cors_configuration(
            enable_cors=False,
            allow_credentials=False,
            origins=[],
            overwrite_origins=True
        )
692274
@Override
    public ContainerResponse filter(ContainerRequest cres, ContainerResponse response) {
        initLazily(servletRequest);
        String requestOrigin = cres.getHeaderValue("Origin");
        if (requestOrigin != null) { // is this is a cors request (ajax request that targets a different domain than the one the page was loaded from)
            if (allowedOrigin != null && allowedOrigin.startsWith(requestOrigin)) {  // no cors allowances make are applied if allowedOrigins == null
                // only return the origin the client informed
                response.getHttpHeaders().add("Access-Control-Allow-Origin", requestOrigin);
                response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
                response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
                response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
                response.getHttpHeaders().add("Access-Control-Max-Age", "1209600");
            }
        }
        return response;
    }
451173
def cors_allow_any(request, response):
    
    origin = request.META.get('HTTP_ORIGIN')
    if not origin:
        return response

    # From the CORS spec: The string "*" cannot be used for a resource that supports credentials.
    response['Access-Control-Allow-Origin'] = origin
    patch_vary_headers(response, ['Origin'])
    response['Access-Control-Allow-Credentials'] = 'true'

    if request.method == 'OPTIONS':
        if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META:
            response['Access-Control-Allow-Headers'] \
                = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
        response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'

    return response
346697
function serve(app, couch) {
  var url = require('url');
  var port = 3000,
      staticDir = 'attachments',
      tmpDir = '/tmp/couchapp-compile-' + process.pid,
      logDbRewrites = false;
  var arg;
  while(arg = process.argv.shift()){
    if(arg == '-p'){
      port = parseInt(process.argv.shift());
    }
    if(arg == '-d'){
      staticDir = process.argv.shift();
    }
    if(arg == '-l'){
      logDbRewrites = true;
    }
  }
  var dbUrlObj = url.parse(couch);

  var proxyPaths = {}
  var dbPrefix = '../../';
  for (var i in app.doc.rewrites){
    var rw = app.doc.rewrites[i];
    // Rewrites starting with '../../' are proxied to the database
    if (rw.to.indexOf(dbPrefix) == 0){
      var proxyPath = rw.from;
      if(proxyPath[proxyPath.length -1] == '*') {
        proxyPath = proxyPath.substring(0,proxyPath.length-1)
      }
      var dbPath = rw.to.substring(dbPrefix.length);
      if(dbPath[dbPath.length - 1] == '*'){
        dbPath = dbPath.substring(0,dbPath.length-1)
      }
      if(dbPath.indexOf('*') >=0 ){
        if(logDbRewrites){
          console.log("Don't know how to proxy '" + rw.from + "' to CouchDB at " + rw.from );
        }
      } else {
        proxyPaths[proxyPath] =
          dbUrlObj.protocol + '//' + dbUrlObj.host +
          path.normalize(dbUrlObj.pathname + dbPath);
          if(logDbRewrites){
            console.log("Proxying rewrite '" + proxyPath + "' to CouchDB at " + proxyPaths[proxyPath] );
          }
      }
    }
  }

  var connect = require('connect');
  var httpProxy = require('http-proxy'),
      connect   = require('connect'),
      logger = require('morgan'),
      serveStatic = require('serve-static'),
      errorHandler = require('errorhandler'),
      connectCompiler;
  try{
      connectCompiler = require('connect-compiler');
  } catch(e) {}


  var proxy = httpProxy.createProxyServer({
    target: {
      host: dbUrlObj.host,
      hostname: dbUrlObj.hostname,
      port: dbUrlObj.port,
      https: dbUrlObj.protocol == 'https:',
    }
  });
  var app = connect()
    .use(logger('dev'))
    .use(serveStatic(staticDir));
  if(connectCompiler){
    console.log('Will compile assets with connect-assets.');
    var ignore = [];
    var quote = function(str) {
      return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
    for(var prefix in proxyPaths){
      ignore.push(quote(prefix));
    }
    if(ignore.length){
      //console.log("Asset compile ignore paths:", '^(' +  ignore.join('|') + ')');
      ignore  = new RegExp('^(' +  ignore.join('|') + ')');
    } else {
      ignore = null;
    }
    app.use(connectCompiler({
      enabled: ['coffee'] ,
      src: staticDir,
      dest: tmpDir,
      ignore :  ignore,
    }))
    .use(serveStatic(tmpDir));
  }
  app.use(function(req, res, next) {
      for(var prefix in proxyPaths){
        var dbPath = proxyPaths[prefix];
        if (req.url.indexOf(prefix) === 0) {
          var dbURL = req.url.replace(prefix,dbPath);
          if(logDbRewrites){
            console.log("*** ", req.url , ' -> ', dbURL);
          }
          req.url = dbURL;
          req.headers['host'] = dbUrlObj.host;
          proxy.proxyRequest(req, res);
          return;
        }
      }
      var body = '404 Not found.\nNo static file or db route matched.';
      res.statusCode = 404;
      res.setHeader('Content-Length', body.length);
      res.end(body);
     })
    .use(errorHandler())
    .listen(port);
  console.log("Serving couchapp at: http://0.0.0.0:" + port +"/");

  //Cleanup the temp directory on exit
  var cleanup = function(){
    var rmDir = function(dirPath) {
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      fs.rmdirSync(dirPath);
    };
    rmDir(tmpDir);
  };
  process.on('exit',cleanup);
  process.on('SIGINT',function(){
    cleanup()
    process.exit();
  });
}
989586
function restifyCORSSimple(req, res, next) {
    var origin;
    if (!(origin = matchOrigin(req, origins))) {
      next();
      return;
    }

    function corsOnHeader() {
      origin = req.headers.origin;

      if (opts.credentials) {
        res.setHeader(AC_ALLOW_CREDS, 'true');
      }

      res.setHeader(AC_ALLOW_ORIGIN, origin);
      res.setHeader(AC_EXPOSE_HEADERS, headers.join(', '));
      res.setHeader(AC_ALLOW_METHODS, ALLOW_METHODS.join(', '));
      res.setHeader(AC_ALLOW_HEADERS, ALLOW_HEADERS.join(', '));
      res.setHeader(AC_REQUEST_HEADERS, REQUEST_HEADERS.join(', '));
    }

    res.once('header', corsOnHeader);
    next();
  }
306708
public static function allowCors()
    {
        $origin = filter_input(INPUT_SERVER, 'HTTP_ORIGIN');
        $protocol = filter_input(INPUT_SERVER, 'REQUEST_SCHEME') ?? 'http';
        $host = preg_replace("/^http(s)?:\/{2}/", "", $origin);
        $allowedHosts = cfg::ALLOW_CORS;
        $allowedHosts[] = cfg::HOST_DEV;

        if (in_array($host, $allowedHosts)) {
            header("Access-Control-Allow-Origin: " . $protocol . "://" . $host);
        }
    }
737068
function() {
    var xhr = new XMLHttpRequest();
    var url = assetsBaseUrl + assetsRelativeUrl['images'];

    // @todo Remove the sync call and use a callback
    xhr.open('GET', url);

    xhr.onload = () => {
      var data = JSON.parse(xhr.responseText);
      this.images = data.images;
      this.images.forEach(image => {
        image.fullPath = assetsBaseUrl + data.basepath.images + image.path;
        image.fullThumbPath =
          assetsBaseUrl + data.basepath.images_thumbnails + image.thumbnail;
      });
      Events.emit('assetsimagesload', this.images);
    };
    xhr.onerror = () => {
      console.error('Error loading registry file.');
    };
    xhr.send();

    this.hasLoaded = true;
  }
22980
function server() {
  // TODO: Show require express error
  var express = require('express')
    , app = express();

  app.configure(function() {
    app.use(express.static(siteBuilder.outputRoot));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  // Map missing trailing slashes for posts
  app.get('*', function(req, res) {
    var postPath = siteBuilder.outputRoot + req.url + '/';
    // TODO: Security
    if (req.url.match(/[^/]$/) && existsSync(postPath)) {
      res.redirect(req.url + '/');
    } else {
      res.send('404');
    }
  });

  app.listen(siteBuilder.config.port);
  log.info('Listening on port', siteBuilder.config.port);
}
529953
function handler(req, res) {

  var origin = req.headers.origin
  if (origin) {
    res.setHeader('Access-Control-Allow-Origin', origin)
  }

  var rating = {}
  rating.uri      = req.body.uri
  rating.rating   = req.body.rating
  rating.reviewer = req.session.userId
  debug(rating)

  if (!rating.reviewer) {
    res.send('must be authenticated')
    return
  }

  config = res.locals.config
  conn   = res.locals.sequelize

  if (isNaN(rating.rating) || !rating.uri) {
    res.status(200)
    res.header('Content-Type', 'text/html')
    res.render('pages/media/rate_input', { ui : config.ui })
    return
  } else {
    qpm_media.addRating(rating, config, conn).then(function(ret) {
      res.status(200)
      res.header('Content-Type', 'text/html')
      res.render('pages/media/rate_success', { ui : config.ui })
      debug(ret)
      return
    }).catch(function(err){
      res.status(200)
      res.header('Content-Type', 'text/html')
      res.render('pages/media/rate_error', { ui : config.ui })
      debug(ret)
      return
    })
  }


}
172337
function extendServerImport(url, cb) {
		if (/^http(s)?\:/.test(url)) {
			return require("request")(url, function(error, response, body) {
				if (error) {
					return cb(error);
				}
				return cb(null, evaluateModule(url, body, response.headers["content-type"]));
			});
		}
		if (/\.(js|json)$/.test(url)) {
			return cb(null, require(url));
		} else {
			return require("fs").readFile(require("path").join(__dirname, url), function(err, result) {
				if (err) {
					cb(err);
				} else {
					cb(null, result.toString());
				}
			});
		}
	}