Example #1
0
/**
 * @param int $errorCode
 * @param string $previousURL
 * @return string
 */
function build_error_path($errorCode, $previousURL)
{
    $path = EDIT_DEFAULT_FILE_NAME;
    $args = http_build_str(array(REPORT_CODE => $errorCode, PREVIOUS_URL => $previousURL));
    $path = $path . '?' . $args;
    return $path;
}
 /**
  * @param string $path
  * @param int $errorCode
  * @return string
  */
 private function buildErrorPath($path, $errorCode)
 {
     if ($errorCode !== ERROR_NONE) {
         $errorArgs = http_build_str(array(REPORT_CODE => $errorCode));
         $path .= '?' . $errorArgs;
     }
     return $path;
 }
 public function addPostFields($data)
 {
     if ($data && is_array($data)) {
         $this->postfields = http_build_str($data);
     } else {
         $this->postfields = $data;
     }
 }
Example #4
0
 /**
  * Builds a query string from a given data array
  */
 public static function getQueryString($data = [], $prefix = '')
 {
     $output = '';
     if (!empty($data) && is_array($data)) {
         $string = http_build_str($data, $prefix);
         if (!empty($string)) {
             $output = trim($string);
         }
     }
     return $output;
 }
Example #5
0
 /** Send a query using a specified request-method.
  *
  * @param	string	$query			Query to send. (Required)
  * @param	string	$requestMethod	Request-method for calling (defaults to 'GET'). (Optional)
  * @return	SimpleXMLElement		A SimpleXMLElement object.
  *
  * @access	protected
  * @internal
  */
 protected function internalCall($params, $requestMethod = 'GET')
 {
     /* Create caching hash. */
     $hash = Cache::createHash($params);
     /* Check if response is cached. */
     if ($this->cache != null && $this->cache->contains($hash) && !$this->cache->isExpired($hash)) {
         /* Get cached response. */
         $response = $this->cache->load($hash);
     } else {
         /* Build request query. */
         $query = http_build_str($params, '', '&');
         /* Set request options. */
         $options = array('useragent' => 'PHP last.fm API (PHP/' . phpversion() . ')');
         /* Clear response headers. */
         $this->headers = array();
         /* Get response */
         if ($requestMethod === 'POST') {
             $response = http_post_data(self::API_URL, $query, $options, $info);
         } else {
             $response = http_get(self::API_URL . '?' . $query, $options, $info);
         }
         $response = http_parse_message($response);
         foreach ($response->headers as $header => $value) {
             $this->headers[$header] = $value;
         }
         $response = $response->body;
         /* Cache it. */
         if ($this->cache != null) {
             if (array_key_exists('Expires', $this->headers)) {
                 $this->cache->store($hash, $response, strtotime($this->headers['Expires']));
             } else {
                 $expiration = $this->cache->getPolicy()->getExpirationTime($params);
                 if ($expiration > 0) {
                     $this->cache->store($hash, $response, time() + $expiration);
                 }
             }
         }
     }
     /* Create SimpleXMLElement from response. */
     $response = new SimpleXMLElement($response);
     /* Return response or throw an error. */
     if (Util::toString($response['status']) === 'ok') {
         if ($response->children()->{0}) {
             return $response->children()->{0};
         }
     } else {
         throw new Error(Util::toString($response->error), Util::toInteger($response->error['code']));
     }
 }
Example #6
0
 /**
  * Send a request and receive the response
  * 
  * Options:
  *     'URL'                  => NULL,
  *     'Host'                 => NULL,       // Override the Host: header
  *     'Method'               => 'GET',      // HTTP Method
  *     'ConnectTimeout'       => 5,          // Connection timeout
  *     'Timeout'              => 5,          // Request timeout
  *     'TransferMode'         => 'normal',   // or 'binary'
  *     'SaveAs'               => NULL,       // Download the response to this file
  *     'Redirects'            => TRUE,       // Allow 302 and 302 redirects
  *     'SSLNoVerify'          => FALSE,      // Verify the remote SSL cert
  *     'PreEncodePost'        => TRUE,       // 
  *     'Cookies'              => TRUE,       // Send user's browser cookies?
  *     'CookieJar'            => FALSE,      // Create a cURL CookieJar?
  *     'CookieSession'        => FALSE,      // Should old cookies be trashed starting now?
  *     'CloseSession'         => TRUE,       // Whether to close the session. Should always do this.
  *     'Redirected'           => FALSE,      // Is this a redirected request?
  *     'Debug'                => FALSE,      // Debug output
  *     'Simulate'             => FALSE       // Don't actually request, just set up
  * 
  * @param array/string $Options URL, or array options
  * @param array $QueryParams GET/POST parameters
  * @param array $Files List of files to upload
  * @param array $ExtraHeaders Any additional headers to tack on
  * @return type 
  */
 public function Request($Options = NULL, $QueryParams = NULL, $Files = NULL, $ExtraHeaders = NULL)
 {
     /*
      * Allow requests that just want to use defaults to provide a string instead
      * of an optionlist.
      */
     if (is_string($Options)) {
         $Options = array('URL' => $Options);
     }
     if (is_null($Options)) {
         $Options = array();
     }
     $this->Options = $Options = array_merge($this->RequestDefaults, $Options);
     $this->ResponseHeaders = array();
     $this->ResponseStatus = "";
     $this->ResponseBody = "";
     $this->RequestBody = "";
     $this->ResponseTime = 0;
     $this->ContentLength = 0;
     $this->ContentType = '';
     $this->ConnectionMode = '';
     $this->ActionLog = array();
     if (is_string($Files)) {
         $Files = array($Files);
     }
     if (!is_array($Files)) {
         $Files = array();
     }
     if (!is_array($ExtraHeaders)) {
         $ExtraHeaders = array();
     }
     // Get the URL
     $RelativeURL = GetValue('URL', $Options, NULL);
     if (is_null($RelativeURL)) {
         $RelativeURL = GetValue('Url', $Options, NULL);
     }
     if (is_null($RelativeURL)) {
         throw new Exception("No URL provided");
     }
     $RequestMethod = GetValue('Method', $Options);
     $ForceHost = GetValue('Host', $Options);
     $FollowRedirects = GetValue('Redirects', $Options);
     $ConnectTimeout = GetValue('ConnectTimeout', $Options);
     $Timeout = GetValue('Timeout', $Options);
     $SaveAs = GetValue('SaveAs', $Options);
     $TransferMode = GetValue('TransferMode', $Options);
     $SSLNoVerify = GetValue('SSLNoVerify', $Options);
     $PreEncodePost = GetValue('PreEncodePost', $Options);
     $SendCookies = GetValue('Cookies', $Options);
     $CookieJar = GetValue('CookieJar', $Options);
     $CookieSession = GetValue('CookieSession', $Options);
     $CloseSesssion = GetValue('CloseSession', $Options);
     $Redirected = GetValue('Redirected', $Options);
     $Debug = GetValue('Debug', $Options, FALSE);
     $Simulate = GetValue('Simulate', $Options);
     $OldVolume = $this->Loud;
     if ($Debug) {
         $this->Loud = TRUE;
     }
     $Url = $RelativeURL;
     $PostData = $QueryParams;
     /*
      * If files were provided, preprocess the list and exclude files that don't
      * exist. Also, change the method to POST if it is currently GET and there 
      * are valid files to send.
      */
     $SendFiles = array();
     foreach ($Files as $File => $FilePath) {
         if (file_exists($FilePath)) {
             $SendFiles[$File] = $FilePath;
         }
     }
     $this->FileTransfer = (bool) sizeof($SendFiles);
     if ($this->FileTransfer && $RequestMethod != "PUT") {
         $this->Options['Method'] = 'POST';
         $RequestMethod = GetValue('Method', $Options);
     }
     /*
      * If extra headers were provided, preprocess the list into the correct 
      * format for inclusion into both cURL and fsockopen header queues.
      */
     // Tack on Host header if forced
     if (!is_null($ForceHost)) {
         $ExtraHeaders['Host'] = $ForceHost;
     }
     $SendExtraHeaders = array();
     foreach ($ExtraHeaders as $ExtraHeader => $ExtraHeaderValue) {
         $SendExtraHeaders[] = "{$ExtraHeader}: {$ExtraHeaderValue}";
     }
     /*
      * If the request is being saved to a file, prepare to save to the 
      * filesystem.
      */
     $this->SaveFile = FALSE;
     if ($SaveAs) {
         $SavePath = dirname($SaveAs);
         $CanSave = @mkdir($SavePath, 0775, TRUE);
         if (!is_writable($SavePath)) {
             throw new Exception("Cannot write to save path: {$SavePath}");
         }
         $this->SaveFile = $SaveAs;
     }
     /*
      * Parse Query Parameters and collapse into a querystring in the case of
      * GETs.
      */
     $RequestMethod = strtoupper($RequestMethod);
     switch ($RequestMethod) {
         case 'PUT':
         case 'POST':
             break;
         case 'GET':
         default:
             $PostData = is_array($PostData) ? http_build_query($PostData) : $PostData;
             if (strlen($PostData)) {
                 if (stristr($RelativeURL, '?')) {
                     $Url .= '&';
                 } else {
                     $Url .= '?';
                 }
                 $Url .= $PostData;
             }
             break;
     }
     $this->Action("Requesting {$Url}");
     $UrlParts = parse_url($Url);
     // Extract scheme
     $Scheme = strtolower(GetValue('scheme', $UrlParts, 'http'));
     $this->Action(" scheme: {$Scheme}");
     // Extract hostname
     $Host = GetValue('host', $UrlParts, '');
     $this->Action(" host: {$Host}");
     // Extract / deduce port
     $Port = GetValue('port', $UrlParts, NULL);
     if (empty($Port)) {
         $Port = $Scheme == 'https' ? 443 : 80;
     }
     $this->Action(" port: {$Port}");
     // Extract Path&Query
     $Path = GetValue('path', $UrlParts, '');
     $Query = GetValue('query', $UrlParts, '');
     $this->UseSSL = $Scheme == 'https' ? TRUE : FALSE;
     $this->Action(" transfer mode: {$TransferMode}");
     $logContext = array('url' => $Url, 'method' => $RequestMethod);
     /*
      * ProxyRequest can masquerade as the current user, so collect and encode
      * their current cookies as the default case is to send them.
      */
     $Cookie = '';
     $EncodeCookies = TRUE;
     foreach ($_COOKIE as $Key => $Value) {
         if (strncasecmp($Key, 'XDEBUG', 6) == 0) {
             continue;
         }
         if (strlen($Cookie) > 0) {
             $Cookie .= '; ';
         }
         $EncodedValue = $EncodeCookies ? urlencode($Value) : $Value;
         $Cookie .= "{$Key}={$EncodedValue}";
     }
     // This prevents problems for sites that use sessions.
     if ($CloseSesssion) {
         @session_write_close();
     }
     $Response = '';
     $this->Action("Parameters: " . print_r($PostData, true));
     // We need cURL
     if (!function_exists('curl_init')) {
         throw new Exception('Encountered an error while making a request to the remote server: Your PHP configuration does not allow cURL requests.');
     }
     $Handler = curl_init();
     curl_setopt($Handler, CURLOPT_HEADER, FALSE);
     curl_setopt($Handler, CURLINFO_HEADER_OUT, TRUE);
     curl_setopt($Handler, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($Handler, CURLOPT_USERAGENT, GetValue('HTTP_USER_AGENT', $_SERVER, 'Vanilla/2.0'));
     curl_setopt($Handler, CURLOPT_CONNECTTIMEOUT, $ConnectTimeout);
     curl_setopt($Handler, CURLOPT_HEADERFUNCTION, array($this, 'CurlHeader'));
     if ($TransferMode == 'binary') {
         curl_setopt($Handler, CURLOPT_BINARYTRANSFER, TRUE);
     }
     if ($RequestMethod != 'GET' && $RequestMethod != 'POST') {
         curl_setopt($Handler, CURLOPT_CUSTOMREQUEST, $RequestMethod);
     }
     if ($CookieJar) {
         curl_setopt($Handler, CURLOPT_COOKIEJAR, $this->CookieJar);
         curl_setopt($Handler, CURLOPT_COOKIEFILE, $this->CookieJar);
     }
     if ($CookieSession) {
         curl_setopt($Handler, CURLOPT_COOKIESESSION, TRUE);
     }
     if ($FollowRedirects) {
         curl_setopt($Handler, CURLOPT_FOLLOWLOCATION, TRUE);
         curl_setopt($Handler, CURLOPT_AUTOREFERER, TRUE);
         curl_setopt($Handler, CURLOPT_MAXREDIRS, 10);
     }
     if ($this->UseSSL) {
         $this->Action(" Using SSL");
         curl_setopt($Handler, CURLOPT_SSL_VERIFYPEER, !$SSLNoVerify);
         curl_setopt($Handler, CURLOPT_SSL_VERIFYHOST, $SSLNoVerify ? 0 : 2);
     }
     if ($Timeout > 0) {
         curl_setopt($Handler, CURLOPT_TIMEOUT, $Timeout);
     }
     if ($Cookie != '' && $SendCookies) {
         $this->Action(" Sending client cookies");
         curl_setopt($Handler, CURLOPT_COOKIE, $Cookie);
     }
     if ($this->SaveFile) {
         $this->Action(" Saving to file: {$this->SaveFile}");
         $FileHandle = fopen($this->SaveFile, 'w+');
         curl_setopt($Handler, CURLOPT_FILE, $FileHandle);
     }
     // Allow POST
     if ($RequestMethod == 'POST') {
         if ($this->FileTransfer) {
             $this->Action(" POSTing files");
             foreach ($SendFiles as $File => $FilePath) {
                 $PostData[$File] = "@{$FilePath}";
             }
         } else {
             if ($PreEncodePost && is_array($PostData)) {
                 $PostData = http_build_query($PostData);
             }
         }
         curl_setopt($Handler, CURLOPT_POST, TRUE);
         curl_setopt($Handler, CURLOPT_POSTFIELDS, $PostData);
         if (!is_array($PostData) && !is_object($PostData)) {
             $SendExtraHeaders['Content-Length'] = strlen($PostData);
         }
         $this->RequestBody = $PostData;
     }
     // Allow PUT
     if ($RequestMethod == 'PUT') {
         if ($this->FileTransfer) {
             $SendFile = GetValue('0', $SendFiles);
             $SendFileSize = filesize($SendFile);
             $this->Action(" PUTing file: {$SendFile}");
             $SendFileObject = fopen($SendFile, 'r');
             curl_setopt($Handler, CURLOPT_PUT, TRUE);
             curl_setopt($Handler, CURLOPT_INFILE, $SendFileObject);
             curl_setopt($Handler, CURLOPT_INFILESIZE, $SendFileSize);
             $SendExtraHeaders[] = "Content-Length: {$SendFileSize}";
         } else {
             curl_setopt($Handler, CURLOPT_CUSTOMREQUEST, 'PUT');
             curl_setopt($Handler, CURLOPT_POSTFIELDS, $PostData);
             if (!is_array($PostData) && !is_object($PostData)) {
                 $SendExtraHeaders['Content-Length'] = strlen($PostData);
             } else {
                 $TempPostData = http_build_str($PostData);
                 $SendExtraHeaders['Content-Length'] = strlen($TempPostData);
             }
             $this->RequestBody = $PostData;
         }
     }
     // Any extra needed headers
     if (sizeof($SendExtraHeaders)) {
         curl_setopt($Handler, CURLOPT_HTTPHEADER, $SendExtraHeaders);
     }
     // Set URL
     curl_setopt($Handler, CURLOPT_URL, $Url);
     curl_setopt($Handler, CURLOPT_PORT, $Port);
     if (val('Log', $Options, TRUE)) {
         Logger::event('http_request', Logger::DEBUG, '{method} {url}', $logContext);
     }
     $this->CurlReceive($Handler);
     if ($Simulate) {
         return NULL;
     }
     curl_close($Handler);
     $logContext['responseCode'] = $this->ResponseStatus;
     $logContext['responseTime'] = $this->ResponseTime;
     if (Debug()) {
         if ($this->ContentType == 'application/json') {
             $body = @json_decode($this->ResponseBody, true);
             if (!$body) {
                 $body = $this->ResponseBody;
             }
             $logContext['responseBody'] = $body;
         } else {
             $logContext['responseBody'] = $this->ResponseBody;
         }
     }
     if (val('Log', $Options, TRUE)) {
         if ($this->ResponseClass('2xx')) {
             Logger::event('http_response', Logger::DEBUG, '{responseCode} {method} {url} in {responseTime}s', $logContext);
         } else {
             Logger::event('http_response_error', Logger::DEBUG, '{responseCode} {method} {url} in {responseTime}s', $logContext);
         }
     }
     $this->Loud = $OldVolume;
     return $this->ResponseBody;
 }
 /**
  * @param string $basename
  * @param array $params
  * @return string
  */
 public static function buildArgumentsRelativePath($basename, $params)
 {
     $queryStr = http_build_str($params);
     $argumentsRelativePath = $basename . '?' . $queryStr;
     return $argumentsRelativePath;
 }
 /**
  * @param bool $isEmpty [optional]
  * @param bool $appendCreateButton [optional]
  * @return string
  */
 public function buildListHTML($isEmpty = false, $appendCreateButton = true)
 {
     if (!$isEmpty) {
         foreach ($this->entityInstances as $entityInstance) {
             $values = $this->extractEntityInstanceListPropertiesValues($entityInstance);
             $actionParams = $entityInstance->getIdentifier();
             if ($this->commonParams) {
                 $actionParams = array_merge($actionParams, $this->commonParams);
             }
             $deleteURL = DELETE_DEFAULT_FILE_NAME . '?' . http_build_str($actionParams);
             $updateURL = EDIT_DEFAULT_FILE_NAME . '?' . http_build_str($actionParams);
             $this->listViewGenerator->appendRow($values, $deleteURL, $updateURL);
         }
         unset($entityInstance);
     }
     return $this->listViewGenerator->getBuiltHTML($appendCreateButton);
 }
 function _requestFile($function = "", $filename, $params = array(), $method = "GET")
 {
     $return = false;
     if ($function != "") {
         $action_url = $this->_shop_url . "modulesshop/api/" . $function;
         $fh = fopen($filename, "w");
         if ($method == "GET") {
             if (count($params) > 0) {
                 $action_url .= "?" . http_build_str($params);
             }
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $action_url);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_HEADER, 0);
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
             curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
             curl_setopt($ch, CURLOPT_USERAGENT, 'iQDesk Engine v.2.0 Shop Connector');
             curl_setopt($ch, CURLOPT_FILE, $fh);
             curl_exec($ch);
         }
         if ($method == "POST") {
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $action_url);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_HEADER, 0);
             curl_setopt($ch, CURLOPT_POST, true);
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
             curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
             curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_str($params));
             curl_setopt($ch, CURLOPT_USERAGENT, 'iQDesk Engine v.2.0 Shop Connector');
             curl_setopt($ch, CURLOPT_FILE, $fh);
             curl_exec($ch);
         }
         fclose($fh);
     }
     return $return;
 }
Example #10
0
 /**
  * @When /^I request "([^"]*)"$/
  */
 public function iRequest($pageUrl)
 {
     $baseUrl = $this->getParameter('base_url');
     $this->_requestUrl = $baseUrl . $pageUrl;
     $first = true;
     foreach ($this->_queryParameters as $name => $value) {
         $this->_requestUrl .= ($first ? '?' : '&') . $name . '=' . $value;
         $first = false;
     }
     //every request should include oauth token
     //$oauth = $this->getOauthHeader();
     //TODO handle that you set a token here
     switch (strtoupper($this->_restObjectMethod)) {
         case 'GET':
             $response = $this->_client->get($this->_requestUrl)->send();
             break;
         case 'POST':
             //$postFields = (array)$this->_restObject;
             $body = json_encode((array) $this->_restObject);
             $response = $this->_client->post($this->_requestUrl, null, $body)->setHeader("Content-Type", "application/json")->send();
             break;
         case 'PUT':
             $body = json_encode((array) $this->_restObject);
             $response = $this->_client->put($this->_requestUrl, null, $body)->setHeader("Content-Type", "application/json")->send();
             break;
         case 'PATCH':
             $body = json_encode((array) $this->_restObject);
             $response = $this->_client->patch($this->_requestUrl, null, $body)->setHeader("Content-Type", "application/json")->send();
             break;
         case 'DELETE':
             $response = $this->_client->delete($this->_requestUrl . '?' . http_build_str((array) $this->_restObject), null)->send();
             break;
     }
     $this->_response = $response;
 }
Example #11
0
 /**
  * Build a URL
  * @link http://php.net/manual/en/function.http-build-url.php
  * @param mixed $url (part(s) of) an URL in form of a string or associative array like parse_url() returns
  * @param mixed $parts same as the first argument
  * @param integer $flags a bitmask of binary or'ed HTTP_URL constants; HTTP_URL_REPLACE is the default
  * @param array $new_url if set, it will be filled with the parts of the composed url like parse_url() would return
  * @return string Returns the new URL as string on success or FALSE on failure.
  */
 function http_build_url($url = array(), $parts = array(), $flags = HTTP_URL_REPLACE, &$new_url = null)
 {
     $defaults = array('scheme' => 'http', 'host' => '', 'port' => '', 'user' => '', 'pass' => '', 'path' => '', 'query' => '', 'fragment' => '');
     is_array($url) or $url = parse_url($url);
     is_array($parts) or $parts = parse_url($parts);
     $new_url = $parts + $url + $defaults;
     $flags or $flags = HTTP_URL_JOIN_PATH;
     // Default flags ?
     $JOIN_PATH = ($flags | HTTP_URL_JOIN_PATH) == $flags;
     $JOIN_QUERY = ($flags | HTTP_URL_JOIN_QUERY) == $flags;
     $STRIP_USER = ($flags | HTTP_URL_STRIP_USER) == $flags;
     $STRIP_PASS = ($flags | HTTP_URL_STRIP_PASS) == $flags;
     $STRIP_PATH = ($flags | HTTP_URL_STRIP_PATH) == $flags;
     $STRIP_QUERY = ($flags | HTTP_URL_STRIP_QUERY) == $flags;
     $STRIP_FRAGMENT = ($flags | HTTP_URL_STRIP_FRAGMENT) == $flags;
     // User
     if ($STRIP_USER) {
         $new_url['user'] = '';
     }
     // Pass
     if (!$new_url['user'] || $new_url['pass'] && $STRIP_PASS) {
         $new_url['pass'] = '';
     }
     // Port
     if ($new_url['port'] && ($flags | HTTP_URL_STRIP_PORT) == $flags) {
         $new_url['port'] = '';
     }
     // Path
     if ($STRIP_PATH) {
         $new_url['path'] = '';
     } else {
         $d_path = $defaults['path'];
         $u_path = isset($url['path']) ? $url['path'] : '';
         $p_path = isset($parts['path']) ? $parts['path'] : '';
         if ($p_path) {
             $u_path = '';
         }
         $path = $d_path;
         if (isset($url['host']) && !$p_path) {
             $path = '/' . ltrim($u_path, '/');
         } elseif (strpos($u_path, '/') === 0) {
             $path = $u_path;
         } elseif ($u_path) {
             $path = pathinfo($path . 'x', PATHINFO_DIRNAME) . '/' . $u_path;
         }
         if (isset($parts['host'])) {
             $path = '/' . ltrim($p_path, '/');
         } elseif (strpos($p_path, '/') === 0) {
             $path = $p_path;
         } elseif ($p_path) {
             $path = pathinfo($path . 'x', PATHINFO_DIRNAME) . '/' . $p_path;
         }
         $path = explode('/', $path);
         $k_stack = array();
         foreach ($path as $k => $v) {
             if ($v == '..') {
                 if ($k_stack) {
                     $k_parent = array_pop($k_stack);
                     unset($path[$k_parent]);
                 }
                 unset($path[$k]);
             } elseif ($v == '.') {
                 // /./
                 unset($path[$k]);
             } else {
                 $k_stack[] = $k;
             }
         }
         $path = implode('/', $path);
         $new_url['path'] = $path;
     }
     $new_url['path'] = '/' . ltrim($new_url['path'], '/');
     // Query
     if ($STRIP_QUERY) {
         $new_url['query'] = '';
     } else {
         $u_query = isset($url['query']) ? $url['query'] : '';
         $p_query = isset($parts['query']) ? $parts['query'] : '';
         $query = $new_url['query'];
         if (is_array($p_query)) {
             $query = $u_query;
         } elseif ($JOIN_QUERY) {
             if (!is_array($u_query)) {
                 parse_str($u_query, $u_query);
             }
             if (!is_array($p_query)) {
                 parse_str($p_query, $p_query);
             }
             $u_query = http_build_str($u_query);
             $p_query = http_build_str($p_query);
             $u_query = str_replace(array('[', '%5B'), '{{{', $u_query);
             $u_query = str_replace(array(']', '%5D'), '}}}', $u_query);
             $p_query = str_replace(array('[', '%5B'), '{{{', $p_query);
             $p_query = str_replace(array(']', '%5D'), '}}}', $p_query);
             parse_str($u_query, $u_query);
             parse_str($p_query, $p_query);
             $query = http_build_str(array_merge($u_query, $p_query));
             $query = str_replace(array('{{{', '%7B%7B%7B'), '%5B', $query);
             $query = str_replace(array('}}}', '%7D%7D%7D'), '%5D', $query);
             parse_str($query, $query);
         }
         if (is_array($query)) {
             $query = http_build_str($query);
         }
         $new_url['query'] = $query;
     }
     // Fragment
     if ($STRIP_FRAGMENT) {
         $new_url['fragment'] = '';
     }
     // Scheme
     $out = $new_url['scheme'] . '://';
     // User
     if ($new_url['user']) {
         $out .= $new_url['user'] . ($new_url['pass'] ? ':' . $new_url['pass'] : '') . '@';
     }
     // Host
     $out .= $new_url['host'];
     // Port
     if ($new_url['port']) {
         $out .= ':' . $new_url['port'];
     }
     // Path
     $out .= $new_url['path'];
     // Query
     if ($new_url['query']) {
         $out .= '?' . $new_url['query'];
     }
     // Fragment
     if ($new_url['fragment']) {
         $out .= '#' . $new_url['fragment'];
     }
     $new_url = array_filter($new_url);
     return $out;
 }
Example #12
0
$entityInstances = ExamResult::getFilteredList($seasonID, $subjectID, $groupID, $professorID, $isImprovement);
$isEmpty = false;
if (empty($entityInstances)) {
    $isEmpty = true;
    array_push($entityInstances, $entityBuilder->createEmpty());
} else {
    $headProfessor = Professor::getBuilder()->getByIdentifier(array(Professor::PROP_ID => $entityInstances[0]->getProperty(ExamResult::PROP_EXAM_HEAD_ID)->getValue()));
    $member1Professor = Professor::getBuilder()->getByIdentifier(array(Professor::PROP_ID => $entityInstances[0]->getProperty(ExamResult::PROP_EXAM_MEMBER1_ID)->getValue()));
    $member2Professor = Professor::getBuilder()->getByIdentifier(array(Professor::PROP_ID => $entityInstances[0]->getProperty(ExamResult::PROP_EXAM_MEMBER2_ID)->getValue()));
}
$listViewAggregator = new ListViewAggregator($entityInstances, true);
$listViewAggregator->setIsUpdateButtonDisplayed(true);
$listViewAggregator->setIsDeleteButtonDisplayed(false);
$baseURL = get_assets_base_url();
$listDefaultFileName = LIST_DEFAULT_FILE_NAME;
$filterArgs = http_build_str($filters);
$previousURL = $baseURL . "result/{$listDefaultFileName}?{$filterArgs}";
$previousURL = urlencode($previousURL);
$listViewAggregator->setCommonParams(array(PREVIOUS_URL => $previousURL));
$subjectInstance = Subject::getBuilder()->getByIdentifier(array(Subject::PROP_ID => $subjectID));
$groupInstance = Group::getBuilder()->getByIdentifier(array(Group::PROP_ID => $groupID));
$contentHeader = $entityBuilder->getLabel();
$contentAction = 'Lista';
$contentHTML = $listViewAggregator->buildListHTML($isEmpty, false);
?>

<!DOCTYPE html>
<html>
<?php 
require_once dirname(dirname(__FILE__)) . '/includes/head.php';
?>
Example #13
0
File: Url.php Project: slkxmail/App
 protected function sortQueryString($queryString)
 {
     $params = array();
     parse_str($queryString, $params);
     ksort($params);
     array_walk_recursive($params, function ($item, $key) {
         return urlencode($item);
     });
     return http_build_str($params, '', '&');
 }
 /**
  * Build a URL (PECL pecl_http >= 0.21.0)
  * @link http://php.net/manual/en/function.http-build-url.php
  * @param   mixed       $url        (Part(s) of) An URL in form of a string or associative array like parse_url() returns.
  * @param   mixed       $parts      Same as the first argument.
  * @param   integer     $flags      A bitmask of binary or'ed HTTP_URL constants; HTTP_URL_REPLACE is the default.
  * @param   array       $new_url    If set, it will be filled with the parts of the composed url like parse_url() would return.
  * @return  string                  Returns the new URL as string on success or FALSE on failure.
  */
 function http_build_url($url = array(), $parts = array(), $flags = HTTP_URL_REPLACE, &$new_url = null)
 {
     // Initialization
     static $all_keys = array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment');
     static $all_keys_flipped;
     static $server_https;
     static $default_host;
     static $request_uri;
     static $request_uri_no_query;
     static $request_uri_path;
     if (!isset($all_keys_flipped)) {
         $all_keys_flipped = array_flip($all_keys);
     }
     if (!isset($server_https)) {
         $server_https = !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
     }
     if (!isset($default_host)) {
         // Avoid this autodetection, it is copy-exact from C code, but $_SERVER['HTTP_HOST'] is vulnerable.
         $default_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '');
         if ($default_host == '') {
             $default_host = function_exists('gethostname') ? gethostname() : php_uname('n');
         }
     }
     if (!isset($request_uri)) {
         if (isset($_SERVER['REQUEST_URI'])) {
             $request_uri = $_SERVER['REQUEST_URI'];
         } else {
             $request_uri = '/';
         }
     }
     if (!isset($request_uri_no_query)) {
         $request_uri_no_query = preg_replace('~^([^\\?]*).*$~', '$1', $request_uri);
     }
     if (!isset($request_uri_path)) {
         $request_uri_path = substr($request_uri_no_query, 0, strrpos($request_uri_no_query, '/') + 1);
     }
     // Translate the flags from the single input parameter.
     $JOIN_PATH = ($flags | HTTP_URL_JOIN_PATH) == $flags;
     $JOIN_QUERY = ($flags | HTTP_URL_JOIN_QUERY) == $flags;
     $STRIP_USER = ($flags | HTTP_URL_STRIP_USER) == $flags;
     $STRIP_PASS = ($flags | HTTP_URL_STRIP_PASS) == $flags;
     $STRIP_PORT = ($flags | HTTP_URL_STRIP_PORT) == $flags;
     $STRIP_PATH = ($flags | HTTP_URL_STRIP_PATH) == $flags;
     $STRIP_QUERY = ($flags | HTTP_URL_STRIP_QUERY) == $flags;
     $STRIP_FRAGMENT = ($flags | HTTP_URL_STRIP_FRAGMENT) == $flags;
     // Parse and validate the input URLs.
     if (!is_array($url)) {
         $url = parse_url($url);
     }
     if (!is_array($parts)) {
         $parts = parse_url($parts);
     }
     $url = array_intersect_key($url, $all_keys_flipped);
     $parts = array_intersect_key($parts, $all_keys_flipped);
     // Unfortunately the 'query' part can not be an array or object type.
     if (isset($url['query']) && !is_string($url['query'])) {
         unset($url['query']);
     }
     // Unfortunately the 'query' part can not be an array or object type.
     if (isset($parts['query']) && !is_string($parts['query'])) {
         unset($parts['query']);
     }
     foreach ($all_keys as $key) {
         if ($key == 'port') {
             if (isset($url[$key])) {
                 $url[$key] = (int) $url[$key];
                 if ($url[$key] <= 0 || $url[$key] >= 65535) {
                     unset($url[$key]);
                 }
             }
             if (isset($parts[$key])) {
                 $parts[$key] = (int) $parts[$key];
                 if ($parts[$key] <= 0 || $parts[$key] >= 65535) {
                     unset($parts[$key]);
                 }
             }
         } else {
             if (isset($url[$key])) {
                 if (is_array($url[$key])) {
                     if (empty($url[$key])) {
                         unset($url[$key]);
                     }
                 } else {
                     $url[$key] = (string) $url[$key];
                     if ($url[$key] == '') {
                         unset($url[$key]);
                     }
                 }
             }
             if (isset($parts[$key])) {
                 if (is_array($parts[$key])) {
                     if (empty($parts[$key])) {
                         unset($parts[$key]);
                     }
                 } else {
                     $parts[$key] = (string) $parts[$key];
                     if ($parts[$key] == '') {
                         unset($parts[$key]);
                     }
                 }
             }
         }
     }
     // Start building the result.
     // Port
     if ($STRIP_PORT) {
         if (isset($url['port'])) {
             unset($url['port']);
         }
     } else {
         if (isset($parts['port'])) {
             $url['port'] = $parts['port'];
         }
     }
     // User
     if ($STRIP_USER) {
         if (isset($url['user'])) {
             unset($url['user']);
         }
     } else {
         if (isset($parts['user'])) {
             $url['user'] = $parts['user'];
         }
     }
     // Password
     if ($STRIP_PASS || !isset($url['user'])) {
         if (isset($url['pass'])) {
             unset($url['pass']);
         }
     } else {
         if (isset($parts['pass'])) {
             $url['pass'] = $parts['pass'];
         }
     }
     // Scheme
     if (isset($parts['scheme'])) {
         $url['scheme'] = $parts['scheme'];
     }
     // Host
     if (isset($parts['host'])) {
         $url['host'] = $parts['host'];
     }
     // Path
     if ($STRIP_PATH) {
         if (isset($url['path'])) {
             unset($url['path']);
         }
     } else {
         if ($JOIN_PATH && isset($parts['path']) && isset($url['path']) && substr($parts['path'], 0, 1) != '/') {
             if (substr($url['path'], -1, 1) != '/') {
                 $base_path = str_replace('\\', '/', dirname($url['path']));
             } else {
                 $base_path = $url['path'];
             }
             if (substr($base_path, -1, 1) != '/') {
                 $base_path .= '/';
             }
             $url['path'] = $base_path . $parts['path'];
         } else {
             if (isset($parts['path'])) {
                 $url['path'] = $parts['path'];
             }
         }
     }
     // Query
     if ($STRIP_QUERY) {
         if (isset($url['query'])) {
             unset($url['query']);
         }
     } else {
         if ($JOIN_QUERY && isset($url['query']) && isset($parts['query'])) {
             // From an original snippet by Sébastien Corne.
             //---------------------------------------------------------------------
             $u_query = $url['query'];
             $p_query = $parts['query'];
             if (!is_array($u_query)) {
                 parse_str($u_query, $u_query);
             }
             if (!is_array($p_query)) {
                 parse_str($p_query, $p_query);
             }
             $u_query = http_build_str($u_query);
             $p_query = http_build_str($p_query);
             $u_query = str_replace(array('[', '%5B'), '{{{', $u_query);
             $u_query = str_replace(array(']', '%5D'), '}}}', $u_query);
             $p_query = str_replace(array('[', '%5B'), '{{{', $p_query);
             $p_query = str_replace(array(']', '%5D'), '}}}', $p_query);
             parse_str($u_query, $u_query);
             parse_str($p_query, $p_query);
             $query = http_build_str(array_merge($u_query, $p_query));
             $query = str_replace(array('{{{', '%7B%7B%7B'), '%5B', $query);
             $query = str_replace(array('}}}', '%7D%7D%7D'), '%5D', $query);
             parse_str($query, $query);
             //---------------------------------------------------------------------
         } else {
             if (isset($parts['query'])) {
                 $query = $parts['query'];
             }
         }
         if (isset($query)) {
             if (is_array($query)) {
                 $query = http_build_str($query);
             }
             $url['query'] = $query;
         }
     }
     if (isset($url['query']) && is_array($url['query'])) {
         $url['query'] = http_build_str($url['query']);
     }
     // Fragment
     if ($STRIP_FRAGMENT) {
         if (isset($url['fragment'])) {
             unset($url['fragment']);
         }
     } else {
         if (isset($parts['fragment'])) {
             $url['fragment'] = $parts['fragment'];
         }
     }
     // Ensure scheme presence.
     if (!isset($url['scheme'])) {
         if ($server_https) {
             $url['scheme'] = 'https';
         } elseif (isset($url['port'])) {
             if ($scheme = getservbyport($url['port'], 'tcp')) {
                 $url['scheme'] = $scheme;
             } else {
                 $url['scheme'] = 'http';
             }
         } else {
             $url['scheme'] = 'http';
         }
     }
     // Ensure host presence.
     if (!isset($url['host'])) {
         $url['host'] = $default_host;
     }
     // Hide standard ports.
     // http://www.iana.org/assignments/port-numbers
     if (isset($url['port'])) {
         if ((int) getservbyname($url['scheme'], 'tcp') == $url['port']) {
             unset($url['port']);
         }
     }
     // Ensure path presence.
     if ($STRIP_PATH) {
         $url['path'] = '';
     } else {
         if (!isset($url['path'])) {
             $url['path'] = $request_uri_no_query;
         } elseif (substr($url['path'], 0, 1) != '/') {
             // A relative path, deal with it.
             $url['path'] = $request_uri_path . $url['path'];
         }
     }
     // Canonize the result path.
     if (strpos($url['path'], './') !== false) {
         // From an original snippet by Sébastien Corne.
         //---------------------------------------------------------------------
         $path = explode('/', $url['path']);
         $k_stack = array();
         foreach ($path as $k => $v) {
             if ($v == '..') {
                 // /../
                 if ($k_stack) {
                     $k_parent = array_pop($k_stack);
                     unset($path[$k_parent]);
                 }
                 unset($path[$k]);
             } elseif ($v == '.') {
                 // /./
                 unset($path[$k]);
             } else {
                 $k_stack[] = $k;
             }
         }
         $url['path'] = implode('/', $path);
         //---------------------------------------------------------------------
     }
     $url['path'] = '/' . ltrim($url['path'], '/');
     // The result as an array type is ready.
     $new_url = $url;
     // Build the result string.
     $result = $url['scheme'] . '://';
     if (isset($url['user'])) {
         $result .= $url['user'] . (isset($url['pass']) ? ':' . $url['pass'] : '') . '@';
     }
     $result .= $url['host'];
     if (isset($url['port'])) {
         $result .= ':' . $url['port'];
     }
     $result .= $url['path'];
     if (isset($url['query'])) {
         $result .= '?' . $url['query'];
     }
     if (isset($new_url['fragment'])) {
         $result .= '#' . $url['fragment'];
     }
     return $result;
 }
/**
 * Test Http functions.
 */
function test_functions()
{
    http_cache_last_modified();
    http_chunked_decode();
    http_deflate();
    http_inflate();
    http_build_cookie();
    http_date();
    http_get_request_body_stream();
    http_get_request_body();
    http_get_request_headers();
    http_match_etag();
    http_match_modified();
    http_match_request_header();
    http_support();
    http_negotiate_charset();
    http_negotiate_content_type();
    http_negotiate_language();
    ob_deflatehandler();
    ob_etaghandler();
    ob_inflatehandler();
    http_parse_cookie();
    http_parse_headers();
    http_parse_message();
    http_parse_params();
    http_persistent_handles_clean();
    http_persistent_handles_count();
    http_persistent_handles_ident();
    http_get();
    http_head();
    http_post_data();
    http_post_fields();
    http_put_data();
    http_put_file();
    http_put_stream();
    http_request_body_encode();
    http_request_method_exists();
    http_request_method_name();
    http_request_method_register();
    http_request_method_unregister();
    http_request();
    http_redirect();
    http_send_content_disposition();
    http_send_content_type();
    http_send_data();
    http_send_file();
    http_send_last_modified();
    http_send_status();
    http_send_stream();
    http_throttle();
    http_build_str();
    http_build_url();
}
Example #16
0
/**
 * Created by PhpStorm.
 * User: Marin Kaçaj
 * Date: 6/14/2015
 * Time: 2:05 PM
 */
use fti\adv_db\aggregator\FormViewAggregator;
use fti\adv_db\entity\Exam;
use fti\adv_db\entity\Result;
use fti\adv_db\entity\Student;
use fti\adv_db\http\HttpEntityParamBuilder;
require_once dirname(dirname(__FILE__)) . '/includes/loader.php';
require_once dirname(dirname(__FILE__)) . '/pages/editHelper.php';
redirectIfNotProfessor();
$previousURL = $_GET[PREVIOUS_URL];
$previousURLArg = http_build_str(array(PREVIOUS_URL => $previousURL));
$identifier = HttpEntityParamBuilder::retrieveFilter(array(Result::PROP_EXAM_ID, Result::PROP_STUDENT_ID));
$entityBuilder = Result::getBuilder();
$entityInstance = $entityBuilder->getByIdentifier($identifier);
if (!$entityInstance) {
    $entityInstance = $entityBuilder->createEmpty();
}
$entityInstance->setProperty(Result::PROP_EXAM_ID, $identifier[Result::PROP_EXAM_ID]);
$entityInstance->setProperty(Result::PROP_STUDENT_ID, $identifier[Result::PROP_STUDENT_ID]);
$examInstance = Exam::getBuilder()->getByIdentifier(array(Exam::PROP_ID => $identifier[Result::PROP_EXAM_ID]));
$studentInstance = Student::getBuilder()->getByIdentifier(array(Student::PROP_ID => $identifier[Result::PROP_STUDENT_ID]));
$entityInstance->getProperty(Result::PROP_EXAM_ID)->setEntityInstances(array($examInstance));
$entityInstance->getProperty(Result::PROP_STUDENT_ID)->setEntityInstances(array($studentInstance));
$formViewAggregator = new FormViewAggregator($entityInstance, $previousURLArg);
$contentHeader = $entityBuilder->getLabel();
$contentAction = 'P&euml;rdit&euml;so';