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;
 }
示例#2
0
文件: sfs.php 项目: NewRoute/glfusion
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;
}
示例#3
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;
 }
 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;
 }
示例#5
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');
}
示例#6
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);
}
示例#7
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;
}
示例#8
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);
}
示例#9
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;
 }
 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));
     }
     //		}
 }
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) {
                        break;
                    }
                }
            } else {
                $error = "This page did not set a cookie";
            }
        }
        if ($error == "" && ($error = $http_connection->Close()) == "" && ($error = $http_connection->Open(array("HostName" => $host_name))) == "" && ($error = $http_connection->SendRequest(array("RequestURI" => $uri, "RequestMethod" => "GET"))) == "" && ($error = $http_connection->ReadReplyHeaders(&$headers)) == "") {
            for (;;) {
                $error = $http_connection->ReadReplyBody(&$body, 1000);
                if ($error != "" || strlen($body) == 0) {
                    break;
                }
                echo $body;
示例#12
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;
 }
示例#13
0
 private function _RunUpdaterUpdate()
 {
     $versionnumber = Yii::app()->getConfig("versionnumber");
     $buildnumber = Yii::app()->getConfig("buildnumber");
     $tempdir = Yii::app()->getConfig("tempdir");
     require_once APPPATH . '/third_party/http/http.php';
     $oHTTPRequest = new http_class();
     $oHTTPRequest->proxy_host_name = Yii::app()->getConfig("proxy_host_name", "");
     $oHTTPRequest->proxy_host_port = Yii::app()->getConfig("proxy_host_port", 80);
     /* Connection timeout */
     $oHTTPRequest->timeout = 0;
     /* Data transfer timeout */
     $oHTTPRequest->data_timeout = 0;
     $oHTTPRequest->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
     $oHTTPRequest->GetRequestArguments($this->getProtocol() . "update.limesurvey.org?updaterbuild={$buildnumber}", $arguments);
     $updateinfo = false;
     $error = $oHTTPRequest->Open($arguments);
     $error = $oHTTPRequest->SendRequest($arguments);
     $oHTTPRequest->ReadReplyHeaders($headers);
     if ($error == "") {
         $body = '';
         $full_body = '';
         for (;;) {
             $error = $oHTTPRequest->ReadReplyBody($body, 10000);
             if ($error != "" || strlen($body) == 0) {
                 break;
             }
             $full_body .= $body;
         }
         $updateinfo = json_decode($full_body, true);
         if ($oHTTPRequest->response_status != '200') {
             $updateinfo['errorcode'] = $oHTTPRequest->response_status;
             $updateinfo['errorhtml'] = $full_body;
         }
     } else {
         $updateinfo['errorcode'] = $error;
         $updateinfo['errorhtml'] = $error;
     }
     unset($oHTTPRequest);
     if ((int) $updateinfo['UpdaterRevision'] <= $buildnumber) {
         // There is no newer updater version on the server
         return true;
     }
     if (!is_writable($tempdir) || !is_writable(APPPATH . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'update.php')) {
         $error = true;
     }
     //  Download the zip file, unpack it and replace the updater file accordingly
     // Create DB and file backups now
     $downloaderror = false;
     require_once APPPATH . '/third_party/http/http.php';
     $oHTTPRequest = new http_class();
     $oHTTPRequest->proxy_host_name = Yii::app()->getConfig("proxy_host_name", "");
     $oHTTPRequest->proxy_host_port = Yii::app()->getConfig("proxy_host_port", 80);
     $oHTTPRequest->proxy_host_name = Yii::app()->getConfig("proxy_host_name", "");
     $oHTTPRequest->proxy_host_port = Yii::app()->getConfig("proxy_host_port", 80);
     // Allow redirects
     $oHTTPRequest->follow_redirect = 1;
     /* Connection timeout */
     $oHTTPRequest->timeout = 0;
     /* Data transfer timeout */
     $oHTTPRequest->data_timeout = 0;
     $oHTTPRequest->user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
     $oHTTPRequest->GetRequestArguments($this->getProtocol() . "update.limesurvey.org/updates/downloadupdater/{$updateinfo['UpdaterRevision']}", $arguments);
     $oHTTPRequesterror = $oHTTPRequest->Open($arguments);
     $oHTTPRequesterror = $oHTTPRequest->SendRequest($arguments);
     $oHTTPRequest->ReadReplyHeaders($headers);
     if ($headers['content-type'] == 'text/html') {
         @unlink($tempdir . '/updater.zip');
     } elseif ($oHTTPRequesterror == '') {
         $body = '';
         $full_body = '';
         for (;;) {
             $oHTTPRequesterror = $oHTTPRequest->ReadReplyBody($body, 100000);
             if ($oHTTPRequesterror != "" || strlen($body) == 0) {
                 break;
             }
             $full_body .= $body;
         }
         file_put_contents($tempdir . '/updater.zip', $full_body);
     }
     $aData['httperror'] = $oHTTPRequesterror;
     //Now unzip the new updater over the existing ones.
     if (file_exists($tempdir . '/updater.zip')) {
         Yii::app()->loadLibrary("admin/pclzip", array('p_zipname' => $tempdir . '/updater.zip'));
         $archive = new PclZip(array('p_zipname' => $tempdir . '/updater.zip'));
         if ($archive->extract(PCLZIP_OPT_PATH, APPPATH . '/controllers/admin/', PCLZIP_OPT_REPLACE_NEWER) == 0) {
             die("Error : " . $archive->errorInfo(true));
         } else {
             unlink($tempdir . '/updater.zip');
         }
         $updater_exists = true;
     } else {
         $updater_exists = false;
         $error = true;
     }
     $aData['updater_exists'] = $updater_exists;
 }
 function ReadPage()
 {
     $this->pagecontent = "";
     set_time_limit(0);
     $http = new http_class();
     $http->timeout = 0;
     $http->data_timeout = 0;
     $http->debug = 0;
     $http->html_debug = 1;
     $url = $this->protocol . "://" . $this->host . "/";
     $error = $http->GetRequestArguments($url, $arguments);
     //$arguments["Headers"]["Pragma"]="nocache";
     $arguments["RequestURI"] = $this->source;
     //echo HtmlEntities($arguments["HostName"]);
     flush();
     $error = $http->Open($arguments);
     if ($error == "") {
         //echo "Sending request for page: ";
         //echo HtmlEntities($arguments["RequestURI"]);
         flush();
         $error = $http->SendRequest($arguments);
         if ($error == "") {
             //echo "<H2><LI>Request:</LI</H2>\n<PRE>\n".HtmlEntities($http->request)."</PRE>\n";
             //$dummy = $http->request;
             //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++) {
                     }
                     //echo $header_name.": ".$http->request_headers[$header_name][$header_value],"\r\n";
                 } else {
                 }
                 //echo $header_name.": ".$http->request_headers[$header_name],"\r\n";
             }
             //echo "</PRE>\n";
             flush();
             $headers = array();
             $error = $http->ReadReplyHeaders($headers);
             if ($error == "") {
                 $redirect = 0;
                 //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 (preg_match("/302/", $header_name)) {
                         $redirect = 1;
                     }
                     if (GetType($headers[$header_name]) == "array") {
                         $fp1 = fopen("redirect.txt", "a");
                         fwrite($fp1, "\r\n");
                         for ($header_value = 0; $header_value < count($headers[$header_name]); $header_value++) {
                             fwrite($fp1, $headers[$header_name][$header_value] . "\r\n");
                             //echo "!".$header_name."!".": ".$headers[$header_name][$header_value],"\r\n\n";
                             //echo "<br>";
                             preg_match_all("@\\/\\/(.*?)\\/@", $headers[$header_name][$header_value], $temp);
                             //echo $temp[1][0];
                             $this->source = $headers[$header_name][$header_value];
                             $this->source = preg_replace("@.*?\\/\\/.*?\\/@", "/", $this->source);
                             $this->host = $temp[1][0];
                             //echo $this->host."<br>";
                             //echo $this->source."<br>";
                         }
                         fclose($fp1);
                     } else {
                         //echo $header_name.": ".$headers[$header_name],"\r\n";
                         if ($header_name == "location") {
                             //echo "Neue Adresse: ".$headers[$header_name],"\r\n";
                             preg_match_all("@\\/\\/(.*?)\\/@", $headers[$header_name], $temp);
                             //echo $temp[1][0];
                             $this->source = $headers[$header_name];
                             $this->source = preg_replace("@.*?\\/\\/.*?\\/@", "/", $this->source);
                             $this->host = $temp[1][0];
                             //echo $this->host."<br>";
                             //echo $this->source."<br>";
                         }
                     }
                 }
                 flush();
                 if ($redirect == 0) {
                     for (;;) {
                         $error = $http->ReadReplyBody($body, 2048);
                         if ($error != "" || strlen($body) == 0) {
                             break;
                         }
                         $this->pagecontent = $this->pagecontent . $body;
                     }
                     flush();
                 }
             }
         }
         $http->Close();
     }
     if (strlen($error)) {
         echo "<CENTER><H2>Error: ", $error, "</H2><CENTER>\n";
         $time = $datum = date("Y.m.d.H.i.s", time());
         $fp = fopen("err.txt", "a");
         fwrite($fp, "Am: " . $time . "\r\n");
         fwrite($fp, "Server: " . $this - host . "\r\n");
         fwrite($fp, "Fehler: " . $error . "\r\n");
         fwrite($fp, "\r\n");
         fclose($fp);
     }
     if ($redirect == 1) {
         $this->ReadPage();
     }
 }
示例#15
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;
 }
示例#16
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;
 }
示例#17
0
            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++) {
                        echo $header_name . ": " . $headers[$header_name][$header_value], "\r\n";
                    }
                } else {
                    echo $header_name . ": " . $headers[$header_name], "\r\n";
                }
            }
            echo "</PRE>\n";
            flush();
            echo "<H2><LI>Response body:</LI</H2>\n<PRE>\n";
            for (;;) {
                $error = $http->ReadReplyBody($body, 1000);
                if ($error != "" || strlen($body) == 0) {
                    break;
                }
                echo HtmlSpecialChars($body);
            }
            echo "</PRE>\n";
            flush();
        }
    }
    $http->Close();
}
if (strlen($error)) {
    echo "<CENTER><H2>Error: ", $error, "</H2><CENTER>\n";
}
?>
/**
 * 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;
}
示例#19
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;
 }
 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;
 }
示例#21
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;
 }
示例#22
0
 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;
 }
示例#23
0
 /**
  * Delete file
  * 
  * @param id[required] 	$id
  * @param reason[required] 	$reason
  * @return Response stdClass if succes, or FALSE if there error.
  */
 public function delete($id = null, $reason = "")
 {
     if ($id == null or empty($id)) {
         throw new Exception("MISSING_PARAMETER: No id given.");
     }
     if ($reason == null or empty($reason)) {
         throw new Exception("MISSING_PARAMETER: No reason given.");
     }
     //Blip.tv fields
     $data = array('cmd' => "delete", 'section' => "posts", 'item_type' => "file", 'post' => "1", 'skin' => "api", 'userlogin' => $this->username, 'password' => $this->password, 'item_id' => $id, 'reason' => $reason);
     //Setting http class settings
     $http = new http_class();
     $http->timeout = 0;
     $http->data_timeout = 0;
     $arguments = array();
     $response = "";
     $http->GetRequestArguments(self::gateway . '?' . http_build_query($data), $arguments);
     $arguments["RequestMethod"] = "POST";
     $arguments["User-Agent"] = "blipPHP (http://code.google.com/p/blip-php/)";
     $arguments["PostValues"] = $data;
     //Make the request
     $http->Open($arguments);
     $http->SendRequest($arguments);
     $http->ReadReplyBody($response, 1000);
     $xml_response = simplexml_load_string($response);
     if (strtoupper($xml_response->status) == "ERROR") {
         if (strtoupper($xml_response->error->code) == "AUTHENTICATION_REQUIRED") {
             throw new Exception("AUTHENTICATION_REQUIRED: Bad login information.");
         }
     }
     return $xml_response;
 }
示例#24
-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));
         }
     }
 }