public function get_attendees($event_id)
 {
     $url = "http://www.eventbrite.com/myattendeestext/" . $event_id . "/attendees-" . $event_id . ".txt?sortby=&show=gross,type,status,prefix,last_name,first_name,email,job_title,company,work,work_phone,survey,actions&filterby=all,attending,all,all";
     $client = new HTTP_Client();
     // log in
     $ret = $client->post("http://www.eventbrite.com/signin", array("submitted" => "1", "referrer" => "", "email" => $this->email, "passwd" => $this->password, "remember_me" => "0"));
     $response = $client->currentResponse();
     //	var_dump($client->currentResponse());
     $dom = new DOMDocument();
     @$dom->loadHTML($response['body']);
     $xp = new DOMXPath($dom);
     //	echo "----------- generated xml ----------------\n";
     //	echo $dom->saveXML();
     $errors = $xp->query("//div[@id='error']");
     if ($errors->length) {
         // an error occurred - most likely
         $error_text = trim($xp->query("text()", $errors->item(0))->item(0)->nodeValue);
         throw new PAException(USER_NOT_FOUND, "Error from EventBrite: " . $error_text);
     }
     // now fetch the attendee list CSV
     $ret = $client->get($url);
     $response = $client->currentResponse();
     $mime_type = $response['headers']['content-type'];
     if ($mime_type != 'text/plain') {
         throw new PAException(GENERAL_SOME_ERROR, "Invalid MIME type received from EventBrite (expected text/plain, received {$mime_type})");
     }
     return $this->parse_attendee_list($response['body']);
 }
function http($method = "GET", $url, $argArray = null)
{
    require_once "HTTP/Client.php";
    $agent = new HTTP_Client();
    if ($method == "POST") {
        $code = $agent->post($url, $argArray);
    } else {
        if ($argArray) {
            // build query string from $argArray
            if (strpos("?", $url)) {
                $query = "&";
            } else {
                $query = "?";
            }
            $url .= $query . http_build_query($argArray);
        }
        $code = $agent->get($url);
    }
    if (PEAR::isError($code)) {
        $error = $code->getMessage();
        Logger::log(basename(__FILE__) . " {$method} {$url} failed: {$error}");
        return false;
    } else {
        $responseArray = $agent->currentResponse();
        return $responseArray['body'];
    }
}
Exemple #3
0
 protected function request($method, $url)
 {
     try {
         $this->http_client->{$method}($url);
         $response = $this->http_client->currentResponse();
     } catch (nc_search_indexer_crawler_exception $e) {
         // слушателю не понравились заголовки
         $response = $e->get_response();
     }
     $response["url"] = $url;
     $response = new nc_search_indexer_crawler_response($response);
     //    if (nc_search::will_log(nc_search::LOG_CRAWLER_REQUEST)) {
     $len = $response->get_content_length();
     nc_search::log(nc_search::LOG_CRAWLER_REQUEST, strtoupper($method) . " {$url}\n" . "Response: {$response->get_code()}\n" . ($response->get_code() < 400 ? "Content-Type: " . $response->get_content_type() . "\n" . "Content-Length: " . (is_null($len) ? "no" : $len) . ", received: " . $response->get_body_length() . " bytes" : ''));
     //    }
     return $response;
 }
 function testSpamTrapPerformance()
 {
     global $base_url;
     while (@ob_end_clean()) {
     }
     $c = new HTTP_Client();
     echo "Hitting some pages to test how the system performs when hit by spambots\n";
     echo "Spidering content ...\n";
     list($dom, $xp) = $this->get_and_parse("{$base_url}/homepage.php");
     $content = array();
     foreach ($xp->query("//a/@href") as $node) {
         if (preg_match("|/content.php\\?|", $node->value)) {
             $content[$node->value] = true;
         }
     }
     $n_retrieved = 0;
     $total_time = 0.0;
     foreach ($content as $url => $foo) {
         echo "Content page to retrieve: {$url}\n";
         list(, , $t_taken) = $this->get_and_parse($url);
         ++$n_retrieved;
         $total_time += $t_taken;
         if ($n_retrieved >= 3) {
             break;
         }
     }
     echo sprintf("avg time per download: %.1f s\n", $total_time / $n_retrieved);
     echo "Posting spam...\n";
     echo "Testing that we can't post comments without being logged in...\n";
     foreach ($content as $url => $foo) {
         echo "Posting anonymous comment to {$url}\n";
         if (!preg_match("/cid=(\\d+)/", $url, $m)) {
             echo "error determining cid from {$url}\n";
             continue;
         }
         $cid = $m[1];
         $c = new HTTP_Client();
         $c->setMaxRedirects(0);
         $ret = $c->post($url, array("addcomment" => "Submit Comment", "name" => "automatic test robot", "email" => "*****@*****.**", "homepage" => "http://peopleaggregator.net/", "cid" => $cid, "ccid" => ""));
         var_dump($c);
         $this->assertEquals($c->_responses[0]['code'], 302);
         break;
     }
     echo "Posting personal messages...\n";
 }
Exemple #5
0
function can_download($url)
{
    echo "<li>Trying to download <code>{$url}</code> ... ";
    flush();
    $client = new HTTP_Client();
    $e = $client->get($url);
    if (PEAR::isError($e)) {
        echo "error " . $e->getCode() . " (" . htmlspecialchars($e->getMessage()) . ")<br>";
        return FALSE;
    }
    $resp = $client->currentResponse();
    $code = $resp['code'];
    if ($code !== 200) {
        echo "bad status: {$code}</li>";
        flush();
        return FALSE;
    }
    $body = $resp['body'];
    echo strlen($body) . " bytes</li>";
    flush();
    return $body;
}
Exemple #6
0
 /**
  * Get user information from pear.php.net
  *
  * This function uses the given username and password to authenticate
  * against the pear.php.net website
  *
  * @param string    Username
  * @param string    Password
  * @return mixed    Error object or boolean
  */
 function fetchData($username, $password)
 {
     $this->log('Auth_Container_PEAR::fetchData() called.', AUTH_LOG_DEBUG);
     $client = new HTTP_Client();
     $this->log('Auth_Container_PEAR::fetchData() getting salt.', AUTH_LOG_DEBUG);
     $code = $client->get('https://pear.php.net/rest-login.php/getsalt');
     if ($code != 200) {
         return PEAR::raiseError('Bad response to salt request.', $code);
     }
     $resp = $client->currentResponse();
     $salt = $resp['body'];
     $this->log('Auth_Container_PEAR::fetchData() calling validate.', AUTH_LOG_DEBUG);
     $code = $client->post('https://pear.php.net/rest-login.php/validate', array('username' => $username, 'password' => md5($salt . md5($password))));
     if ($code != 200) {
         return PEAR::raiseError('Bad response to validate request.', $code);
     }
     $resp = $client->currentResponse();
     list($code, $message) = explode(' ', $resp['body'], 1);
     if ($code != 8) {
         return PEAR::raiseError($message, $code);
     }
     return true;
 }
Exemple #7
0
 public function get_and_parse($url, $c = NULL, $method = "GET", $data = NULL)
 {
     if (empty($c)) {
         $c = new HTTP_Client();
     }
     $t_start = microtime(TRUE);
     switch ($method) {
         case "POST":
             //      $c->setDefaultHeader("Content-Type", "application/x-www-form-urlencoded");
             $code = $c->post($url, $data);
             break;
         default:
             $code = $c->get($url);
             break;
     }
     $t_retrieved = microtime(TRUE);
     $this->assertEquals(200, $code, "Error {$code} retrieving {$url}");
     $resp = $c->currentResponse();
     list($dom, $xp) = Test::parse_html($resp['body']);
     $t_finish = microtime(TRUE);
     echo sprintf("Downloaded %s in %.1f s\n", $url, $t_retrieved - $t_start);
     return array($dom, $xp, $t_retrieved - $t_start, $c);
 }
Exemple #8
0
 public static function getResponseCode($url)
 {
     $client = new HTTP_Client();
     $client->setRequestParameter('timeout', $timeout);
     $client->setDefaultHeader('User-Agent', 'Monazilla/1.00');
     if (!empty($_conf['proxy_use'])) {
         $client->setRequestParameter('proxy_host', $_conf['proxy_host']);
         $client->setRequestParameter('proxy_port', $_conf['proxy_port']);
     }
     return $client->head($url);
 }
--TEST--
core.get_post default
--FILE--
<?php 
require_once 'HTTP/Client.php';
$http = new HTTP_Client();
$http->get('http://wordpress.test/?json=core.get_post&slug=about-us&dev=1');
$response = $http->currentResponse();
$response = json_decode($response['body']);
echo "Response status: {$response->status}\n";
echo "post title: {$response->post->title}\n";
?>
--EXPECT--
Response status: ok
post title: Markup: HTML Tags and Formatting
$port = @$parsed['port'];
if (empty($port)) {
    $port = "80";
}
$contenttype = @$_REQUEST['contenttype'];
if (empty($contenttype)) {
    $contenttype = "text/xml";
}
$data = @$GLOBALS["HTTP_RAW_POST_DATA"];
// define content type
header("Content-type: " . $contenttype);
if (empty($data)) {
    $result = send_request();
} else {
    // post XML
    $posting = new HTTP_Client($host, $port, $data);
    $posting->set_path($path);
    $result = $posting->send_request();
}
// strip leading text from result and output result
$len = strlen($result);
$pos = strpos($result, "<");
if ($pos > 1) {
    $result = substr($result, $pos, $len);
}
//$result = str_replace("xlink:","",$result);
echo $result;
// define class with functions to open socket and post XML
// from http://www.phpbuilder.com/annotate/message.php3?id=1013274 by Richard Hundt
class HTTP_Client
{
Exemple #11
0
}
$prefix = $template[0];
$suffix = $template[1];
// Match the recipient address to the address template
if (!isset($_ENV["RECIPIENT"])) {
    error_log("Recipient address not set, unable to get bounce token");
    exit(1);
}
$recipient = $_ENV["RECIPIENT"];
$token_length = strlen($recipient) - strlen($prefix) - strlen($suffix);
if ($token_length <= 0 || substr($recipient, 0, strlen($prefix)) != $prefix || substr($recipient, strlen($prefix) + $token_length) != $suffix) {
    error_log("Recipient address does not match address template: {$recipient}");
    exit(1);
}
$token = substr($recipient, strlen($prefix), $token_length);
// Log the bounce to the configured bounce logger
if (substr($BOUNCE_LOGGER, 0, strlen("file://")) == "file://") {
    $fh = fopen(substr($BOUNCE_LOGGER, strlen("file://")), "w+");
    if ($fh) {
        fwrite($fh, "{$token}\n");
        fclose($fh);
        exit(0);
    }
} elseif (substr($BOUNCE_LOGGER, 0, strlen("http://")) == "http://" || substr($BOUNCE_LOGGER, 0, strlen("https://")) == "https://") {
    /** @ ignore */
    $client = new HTTP_Client();
    $client->post($BOUNCE_LOGGER, array("token" => $token));
    exit(0);
}
error_log("Error logging bounce token: {$BOUNCE_LOGGER}");
exit(1);
Exemple #12
0
}
// Domain control
if ($domains) {
    $found = false;
    foreach ($domains as $domain) {
        if (strpos($link, $domain) !== false) {
            $found = true;
        }
    }
    if (!$found) {
        error_log("Forbidden redirect: {$link}");
        header("Status: 403 Forbidden");
        exit(0);
    }
}
// Send the redirect
header("Location: {$link}");
// Log the link to the configured link logger
if (substr($logger, 0, strlen("file://")) == "file://") {
    $fh = fopen(substr($logger, strlen("file://")), "w+");
    if ($fh) {
        fwrite($fh, "{$token} {$link}\n");
        fclose($fh);
    }
} elseif (substr($logger, 0, strlen("http://")) == "http://" || substr($logger, 0, strlen("https://")) == "https://") {
    $client = new HTTP_Client();
    $client->post($logger, array("token" => $token, "link" => $link));
} else {
    error_log("link detected: {$token} {$link}");
}
exit(0);
Exemple #13
0
$cache = new Cache_Lite($options);
// del http cache parameter _dc=12334234
$route = preg_replace('/&_dc=(\\d+)$/i', '', substr($_SERVER["QUERY_STRING"], 6));
if ($data = $cache->get($route)) {
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    echo $data;
} else {
    $parsed_url = parse_url($route);
    if ($parsed_url) {
        if (array_key_exists("host", $parsed_url)) {
            $url = $route;
        } else {
            $url = 'http://api.worldbank.org' . $route;
        }
    } else {
        $url = 'http://api.worldbank.org' . $route;
    }
    $hc = new HTTP_Client();
    $hc->setMaxRedirects(1);
    $hc->get($url);
    $response = $hc->currentResponse();
    $headers = $response['headers'];
    $data = $response['body'];
    foreach ($headers as $k => $v) {
        header($k . ': ' . $v);
    }
    echo $data;
    $cache->save($data, $route);
}
 private function can_download($url, &$res)
 {
     $client = new HTTP_Client();
     $e = $client->get($url);
     if (PEAR::isError($e)) {
         $res = $e->getCode() . '(' . htmlspecialchars($e->getMessage()) . ')';
         return FALSE;
     }
     $resp = $client->currentResponse();
     $code = $resp['code'];
     if ($code !== 200) {
         $res = "bad status - {$code}";
         return FALSE;
     } else {
         $res = '200 OK';
     }
     $body = $resp['body'];
     return $body;
 }
Exemple #15
0
//Open stdin by hand
$stdin = fopen('php://stdin', 'r');
if (!$stdin) {
    error_log("Cannot open stdin");
    exit(1);
}
//Get the message source from it
$message_source = '';
while (!feof($stdin)) {
    $message_source .= fread($stdin, 4096);
}
fclose($stdin);
//Sanity check
if (empty($message_source)) {
    error_log('Got empty message, aborting');
    exit(1);
}
//Post to target
$client = new HTTP_Client();
$stat = $client->post($POST_TO, array('message_source' => $message_source));
$response = $client->currentResponse();
//If anything at all goes wrong dump debug data and exit with errorcode
if ($stat != 200 || $response['code'] != 200 || stristr($response['body'], 'error')) {
    ob_start();
    print_r($response);
    $response_str = ob_get_contents();
    ob_end_clean();
    error_log("Error posting message to: {$POST_TO} ({$stat}), dumping response data:\n===\n{$response_str}===\n");
    exit(1);
}
exit(0);
 public function _request($site, $func_name, $request_method, $data, $auth = FALSE)
 {
     $headers = array("User-Agent" => "PeopleAggregator/" . PA_VERSION);
     global $fortythree_api_key;
     $data['api_key'] = $fortythree_api_key;
     if ($auth) {
         switch ($this->pw_type) {
             case 'raw':
                 $data['username'] = $this->login;
                 $data['password'] = $this->password;
                 break;
             case 'wsse':
                 $headers['Authorization'] = 'WSSE profile="UsernameToken"';
                 $headers['X-WSSE'] = $this->_make_wsse($this->login, $this->password);
                 var_dump($headers);
                 break;
             default:
                 throw new PAException(0, "Invalid password type {$this->pw_type}");
         }
     }
     $url = "http://www.{$site}.com/service/{$func_name}";
     $c = new HTTP_Client(null, $headers);
     switch ($request_method) {
         case 'GET':
             $ret = $c->get($url, $data);
             break;
         case 'POST':
             $preEncoded = gettype($data) == "string";
             $ret = $c->post($url, $data, $preEncoded);
             break;
         default:
             throw new PAException("invalid request method: {$request_method}");
     }
     $r = $c->currentResponse();
     echo "did http request to {$url} with data ";
     var_dump($data);
     echo ", returned {$ret}.<br>";
     $xml = $r["body"];
     echo "xml = <pre>" . htmlspecialchars($xml) . "</pre><hr>";
     $dom = DomDocument::loadXML($xml);
     $xp = new DOMXPath($dom);
     $xp->registerNamespace("dc", "http://purl.org/dc/elements/1.1/");
     $xp->registerNamespace("th", "http://43things.com/xml/2005/rc#");
     $xp->registerNamespace("pl", "http://43places.com/xml/2005/rc#");
     $xp->registerNamespace("pe", "http://43people.com/xml/2005/rc#");
     return array("xml" => $xml, "dom" => $dom, "xpath" => $xp);
 }
Exemple #17
0
function tgrep_search($query)
{
    global $_conf;
    $client = new HTTP_Client();
    $client->setDefaultHeader('User-Agent', 'p2-tgrep-client');
    $code = $client->get($_conf['expack.tgrep_url'] . '?' . $query);
    if (PEAR::isError($code)) {
        p2die($code->getMessage());
    } elseif ($code != 200) {
        p2die("HTTP Error - {$code}");
    }
    $response = $client->currentResponse();
    $result = unserialize($response['body']);
    if (!$result) {
        p2die('Error: 検索結果の展開に失敗しました。');
    }
    return $result;
}
Exemple #18
0
 function Program()
 {
     $param = $this->param . "?id=" . $this->id . "&phoneNumber=" . urlencode($this->phone_number) . "&psw=" . $this->pwd . "&textSms=" . urlencode($this->text_sms) . "&descripcion=" . urlencode($this->descriptionEP) . "&fecha=" . $this->dateEP . "&hora=" . $this->timeEP . "&periodicidadEnvio=" . $this->periodEP;
     if ($this->from != "") {
         $param .= "&remite=" . urlencode($this->from);
     }
     $url = $this->servletProgram . $param;
     $httpclient = new HTTP_Client($this->server, $this->port, $timeout = 30);
     $httpclient->path = $url;
     $resultado = $httpclient->send_request();
     if ($resultado == -1) {
         $this->smsResult = "KO";
         $this->smsDescription = "Error de conexión al servidor SMS";
     } else {
         $simple = $resultado;
         // Decodifico el resultado
         $p = xml_parser_create();
         $skipWhite = xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
         xml_parse_into_struct($p, $simple, $vals, $index);
         xml_parser_free($p);
         $auxResult = $index[RESULT][0];
         $estadoResult = $vals[$auxResult][value];
         $auxDescription = $index[DESCRIPTION][0];
         $estadoDescription = $vals[$auxDescription][value];
         $auxCredito = $index[CREDIT][0];
         $estadoCredito = $vals[$auxCredito][value];
         $this->smsResult = $estadoResult;
         $this->smsDescription = $estadoDescription;
         $this->smsCredit = $estadoCredito;
     }
     return $resultado;
 }
/**
 *
 * auto_post.php
 *
 * @package    core
 * @author     John.meng <*****@*****.**>
 * @author     цот╤РШ
 * @author     QQ:3440895
 * @version    CVS: $Id: auto_post.php,v 1.1 2006/10/25 08:55:54 arzen Exp $
 */
set_time_limit(0);
define('APF_ROOT_DIR', realpath(dirname(__FILE__) . '/../..'));
require_once APF_ROOT_DIR . DIRECTORY_SEPARATOR . 'init.php';
require_once 'HTTP/Client.php';
$fields = array('handle' => 'admin', 'passwd' => 'admin', 'category' => '1', 'name' => 'product' . mt_rand(5000, 99999), 'price' => '5.23');
// uploade file
$files = array();
$files[] = array('name' => 'photo', 'filename' => 'C:/Documents and Settings/john.meng/My Documents/My Pictures/001004183175_tb.jpg');
$search_action = 'http://localhost/dev/AutoPhpFramework/web/backend.php/product/apf_product/addsubmit';
$headers = array('User-Agent' => 'Mozilla/4.0 (compatible; MSIE 6.0)', 'Accept-Language' => 'zh-cn');
$h = new HTTP_Client(NULL, $headers);
$code = $h->post($search_action, $fields, false, $files);
//false,$files
if ($code == 200) {
    $resp = $h->currentResponse();
    $body = $resp['body'];
    echo $body;
} else {
    echo "fetch the result error.";
}
Exemple #20
0
 /**
  * Get user information from pear.php.net
  *
  * This function uses the given username and password to authenticate
  * against the pear.php.net website
  *
  * @param string    Username
  * @param string    Password
  * @return mixed    Error object or boolean
  */
 function fetchData($username, $password)
 {
     $this->log('Auth_Container_PEAR::fetchData() called.', AUTH_LOG_DEBUG);
     $client = new HTTP_Client();
     $this->log('Auth_Container_PEAR::fetchData() getting salt.', AUTH_LOG_DEBUG);
     $code = $client->get($this->url . '/getsalt');
     if ($code instanceof PEAR_Error) {
         return $code;
     }
     if ($code != 200) {
         return PEAR::raiseError('Bad response to salt request.', $code);
     }
     $resp = $client->currentResponse();
     $salt = $resp['body'];
     $this->log('Auth_Container_PEAR::fetchData() calling validate.', AUTH_LOG_DEBUG);
     $postOptions = array('username' => $username, 'password' => md5($salt . md5($password)));
     if (is_array($this->karma) && count($this->karma) > 0) {
         $postOptions['karma'] = implode(',', $this->karma);
     }
     $code = $client->post($this->url . '/validate', $postOptions);
     if ($code instanceof PEAR_Error) {
         return $code;
     }
     if ($code != 200) {
         return PEAR::raiseError('Bad response to validate request.', $code);
     }
     $resp = $client->currentResponse();
     list($code, $message) = explode(' ', $resp['body'], 2);
     if ($code != 8) {
         return PEAR::raiseError($message, $code);
     }
     return true;
 }
Exemple #21
0
    /**
     * Send the error details to the server via HTTP.
     * @return void
     */
    public function sendToServer()
    {
        $client = new HTTP_Client();
        $code = $client->post
            ($this->m_newReport, array('f_software' => $this->m_software,
                                       'f_version' => $this->m_version,
                                       'f_num' => $this->m_num,
                                       'f_str' => $this->m_str,
                                       'f_line' => $this->m_line,
                                       'f_id' => $this->getId(),
                                       'f_backtrace' => $this->getBacktraceString(),
                                       'f_time' => $this->getTime(),
                                       'f_description' => $this->getDescription(),
                                       'f_email' => $this->getEmail(),
                                       '__FORM_TOKEN' => $this->getFormToken($client),
                                    ));

        $response = $client->currentResponse();
        $this->__responseHeader = $response['headers'];
        $this->__responseBody = $response['body'];
        $this->__responseCode = $code;

        if ($code != 200) {
        	return false;
        } elseif (preg_match ("/\baccepted\b/", $this->__responseBody)) {
        	// --- Did we get an "accepted"?
        	return true;
        } else {
        	return false;
        }
    } // fn sendToServer
Exemple #22
0
	/**
	 * Download the remote file and save it to disk, create a thumbnail for it,
	 * and create a database entry for the file.
	 *
	 * @param string $p_url
	 *		The remote location of the file. ("http://...");
	 *
	 * @param array $p_attributes
	 *		Optional attributes which are stored in the database.
	 *		Indexes can be the following: 'Description', 'Photographer', 'Place', 'Date'
	 *
	 * @param int $p_userId
	 *		The user ID of the user who uploaded the image.
	 *
	 * @param int $p_id
	 *		If you are updating an image, specify its ID here.
	 *
	 * @return mixed
	 * 		Return an Image object on success, return a PEAR_Error otherwise.
	 */
	public static function OnAddRemoteImage($p_url, $p_attributes,
	                                        $p_userId = null, $p_id = null)
	{
		global $Campsite;
		if (function_exists("camp_load_translation_strings")) {
			camp_load_translation_strings("api");
		}

		// Check if thumbnail directory is writable.
		$imageDir = $Campsite['IMAGE_DIRECTORY'];
		$thumbDir = $Campsite['THUMBNAIL_DIRECTORY'];
		if (!file_exists($imageDir) || !is_writable($imageDir)) {
			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $imageDir), CAMP_ERROR_WRITE_DIR);
		}
		if (!file_exists($thumbDir) || !is_writable($thumbDir)) {
			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $thumbDir), CAMP_ERROR_WRITE_DIR);
		}

		$client = new HTTP_Client();
	    $client->get($p_url);
	    $response = $client->currentResponse();
	    if ($response['code'] != 200) {
	    	return new PEAR_Error(getGS("Unable to fetch image from remote server."));
	    }
	    foreach ($response['headers'] as $headerName => $value) {
	    	if (strtolower($headerName) == "content-type") {
	    		$ContentType = $value;
	    		break;
	    	}
	    }

        // Check content type
        if (!preg_match('/image/', $ContentType)) {
            // wrong URL
            return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url));
        }

    	// Save the file
        $tmpname = $Campsite['TMP_DIRECTORY'].'img'.md5(rand());
        if (is_writable($Campsite['TMP_DIRECTORY'])) {
	        if ($tmphandle = fopen($tmpname, 'w')) {
	            fwrite($tmphandle, $response['body']);
	            fclose($tmphandle);
	        }
        } else {
	    	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE);
	    }

        // Check if it is really an image file
        $imageInfo = getimagesize($tmpname);
        if ($imageInfo === false) {
        	unlink($tmpname);
            return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL));
        }

        // content-type = image
        if (!is_null($p_id)) {
        	// Updating the image
        	$image = new Image($p_id);
        	$image->update($p_attributes);
	    	// Remove the old image & thumbnail because
	    	// the new file might have a different file extension.
	    	if (file_exists($image->getImageStorageLocation())) {
				if (is_writable(dirname($image->getImageStorageLocation()))) {
		    		unlink($image->getImageStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
	    	if (file_exists($image->getThumbnailStorageLocation())) {
				if (is_writable(dirname($image->getThumbnailStorageLocation()))) {
		    		unlink($image->getThumbnailStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
        } else {
        	// Creating the image
        	$image = new Image();
        	$image->create($p_attributes);
        	$image->setProperty('TimeCreated', 'NULL', true, true);
        	$image->setProperty('LastModified', 'NULL', true, true);
        }
        if (!isset($p_attributes['Date'])) {
        	$image->setProperty('Date', 'NOW()', true, true);
        }
        $image->setProperty('Location', 'remote', false);
        $image->setProperty('URL', $p_url, false);
	    if (isset($imageInfo['mime'])) {
	    	$image->setProperty('ContentType', $imageInfo['mime'], false);
	    }

        // Remember who uploaded the image
        if (!is_null($p_userId)) {
			$image->setProperty('UploadedByUser', $p_userId, false);
        }

        if ($Campsite['IMAGEMAGICK_INSTALLED']) {
		    // Set thumbnail file name
		    $extension = Image::__ImageTypeToExtension($imageInfo[2]);
		    $thumbnail = $image->generateThumbnailStorageLocation($extension);
		    $image->setProperty('ThumbnailFileName', basename($thumbnail), false);

		    if (!is_writable(dirname($image->getThumbnailStorageLocation()))) {
            	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE);
		    }

		    // Create the thumbnail
            $cmd = $Campsite['THUMBNAIL_COMMAND'].' '
            	. $tmpname . ' ' . $image->getThumbnailStorageLocation();
            system($cmd);
            if (file_exists($image->getThumbnailStorageLocation())) {
            	chmod($image->getThumbnailStorageLocation(), 0644);
            }
        }
        unlink($tmpname);
        $image->commit();

		$logtext = getGS('The image $1 has been added.',
						$image->m_data['Description']." (".$image->m_data['Id'].")");
		Log::Message($logtext, null, 41);

	    return $image;
	} // fn OnAddRemoteImage
Exemple #23
0
 /**
  * HTTP_Client::post() のラッパーメソッド
  *
  * @param string $uri
  * @param mixed $data
  * @param bool $preEncoded
  * @param array $files
  * @param array $headers
  * @return array HTTPレスポンス
  * @throws P2Exception
  */
 protected function httpPost($uri, $data, $preEncoded = false, $files = array(), $headers = array())
 {
     $code = $this->_httpClient->post($uri, $data, $preEncoded, $files, $headers);
     P2Exception::pearErrorToP2Exception($code);
     if ($code != 200) {
         throw new P2Exception('HTTP ' . $code);
     }
     return $this->_httpClient->currentResponse();
 }
 private function _request($url, $xml)
 {
     $headers = array("Accept" => "application/xml", "Content-Type" => "application/xml");
     $c = new HTTP_Client(null, $headers);
     $c->setRequestParameter(array("user" => $this->login, "pass" => $this->password));
     $ret = $c->post($url, $xml, TRUE);
     switch ($ret) {
         case 200:
             // ok
             break;
         case 401:
             throw new PAException(USER_INVALID_PASSWORD, "Login incorrect");
         case 403:
             throw new PAException(USER_ACCESS_DENIED, "Access denied");
         default:
             throw new PAException(GENERAL_SOME_ERROR, "BaseCamp API returned HTTP error code {$ret}");
     }
     $r = $c->currentResponse();
     //        echo "did http request to $url with data "; var_dump($xml); echo ", returned $ret.<br>";
     $xmlret = $r["body"];
     //        echo "xml response: <pre>".htmlspecialchars($xmlret)."</pre>";
     return simplexml_load_string($xmlret);
 }
 private function sendPlaxoCmd($argArray = null)
 {
     if ($this->debug) {
         echo '<pre>';
         echo print_r($argArray, 1);
         echo '</pre>';
     }
     $url = PLAXO_SERVICE_URL;
     $agent = new HTTP_Client();
     $code = $agent->post($url, $argArray, true);
     if (PEAR::isError($code)) {
         $error = $code->getMessage();
         Logger::log(basename(__FILE__) . " {$method} {$url} failed: {$error}");
         return false;
     } else {
         $responseArray = $agent->currentResponse();
         return $responseArray['body'];
     }
 }
Exemple #26
0
}
// 画像がエラーログにあるか確認
if (!$force && $ini['Getter']['checkerror']) {
    $errlog = new IC2_DataObject_Errors();
    if ($errlog->get($uri)) {
        ic2_error($errlog->errcode, '', false);
    }
}
// }}}
// {{{ init http-client
// 設定を確認
$conn_timeout = isset($ini['Getter']['conn_timeout']) && $ini['Getter']['conn_timeout'] > 0 ? (double) $ini['Getter']['conn_timeout'] : 60.0;
$read_timeout = isset($ini['Getter']['read_timeout']) && $ini['Getter']['read_timeout'] > 0 ? (int) $ini['Getter']['read_timeout'] : 60;
$ic2_ua = !empty($_conf['expack.user_agent']) ? $_conf['expack.user_agent'] : $_SERVER['HTTP_USER_AGENT'];
// キャッシュされていなければ、取得を試みる
$client = new HTTP_Client();
$client->setRequestParameter('timeout', $conn_timeout);
$client->setRequestParameter('readTimeout', array($read_timeout, 0));
$client->setMaxRedirects(3);
$client->setDefaultHeader('User-Agent', $ic2_ua);
if ($force && $time) {
    $client->setDefaultHeader('If-Modified-Since', http_date($time));
}
// プロキシ設定
if ($ini['Proxy']['enabled'] && $ini['Proxy']['host'] && $ini['Proxy']['port']) {
    $client->setRequestParameter('proxy_host', $ini['Proxy']['host']);
    $client->setRequestParameter('proxy_port', $ini['Proxy']['port']);
    if ($ini['Proxy']['user']) {
        $client->setRequestParameter('proxy_user', $ini['Proxy']['user']);
        $client->setRequestParameter('proxy_pass', $ini['Proxy']['pass']);
        $proxy_auth_data = base64_encode($ini['Proxy']['user'] . ':' . $ini['Proxy']['pass']);
function officeautopilot_addContact($info, $tag, $api_key, $api_id)
{
    require_once 'HTTP_Client-1.2.1/Client.php';
    $httpc = new HTTP_Client();
    $first_name = $info['first_name'];
    $last_name = $info['last_name'];
    $email = $info['email'];
    $tagsXml = '<field name="Contact Tags">*/*' . $tag . '*/*</field>';
    $xml = '<contact>
    <Group_Tag name="Contact Information">
        <field name="First Name">' . utf8_encode($first_name) . '</field>
        <field name="Last Name">' . utf8_encode($last_name) . '</field>
        <field name="E-Mail">' . $email . '</field>
    </Group_Tag>
    <Group_Tag name="Sequences and Tags">
        ' . $tagsXml . '
    </Group_Tag>
</contact>';
    $postContact = array('Appid' => $api_id, 'Key' => $api_key, 'reqType' => 'add', 'data' => $xml);
    try {
        $httpc->post('http://api.moon-ray.com/cdata.php', $postContact);
        $response = $httpc->currentResponse();
        return true;
    } catch (Exception $e) {
        return false;
    }
    return true;
}