Global proxy for CiiMS to support JavaScript endpoints that either don't have proper CORS headers or SSL
This endpoint will only process JSON, and will cache data for 10 minutes.
@return mixed
17963
public function actionJsonProxyPost()
	{
		$url = Cii::get($_POST, 'url', false);

		if ($url === false)
			throw new CHttpException(400, Yii::t('Api.index', 'Missing $_POST[url] parameter'));

		$hash = md5($url);
		$response = Yii::app()->cache->get('CiiMS::API::Proxy::'.$hash);

		if ($response == false)
		{
			$curl = new \Curl\Curl;			
			$response = serialize($curl->get($url));

			if ($curl->error)
				throw new CHttpException(500, Yii::t('Api.index', 'Failed to retrieve remote resource.'));

			$curl->close();

			Yii::app()->cache->set('API::Proxy::'.$hash, $response, 600);
		}
		
		return unserialize($response);
	}
935610
public function getJsapiTicket() {
		$time = time();
		if(empty($this->app->jsapi_ticket) || $this->app->jsapi_ticket_expired_at < $time) {
			$data = $this->getData('/cgi-bin/ticket/getticket', [
				'access_token' => $this->getAccessToken(),
				'type' => 'jsapi',
			]);
			if(isset($data['ticket']) && isset($data['expires_in'])) {
				$this->app->jsapi_ticket = $data['ticket'];
				$this->app->jsapi_ticket_expired_at = $time + $data['expires_in'];
				$this->app->save();
			}
		}

		return $this->app->jsapi_ticket;
	}
1352138
public function fetchData() {
        /* If using PHP in CGI mode and non standard environment */
        if (isset($_SERVER[$this->options["environment"]])) {
            $message = "Using token from environent";
            $header = $_SERVER[$this->options["environment"]];
        } else {
            $message = "Using token from request header";
            $header = $this->app->request->headers("Authorization");
        }

        $matches = null;

        if (preg_match("/Bearer\s+(.*)$/i", $header, $matches)) {
            $this->log(LogLevel::DEBUG, $message);
            return array(self::KEY_TOKEN => $matches[1]);
        }

        /* Bearer not found, try a cookie. */
        if ($this->app->getCookie($this->options["cookie"])) {
            $this->log(LogLevel::DEBUG, "Using token from cookie");
            $token = $this->app->getCookie($this->options["cookie"]);
            return array(self::KEY_TOKEN => $token);
        }

        /* If everything fails log and return false. */
        $message = "Token not found";

        $this->error = new \SlimPower\Authentication\Error();
        $this->error->setDescription($message);

        $this->log(LogLevel::WARNING, $message);
        return false;
    }
1160861
public static function createServerRequestFromGlobals()
    {
        $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
        $headers = function_exists('getallheaders') ? getallheaders() : [];

        foreach ($headers as $name => $value) {
            unset($headers[$name]);
            $name = str_replace('-', '_', $name);
            $headers[$name] = $value;
        }

        return new static($method, static::createUriFromGlobal($_SERVER), $headers, new PhpInputStream(), $_SERVER);
    }
553871
public function getJson()
    {
        $response = [
            'status' => $this->status,
        ];

        switch ($this->status) {
            case self::STATUS_SUCCESS:
            case self::STATUS_FAIL:
                $response = array_merge(
                    $response,
                    [
                        'data' => $this->data,
                    ]
                );
                break;
            case self::STATUS_ERROR;
                $code     = $this->code ? ['code' => $this->code] : [];
                $data     = $this->data ? ['data' => $this->data] : [];
                $response = array_merge(
                    $response,
                    [
                        'message' => $this->message,
                    ],
                    $code,
                    $data
                );
                break;
            default:
                // because of the check in setStatus, this should never occur
                $response = [
                    'status'  => self::STATUS_ERROR,
                    'code'    => 500,
                    'message' => 'JSend response was built illegally',
                    'data'    => [
                        'original-data' => [
                            'status'  => $this->status,
                            'code'    => $this->code,
                            'message' => $this->message,
                            'data'    => $this->data,
                        ],
                    ],
                ];
                break;
        }

        return json_encode($response);
    }
156132
static public function createFromGlobals()
    {
        $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);

        if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
            && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE'))
        ) {
            parse_str($request->getContent(), $data);
            $request->request = new Collection($data);
        }

        return $request;
    }
660760
protected function getJson()
    {
        if ($this->str_request_body_json === null) {
            $this->str_request_body_json = json_decode($this->getBody());
        }
        return $this->str_request_body_json;
    }
721941
public function cgetAction()
    {
        /** @var WebspaceManagerInterface $webspaceManager */
        $webspaceManager = $this->get('sulu_core.webspace.webspace_manager');

        $localizations = [];
        $locales = [];

        /** @var Webspace $webspace */
        foreach ($webspaceManager->getWebspaceCollection() as $webspace) {
            $i = 0;
            foreach ($webspace->getAllLocalizations() as $localization) {
                if (!in_array($localization->getLocale(), $locales)) {
                    $locales[] = $localization->getLocale();
                    $localizations[] = [
                        'localization' => $localization->getLocale(),
                        'name' => $localization->getLocale(Localization::DASH),
                        'id' => $i++,
                    ];
                }
            }
        }

        $data = [
            '_embedded' => $localizations,
            'total' => count($localizations),
        ];

        return new JsonResponse($data);
    }
915522
public function callback()
    {
        //Salesforce sends us an authorization code as part of the Web Server OAuth Authentication Flow
        $code = $this->input->get('code');

        $stateOptions = json_decode(urldecode($this->input->get('state')), true);

        //Store instance URL
        $loginURL = $stateOptions['loginUrl'];

        // Store user options so they can be used later
        $this->stateRepo->put($stateOptions);

        $tokenURL = $loginURL.'/services/oauth2/token';

        $jsonResponse = $this->httpClient->request('post', $tokenURL, [
            'form_params' => [
                'code'          => $code,
                'grant_type'    => 'authorization_code',
                'client_id'     => $this->credentials['consumerKey'],
                'client_secret' => $this->credentials['consumerSecret'],
                'redirect_uri'  => $this->credentials['callbackURI'],
            ],
        ]);

        // Response returns an json of access_token, instance_url, id, issued_at, and signature.
        $response = json_decode($jsonResponse->getBody(), true);
        $this->handleAuthenticationErrors($response);

        // Encrypt token and store token in storage.
        $this->tokenRepo->put($response);

        if (isset($response['refresh_token'])) {
            $this->refreshTokenRepo->put($response['refresh_token']);
        }

        $this->storeVersion();
        $this->storeResources();

        // Return settings
        return $stateOptions;
    }
628530
public function getData()
    {
        $data = GuzzleHttp\json_decode($this->response->getBody(), true);
        
        if (!isset($data["result"])) {
            throw new EndpointException("Invalid result structure: " . $this->response->getBody());
        }
        
        $this->checkStatus($data["result"]);
        
        return $data;
    }
589990
public static function getUriFromGlobals()
    {
        $uri = new Uri('');

        $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http');

        $hasPort = false;
        if (isset($_SERVER['HTTP_HOST'])) {
            list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']);
            if ($host !== null) {
                $uri = $uri->withHost($host);
            }

            if ($port !== null) {
                $hasPort = true;
                $uri = $uri->withPort($port);
            }
        } elseif (isset($_SERVER['SERVER_NAME'])) {
            $uri = $uri->withHost($_SERVER['SERVER_NAME']);
        } elseif (isset($_SERVER['SERVER_ADDR'])) {
            $uri = $uri->withHost($_SERVER['SERVER_ADDR']);
        }

        if (!$hasPort && isset($_SERVER['SERVER_PORT'])) {
            $uri = $uri->withPort($_SERVER['SERVER_PORT']);
        }

        $hasQuery = false;
        if (isset($_SERVER['REQUEST_URI'])) {
            $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2);
            $uri = $uri->withPath($requestUriParts[0]);
            if (isset($requestUriParts[1])) {
                $hasQuery = true;
                $uri = $uri->withQuery($requestUriParts[1]);
            }
        }

        if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) {
            $uri = $uri->withQuery($_SERVER['QUERY_STRING']);
        }

        return $uri;
    }
380723
private function getHTTPClient()
    {
        $config = [
            'base_uri' => sprintf(
                'http://%s.%s/',
                $this->subdomain,
                $this->domain
            ),
            'headers' => [
                'Accept' => 'application/json',
                'User-Agent' => sprintf('Montage PHP v%d', $this->version),
                'X-Requested-With' => 'XMLHttpRequest'
            ]
        ];

        //Set the token if it exists
        if ($this->token)
        {
           $config['headers']['Authorization'] = sprintf('Token %s', $this->token);
        }

        if ($this->debug)
        {
            $config['debug'] = true;
        }

        return new Client($config);
    }
774336
public function getRequestHeaders()
    {
        // common headers
        $headers = array(
            'Accept' => 'application/json',
        );

        // set content type
        if ($this->getHttpMethod() !== 'GET') {
            $headers['Content-Type']    = 'application/x-www-form-urlencoded';
        }

        // prevent duplicate POSTs
        if ($this->getHttpMethod() === 'POST') {
            $headers['Idempotency-Key'] = $this->getIdempotencyKey();
        }

        return $headers;
    }
473447
public function get_js_data() {
        global $CFG;

        $ret = new stdClass;

        // Sort the types by priority.
        uasort($this->types, array($this, 'type_compare'));

        $ret->types = array();
        if (!empty($CFG->dndallowtextandlinks)) {
            foreach ($this->types as $type) {
                if (empty($type->handlers)) {
                    continue; // Skip any types without registered handlers.
                }
                $ret->types[] = $type;
            }
        }

        $ret->filehandlers = $this->filehandlers;
        $uploadrepo = repository::get_instances(array('type' => 'upload', 'currentcontext' => $this->context));
        if (empty($uploadrepo)) {
            $ret->filehandlers = array(); // No upload repo => no file handlers.
        }

        return $ret;
    }
137792
public function sync()
    {
        // @todo Add support for filtering.
        $query = [
            'clientId' => $this->clientId,
            'form' => 'cjson',
            'schema' => '1.10',
        ];

        if ($this->authenticatedClient->hasAccount()) {
            $query['account'] = (string) $this->authenticatedClient->getAccount()->getMpxId();
        }

        return $this->authenticatedClient->requestAsync('GET', $this->uri, [
            'query' => $query,
        ])->then(function (ResponseInterface $response) {
            $data = \GuzzleHttp\json_decode($response->getBody(), true);

            return $data[0]['id'];
        });
    }
795788
protected function getFromCache()
    {
        $cacheKey = $this->getCacheKey();
        $result = $this->getCache()->get($cacheKey, false);
        if ($result === false) {
            return false;
        }

        // Deserialize JSON object and return as an array
        return Convert::json2array($result);
    }
523716
public function getProxyServer()
    {
        $proxy_options = $this->getOption(EnumRequestOption::PROXY_OPTIONS, []);
        return isset($proxy_options[EnumProxyOption::PROXY_SERVER]) ? $proxy_options[EnumProxyOption::PROXY_SERVER] : '';
    }