Example #1
0
function http_adv_get($qtype, $url, $extra = array(), $headers = array())
{
    $http = new http_class();
    $http->debug = 0;
    $http->html_debug = 0;
    $http->request_method = $qtype;
    $http->GetRequestArguments($url, $args);
    $err = $http->Open($args);
    foreach ($extra as $key => $value) {
        $args[$key] = $value;
    }
    $body = "";
    foreach ($headers as $key => $value) {
        $args['Headers'][$key] = $value;
    }
    if ($err == "") {
        $err = $http->Open($args);
        $err = $http->SendRequest($args);
        $http->ReadReplyHeaders($headers);
        if ($err == "") {
            if ($err == "") {
                for (;;) {
                    $err = $http->ReadReplyBody($acc, 2000);
                    if ($err != "" || $acc == "") {
                        break;
                    }
                    $body .= $acc;
                }
            }
        }
        $http->close();
    }
    return array($headers, $body);
}
Example #2
0
function _checkSFS($username, $email, $ip = '')
{
    global $_TABLES, $_SPX_CONF, $LANG_SX00;
    $rc = 0;
    $arguments = array();
    $response = '';
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    $http->debug = 0;
    $http->html_debug = 0;
    $http->user_agent = 'glFusion/' . GVERSION;
    $url = "http://www.stopforumspam.com/api";
    $requestArgs = '?f=serial&';
    if ($ip != '') {
        $requestArgs .= 'ip=' . $ip . '&';
    }
    if ($email != '') {
        $requestArgs .= 'email=' . urlencode($email) . '&';
    }
    if ($username != '') {
        $requestArgs .= 'username='******'&';
    }
    $requestArgs .= 'cmd=display';
    $url = $url . $requestArgs;
    $error = $http->GetRequestArguments($url, $arguments);
    $error = $http->Open($arguments);
    $error = $http->SendRequest($arguments);
    if ($error == "") {
        $error = $http->ReadReplyBody($body, 1024);
        if ($error != "" || strlen($body) == 0) {
            break;
        }
        $response = $response . $body;
        $result = @unserialize($response);
        if (!$result) {
            return 0;
        }
        // invalid data, assume ok
        if (isset($result['email']) && $result['email']['appears'] == 1) {
            $rc = $rc + 1;
        }
        if (isset($result['ip']) && $result['ip']['appears'] == 1) {
            $rc = $rc + 2;
        }
        if (isset($result['username']) && $result['username']['appears'] == 1) {
            $rc = $rc + 4;
        }
    }
    return $rc;
}
 public function send_request($request)
 {
     $response_code = '0';
     $response_info = array();
     $response_headers = array();
     $error = '';
     $http = new http_class();
     $http->follow_redirect = 1;
     $http->redirection_limit = 5;
     $http->prefer_curl = 0;
     $error = $http->GetRequestArguments($request->uri, $arguments);
     if ($request->credentials != null) {
         $http->authentication_mechanism = "Digest";
         $arguments['AuthUser'] = $request->credentials->get_username();
         $arguments['AuthPassword'] = $request->credentials->get_password();
     }
     $arguments["RequestMethod"] = $request->method;
     foreach ($request->headers as $k => $v) {
         $arguments["Headers"][$k] = $v;
     }
     if ($request->body != null) {
         $arguments["Body"] = $request->body;
     }
     $error = $http->Open($arguments);
     if (!$error) {
         $error = $http->SendRequest($arguments);
     }
     if (!$error) {
         $error = $http->ReadReplyHeaders($response_headers);
         $response_code = $http->response_status;
         $response_body = '';
         for (;;) {
             $error = $http->ReadReplyBody($body, 1000);
             if ($error != "" || strlen($body) == 0) {
                 break;
             }
             $response_body .= $body;
         }
     } else {
         if ($request->_cache && $cached_response) {
             return $cached_response;
         }
         $response_body = "Request failed: " . $error;
     }
     $http->Close();
     $response = new HttpResponse();
     $response->status_code = $response_code;
     $response->headers = $response_headers;
     $response->body = $response_body;
     $response->info = $response_info;
     //ID20100317    $response->request = $request;
     $response->request_method = $request->method;
     $response->request_uri = $request->uri;
     $response->request_headers = $request->headers;
     $response->request_body = $request->body;
     $key = spl_object_hash($request);
     $this->responses[$key] = $response;
     return $key;
 }
Example #4
0
 /**
  * Fetch a remote URI then return results.
  *
  * If this method is triggered without the second parameter, <b>$target</b>, then
  * result will be return in the following format:
  *
  * <pre>array(
  *     'header' => array(
  *         'header_1' => 'header_value_1',
  *         'header_2' => 'header_value_2',
  *         etc...
  *     ),
  *     'body' => 'fetched response body'
  * )</pre>
  *
  * Otherwise, the fetched response body will be saved to the local file specified
  * by the variable <b>$target</b>. The example below will download the remote image
  * <b>http://placehold.it/300x200.gif</b> then save to the local file
  * <b>/tmp/downloaded_image.gif</b>:
  *
  * <pre>JSNUtilsHttp::get(
  *     'http://placehold.it/300x200.gif',
  *     '/tmp/downloaded_image.gif'
  * );</pre>
  *
  * When the second parameter is set in method call, the method will always return
  * the boolean value <b>true</b> if file is successfully saved or <b>false</b>
  * if file is not saved.
  *
  * @param   string   $uri             Remote URI for fetching content.
  * @param   string   $target          Set to a file path to save fetched content as local file.
  * @param   boolean  $validateHeader  Check for 200 OK header or not?
  *
  * @return  array  array('header' => 'Associative array of fetched header', 'body' => 'Fetched content')
  */
 public static function get($uri, $target = '', $validateHeader = false)
 {
     // Preset return result
     $result = array();
     // Initialize HTTP client
     $http = new http_class();
     $http->follow_redirect = 1;
     $http->redirection_limit = 5;
     $http->GetRequestArguments($uri, $arguments);
     // Open connection
     if (($error = $http->Open($arguments)) == '') {
         if (($error = $http->SendRequest($arguments)) == '') {
             // Get response header
             $header = array();
             if (($error = $http->ReadReplyHeaders($header)) != '') {
                 throw new Exception(JText::sprintf('JSN_EXTFW_HTTP_CONNECTION_ERROR', $error));
             }
             $result['header'] = $header;
             // Validate header
             if ($validateHeader) {
                 foreach ($result['header'] as $header => $value) {
                     if (strtolower(substr($header, 0, 5)) == 'http/' and strpos($header, '200') === false) {
                         throw new Exception(JText::sprintf('JSN_EXTFW_HTTP_CONNECTION_ERROR', substr($header, strpos($header, ' '))));
                     }
                 }
             }
             // Get response body
             $result['body'] = '';
             while (true) {
                 if (($error = $http->ReadReplyBody($body, 1000)) != '' or strlen($body) == 0) {
                     break;
                 }
                 $result['body'] .= $body;
             }
         } else {
             throw new Exception(JText::sprintf('JSN_EXTFW_HTTP_CONNECTION_ERROR', $error));
         }
         // Close connection
         $http->Close();
     } else {
         throw new Exception(JText::sprintf('JSN_EXTFW_HTTP_CONNECTION_ERROR', $error));
     }
     return !empty($target) ? JFile::write($target, $result['body']) : $result;
 }
Example #5
0
/**
* Send an HTTP HEAD request for the given URL
*
* @param    string  $url        URL to request
* @param    string  $errmsg     error message, if any (on return)
* @return   int                 HTTP response code or 777 on error
*
*/
function doHeadRequest($url, &$errmsg)
{
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    $http->debug = 0;
    $http->html_debug = 0;
    $http->user_agent = 'glFusion/' . GVERSION;
    $error = $http->GetRequestArguments($url, $arguments);
    $error = $http->Open($arguments);
    $error = $http->SendRequest($arguments);
    if ($error == "") {
        $http->ReadReplyHeaders($headers);
        return $http->response_status;
    } else {
        $errmsg = $error;
        return 777;
    }
}
Example #6
0
 /**
  * Check for spam links
  *
  * @param    string  $post   post to check for spam
  * @return   boolean         true = spam found, false = no spam
  *
  * Note: Also returns 'false' in case of problems communicating with SFS.
  *       Error messages are logged in glFusion's error.log
  *
  */
 function CheckForSpam($post)
 {
     global $_SPX_CONF, $REMOTE_ADDR;
     $retval = false;
     $ip = $REMOTE_ADDR;
     if (empty($post) || $ip == '') {
         return $retval;
     }
     $arguments = array();
     $response = '';
     $http = new http_class();
     $http->timeout = 0;
     $http->data_timeout = 0;
     $http->debug = 0;
     $http->html_debug = 0;
     $http->user_agent = 'glFusion/' . GVERSION;
     $url = "http://www.stopforumspam.com/api";
     $requestArgs = '?f=serial&';
     if ($ip != '') {
         $requestArgs .= 'ip=' . $ip . '&';
     }
     $requestArgs .= 'cmd=display';
     $url = $url . $requestArgs;
     $error = $http->GetRequestArguments($url, $arguments);
     $error = $http->Open($arguments);
     $error = $http->SendRequest($arguments);
     if ($error == "") {
         $error = $http->ReadReplyBody($body, 1024);
         if ($error == "" || strlen($body) > 0) {
             $response = $response . $body;
             $result = @unserialize($response);
             if (!$result) {
                 return 0;
             }
             // invalid data, assume ok
             if (isset($result['ip']) && $result['ip']['appears'] == 1 && $result['ip']['confidence'] > (double) 25) {
                 $retval = true;
                 SPAMX_log("SFS: spam detected");
             }
         }
     }
     return $retval;
 }
Example #7
0
/**
 * Get the Pingback URL for a given URL
 *
 * @param    string $url URL to get the Pingback URL for
 * @return   string          Pingback URL or empty string
 */
function PNB_getPingbackUrl($url)
{
    $retval = '';
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    $http->debug = 0;
    $http->html_debug = 0;
    $http->user_agent = 'glFusion/' . GVERSION;
    $error = $http->GetRequestArguments($url, $arguments);
    $error = $http->Open($arguments);
    $error = $http->SendRequest($arguments);
    if ($error == "") {
        $http->ReadReplyHeaders($headers);
        if (isset($headers['x-pingback'])) {
            $retval = $headers['x-pingback'];
        } else {
            COM_errorLog("Pingback (HEAD): unable to locate x-pingback header");
        }
    } else {
        COM_errorLog('Pingback (HEAD): ' . $error);
        return false;
    }
    if (empty($retval)) {
        // search for <link rel="pingback">
        $http = new http_class();
        $http->timeout = 0;
        $http->data_timeout = 0;
        $http->debug = 0;
        $http->html_debug = 0;
        $http->user_agent = 'glFusion/' . GVERSION;
        $error = $http->GetRequestArguments($url, $arguments);
        $error = $http->Open($arguments);
        $error = $http->SendRequest($arguments);
        if ($error == "") {
            $http->ReadReplyHeaders($headers);
            if ($http->response_status == 200) {
                $error = $http->ReadWholeReplyBody($body);
                if ($error != "" && strlen($body) === 0) {
                    COM_errorLog("Pingback (GET): unable to retrieve response body");
                    return false;
                }
            } else {
                COM_errorLog("Pingback (GET): Got HTTP response code " . $http->response_status . " when requesting " . $url);
                return false;
            }
        } else {
            COM_errorLog("Pingback (GET): " . $error . " when requesting " . $url);
            return false;
        }
        // only search for the first match - it doesn't make sense to have
        // more than one pingback URL
        $found = preg_match("/<link rel=\"pingback\"[^>]*href=[\"']([^\"']*)[\"'][^>]*>/i", $body, $matches);
        if ($found === 1 && !empty($matches[1])) {
            $url = str_replace('&amp;', '&', $matches[1]);
            $retval = urldecode($url);
        }
    }
    return $retval;
}
 function open_url($type, $params = array())
 {
     $http = new http_class();
     $http->request_method = 'POST';
     $http->user_agent = "cesar-rodas/1.0 | Akismet-Class/" . CLASS_VERSION;
     $http->follow_redirect = 1;
     $http->redirection_limit = 5;
     $http->exclude_address = "";
     $http->protocol_version = "1.1";
     $http->GetRequestArguments($this->get_url($type), $arguments);
     $arguments['PostValues'] = $params;
     $this->err = $http->Open($arguments);
     if ($this->err != "") {
         return false;
     }
     $this->err = $http->SendRequest($arguments);
     if ($this->err != "") {
         return false;
     }
     $this->err = $http->ReadReplyHeaders($gHeaders);
     if ($this->err != "") {
         return false;
     }
     if ($http->response_status != 200) {
         $this->err = "Pages status: " . $http->response_status;
         $http->Close();
         return false;
     }
     $response = '';
     for (;;) {
         $this->error = $http->ReadReplyBody($body, 1000);
         if ($this->error != "" || strlen($body) == 0) {
             break;
         }
         $response .= $body;
     }
     $http->close();
     return $response;
 }
Example #9
0
 function httpClientPost($url, $paramters)
 {
     //$url='https://login.yahoo.com/config/login?';
     //$url="https://accounts.google.com/ServiceLogin";
     //log echo  '<br/> httpClient $url: '.  $url ;
     //log echo  '<br/> httpClient $paramters: '    ;
     //log var_dump($paramters);
     $resultbody;
     set_time_limit(0);
     $http = new http_class();
     $http->timeout = 0;
     $http->data_timeout = 0;
     $http->debug = 0;
     $http->html_debug = 1;
     //$url="https://login.yahoo.com/config/login";
     if ($this->isDebug) {
         echo "<br/>url:" . $url;
         echo "<br/>arguments:<br/>";
         var_dump($paramters);
     }
     $error = $http->GetRequestArguments($url, $arguments);
     $arguments["RequestMethod"] = "POST";
     //$arguments['Protocol']='https';
     //$arguments['HostName']='login.yahoo.com';
     //$arguments['HostPort']='443';
     //$arguments['RequestMethod']='POST';
     $arguments['PostValues'] = $paramters;
     /*
     $arguments["PostValues"]=array(
     	"somefield"=>"Upload forms",
     	"MAX_FILE_SIZE"=>"1000000"
     );
     $arguments["PostFiles"]=array(
     	"userfile"=>array(
     		"Data"=>"This is just a plain text attachment file named attachment.txt .",
     		"Name"=>"attachment.txt",
     		"Content-Type"=>"automatic/name",
     	),
     	"anotherfile"=>array(
     		"FileName"=>"test_http_post.php",
     		"Content-Type"=>"automatic/name",
     	)
     );
     $arguments["Referer"]="http://www.alltheweb.com/";
     */
     if ($this->isDebug) {
         echo "<H2><LI>Opening connection to:</H2>\n<PRE>", HtmlEntities($arguments["HostName"]), "</PRE>\n";
         echo '<br/> <b>$arguments: </b><br/> ';
         var_dump($arguments);
     }
     flush();
     $error = $http->Open($arguments);
     if ($this->isDebug) {
         echo "<br/><br/>http->open:" . $error . "<br/>";
     }
     if ($error == "") {
         $error = $http->SendRequest($arguments);
         if ($this->isDebug) {
             echo "<br/>[http->SendRequest:" . $error . "]<br/><br/>";
         }
         if ($error == "") {
             //log echo "<H2><LI>Request:</LI</H2>\n<PRE>\n".HtmlEntities($http->request)."</PRE>\n";
             //log echo "<H2><LI>Request headers:</LI</H2>\n<PRE>\n";
             for (Reset($http->request_headers), $header = 0; $header < count($http->request_headers); Next($http->request_headers), $header++) {
                 $header_name = Key($http->request_headers);
                 if (GetType($http->request_headers[$header_name]) == "array") {
                     for ($header_value = 0; $header_value < count($http->request_headers[$header_name]); $header_value++) {
                         //log echo $header_name.": ".$http->request_headers[$header_name][$header_value],"\r\n";
                     }
                 } else {
                     //log echo $header_name.": ".$http->request_headers[$header_name],"\r\n";
                 }
             }
             //log echo "</PRE>\n";
             if ($this->isDebug) {
                 echo "<H4><LI>HTTP Request body:</LI></H4>error_code:\n" . $http->error_code . "<br/><PRE>request_body:\n" . HtmlEntities($http->request_body) . "</PRE>\n";
             }
             flush();
             $headers = array();
             $error = $http->ReadReplyHeaders($headers);
             if ($error == "") {
                 //log echo "<H2><LI>Response headers:</LI</H2>\n<PRE>\n";
                 for (Reset($headers), $header = 0; $header < count($headers); Next($headers), $header++) {
                     $header_name = Key($headers);
                     if (GetType($headers[$header_name]) == "array") {
                         for ($header_value = 0; $header_value < count($headers[$header_name]); $header_value++) {
                             if ($this->isDebug) {
                                 echo "http header:" . $header_name . ": " . $headers[$header_name][$header_value], "\r\n";
                             }
                         }
                     } else {
                         if ($this->isDebug) {
                             echo $header_name . ": " . $headers[$header_name], "\r\n";
                         }
                     }
                 }
                 //log echo "</PRE>\n";
                 flush();
                 //log echo "<H2><LI>Response body:</LI</H2>\n<PRE>\n";
                 for (;;) {
                     $error = $http->ReadReplyBody($body, 1000);
                     if ($error != "" || strlen($body) == 0) {
                         break;
                     }
                     //log echo HtmlSpecialChars($body);
                     $this->httpResponseStatus = $http->response_status;
                     $resultbody = $body;
                     if ($this->isDebug) {
                         echo "<br/>http->  get response_status: " . $http->response_status . "<br/> ";
                         echo "<br/>http->  get body: " . $resultbody . "<br/> ";
                     }
                 }
                 //log echo "</PRE>\n";
                 flush();
             }
         }
         $http->Close();
     }
     if (strlen($error)) {
         if ($this->isDebug) {
             echo " <H4>POST Error: ", $error, "</H4> ";
         }
     }
     return $resultbody;
 }
Example #10
0
 function SendAPIRequest($url, $method, $parameters, $oauth, $options, &$response)
 {
     $this->response_status = 0;
     $http = new http_class();
     $http->debug = $this->debug && $this->debug_http;
     $http->log_debug = true;
     $http->sasl_authenticate = 0;
     $http->user_agent = $this->oauth_user_agent;
     $http->redirection_limit = isset($options['FollowRedirection']) ? intval($options['FollowRedirection']) : 0;
     $http->follow_redirect = $http->redirection_limit != 0;
     if ($this->debug) {
         $this->OutputDebug('Accessing the ' . $options['Resource'] . ' at ' . $url);
     }
     $post_files = array();
     $method = strtoupper($method);
     $authorization = '';
     $request_content_type = isset($options['RequestContentType']) ? strtolower(trim(strtok($options['RequestContentType'], ';'))) : ($method === 'POST' || isset($oauth) ? 'application/x-www-form-urlencoded' : '');
     $files = isset($options['Files']) ? $options['Files'] : array();
     if (count($files)) {
         foreach ($files as $name => $value) {
             if (!isset($parameters[$name])) {
                 return $this->SetError('it was specified an file parameters named ' . $name);
             }
             $file = array();
             switch (isset($value['Type']) ? $value['Type'] : 'FileName') {
                 case 'FileName':
                     $file['FileName'] = $parameters[$name];
                     break;
                 case 'Data':
                     $file['Data'] = $parameters[$name];
                     break;
                 default:
                     return $this->SetError($value['Type'] . ' is not a valid type for file ' . $name);
             }
             $file['Content-Type'] = isset($value['ContentType']) ? $value['ContentType'] : 'automatic/name';
             $post_files[$name] = $file;
         }
         unset($parameters[$name]);
         if ($method !== 'POST') {
             $this->OutputDebug('For uploading files the method should be POST not ' . $method);
             $method = 'POST';
         }
         if ($request_content_type !== 'multipart/form-data') {
             if (isset($options['RequestContentType'])) {
                 return $this->SetError('the request content type for uploading files should be multipart/form-data');
             }
             $request_content_type = 'multipart/form-data';
         }
     }
     if (isset($oauth)) {
         if (!$this->Sign($url, $method, $parameters, $oauth, $request_content_type, count($files) !== 0, isset($options['PostValuesInURI']) && $options['PostValuesInURI'], $authorization, $post_values)) {
             return false;
         }
     } else {
         $post_values = $parameters;
         if (count($parameters)) {
             switch ($request_content_type) {
                 case 'application/x-www-form-urlencoded':
                 case 'multipart/form-data':
                 case 'application/json':
                     break;
                 default:
                     $first = strpos($url, '?') === false;
                     foreach ($parameters as $name => $value) {
                         if (GetType($value) === 'array') {
                             foreach ($value as $index => $value) {
                                 $url .= ($first ? '?' : '&') . $name . '=' . UrlEncode($value);
                                 $first = false;
                             }
                         } else {
                             $url .= ($first ? '?' : '&') . $name . '=' . UrlEncode($value);
                             $first = false;
                         }
                     }
             }
         }
     }
     if (strlen($authorization) === 0 && !strcasecmp($this->access_token_type, 'Bearer')) {
         $authorization = 'Bearer ' . $this->access_token;
     }
     if (strlen($error = $http->GetRequestArguments($url, $arguments))) {
         return $this->SetError('it was not possible to open the ' . $options['Resource'] . ' URL: ' . $error);
     }
     if (strlen($error = $http->Open($arguments))) {
         return $this->SetError('it was not possible to open the ' . $options['Resource'] . ' URL: ' . $error);
     }
     if (count($post_files)) {
         $arguments['PostFiles'] = $post_files;
     }
     $arguments['RequestMethod'] = $method;
     switch ($request_content_type) {
         case 'application/x-www-form-urlencoded':
         case 'multipart/form-data':
             if (isset($options['RequestBody'])) {
                 return $this->SetError('the request body is defined automatically from the parameters');
             }
             $arguments['PostValues'] = $post_values;
             break;
         case 'application/json':
             $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
             $arguments['Body'] = isset($options['RequestBody']) ? $options['RequestBody'] : json_encode($parameters);
             break;
         default:
             if (!isset($options['RequestBody'])) {
                 if (isset($options['RequestContentType'])) {
                     return $this->SetError('it was not specified the body value of the of the API call request');
                 }
                 break;
             }
             $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
             $arguments['Body'] = $options['RequestBody'];
             break;
     }
     $arguments['Headers']['Accept'] = isset($options['Accept']) ? $options['Accept'] : '*/*';
     switch ($authentication = isset($options['AccessTokenAuthentication']) ? strtolower($options['AccessTokenAuthentication']) : '') {
         case 'basic':
             $arguments['Headers']['Authorization'] = 'Basic ' . base64_encode($this->client_id . ':' . ($this->get_token_with_api_key ? $this->api_key : $this->client_secret));
             break;
         case '':
             if (strlen($authorization)) {
                 $arguments['Headers']['Authorization'] = $authorization;
             }
             break;
         default:
             return $this->SetError($authentication . ' is not a supported authentication mechanism to retrieve an access token');
     }
     if (isset($options['RequestHeaders'])) {
         $arguments['Headers'] = array_merge($arguments['Headers'], $options['RequestHeaders']);
     }
     if (strlen($error = $http->SendRequest($arguments)) || strlen($error = $http->ReadReplyHeaders($headers))) {
         $http->Close();
         return $this->SetError('it was not possible to retrieve the ' . $options['Resource'] . ': ' . $error);
     }
     $error = $http->ReadWholeReplyBody($data);
     $http->Close();
     if (strlen($error)) {
         return $this->SetError('it was not possible to access the ' . $options['Resource'] . ': ' . $error);
     }
     $this->response_status = intval($http->response_status);
     $content_type = isset($options['ResponseContentType']) ? $options['ResponseContentType'] : (isset($headers['content-type']) ? strtolower(trim(strtok($headers['content-type'], ';'))) : 'unspecified');
     $content_type = preg_replace('/^(.+\\/).+\\+(.+)$/', '\\1\\2', $content_type);
     switch ($content_type) {
         case 'text/javascript':
         case 'application/json':
             if (!function_exists('json_decode')) {
                 return $this->SetError('the JSON extension is not available in this PHP setup');
             }
             $object = json_decode($data);
             switch (GetType($object)) {
                 case 'object':
                     if (!isset($options['ConvertObjects']) || !$options['ConvertObjects']) {
                         $response = $object;
                     } else {
                         $response = array();
                         foreach ($object as $property => $value) {
                             $response[$property] = $value;
                         }
                     }
                     break;
                 case 'array':
                     $response = $object;
                     break;
                 default:
                     if (!isset($object)) {
                         return $this->SetError('it was not returned a valid JSON definition of the ' . $options['Resource'] . ' values');
                     }
                     $response = $object;
                     break;
             }
             break;
         case 'application/x-www-form-urlencoded':
         case 'text/plain':
         case 'text/html':
             parse_str($data, $response);
             break;
         case 'text/xml':
             if (isset($options['DecodeXMLResponse'])) {
                 switch (strtolower($options['DecodeXMLResponse'])) {
                     case 'simplexml':
                         if ($this->debug) {
                             $this->OutputDebug('Decoding XML response with simplexml');
                         }
                         try {
                             $response = @new SimpleXMLElement($data);
                         } catch (Exception $exception) {
                             return $this->SetError('Could not parse XML response: ' . $exception->getMessage());
                         }
                         break 2;
                     default:
                         return $this->SetError($options['DecodeXML'] . ' is not a supported method to decode XML responses');
                 }
             }
         default:
             $response = $data;
             break;
     }
     if ($this->response_status >= 200 && $this->response_status < 300) {
         $this->access_token_error = '';
     } else {
         $this->access_token_error = 'it was not possible to access the ' . $options['Resource'] . ': it was returned an unexpected response status ' . $http->response_status . ' Response: ' . $data;
         if ($this->debug) {
             $this->OutputDebug('Could not retrieve the OAuth access token. Error: ' . $this->access_token_error);
         }
         if (isset($options['FailOnAccessError']) && $options['FailOnAccessError']) {
             $this->error = $this->access_token_error;
             return false;
         }
     }
     return true;
 }
$password = "";
/* Define your PHP Classes site access name here */
$password_line = __LINE__;
$host_name = "phpclasses.UpperDesign.com";
$uri = "/browse.html/file/5/download/1/name/http.php";
if ($user == "") {
    echo "PHP Classes site user was not specified in script " . __FILE__ . " line {$user_line}\n";
    exit;
}
if ($password == "") {
    echo "PHP Classes site password was not specified in script " . __FILE__ . " line {$password_line}\n";
    exit;
}
require "http.php";
set_time_limit(0);
$http_connection = new http_class();
$error = $http_connection->Open(array("HostName" => $host_name));
if ($error == "") {
    $error = $http_connection->SendRequest(array("RequestURI" => $uri, "RequestMethod" => "POST", "PostValues" => array("alias" => $user, "password" => $password, "Submit" => "Login", "dologin" => 1)));
    if ($error == "") {
        $error = $http_connection->ReadReplyHeaders(&$headers);
        if ($error == "") {
            for ($header = 0, Reset($headers); $header < count($headers); Next($headers), $header++) {
                if (Key($headers) == "set-cookie") {
                    break;
                }
            }
            if ($header < count($headers)) {
                for (;;) {
                    $error = $http_connection->ReadReplyBody(&$body, 1000);
                    if ($error != "" || strlen($body) == 0) {
Example #12
0
 * @(#) $Header: /opt2/ena/metal/http/test_http_post.php,v 1.5 2004/08/11 00:46:11 mlemos Exp $
 *
 */
?>
<HTML>
<HEAD>
<TITLE>Test for Manuel Lemos' PHP HTTP class to simulate a HTTP POST form submission</TITLE>
</HEAD>
<BODY>
<H1><CENTER>Test for Manuel Lemos' PHP HTTP class to simulate a HTTP POST form submission</CENTER></H1>
<HR>
<UL>
<?php 
require "http.php";
set_time_limit(0);
$http = new http_class();
$http->timeout = 0;
$http->data_timeout = 0;
$http->debug = 0;
$http->html_debug = 1;
$url = "http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echoraw.cgi";
$error = $http->GetRequestArguments($url, $arguments);
$arguments["RequestMethod"] = "POST";
$arguments["PostValues"] = array("somefield" => "Upload forms", "MAX_FILE_SIZE" => "1000000");
$arguments["PostFiles"] = array("userfile" => array("Data" => "This is just a plain text attachment file named attachment.txt .", "Name" => "attachment.txt", "Content-Type" => "automatic/name"), "anotherfile" => array("FileName" => "test_http_post.php", "Content-Type" => "automatic/name"));
$arguments["Referer"] = "http://www.alltheweb.com/";
echo "<H2><LI>Opening connection to:</H2>\n<PRE>", HtmlEntities($arguments["HostName"]), "</PRE>\n";
flush();
$error = $http->Open($arguments);
if ($error == "") {
    $error = $http->SendRequest($arguments);
Example #13
0
 protected function _saveUserPhoto($from, $to)
 {
     $ret = 0;
     $img = '';
     $arguments = array();
     $http = new http_class();
     $http->user_agent = 'glFusion/' . GVERSION;
     $error = $http->GetRequestArguments($from, $arguments);
     $error = $http->Open($arguments);
     if ($error == "") {
         $error = $http->SendRequest($arguments);
         if ($error == "") {
             for (;;) {
                 $error = $http->ReadReplyBody($body, 10240);
                 if ($error != "" || strlen($body) == 0) {
                     break;
                 }
                 $img = $img . $body;
             }
             $ret = file_put_contents($to, $img);
         }
     }
     $http->Close();
     return $ret;
 }
Example #14
0
function UpdateStep4()
{
    global $clang, $scriptname, $homedir, $buildnumber, $updatebuild, $debug, $rootdir, $publicdir, $tempdir, $database_exists, $databasetype, $action, $demoModeOnly;

    echo '<div class="header ui-widget-header">'.sprintf($clang->gT('ComfortUpdate step %s'),'4').'</div><div class="updater-background"><br />';
    if (!isset( $_SESSION['updateinfo']))
    {
        echo $clang->gT('On requesting the update information from limesurvey.org there has been an error:').'<br />';

        if ($updateinfo['error']==1)
        {
            setGlobalSetting('updatekey','');
            echo $clang->gT('Your update key is invalid and was removed. ').'<br />';
        }
        else
        echo $clang->gT('On requesting the update information from limesurvey.org there has been an error:').'<br />';
    }
    else
    {
        $updateinfo=$_SESSION['updateinfo'];
    }
    // this is the last step - Download the zip file, unpack it and replace files accordingly
    // Create DB and file backups now
    require_once("classes/pclzip/pclzip.lib.php");

    //   require_once('classes/pclzip/pcltrace.lib.php');
    //   require_once('classes/pclzip/pclzip-trace.lib.php');

    // PclTraceOn(2);
    require_once($homedir."/classes/http/http.php");

    $downloaderror=false;
    $http=new http_class;

    // Allow redirects
    $http->follow_redirect=1;
    /* Connection timeout */
    $http->timeout=0;
    /* Data transfer timeout */
    $http->data_timeout=0;
    $http->user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
    $http->GetRequestArguments("http://update.limesurvey.org/updates/download/{$updateinfo['downloadid']}",$arguments);
    $http->RestoreCookies($_SESSION['updatesession']);

    $error=$http->Open($arguments);
    $error=$http->SendRequest($arguments);
    $http->ReadReplyHeaders($headers);
    if ($headers['content-type']=='text/html')
    {
        @unlink($tempdir.'/update.zip');
    }
    elseif($error=='') {
        $body='';
        $pFile = fopen($tempdir.'/update.zip', 'w');
        for(;;){
            $error = $http->ReadReplyBody($body,100000);
            if($error != "" || strlen($body)==0) break;
            fwrite($pFile, $body);
        }
        fclose($pFile);
    }
    else
    {
        print( $error );
    }

    // Now remove all files that are to be deleted according to update process
    foreach ($updateinfo['files'] as $afile)
    {
        if ($afile['type']=='D' && file_exists($rootdir.$afile['file']))
        {
            if (is_file($rootdir.$afile['file']))
            {
                unlink($rootdir.$afile['file']);
            }
            else{
                rmdirr($rootdir.$afile['file']);
            }
            echo sprintf($clang->gT('File deleted: %s'),$afile['file']).'<br />';
        }
    }

    //Now unzip the new files over the existing ones.
    if (file_exists($tempdir.'/update.zip')){
        $archive = new PclZip($tempdir.'/update.zip');
        if ($archive->extract(PCLZIP_OPT_PATH, $rootdir.'/', PCLZIP_OPT_REPLACE_NEWER)== 0) {
            die("Error : ".$archive->errorInfo(true));
        }
        else
        {
            echo $clang->gT('New files were successfully installed.').'<br />';
            unlink($tempdir.'/update.zip');
        }
    }
    else
    {
        echo $clang->gT('There was a problem downloading the update file. Please try to restart the update process.').'<br />';
        $downloaderror=true;
    }
    //  PclTraceDisplay();

    // Now we have to update version.php
    if (!$downloaderror)
    {
        @ini_set('auto_detect_line_endings', true);
        $versionlines=file($rootdir.'/version.php');
        $handle = fopen($rootdir.'/version.php', "w");
        foreach ($versionlines as $line)
        {
            if(strpos($line,'$buildnumber')!==false)
            {
                $line='$buildnumber'." = '{$_SESSION['updateinfo']['toversion']}';\r\n";
            }
            fwrite($handle,$line);
        }
        fclose($handle);
        echo sprintf($clang->gT('Buildnumber was successfully updated to %s.'),$_SESSION['updateinfo']['toversion']).'<br />';
        echo $clang->gT('Please check any problems above - update was done.').'<br />';
    }


    echo "<p><button onclick=\"window.open('$scriptname?action=globalsettings&amp;subaction=updatecheck', '_top')\" >".$clang->gT('Back to main menu')."</button></p>";
    echo '</div>';
    setGlobalSetting('updatelastcheck','1980-01-01 00:00');
    setGlobalSetting('updateavailable','0');
}
Example #15
0
 /**
  * Fetch a remote URI then return results.
  *
  * If this method is triggered without the second parameter, <b>$target</b>, then
  * result will be return in the following format:
  *
  * <pre>array(
  *     'header' => array(
  *         'header_1' => 'header_value_1',
  *         'header_2' => 'header_value_2',
  *         etc...
  *     ),
  *     'body' => 'fetched response body'
  * )</pre>
  *
  * Otherwise, the fetched response body will be saved to the local file specified
  * by the variable <b>$target</b>. The example below will download the remote image
  * <b>http://placehold.it/300x200.gif</b> then save to the local file
  * <b>/tmp/downloaded_image.gif</b>:
  *
  * <pre>JSNUtilsHttp::get(
  *     'http://placehold.it/300x200.gif',
  *     '/tmp/downloaded_image.gif'
  * );</pre>
  *
  * When the second parameter is set in method call, the method will always return
  * the boolean value <b>true</b> if file is successfully saved or <b>false</b>
  * if file is not saved.
  *
  * @param   string   $uri             Remote URI for fetching content.
  * @param   string   $target          Set to a file path to save fetched content as local file.
  * @param   boolean  $validateHeader  Check for 200 OK header or not?
  * @param   array    $options         Custom options to pass to http_class object.
  *
  * @return  array  array('header' => 'Associative array of fetched header', 'body' => 'Fetched content')
  */
 public static function get($uri, $target = '', $validateHeader = true, $options = array())
 {
     // Preset return result
     $result = array();
     // Initialize HTTP client
     $http = new http_class();
     $http->follow_redirect = 1;
     $http->redirection_limit = 5;
     $http->GetRequestArguments($uri, $arguments);
     // Set custom options
     if (is_array($options) and count($options)) {
         foreach ($options as $k => $v) {
             $arguments[$k] = $v;
         }
     }
     // Open connection
     if (($error = $http->Open($arguments)) == '') {
         if (($error = $http->SendRequest($arguments)) == '') {
             // Get response header
             $header = array();
             if (($error = $http->ReadReplyHeaders($header)) != '') {
                 throw new Exception(JText::sprintf('JSN_TPLFW_HTTP_CONNECTION_ERROR', $error));
             }
             $result['header'] = $header;
             // Validate header
             if ($validateHeader) {
                 foreach ($result['header'] as $header => $value) {
                     if (strtolower(substr($header, 0, 5)) == 'http/' and strpos($header, '200') === false) {
                         throw new Exception(JText::sprintf('JSN_TPLFW_HTTP_CONNECTION_ERROR', substr($header, strpos($header, ' '))));
                     }
                 }
             }
             // Get response body
             $result['body'] = '';
             while (true) {
                 if (($error = $http->ReadReplyBody($body, 1000)) != '' or strlen($body) == 0) {
                     break;
                 }
                 $result['body'] .= $body;
             }
             // Validate header
             if (is_array($validateHeader)) {
                 foreach ($validateHeader as $k => $v) {
                     foreach ($result['header'] as $header => $value) {
                         if (strcasecmp($header, $k) == 0) {
                             is_array($v) or $v = array($v);
                             if (!in_array($value, $v)) {
                                 throw new Exception($result['body']);
                             }
                         }
                     }
                 }
             }
         } else {
             throw new Exception(JText::sprintf('JSN_TPLFW_HTTP_CONNECTION_ERROR', $error));
         }
         // Close connection
         $http->Close();
     } else {
         throw new Exception(JText::sprintf('JSN_TPLFW_HTTP_CONNECTION_ERROR', $error));
     }
     // Write to local file if target is given
     empty($target) or JFile::write($target, $result['body']);
     return $result;
 }
Example #16
0
function acc_doPostRequest($request, $params = false, $proxy = false, $auth = false)
{
    require_once 'modules/Accounting/sasl/http.php';
    $authentication = "";
    $realm = "";
    $workstation = "";
    set_time_limit(120);
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    $http->follow_redirect = 1;
    $http->debug = 0;
    $http->html_debug = 1;
    if ($auth !== false || $proxy !== false) {
        require_once "modules/Accounting/sasl/sasl.php";
    }
    // Basic Authentication
    if ($auth !== false) {
        $user = $auth["user"];
        $password = $auth["password"];
        $realm = $auth["realm"];
        // Authentication realm or domain
        $workstation = $auth["workstation"];
        // Workstation for NTLM authentication
        $authentication = strlen($user) ? UrlEncode($user) . ":" . UrlEncode($password) . "@" : "";
    }
    $url = $request['scheme'] . "://" . $authentication . $request['url'];
    $url = trim($url, " ");
    $error = $http->GetRequestArguments($url, $arguments);
    if ($error != "") {
        return false;
    }
    $arguments["RequestMethod"] = $request['method'];
    if ($request['method'] == 'POST') {
        $arguments["PostValues"] = $params;
    } else {
        $url .= "?";
        foreach ($params as $param => $value) {
            $url .= $param . "=" . $value . "&";
        }
        $url = rtrim($url, "&");
    }
    // Auth
    if ($auth !== false) {
        $arguments["AuthRealm"] = $realm;
    }
    if ($auth !== false) {
        $arguments["AuthWorkstation"] = $workstation;
    }
    $arguments["Headers"]["Pragma"] = "nocache";
    // Proxy
    if ($proxy !== false) {
        $arguments["ProxyHostName"] = isset($proxy["host"]) ? $proxy["host"] : "";
        $arguments["ProxyHostPort"] = isset($proxy["port"]) ? $proxy["port"] : 0;
        $arguments["ProxyUser"] = isset($proxy["user"]) ? $proxy["user"] : "";
        $arguments["ProxyPassword"] = isset($proxy["password"]) ? $proxy["password"] : "";
        $arguments["ProxyRealm"] = isset($proxy["realm"]) ? $proxy["realm"] : "";
        // Proxy authentication realm or domain
        $arguments["ProxyWorkstation"] = isset($proxy["workstation"]) ? $proxy["workstation"] : "";
        // Workstation for NTLM proxy authentication
        $http->proxy_authentication_mechanism = isset($proxy["mechanism"]) ? $proxy["mechanism"] : "";
        // force a given proxy authentication mechanism;
    }
    $result = false;
    $error = $http->Open($arguments);
    if ($error == "") {
        $error = $http->SendRequest($arguments);
        if ($error == "") {
            $headers = array();
            $error = $http->ReadReplyHeaders($headers);
            if ($error == "") {
                for (;;) {
                    $error = $http->ReadReplyBody($body, 1000);
                    if ($error != "" || strlen($body) == 0) {
                        break;
                    }
                    $result .= $body;
                }
            }
        }
        $http->Close();
    }
    return $result;
}
 public function switchAction($action, $httpVars, $fileVars)
 {
     //$this->logInfo("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $dlURL = null;
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $httpVars["file"];
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $realFile;
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
             session_write_close();
             $httpClient = new http_class();
             $arguments = array();
             $httpClient->GetRequestArguments($httpVars["file"], $arguments);
             $err = $httpClient->Open($arguments);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             if (empty($err)) {
                 $err = $httpClient->SendRequest($arguments);
                 $httpClient->follow_redirect = true;
                 $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
                 if (is_file($pidHiddenFileName)) {
                     $pid = file_get_contents($pidHiddenFileName);
                     @unlink($pidHiddenFileName);
                 }
                 if (empty($err)) {
                     $httpClient->ReadReplyHeaders($collectHeaders);
                     $totalSize = -1;
                     if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                         $ar = explode("filename=", $collectHeaders["content-disposition"]);
                         $basename = trim(array_pop($ar));
                         $basename = str_replace("\"", "", $basename);
                         // Remove quotes
                     }
                     if (!empty($collectHeaders["content-length"])) {
                         $totalSize = intval($collectHeaders["content-length"]);
                         $this->logDebug("Should download {$totalSize} bytes!");
                     }
                     if ($totalSize != -1) {
                         $node = new AJXP_Node($destStreamURL . $basename);
                         AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
                     }
                     $tmpFilename = $destStreamURL . $basename . ".dlpart";
                     $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
                     $filename = $destStreamURL . $basename;
                     $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
                     if (isset($pid)) {
                         $dlData["pid"] = $pid;
                     }
                     //file_put_contents($hiddenFilename, serialize($dlData));
                     $fpHid = fopen($hiddenFilename, "w");
                     fputs($fpHid, serialize($dlData));
                     fclose($fpHid);
                     // NOW READ RESPONSE
                     $destStream = fopen($tmpFilename, "w");
                     while (true) {
                         $body = "";
                         $error = $httpClient->ReadReplyBody($body, 1000);
                         if ($error != "" || strlen($body) == 0) {
                             break;
                         }
                         fwrite($destStream, $body, strlen($body));
                     }
                     fclose($destStream);
                     rename($tmpFilename, $filename);
                     unlink($hiddenFilename);
                 }
                 $httpClient->Close();
                 if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                     AJXP_Controller::applyHook("node.before_path_change", array(new AJXP_Node($dlFile)));
                     unlink($dlFile);
                     AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
                 }
                 $mess = ConfService::getMessages();
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
                 AJXP_XMLWriter::close();
             }
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 $node = new AJXP_Node($destStreamURL . $file);
                 if (method_exists($node->getDriver(), "filesystemFileSize")) {
                     $filesize = $node->getDriver()->filesystemFileSize($node->getUrl());
                 } else {
                     $filesize = filesize($node->getUrl());
                 }
                 echo $filesize;
             } else {
                 echo "stop";
             }
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             $this->logDebug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             break;
         default:
             break;
     }
     return false;
 }
 function testFetch($url)
 {
     $http = new http_class();
     owa_coreAPI::debug('hello owa_http testfetch method');
     /* Connection timeout */
     $http->timeout = 0;
     /* Data transfer timeout */
     $http->data_timeout = 0;
     /* Output debugging information about the progress of the connection */
     $http->debug = 1;
     $http->user_agent = owa_coreAPI::getSetting('base', 'owa_user_agent');
     $http->follow_redirect = 1;
     $http->redirection_limit = 5;
     $http->exclude_address = "";
     $http->prefer_curl = 0;
     $arguments = array();
     $error = $http->GetRequestArguments($url, $arguments);
     $error = $http->Open($arguments);
     //for(;;)
     //		{
     $error = $http->ReadReplyBody($body, 50000);
     if ($error != "" || strlen($body) == 0) {
         owa_coreAPI::debug(HtmlSpecialChars($body));
     }
     //		}
 }
function testAuthenticationSQLi($urlToCheck, $urlOfSite, $testId)
{
    connectToDb($db);
    updateStatus($db, "Testing {$urlToCheck} for Broken Authentication using SQL Injection...", $testId);
    $log = new Logger();
    $log->lfile('logs/eventlogs');
    $log->lwrite("Starting Broken Authentication SQLi test function on {$urlToCheck}");
    $postUrl = $urlToCheck;
    $postUrlPath = parse_url($postUrl, PHP_URL_PATH);
    //Check URL is not responding with 5xx codes
    $log->lwrite("Checking what response code is received from {$urlToCheck}");
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    //$http->debug=1;
    $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
    $http->follow_redirect = 1;
    $http->redirection_limit = 5;
    $http->setTestId($testId);
    $error = $http->GetRequestArguments($urlToCheck, $arguments);
    $error = $http->Open($arguments);
    $log->lwrite("URL to be requested is: {$urlToCheck}");
    if ($error == "") {
        $log->lwrite("Sending HTTP request to {$urlToCheck}");
        $error = $http->SendRequest($arguments);
        if ($error == "") {
            $headers = array();
            $error = $http->ReadReplyHeaders($headers);
            if ($error == "") {
                $responseCode = $http->response_status;
                //This is a string
                $log->lwrite("Received response code: {$responseCode}");
                if (intval($responseCode) >= 500 && intval($responseCode) < 600) {
                    $log->lwrite("Response code: {$responseCode} received from: {$urlToCheck}");
                    return;
                }
            }
        }
        $http->Close();
    }
    if (strlen($error)) {
        echo "<H2 align=\"center\">Error: ", $error, "</H2>\n";
        $log->lwrite("Error: {$error}");
    }
    $html = file_get_html($postUrl, $testId);
    if (empty($html)) {
        //This can happen due to file_get_contents returning a 500 code. Then the parser won't parse it
        updateStatus($db, "Problem getting contents from {$urlToCheck}...", $testId);
        $log->lwrite("Problem getting contents from {$urlToCheck}");
        return;
    }
    //Array containing all form objects found
    $arrayOfForms = array();
    //Array containing all input fields
    $arrayOfInputFields = array();
    $log->lwrite("Searching {$postUrl} for forms");
    $formNum = 1;
    //Must use an integer to identify form as forms could have same names and ids
    foreach ($html->find('form') as $form) {
        isset($form->attr['id']) ? $formId = htmlspecialchars($form->attr['id']) : ($formId = '');
        isset($form->attr['name']) ? $formName = htmlspecialchars($form->attr['name']) : ($formName = '');
        isset($form->attr['method']) ? $formMethod = htmlspecialchars($form->attr['method']) : ($formMethod = 'get');
        isset($form->attr['action']) ? $formAction = htmlspecialchars($form->attr['action']) : ($formAction = '');
        $formMethod = strtolower($formMethod);
        //If the action of the form is empty, set the action equal to everything
        //after the URL that the user entered
        if (empty($formAction)) {
            $strLengthUrl = strlen($urlToCheck);
            $strLengthSite = strlen($urlOfSite);
            $firstIndexOfSlash = strpos($urlToCheck, '/', $strLengthSite - 1);
            $formAction = substr($urlToCheck, $firstIndexOfSlash + 1, $strLengthUrl);
        }
        $log->lwrite("Found form on {$postUrl}: {$formId} {$formName} {$formMethod} {$formAction} {$formNum}");
        $newForm = new Form($formId, $formName, $formMethod, $formAction, $formNum);
        array_push($arrayOfForms, $newForm);
        foreach ($form->find('input') as $input) {
            isset($input->attr['id']) ? $inputId = htmlspecialchars($input->attr['id']) : ($inputId = '');
            isset($input->attr['name']) ? $inputName = htmlspecialchars($input->attr['name']) : ($inputName = '');
            isset($input->attr['value']) ? $inputValue = htmlspecialchars($input->attr['value']) : ($inputValue = '');
            isset($input->attr['type']) ? $inputType = htmlspecialchars($input->attr['type']) : ($inputType = '');
            $log->lwrite("Found input field on {$postUrl}: {$inputId} {$inputName} {$formId} {$formName} {$inputValue} {$inputType} {$formNum}");
            $inputField = new InputField($inputId, $inputName, $formId, $formName, $inputValue, $inputType, $formNum);
            array_push($arrayOfInputFields, $inputField);
        }
        $formNum++;
    }
    //At this stage, we should have captured all forms and their input fields into the appropriate arrays
    //Begin testing each of the forms
    //Defintion of all payloads used and warnings to examine for
    //Payloads can be added to this
    $arrayOfPayloads = array("1'or'1'='1", "1'or'1'='1';#");
    //Check if the URL passed into this function displays the same webpage at different intervals
    //If it does then attempt to login and if this URL displays a different page, the vulnerability is present
    //e.g. a login page would always look different when you are and are not logged in
    $log->lwrite("Checking if {$urlToCheck} displays the same page at different intervals");
    $responseBodies = array();
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    //$http->debug=1;
    $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
    $http->follow_redirect = 1;
    $http->redirection_limit = 5;
    $http->setTestId($testId);
    for ($a = 0; $a < 3; $a++) {
        $error = $http->GetRequestArguments($urlToCheck, $arguments);
        $error = $http->Open($arguments);
        if ($error == "") {
            $number = $a + 1;
            $log->lwrite("Sending HTTP request number {$number} to {$urlToCheck}");
            $error = $http->SendRequest($arguments);
            if ($error == "") {
                $headers = array();
                $error = $http->ReadReplyHeaders($headers);
                if ($error == "") {
                    $error = $http->ReadWholeReplyBody($body);
                    if (strlen($error) == 0) {
                        array_push($responseBodies, $body);
                    }
                }
            }
            $http->Close();
        }
        if (strlen($error)) {
            echo "<H2 align=\"center\">Error: a= {$a} ", $error, "</H2>\n";
        }
    }
    $pageChanges = true;
    $bodyOfUrl = "";
    if ($responseBodies[0] == $responseBodies[1] && $responseBodies[1] == $responseBodies[2]) {
        $bodyOfUrl = $responseBodies[0];
        $pageChanges = false;
    }
    $log->lwrite('Beginning testing of forms');
    for ($i = 0; $i < sizeof($arrayOfForms); $i++) {
        $currentForm = $arrayOfForms[$i];
        $currentFormId = $currentForm->getId();
        $currentFormName = $currentForm->getName();
        $currentFormMethod = $currentForm->getMethod();
        $currentFormAction = $currentForm->getAction();
        $currentFormNum = $currentForm->getFormNum();
        $arrayOfCurrentFormsInputs = array();
        $log->lwrite("Beginning testing of form on {$postUrl}: {$currentFormId} {$currentFormName} {$currentFormMethod} {$currentFormAction}");
        for ($j = 0; $j < sizeof($arrayOfInputFields); $j++) {
            $currentInput = $arrayOfInputFields[$j];
            $currentInputIdOfForm = $currentInput->getIdOfForm();
            $currentInputNameOfForm = $currentInput->getNameOfForm();
            $currentInputFormNum = $currentInput->getFormNum();
            if ($currentFormNum == $currentInputFormNum) {
                array_push($arrayOfCurrentFormsInputs, $currentInput);
            }
        }
        $log->lwrite("Beginning testing input fields of form on {$postUrl}: {$currentFormId} {$currentFormName} {$currentFormMethod} {$currentFormAction}");
        foreach ($arrayOfPayloads as $currentPayload) {
            echo '<br>Size of current form inputs = ' . sizeof($arrayOfCurrentFormsInputs) . '<br>';
            $arrayOfValues = array();
            //Array of PostOrGetObject objects
            for ($k = 0; $k < sizeof($arrayOfCurrentFormsInputs); $k++) {
                $currentFormInput = $arrayOfCurrentFormsInputs[$k];
                $currentFormInputName = $currentFormInput->getName();
                $currentFormInputType = $currentFormInput->getType();
                $currentFormInputValue = $currentFormInput->getValue();
                if ($currentFormInputType != 'reset') {
                    $log->lwrite("Using payload: {$currentPayload}, to all input fields of form w/ action: {$currentFormAction}");
                    //Add current input and other inputs to array of post values and set their values
                    if ($currentFormInputType == 'text' || $currentFormInputType == 'password') {
                        $postObject = new PostOrGetObject($currentFormInputName, $currentPayload);
                        array_push($arrayOfValues, $postObject);
                    } else {
                        if ($currentFormInputType == 'checkbox' || $currentFormInputType == 'submit') {
                            $postObject = new PostOrGetObject($currentFormInputName, $currentFormInputValue);
                            array_push($arrayOfValues, $postObject);
                        } else {
                            if ($currentFormInputType == 'radio') {
                                $postObject = new PostOrGetObject($currentFormInputName, $currentFormInputValue);
                                //Check if a radio button in the radio group has already been added
                                $found = false;
                                for ($n = 0; $n < sizeof($arrayOfValues); $n++) {
                                    if ($arrayOfValues[$n]->getName() == $postObject->getName()) {
                                        $found = true;
                                        break;
                                    }
                                }
                                if (!$found) {
                                    array_push($arrayOfValues, $postObject);
                                }
                            }
                        }
                    }
                }
            }
            if ($currentFormMethod == 'get') {
                //Build query string and submit it at end of URL
                if ($urlOfSite[strlen($urlOfSite) - 1] == '/') {
                    $actionUrl = $urlOfSite . $currentFormAction;
                } else {
                    $actionUrl = $urlOfSite . '/' . $currentFormAction;
                }
                $totalTestStr = '';
                //Make a string to show the user how the vulnerability was tested for i.e. the data submitted to exploit the vulnerability
                for ($p = 0; $p < sizeof($arrayOfValues); $p++) {
                    $currentPostValue = $arrayOfValues[$p];
                    $currentPostValueName = $currentPostValue->getName();
                    $currentPostValueValue = $currentPostValue->getValue();
                    $totalTestStr .= $currentPostValueName;
                    $totalTestStr .= '=';
                    $totalTestStr .= $currentPostValueValue;
                    if ($p != sizeof($arrayOfValues) - 1) {
                        $totalTestStr .= '&';
                    }
                }
                $actionUrl .= '?';
                $actionUrl .= $totalTestStr;
                $error = $http->GetRequestArguments($actionUrl, $arguments);
                $error = $http->Open($arguments);
                $log->lwrite("URL to be requested is: {$actionUrl}");
                if ($error == "") {
                    $log->lwrite("Sending HTTP request to {$actionUrl}");
                    $error = $http->SendRequest($arguments);
                    if ($error == "") {
                        $headers = array();
                        $error = $http->ReadReplyHeaders($headers);
                        if ($error == "") {
                            $error = $http->ReadWholeReplyBody($body);
                            if (strlen($error) == 0) {
                                $http->Close();
                                $vulnerabilityFound = checkIfVulnerabilityFound($urlToCheck, $pageChanges, $bodyOfUrl, $log, $currentPayload, $http);
                                if ($vulnerabilityFound) {
                                    $totalTestStr = '';
                                    //Make a test string to show the user how the vulnerability was tested for
                                    for ($p = 0; $p < sizeof($arrayOfValues); $p++) {
                                        $currentPostValue = $arrayOfValues[$p];
                                        $currentPostValueName = $currentPostValue->getName();
                                        $currentPostValueValue = $currentPostValue->getValue();
                                        $totalTestStr .= $currentPostValueName;
                                        $totalTestStr .= '=';
                                        $totalTestStr .= $currentPostValueValue;
                                        if ($p != sizeof($arrayOfValues) - 1) {
                                            $totalTestStr .= '&';
                                        }
                                    }
                                    //The echo's below are for testing the function on its own i.e. requesting this script with your browser
                                    echo 'Broken Authentication Present!<br>Query: ' . HtmlSpecialChars($totalTestStr) . '<br>';
                                    echo 'Method: ' . $currentFormMethod . '<br>';
                                    echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>';
                                    echo 'Error: Successfully Logged In with SQL injection';
                                    $tableName = 'test' . $testId;
                                    //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB.
                                    $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'basqli' AND method = '{$currentFormMethod}' AND url = '" . addslashes($actionUrl) . "' AND attack_str = '" . addslashes($totalTestStr) . "'";
                                    $result = $db->query($query);
                                    if (!$result) {
                                        $log->lwrite("Could not execute query {$query}");
                                    } else {
                                        $log->lwrite("Successfully executed query {$query}");
                                        $numRows = $result->num_rows;
                                        if ($numRows == 0) {
                                            $log->lwrite("Number of rows is {$numRows} for query: {$query}");
                                            insertTestResult($db, $testId, 'basqli', $currentFormMethod, addslashes($actionUrl), addslashes($totalTestStr));
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                if (strlen($error)) {
                    echo "<H2 align=\"center\">Error: ", $error, "</H2>\n";
                    echo 'Method: ' . $currentFormMethod . '<br>';
                    echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>';
                }
            } else {
                if ($currentFormMethod == 'post') {
                    //Build query string and submit it at end of URL
                    if ($urlOfSite[strlen($urlOfSite) - 1] == '/') {
                        $actionUrl = $urlOfSite . $currentFormAction;
                    } else {
                        $actionUrl = $urlOfSite . '/' . $currentFormAction;
                    }
                    $error = $http->GetRequestArguments($actionUrl, $arguments);
                    $arguments["RequestMethod"] = "POST";
                    $arguments["PostValues"] = array();
                    for ($p = 0; $p < sizeof($arrayOfValues); $p++) {
                        $currentPostValue = $arrayOfValues[$p];
                        $currentPostValueName = $currentPostValue->getName();
                        $currentPostValueValue = $currentPostValue->getValue();
                        $tempArray = array($currentPostValueName => $currentPostValueValue);
                        $arguments["PostValues"] = array_merge($arguments["PostValues"], $tempArray);
                    }
                    $error = $http->Open($arguments);
                    $log->lwrite("URL to be requested is: {$actionUrl}");
                    if ($error == "") {
                        $log->lwrite("Sending HTTP request to {$actionUrl}");
                        $error = $http->SendRequest($arguments);
                        if ($error == "") {
                            $headers = array();
                            $error = $http->ReadReplyHeaders($headers);
                            if ($error == "") {
                                $error = $http->ReadWholeReplyBody($body);
                                if (strlen($error) == 0) {
                                    $http->Close();
                                    $vulnerabilityFound = checkIfVulnerabilityFound($urlToCheck, $pageChanges, $bodyOfUrl, $log, $currentPayload, $http);
                                    if ($vulnerabilityFound) {
                                        $totalTestStr = '';
                                        //Compile a test string to show the user how the vulnerability was tested for
                                        for ($p = 0; $p < sizeof($arrayOfValues); $p++) {
                                            $currentPostValue = $arrayOfValues[$p];
                                            $currentPostValueName = $currentPostValue->getName();
                                            $currentPostValueValue = $currentPostValue->getValue();
                                            $totalTestStr .= $currentPostValueName;
                                            $totalTestStr .= '=';
                                            $totalTestStr .= $currentPostValueValue;
                                            if ($p != sizeof($arrayOfValues) - 1) {
                                                $totalTestStr .= '&';
                                            }
                                        }
                                        //The echo's below are for testing the function on its own i.e. requesting this script with your browser
                                        echo 'Broken Authentication Present!<br>Query: ' . HtmlSpecialChars($totalTestStr) . '<br>';
                                        echo 'Method: ' . $currentFormMethod . '<br>';
                                        echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>';
                                        echo 'Error: Successfully Logged In with SQL injection';
                                        $tableName = 'test' . $testId;
                                        //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB.
                                        $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'basqli' AND method = '{$currentFormMethod}' AND url = '" . addslashes($actionUrl) . "' AND attack_str = '" . addslashes($totalTestStr) . "'";
                                        $result = $db->query($query);
                                        if (!$result) {
                                            $log->lwrite("Could not execute query {$query}");
                                        } else {
                                            $log->lwrite("Successfully executed query {$query}");
                                            $numRows = $result->num_rows;
                                            if ($numRows == 0) {
                                                $log->lwrite("Number of rows is {$numRows} for query: {$query}");
                                                insertTestResult($db, $testId, 'basqli', $currentFormMethod, addslashes($actionUrl), addslashes($totalTestStr));
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (strlen($error)) {
                        echo "<H2 align=\"center\">Error: ", $error, "</H2>\n";
                        echo 'Method: ' . $currentFormMethod . '<br>';
                        echo 'Url: ' . HtmlSpecialChars($actionUrl) . '<br>';
                    }
                }
            }
        }
    }
}
/**
 * This function requests the latest update information from the LimeSurvey.org website
 *
 * @returns array Contains update information or false if the request failed for some reason
 */
function GetUpdateInfo()
{
    global $homedir, $debug, $buildnumber, $versionnumber;
    require_once $homedir . "/classes/http/http.php";
    $http = new http_class();
    /* Connection timeout */
    $http->timeout = 0;
    /* Data transfer timeout */
    $http->data_timeout = 0;
    $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
    $http->GetRequestArguments("http://update.limesurvey.org?build={$buildnumber}", $arguments);
    $updateinfo = false;
    $error = $http->Open($arguments);
    $error = $http->SendRequest($arguments);
    $http->ReadReplyHeaders($headers);
    if ($error == "") {
        $body = '';
        $full_body = '';
        for (;;) {
            $error = $http->ReadReplyBody($body, 10000);
            if ($error != "" || strlen($body) == 0) {
                break;
            }
            $full_body .= $body;
        }
        $updateinfo = json_decode($full_body, true);
        if ($http->response_status != '200') {
            $updateinfo['errorcode'] = $http->response_status;
            $updateinfo['errorhtml'] = $full_body;
        }
    } else {
        $updateinfo['errorcode'] = $error;
        $updateinfo['errorhtml'] = $error;
    }
    unset($http);
    return $updateinfo;
}
Example #21
0
 /**
  * Private internal method, this actually processes a given ip
  * address against a blacklist of IP regular expressions.
  *
  * @param   strint  $ip     IP address of comment poster
  * @return  int             0: no spam, else: spam detected
  * @access  private
  */
 function _process($type, $email = '', $ip = '', $username = '')
 {
     global $_TABLES, $_SPX_CONF, $LANG_SX00;
     if (!isset($_SPX_CONF['sfs_username_confidence'])) {
         $_SPX_CONF['sfs_username_confidence'] = (double) 99.0;
     }
     if (!isset($_SPX_CONF['sfs_email_confidence'])) {
         $_SPX_CONF['sfs_email_confidence'] = (double) 50.0;
     }
     if (!isset($_SPX_CONF['sfs_ip_confidence'])) {
         $_SPX_CONF['sfs_ip_confidence'] = (double) 25.0;
     }
     $arguments = array();
     $response = '';
     $http = new http_class();
     $http->timeout = 0;
     $http->data_timeout = 0;
     $http->debug = 0;
     $http->html_debug = 0;
     $http->user_agent = 'glFusion/' . GVERSION;
     $url = "http://www.stopforumspam.com/api";
     $requestArgs = '?f=serial&';
     if ($ip != '') {
         $requestArgs .= 'ip=' . $ip . '&';
     }
     if ($email != '') {
         $requestArgs .= 'email=' . urlencode($email) . '&';
     }
     if ($username != '') {
         $requestArgs .= 'username='******'&';
     }
     $requestArgs .= 'cmd=display';
     $url = $url . $requestArgs;
     $error = $http->GetRequestArguments($url, $arguments);
     $error = $http->Open($arguments);
     $error = $http->SendRequest($arguments);
     if ($error == "") {
         $error = $http->ReadReplyBody($body, 1024);
         if ($error != "" || strlen($body) == 0) {
             return 0;
         }
         $response = $response . $body;
         $result = @unserialize($response);
         if (!$result) {
             return 0;
         }
         // invalid data, assume ok
         if (isset($result['ip']) && $result['ip']['appears'] == 1) {
             if ($result['ip']['confidence'] > (double) $_SPX_CONF['sfs_ip_confidence']) {
                 SPAMX_log($type . ' - Found ' . $type . ' matching ' . 'Stop Forum Spam (SFS)' . 'for IP ' . $ip . ' with confidence level of ' . $result['ip']['confidence'] . $LANG_SX00['foundspam3'] . $_SERVER['REMOTE_ADDR']);
                 return 1;
             } else {
                 COM_errorLog("Spamx: SFS found match on IP, but confidence level was only " . $result['ip']['confidence']);
             }
         }
         if (isset($result['email']) && $result['email']['appears'] == 1) {
             if ($result['email']['confidence'] > (double) $_SPX_CONF['sfs_email_confidence']) {
                 SPAMX_log($type . ' - Found ' . $type . ' matching ' . 'Stop Forum Spam (SFS)' . 'for email ' . $email . ' with confidence level of ' . $result['email']['confidence'] . $LANG_SX00['foundspam3'] . $_SERVER['REMOTE_ADDR']);
                 return 1;
             }
         }
         if (isset($result['username']) && $result['username']['appears'] == 1) {
             if ($result['username']['confidence'] > (double) $_SPX_CONF['sfs_username_confidence']) {
                 SPAMX_log($type . ' - Found ' . $type . ' matching ' . 'Stop Forum Spam (SFS)' . 'for username ' . $username . ' with confidence level of ' . $result['username']['confidence'] . $LANG_SX00['foundspam3'] . $_SERVER['REMOTE_ADDR']);
                 return 1;
             }
         }
         // Passed the checks
         return 0;
     }
     return 0;
 }
function testDirectoryListingEnabled($urlToScan, $siteBeingTested, $testId, $crawlUrlFlag)
{
    connectToDb($db);
    updateStatus($db, "Testing for {$urlToScan} for Directory Listing enabled...", $testId);
    $log = new Logger();
    $log->lfile('logs/eventlogs');
    $log->lwrite("Testing for {$urlToScan} for Directory Listing enabled");
    if ($crawlUrlFlag) {
        //Perform crawl again but allow images, etc. this time to capture every URL
        $crawlerNew =& new MyCrawler();
        $crawlerNew->setURL($urlToScan);
        $crawlerNew->setTestId($testId);
        $crawlerNew->addReceiveContentType("/text\\/html/");
        $crawlerNew->setCookieHandling(true);
        $crawlerNew->setFollowMode(3);
        $log->lwrite("Crawling {$urlToScan} again for all links including images, css, etc, in order to identify directories");
        $crawlerNew->go();
        $urlsFound = $crawlerNew->urlsFound;
        $logStr = sizeof($urlsFound) . ' URLs found for test: ' . $testId;
        $log->lwrite("All URLs found during crawl for directory listing check:");
        foreach ($urlsFound as $currentUrl) {
            $log->lwrite($currentUrl);
        }
        $relativePathUrls = array();
        foreach ($urlsFound as $currentUrl) {
            $currentUrl = str_replace($urlToScan, '', $currentUrl);
            array_push($relativePathUrls, $currentUrl);
        }
        $directories = array();
        //Check if relative path contain a directory and if they do, add it to a list of directories
        foreach ($relativePathUrls as $relativePathUrl) {
            if (dirname($relativePathUrl) != '.') {
                $dir = dirname($relativePathUrl);
                if (!in_array($dir, $directories) && !empty($dir) && !strpos($dir, '?')) {
                    array_push($directories, $dir);
                    $log->lwrite("Found directory {$dir}");
                }
            }
        }
    } else {
        $directories = array(1);
    }
    //Just need to make an array of size one so the for loop below iterates once
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    //$http->debug=1;
    $http->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
    $http->follow_redirect = 1;
    $http->redirection_limit = 5;
    $http->setTestId($testId);
    //Regular expressions that will indicate directory listing is enabled
    $regexs = array("/Parent Directory/", "/\\bDirectory Listing\\b.*(Tomcat|Apache)/", "/Parent directory/", "/\\bDirectory\\b/", "/[\\s<]+IMG\\s*=/");
    //General
    foreach ($directories as $directory) {
        if ($crawlUrlFlag) {
            $testUrl = $urlToScan . $directory . '/';
        } else {
            $testUrl = $siteBeingTested;
        }
        $error = $http->GetRequestArguments($testUrl, $arguments);
        $error = $http->Open($arguments);
        $log->lwrite("URL to be requested is: {$testUrl}");
        if ($error == "") {
            $log->lwrite("Sending HTTP request to {$testUrl}");
            $error = $http->SendRequest($arguments);
            if ($error == "") {
                $headers = array();
                $error = $http->ReadReplyHeaders($headers);
                if ($error == "") {
                    $responseCode = $http->response_status;
                    //This is a string
                    $log->lwrite("Received response code: {$responseCode}");
                    if (intval($responseCode) >= 200 && intval($responseCode) < 300) {
                        $vulnerabilityFound = false;
                        $error = $http->ReadWholeReplyBody($body);
                        if (strlen($error) == 0) {
                            $indicatorStr = '';
                            if (preg_match($regexs[0], $body)) {
                                $vulnerabilityFound = true;
                                $indicatorStr = $regexs[0];
                            } else {
                                if (preg_match($regexs[1], $body)) {
                                    $vulnerabilityFound = true;
                                    $indicatorStr = $regexs[1];
                                } else {
                                    if (preg_match($regexs[2], $body)) {
                                        $vulnerabilityFound = true;
                                        $indicatorStr = $regexs[2];
                                    } else {
                                        if (preg_match($regexs[3], $body)) {
                                            if (preg_match($regexs[4], $body)) {
                                                $vulnerabilityFound = true;
                                                $indicatorStr = $regexs[3] . ' and ' . $regexs[4];
                                            }
                                        }
                                    }
                                }
                            }
                            if ($vulnerabilityFound) {
                                //The echo's are for testing function on its own
                                echo '<br>Directory Listing Enabled!<br>Url: ' . $testUrl . '<br>';
                                echo 'Method: GET <br>';
                                echo 'Url Requested: ' . $testUrl . '<br>';
                                echo "Error: Received response code: {$responseCode} after requesting a directory and regular expression: {$indicatorStr}<br>";
                                $tableName = 'test' . $testId;
                                //Check if this vulnerability has already been found and added to DB. If it hasn't, add it to DB.
                                $query = "SELECT * FROM test_results WHERE test_id = {$testId} AND type = 'dirlist' AND method = 'get' AND url = '{$testUrl}' AND attack_str = '{$testUrl}'";
                                $result = $db->query($query);
                                if (!$result) {
                                    $log->lwrite("Could not execute query {$query}");
                                } else {
                                    $log->lwrite("Successfully executed query {$query}");
                                    $numRows = $result->num_rows;
                                    if ($numRows == 0) {
                                        $log->lwrite("Number of rows is {$numRows} for query: {$query}");
                                        insertTestResult($db, $testId, 'dirlist', 'get', $testUrl, $testUrl);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $http->Close();
        }
        if (strlen($error)) {
            echo "<H2 align=\"center\">Error: ", $error, "</H2>\n";
            $log->lwrite("Error: {$error}");
        }
    }
}
 public function switchAction($action, $httpVars, $filesVars)
 {
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     $selectedNode = $selection->getUniqueNode();
     $selectedNodeUrl = $selectedNode->getUrl();
     if ($action == "post_to_server") {
         // Backward compat
         if (strpos($httpVars["file"], "base64encoded:") !== 0) {
             $legacyFilePath = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
             $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $legacyFilePath);
             $selectedNodeUrl = $selectedNode->getUrl();
         }
         $target = rtrim(base64_decode($httpVars["parent_url"]), '/') . "/plugins/editor.pixlr";
         $tmp = AJXP_MetaStreamWrapper::getRealFSReference($selectedNodeUrl);
         $tmp = SystemTextEncoding::fromUTF8($tmp);
         $this->logInfo('Preview', 'Sending content of ' . $selectedNodeUrl . ' to Pixlr server.', array("files" => $selectedNodeUrl));
         AJXP_Controller::applyHook("node.read", array($selectedNode));
         $saveTarget = $target . "/fake_save_pixlr.php";
         if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) {
             $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php";
         }
         $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($selectedNodeUrl)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source");
         require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
         $arguments = array();
         $httpClient = new http_class();
         $httpClient->request_method = "POST";
         $httpClient->GetRequestArguments("https://pixlr.com/editor/", $arguments);
         $arguments["PostValues"] = $params;
         $arguments["PostFiles"] = array("image" => array("FileName" => $tmp, "Content-Type" => "automatic/name"));
         $err = $httpClient->Open($arguments);
         if (empty($err)) {
             $err = $httpClient->SendRequest($arguments);
             if (empty($err)) {
                 $response = "";
                 while (true) {
                     $header = array();
                     $error = $httpClient->ReadReplyHeaders($header, 1000);
                     if ($error != "" || $header != null) {
                         break;
                     }
                     $response .= $header;
                 }
             }
         }
         header("Location: {$header['location']}");
         //$response");
     } else {
         if ($action == "retrieve_pixlr_image") {
             $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file);
             $selectedNode->loadNodeInfo();
             $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.', array("files" => $file));
             AJXP_Controller::applyHook("node.before_change", array(&$selectedNode));
             $url = $httpVars["new_url"];
             $urlParts = parse_url($url);
             $query = $urlParts["query"];
             if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) {
                 $scriptName = basename($urlParts["path"]);
                 $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName);
                 if ($token != md5($httpVars["secure_token"])) {
                     throw new AJXP_Exception("Invalid Token, this could mean some security problem!");
                 }
             }
             $params = array();
             parse_str($query, $params);
             $image = $params['image'];
             $headers = get_headers($image, 1);
             $content_type = explode("/", $headers['Content-Type']);
             if ($content_type[0] != "image") {
                 throw new AJXP_Exception("Invalid File Type");
             }
             $content_length = intval($headers["Content-Length"]);
             if ($content_length != 0) {
                 AJXP_Controller::applyHook("node.before_change", array(&$selectedNode, $content_length));
             }
             $orig = fopen($image, "r");
             $target = fopen($selectedNode->getUrl(), "w");
             if (is_resource($orig) && is_resource($target)) {
                 while (!feof($orig)) {
                     fwrite($target, fread($orig, 4096));
                 }
                 fclose($orig);
                 fclose($target);
             }
             clearstatcache(true, $selectedNode->getUrl());
             $selectedNode->loadNodeInfo(true);
             AJXP_Controller::applyHook("node.change", array(&$selectedNode, &$selectedNode));
         }
     }
 }
Example #24
0
 * @(#) $Header: /opt2/ena/metal/http/test_cookies.php,v 1.1 2007/02/07 22:20:07 mlemos Exp $
 *
 */
?>
<HTML>
<HEAD>
<TITLE>Test for Manuel Lemos' PHP HTTP class to save and restore cookies</TITLE>
</HEAD>
<BODY>
<H1><CENTER>Test for Manuel Lemos' PHP HTTP class to save and restore cookies</CENTER></H1>
<HR>
<UL>
<?php 
require "http.php";
set_time_limit(0);
$http = new http_class();
$http->debug = 0;
$http->html_debug = 1;
$http->follow_redirect = 1;
$url = "http://my.yahoo.com/";
$error = $http->GetRequestArguments($url, $arguments);
echo "<H2><LI>Opening connection to:</H2>\n<PRE>", HtmlEntities($arguments["HostName"]), "</PRE>\n";
flush();
$error = $http->Open($arguments);
if ($error == "") {
    echo "<H2><LI>Sending request for page:</H2>\n";
    echo "<PRE>", HtmlSpecialChars($arguments["RequestURI"]), "</PRE>\n";
    flush();
    $error = $http->SendRequest($arguments);
    if ($error == "") {
        echo "<H2><LI>Getting response headers ...</H2>\n";
Example #25
0
 /**
  * Get remote content via http client.
  *
  * @param   string  $url  URL to fetch content.
  *
  * @return  string  Fetched content.
  */
 protected function fetchHttp($url)
 {
     $result = '';
     // Initialize HTTP client
     class_exists('http_class') or (require_once JPATH_COMPONENT_ADMINISTRATOR . '/libraries/3rd-party/httpclient/http.php');
     $http = new http_class();
     $http->follow_redirect = 1;
     $http->redirection_limit = 5;
     $http->GetRequestArguments($url, $arguments);
     // Open connection
     if (($error = $http->Open($arguments)) == '') {
         if (($error = $http->SendRequest($arguments)) == '') {
             // Get response body
             while (true) {
                 if (($error = $http->ReadReplyBody($body, 1000)) != '' or strlen($body) == 0) {
                     break;
                 }
                 $result .= $body;
             }
         } else {
             throw new Exception($error);
         }
         // Close connection
         $http->Close();
     } else {
         throw new Exception($error);
     }
     return $result;
 }
Example #26
0
function _checkVersion()
{
    global $_CONF, $_USER, $_PLUGIN_INFO;
    // build XML request
    require_once $_CONF['path'] . 'lib/http/http.php';
    $result = '';
    $http = new http_class();
    $http->timeout = 5;
    $http->data_timeout = 5;
    $http->debug = 0;
    $http->html_debug = 0;
    $http->user_agent = 'glFusion/' . GVERSION;
    $url = "http://www.glfusion.org/versions/index.php";
    $error = $http->GetRequestArguments($url, $arguments);
    $arguments["RequestMethod"] = "POST";
    $arguments["PostValues"] = array("v" => "v" . GVERSION . PATCHLEVEL);
    if ($_CONF['send_site_data']) {
        $arguments["PostValues"]['s'] = $_CONF['site_url'];
    }
    $error = $http->Open($arguments);
    if ($error == "") {
        $error = $http->SendRequest($arguments);
        if ($error == "") {
            for (;;) {
                $error = $http->ReadReplyBody($body, 1000);
                if ($error != "" || strlen($body) == 0) {
                    break;
                }
                $result = $result . $body;
            }
        }
    }
    if (!$result) {
        return array(-1, -1, array());
    }
    // parse XML response
    $response = xml2array($result);
    if (isset($response['response'])) {
        if (isset($response['response']['glfusion'])) {
            $latest = $response['response']['glfusion']['version'];
        } else {
            $latest = 'unknown';
        }
        if (isset($response['response']['glfusion']['date'])) {
            $releaseDate = $response['response']['glfusion']['date'];
        } else {
            $releaseDate = 'unknown';
        }
    }
    // check glFusion CMS version
    $current = GVERSION . PATCHLEVEL;
    list($latestMajor, $latestMinor, $latestRev, $latestExtra) = explode('.', $latest . '....');
    list($currentMajor, $currentMinor, $currentRev, $currentExtra) = explode('.', $current . '....');
    $glFusionUpToDate = 0;
    if ($currentMajor >= $latestMajor) {
        if ($currentMajor > $latestMajor) {
            $glFusionUpToDate = 2;
        } else {
            if ($currentMinor >= $latestMinor) {
                if ($currentMinor > $latestMinor) {
                    $glFusionUpToDate = 2;
                } else {
                    if ($currentRev >= $latestRev) {
                        if ($currentRev > $latestRev) {
                            $glFusionUpToDate = 2;
                        } else {
                            if ($currentExtra != '' || $latestExtra != '') {
                                if (strcmp($currentExtra, $latestExtra) == 0) {
                                    $glFusionUpToDate = 1;
                                }
                            } else {
                                $glFusionUpToDate = 1;
                            }
                        }
                    }
                }
            }
        }
    }
    // run through all our active plugins and see if any are out of date
    $pluginsUpToDate = 1;
    $done = 0;
    if (is_array($response['response']['plugin'])) {
        foreach ($_PLUGIN_INFO as $iPlugin => $iPluginVer) {
            $upToDate = 0;
            foreach ($response['response']['plugin'] as $plugin) {
                if (strcmp($plugin['name'], $iPlugin) == 0) {
                    if (_upToDate($plugin['version'], $iPluginVer) == 0) {
                        $pluginsUpToDate = 0;
                        $done = 1;
                        break;
                    }
                }
            }
            if ($done) {
                break;
            }
        }
    }
    // build data if we need it...
    $pluginData = array();
    $pluginData['glfusioncms']['plugin'] = 'glfusioncms';
    $pluginData['glfusioncms']['installed_version'] = $current;
    $pluginData['glfusioncms']['display_name'] = '';
    $pluginData['glfusioncms']['latest_version'] = $latest;
    $pluginData['glfusioncms']['release_date'] = $releaseDate;
    $pluginData['glfusioncms']['url'] = '';
    if (is_array($response['response']['plugin'])) {
        foreach ($_PLUGIN_INFO as $iPlugin => $iPluginVer) {
            $upToDate = 0;
            $pluginData[$iPlugin]['plugin'] = $iPlugin;
            $pluginData[$iPlugin]['installed_version'] = $iPluginVer;
            $pluginData[$iPlugin]['display_name'] = $iPlugin;
            $pluginData[$iPlugin]['latest_version'] = 0;
            $pluginData[$iPlugin]['release_date'] = 0;
            $pluginData[$iPlugin]['url'] = '';
            foreach ($response['response']['plugin'] as $plugin) {
                if (strcmp($plugin['name'], $iPlugin) == 0) {
                    $pluginData[$iPlugin]['display_name'] = $plugin['displayname'];
                    $pluginData[$iPlugin]['latest_version'] = $plugin['version'];
                    $pluginData[$iPlugin]['release_date'] = $plugin['date'];
                    if (isset($plugin['url'])) {
                        $pluginData[$iPlugin]['url'] = $plugin['url'];
                    }
                }
            }
        }
    }
    return array($glFusionUpToDate, $pluginsUpToDate, $pluginData);
}
 function SendAPIRequest($url, $method, $parameters, $oauth, $options, &$response)
 {
     $this->response_status = 0;
     $http = new http_class();
     $http->debug = $this->debug && $this->debug_http;
     $http->log_debug = true;
     $http->sasl_authenticate = 0;
     $http->user_agent = $this->oauth_user_agent;
     if ($this->debug) {
         $this->OutputDebug('Accessing the ' . $options['Resource'] . ' at ' . $url);
     }
     $arguments = array();
     $method = strtoupper($method);
     $authorization = '';
     $type = isset($options['RequestContentType']) ? strtolower(trim(strtok($options['RequestContentType'], ';'))) : 'application/x-www-form-urlencoded';
     if (isset($oauth)) {
         $values = array('oauth_consumer_key' => $this->client_id, 'oauth_nonce' => md5(uniqid(rand(), true)), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => time(), 'oauth_version' => '1.0');
         if ($this->url_parameters && $type === 'application/x-www-form-urlencoded' && count($parameters)) {
             $first = strpos($url, '?') === false;
             foreach ($parameters as $parameter => $value) {
                 $url .= ($first ? '?' : '&') . UrlEncode($parameter) . '=' . UrlEncode($value);
             }
             $parameters = array();
         }
         $value_parameters = $type !== 'application/x-www-form-urlencoded' ? array() : $parameters;
         $values = array_merge($values, $oauth, $value_parameters);
         $uri = strtok($url, '?');
         $sign = $method . '&' . $this->Encode($uri) . '&';
         $first = true;
         $sign_values = $values;
         $u = parse_url($url);
         if (isset($u['query'])) {
             parse_str($u['query'], $q);
             foreach ($q as $parameter => $value) {
                 $sign_values[$parameter] = $value;
             }
         }
         KSort($sign_values);
         foreach ($sign_values as $parameter => $value) {
             $sign .= $this->Encode(($first ? '' : '&') . $parameter . '=' . $this->Encode($value));
             $first = false;
         }
         $key = $this->Encode($this->client_secret) . '&' . $this->Encode($this->access_token_secret);
         $values['oauth_signature'] = base64_encode($this->HMAC('sha1', $sign, $key));
         if ($this->authorization_header) {
             $authorization = 'OAuth';
             $first = true;
             foreach ($values as $parameter => $value) {
                 $authorization .= ($first ? ' ' : ',') . $parameter . '="' . $this->Encode($value) . '"';
                 $first = false;
             }
         } else {
             if ($method === 'GET') {
                 $first = strcspn($url, '?') == strlen($url);
                 foreach ($values as $parameter => $value) {
                     $url .= ($first ? '?' : '&') . $parameter . '=' . $this->Encode($value);
                     $first = false;
                 }
                 $post_values = array();
             } else {
                 $post_values = $values;
             }
         }
     }
     if (strlen($error = $http->GetRequestArguments($url, $arguments))) {
         return $this->SetError('it was not possible to open the ' . $options['Resource'] . ' URL: ' . $error);
     }
     if (strlen($error = $http->Open($arguments))) {
         return $this->SetError('it was not possible to open the ' . $options['Resource'] . ' URL: ' . $error);
     }
     $arguments['RequestMethod'] = $method;
     switch ($type) {
         case 'application/x-www-form-urlencoded':
             if (isset($options['RequestBody'])) {
                 return $this->SetError('the request body is defined automatically from the parameters');
             }
             $arguments['PostValues'] = $parameters;
             break;
         case 'application/json':
             $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
             if (!isset($options['RequestBody'])) {
                 $arguments['Body'] = json_encode($parameters);
                 break;
             }
         default:
             if (!isset($options['RequestBody'])) {
                 return $this->SetError('it was not specified the body value of the of the API call request');
             }
             $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
             $arguments['Body'] = $options['RequestBody'];
             break;
     }
     $arguments['Headers']['Accept'] = isset($options['Accept']) ? $options['Accept'] : '*/*';
     if (strlen($authorization)) {
         $arguments['Headers']['Authorization'] = $authorization;
     }
     if (strlen($error = $http->SendRequest($arguments)) || strlen($error = $http->ReadReplyHeaders($headers))) {
         $http->Close();
         return $this->SetError('it was not possible to retrieve the ' . $options['Resource'] . ': ' . $error);
     }
     $error = $http->ReadWholeReplyBody($data);
     $http->Close();
     if (strlen($error)) {
         return $this->SetError('it was not possible to access the ' . $options['Resource'] . ': ' . $error);
     }
     $this->response_status = intval($http->response_status);
     $content_type = isset($headers['content-type']) ? strtolower(trim(strtok($headers['content-type'], ';'))) : 'unspecified';
     switch ($content_type) {
         case 'text/javascript':
         case 'application/json':
             if (!function_exists('json_decode')) {
                 return $this->SetError('the JSON extension is not available in this PHP setup');
             }
             $object = json_decode($data);
             switch (GetType($object)) {
                 case 'object':
                     if (!isset($options['ConvertObjects']) || !$options['ConvertObjects']) {
                         $response = $object;
                     } else {
                         $response = array();
                         foreach ($object as $property => $value) {
                             $response[$property] = $value;
                         }
                     }
                     break;
                 case 'array':
                     $response = $object;
                     break;
                 default:
                     if (!isset($object)) {
                         return $this->SetError('it was not returned a valid JSON definition of the ' . $options['Resource'] . ' values');
                     }
                     $response = $object;
                     break;
             }
             break;
         case 'application/x-www-form-urlencoded':
         case 'text/plain':
         case 'text/html':
             parse_str($data, $response);
             break;
         default:
             $response = $data;
             break;
     }
     if ($this->response_status >= 200 && $this->response_status < 300) {
         $this->access_token_error = '';
     } else {
         $this->access_token_error = 'it was not possible to access the ' . $options['Resource'] . ': it was returned an unexpected response status ' . $http->response_status . ' Response: ' . $data;
         if ($this->debug) {
             $this->OutputDebug('Could not retrieve the OAuth access. Error: ' . $this->access_token_error);
         }
         if (isset($options['FailOnAccessError']) && $options['FailOnAccessError']) {
             $this->error = $this->access_token_error;
             return false;
         }
     }
     return true;
 }
 protected function _sendHttp($post_values, $uri)
 {
     /*
       This function Copyright (C) 2005-2006 Thomas Harding, Manuel Lemos
     */
     $this->response_completed[] = "no";
     unset($this->serverouptut);
     self::_putDebug(_("Processing HTTP request"), 2);
     $this->serveroutput->headers = array();
     $this->serveroutput->body = "";
     $http = new http_class();
     if (!$this->unix) {
         $http->host = $this->host;
     } else {
         $http->host = "localhost";
     }
     $http->with_exceptions = $this->with_exceptions;
     if ($this->debug_http) {
         $http->debug = 1;
         $http->html_debug = 0;
     } else {
         $http->debug = 0;
         $http->html_debug = 0;
     }
     $url = "http://" . $this->host;
     if ($this->ssl) {
         $url = "https://" . $this->host;
     }
     if ($this->unix) {
         $url = "unix://" . $this->host;
     }
     $http->port = $this->port;
     $http->timeout = $this->http_timeout;
     $http->data_timeout = $this->http_data_timeout;
     $http->force_multipart_form_post = false;
     $http->user = $this->username;
     $http->password = $this->password;
     $error = $http->GetRequestArguments($url, $arguments);
     $arguments["RequestMethod"] = "POST";
     $arguments["Headers"] = array("Content-Type" => "application/ipp");
     $arguments["BodyStream"] = array(array("Data" => $post_values["Data"]));
     if (isset($post_values["File"])) {
         $arguments["BodyStream"][] = array("File" => $post_values["File"]);
     }
     if (isset($post_values["FileType"]) && !strcmp($post_values["FileType"], "TEXT")) {
         $arguments["BodyStream"][] = array("Data" => Chr(12));
     }
     $arguments["RequestURI"] = $uri;
     if ($this->with_exceptions && $this->handle_http_exceptions) {
         try {
             $success = $http->Open($arguments);
         } catch (httpException $e) {
             throw new ippException(sprintf("http error: %s", $e->getMessage()), $e->getErrno());
         }
     } else {
         $success = $http->Open($arguments);
     }
     if ($success[0] == true) {
         $success = $http->SendRequest($arguments);
         if ($success[0] == true) {
             self::_putDebug("H T T P    R E Q U E S T :");
             self::_putDebug("Request headers:");
             for (Reset($http->request_headers), $header = 0; $header < count($http->request_headers); Next($http->request_headers), $header++) {
                 $header_name = Key($http->request_headers);
                 if (GetType($http->request_headers[$header_name]) == "array") {
                     for ($header_value = 0; $header_value < count($http->request_headers[$header_name]); $header_value++) {
                         self::_putDebug($header_name . ": " . $http->request_headers[$header_name][$header_value]);
                     }
                 } else {
                     self::_putDebug($header_name . ": " . $http->request_headers[$header_name]);
                 }
             }
             self::_putDebug("Request body:");
             self::_putDebug(htmlspecialchars($http->request_body) . "*********** END REQUEST BODY *********");
             $i = 0;
             $headers = array();
             unset($this->serveroutput->headers);
             $http->ReadReplyHeaders($headers);
             self::_putDebug("H T T P    R E S P O N S E :");
             self::_putDebug("Response headers:");
             for (Reset($headers), $header = 0; $header < count($headers); Next($headers), $header++) {
                 $header_name = Key($headers);
                 if (GetType($headers[$header_name]) == "array") {
                     for ($header_value = 0; $header_value < count($headers[$header_name]); $header_value++) {
                         self::_putDebug($header_name . ": " . $headers[$header_name][$header_value]);
                         $this->serveroutput->headers[$i] = $header_name . ": " . $headers[$header_name][$header_value];
                         $i++;
                     }
                 } else {
                     self::_putDebug($header_name . ": " . $headers[$header_name]);
                     $this->serveroutput->headers[$i] = $header_name . ": " . $headers[$header_name];
                     $i++;
                 }
             }
             self::_putDebug("\n\nResponse body:\n");
             $this->serveroutput->body = "";
             for (;;) {
                 $http->ReadReplyBody($body, 1024);
                 if (strlen($body) == 0) {
                     break;
                 }
                 self::_putDebug(htmlentities($body));
                 $this->serveroutput->body .= $body;
             }
             self::_putDebug("********* END RESPONSE BODY ********");
         }
     }
     $http->Close();
     return true;
 }
Example #29
0
/**
 * Handle a pingback for an entry.
 * Also takes care of the speedlimit and spam. Assumes that the caller of this
 * function has already checked permissions!
 *
 * @param    string $id     ID of entry that got pinged
 * @param    string $type   type of that entry ('article' for stories, etc.)
 * @param    string $url    URL of the page that pinged us
 * @param    string $oururl URL that got pinged on our site
 * @return   object          XML-RPC response
 */
function PNB_handlePingback($id, $type, $url, $oururl)
{
    global $_CONF, $_TABLES, $PNB_ERROR;
    require_once 'HTTP/Request.php';
    if (!isset($_CONF['check_trackback_link'])) {
        $_CONF['check_trackback_link'] = 2;
    }
    // handle pingbacks to articles on our own site
    $skip_speedlimit = false;
    if ($_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR']) {
        if (!isset($_CONF['pingback_self'])) {
            $_CONF['pingback_self'] = 0;
            // default: skip self-pingbacks
        }
        if ($_CONF['pingback_self'] == 0) {
            return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['skipped']));
        } elseif ($_CONF['pingback_self'] == 2) {
            $skip_speedlimit = true;
        }
    }
    COM_clearSpeedlimit($_CONF['commentspeedlimit'], 'pingback');
    if (!$skip_speedlimit) {
        $last = COM_checkSpeedlimit('pingback');
        if ($last > 0) {
            return new XML_RPC_Response(0, 49, sprintf($PNB_ERROR['speedlimit'], $last, $_CONF['commentspeedlimit']));
        }
    }
    // update speed limit in any case
    COM_updateSpeedlimit('pingback');
    if ($_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']) {
        if ($_CONF['check_trackback_link'] & 4) {
            $parts = parse_url($url);
            if (empty($parts['host'])) {
                TRB_logRejected('Pingback: No valid URL', $url);
                return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']);
            } else {
                $ip = gethostbyname($parts['host']);
                if ($ip != $_SERVER['REMOTE_ADDR']) {
                    TRB_logRejected('Pingback: IP address mismatch', $url);
                    return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']);
                }
            }
        }
    }
    // See if we can read the page linking to us and extract at least
    // the page's title out of it ...
    $title = '';
    $excerpt = '';
    $http = new http_class();
    $http->timeout = 0;
    $http->data_timeout = 0;
    $http->debug = 0;
    $http->html_debug = 0;
    $http->user_agent = 'glFusion/' . GVERSION;
    $error = $http->GetRequestArguments($url, $arguments);
    $error = $http->Open($arguments);
    $error = $http->SendRequest($arguments);
    if ($error == "") {
        $http->ReadReplyHeaders($headers);
        if ($http->response_status == 200) {
            $error = $http->ReadWholeReplyBody($body);
            if ($error == "" || strlen($body) > 0) {
                if ($_CONF['check_trackback_link'] & 3) {
                    if (!TRB_containsBacklink($body, $oururl)) {
                        TRB_logRejected('Pingback: No link to us', $url);
                        $comment = TRB_formatComment($url);
                        PLG_spamAction($comment, $_CONF['spamx']);
                        return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']);
                    }
                }
                preg_match(':<title>(.*)</title>:i', $body, $content);
                if (empty($content[1])) {
                    $title = '';
                    // no title found
                } else {
                    $title = trim(COM_undoSpecialChars($content[1]));
                }
                if ($_CONF['pingback_excerpt']) {
                    // Check which character set the site that sent the Pingback
                    // is using
                    $charset = 'ISO-8859-1';
                    // default, see RFC 2616, 3.7.1
                    $ctype = $headers['content-type'];
                    $c = explode(';', $ctype);
                    foreach ($c as $ct) {
                        $ch = explode('=', trim($ct));
                        if (count($ch) === 2) {
                            if (trim($ch[0]) === 'charset') {
                                $charset = trim($ch[1]);
                                break;
                            }
                        }
                    }
                    if (!empty($charset) && strcasecmp($charset, COM_getCharset()) !== 0) {
                        if (function_exists('mb_convert_encoding')) {
                            $body = @mb_convert_encoding($body, COM_getCharset(), $charset);
                        } elseif (function_exists('iconv')) {
                            $body = @iconv($charset, COM_getCharset(), $body);
                        }
                    }
                    $excerpt = PNB_makeExcerpt($body, $oururl);
                }
                // we could also run the rest of the other site's page
                // through the spam filter here ...
            } else {
                COM_errorLog("Pingback verification: unable to retrieve response body");
                return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']);
            }
        } else {
            COM_errorLog("Pingback verification: Got HTTP response code " . $http->response_status . " when requesting {$url}");
            return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']);
        }
    } else {
        COM_errorLog("Pingback verification: " . $error . " when requesting " . $url);
        return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']);
    }
    // check for spam first
    $saved = TRB_checkForSpam($url, $title, '', $excerpt);
    if ($saved == TRB_SAVE_SPAM) {
        return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']);
    }
    // save as a trackback comment
    $saved = TRB_saveTrackbackComment($id, $type, $url, $title, '', $excerpt);
    if ($saved == TRB_SAVE_REJECT) {
        return new XML_RPC_Response(0, 49, $PNB_ERROR['multiple']);
    }
    if (isset($_CONF['notification']) && in_array('pingback', $_CONF['notification'])) {
        TRB_sendNotificationEmail($saved, 'pingback');
    }
    return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['success']));
}
Example #30
-1
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "post_to_zohoserver") {
         $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv");
         $presExt = explode(",", "ppt,pps,odp,sxi");
         $docExt = explode(",", "doc,docx,rtf,odt,sxw");
         require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
         $selection = new UserSelection($repository, $httpVars);
         // Backward compat
         if (strpos($httpVars["file"], "base64encoded:") !== 0) {
             $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
         } else {
             $file = $selection->getUniqueFile();
         }
         $target = base64_decode($httpVars["parent_url"]);
         $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file);
         $tmp = SystemTextEncoding::fromUTF8($tmp);
         $node = new AJXP_Node($destStreamURL . $file);
         AJXP_Controller::applyHook("node.read", array($node));
         $this->logInfo('Preview', 'Posting content of ' . $file . ' to Zoho server');
         $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION));
         $httpClient = new http_class();
         $httpClient->request_method = "POST";
         $secureToken = $httpVars["secure_token"];
         $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file;
         $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime());
         if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) {
             $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId());
         } else {
             $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php";
         }
         $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]);
         $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository->getId()), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig);
         $service = "exportwriter";
         if (in_array($extension, $sheetExt)) {
             $service = "sheet";
         } else {
             if (in_array($extension, $presExt)) {
                 $service = "show";
             } else {
                 if (in_array($extension, $docExt)) {
                     $service = "exportwriter";
                 }
             }
         }
         $arguments = array();
         $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments);
         $arguments["PostValues"] = $params;
         $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name"));
         $err = $httpClient->Open($arguments);
         if (empty($err)) {
             $err = $httpClient->SendRequest($arguments);
             if (empty($err)) {
                 $response = "";
                 while (true) {
                     $body = "";
                     $error = $httpClient->ReadReplyBody($body, 1000);
                     if ($error != "" || strlen($body) == 0) {
                         break;
                     }
                     $response .= $body;
                 }
                 $result = trim($response);
                 $matchlines = explode("\n", $result);
                 $resultValues = array();
                 foreach ($matchlines as $line) {
                     list($key, $val) = explode("=", $line, 2);
                     $resultValues[$key] = $val;
                 }
                 if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) {
                     header("Location: " . $resultValues["URL"]);
                 } else {
                     echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"];
                     echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>";
                 }
             }
             $httpClient->Close();
         }
     } else {
         if ($action == "retrieve_from_zohoagent") {
             $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"];
             $id = $_SESSION["ZOHO_CURRENT_UUID"];
             $ext = pathinfo($targetFile, PATHINFO_EXTENSION);
             $node = new AJXP_Node($targetFile);
             $node->loadNodeInfo();
             AJXP_Controller::applyHook("node.before_change", array(&$node));
             $b64Sig = $this->signID($id);
             if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) {
                 $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig;
                 $data = AJXP_Utils::getRemoteContent($url);
                 if (strlen($data)) {
                     file_put_contents($targetFile, $data);
                     echo "MODIFIED";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext)) {
                     copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext, $targetFile);
                     unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext);
                     echo "MODIFIED";
                 }
             }
             $this->logInfo('Edit', 'Retrieved content of ' . $node->getUrl());
             AJXP_Controller::applyHook("node.change", array(null, &$node));
         }
     }
 }