Code Monkey home page Code Monkey logo

cloudflare's Introduction

Note: Please use the official Cloudflare PHP package

https://github.com/cloudflare/cloudflare-php

I will continue to fix bugs but there will be no futher development on this library given Cloudflare have released an official package.

You can read more about the official package here:

Build Status Coverage Status Dependency Status Latest Stable Version Total Downloads StyleCI License Scrutinizer Code Quality

CloudFlare API - PHP

The documentation for the API can be found at https://api.cloudflare.com, I will try to update this as soon as possible when new features are added to the API. If I miss one please submit a pull request.

If you spot an issue with the package just let me know via issues but please include as much detail as possible, ideally with code examples, environment information etc.

Documentation for this package can be viewed here: https://jamesryanbell.github.io/cloudflare/

Installation

Installation should be done via composer, details of how to install composer can be found at https://getcomposer.org/

$ composer require jamesryanbell/cloudflare

Features

The current feature list includes:

Usage

In situations where you want to make multiple calls to the API across different services it's easier to create a connection to the api first and then pass that around the other services e.g.

    use Cloudflare\Zone\Dns;

    // Create a connection to the Cloudflare API which you can
    // then pass into other services, e.g. DNS, later on
    $client = new Cloudflare\Api('[email protected]', 'API_KEY');

    // Create a new DNS record
    $dns = new Cloudflare\Zone\Dns($client);
    $dns->create('12345678901234567890', 'A', 'name.com', '127.0.0.1', 120);

If you are just performing a single action then you can connect to the API directly when you instantiate the class e.g.

    use Cloudflare\Zone\Dns;

    // Create a connection to the Cloudflare API which you can
    // then pass into other services, e.g. DNS, later on
    $dns = new Cloudflare\Zone\Dns('[email protected]', 'API_KEY');
    $dns->create('12345678901234567890', 'TXT', 'name.com', '127.0.0.1', 120);

PageRules

    use Cloudflare\Zone\Pagerules;

    // Define your targets
    // Currently you can only specify one URL per page rule but this implementation matches the API
    // so I am leaving it for now in the assumption they are planning to add multiple targets.
    $targets = [
        [
            'target' => 'url',
            'constraint' =>
            [
                'operator' => 'matches',
                'value' => 'http://example.co.uk/*'
            ]
        ]
    ];

    // Define your actions
    // Each action is held within it's own array.
    $actions = [
        [
            'id' => 'always_online',
            'value' => 'on'
        ]
    ];

    $pagerules = new Cloudflare\Zone\Pagerules('[email protected]', 'API_KEY');
    $pagerules->create($zoneId, $targets, $actions);

License

MIT

cloudflare's People

Contributors

aidask avatar ashleyhindle avatar benjojo avatar farnabaz avatar gassenta avatar holtkamp avatar jamesryanbell avatar littlestfluffy avatar nikolaevas avatar tangrufus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloudflare's Issues

Zone AccessRules return 404 due to duplicated //

I know you're not maintaining this since the official Cloudflare API is available now, but we still use your project so I thought I'd report this.

Recently we're starting to see 404 errors from the Zone\Firewall]\AccessRules class.

The returned output looks like this:

{ "code": 1000, "error": "not_found" }

It turns out the problem has to do with the request URL. All request URLs have a double // in them, which doesn't affect any of the API queries except for the zones one it seems.

Eg this works fine:

GET https://api.cloudflare.com/client/v4//user/firewall/access_rules/rules

But this will be a 404:

GET https://api.cloudflare.com/client/v4//zones/:zoneid/firewall/access_rules/rules

The reason why there are doubled // in the URL path is that all the requests look like this in the code:

return $this->get('/zones/'.$zone_id.'/firewall/access_rules/rules', $data);

But in the get request function it does this:

$url = 'https://api.cloudflare.com/client/v4/'.$path;

The fix is to to remove the extra / in the call to get, eg:

return $this->get('zones/'.$zone_id.'/firewall/access_rules/rules', $data);

Or more universally it's possible to remove the trailing / in the request function.

API rate limiting

Hi,

my server have been blocked from Cloudflare, because script overload API requests. It is possible to implement API rate limiting?

https://api.cloudflare.com/#requests

"Rate limiting
The CloudFlare API sets a maximum of 1,200 requests in a five minute period.
Cache-Tag purging has a lower rate limit of up to 2,000 purge API calls in every 24 hour period. You may purge up to 30 tags in one API call."

Enable Cloudflare when creating DNS zone

I'm trying to enable Cloudflare features when creating a new zone, by default its only DNS, it should be doable by adding proxied => true to the data array in the create function.

But the code, as is, doesn't work as the bool will be converted to something that Cloudflare doesn't accept.

Casting the parameters as an object seems to do it, but would require some changes.

  if($method === 'post') {
            if(preg_match("/\/dns_records/", $path))
              $data = (object) array (
                    'type'    => "A",
                    'name'    => "website.com",
                    'content' => "188.18.28.38",
                'proxied' => true,
                    'ttl'     => 120
                );
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            $headers[] = "Content-type: application/json";
        } else if ($method === 'put') {

Any ideas what would be the best way to do it?

Add zone to cloudflare

Hi, i'm trying to add a zone to cloudflare, without the need for an interaction in the browser.
I successfullly added a zone, but i get stuk on step2 of the wizzard. I added the dns-records, changed the namservers, but the zone keeps at step 2 (add dns records). I already did a activation check, but this does not work.

Is this an issue with the API, or am I missing a step to actually enable the zone?

More Predictable Versioning

Is there any chance we could get a more predictable versioning system for this package? I see you tagged a v1 release back in 2015, but since that release is out of date any of us that want to stay up to date are forced to use the dev-master tag through Composer, which is never a good practice. Would it be possible to have new releases follow a versioning system so that we can define a set version for Packagist and make sure that we don't end up pulling breaking changes in the future?

Thanks!

Prevent use of func_get_args() in constructor

While I like the dynamic aspects of func_get_args() in Api::__construct(), it prevents proper "autowiring" by Dependency Injection Containers.

$num_args = func_num_args();

We use PHP-DI as Dependency Injection Container, which would/should allow us to define a dependency as:

Cloudflare\Api::class => object()->constructor(get('settings.cloudFlare.credentials.email'), get('settings.cloudFlare.credentials.apiKey'))

However, this does not work since the autowiring process can not figure out the exact parameters using reflection. So we have to use:

\Cloudflare\Api::class => object()->constructor()
        ->method('setEmail', get('settings.cloudFlare.credentials.email'))
        ->method('setAuthKey', get('settings.cloudFlare.credentials.apiKey')),

Additionally, for the more specific API classes:

\Cloudflare\Zone::class => object()->lazy(), //Can not be used, since the autowiring mechanism fails

can not be used, so we must use the more complex:

\Cloudflare\Zone::class => function (ContainerInterface $container) {
    return new \Cloudflare\Zone($container->get(Cloudflare\Api::class)); 
}

I see two options to overcome this limitation:

  • explicit use of parameters: Api::__construct($emailAddressOrClient, $password = null)
  • introduce static 'factory' methods:
    • Api::getInstance($email, $apiKey)
    • Api::getInstanceUsingExistingClient(Api $client)

I know this is kind of an edge case, but I hope I described this "issue" properly ๐Ÿ˜„ , what do you think?

CloudFlare API request limits

Hi James!
First of all thank you for your job ๐Ÿ‘

I am programming sort of CRM which should work with the CloudFlare bulk actions and so should avoid CF limits. I thought about queuing API requests, counting their total count, start-end delta and use delays between calls. It looks like the best place to do so is at API->request() method due to inheritence of API class to all other. But it looks like there's no way to extend/modify this code except forking from your repository (and it's not best idea).
Maybe I just missed important part about error handling and cases for CF limits.
What is your best practice to handle CF request limits?
Thank you.

Invalid request headers... Invalid Content-Type header

This happens when running the activation_check() from Cloudflare\Zone.

Full error log is:

array:5 [โ–ผ
  "error" => ""
  "http_code" => 400
  "method" => "put"
  "result" => "{"success":false,"errors":[{"code":6003,"message":"Invalid request headers","error_chain":[{"code":6105,"message":"Invalid Content-Type header, valid values are application\/json,multipart\/form-data"}]}],"messages":[],"result":null}"
  "information" => array:26 [โ–ถ]
]

There seems to be a few forks fixing this.

Unable to create MX records

I'm receiving the following error when trying to create MX records using CloudFlare/Zone/Dns->create():

object(stdClass)[17]
      public 'code' => int 1004
      public 'message' => string 'DNS Validation Error' (length=20)
      public 'error_chain' => 
        array (size=1)
          0 => 
            object(stdClass)[16]
              public 'code' => int 9008
              public 'message' => string 'Invalid priority, priority must be set and be between 0 and 65535' (length=65)

This appears to be because there is no parameter for setting a priority. Am I missing something here or does it just need to be added to the function?

Cheers

The zone_create says it needs a valid domain

Hello, I am very glad you've created such a great tool, I tried the script out but unfortunately the
zone class reports it needs a valid domain though the domain name was 100% valid, usable and registered. Can you please have a look at it fix the bug (if it's a bug)?...
Thanks for your attention.

Cloudflare\Zone\Plan->available() fix

    public function available($zone_identifier)
    {
        return $this->get('zones/'.$zone_identifier.'/plans');
    }

should be changed to

    public function available($zone_identifier)
    {
        return $this->get('zones/'.$zone_identifier.'/available_rate_plans');
    }

thanks for your tool btw)

PHP Fatal error: Class 'Cloudflare\Api' not found in

<?php use Cloudflare\Zone\Dns; // Create a connection to the Cloudflare API which you can // then pass into other services, e.g. DNS, later on $client = new Cloudflare\Api('[email protected]', 'dc88c3098d023ea0d47874698bc8cc027b1c5'); // Create a new DNS record $dns = new Cloudflare\Zone\Dns($client); $dns->create('www', 'A', 'name.com', '192.168.1.2', 120);

according to eg, i name above code to cf_dns.php

but when i run " php cf_dns.php" command

get "PHP Fatal error: Class 'Cloudflare\Api' not found in /root/cf_dns.php on line 5"

where is wrong?
could you help me check it?
thx

User-Agent is now required for API requests

As of yesterday all my API requests to CF have been blocked as being a security threat. I opened a service ticket (after waiting for their support system to come back up :-/ ) and their response was due to changes in the API, User-Agent may now be a required field. I'm not sure if this is for all users or just certain ones marked as "security threats" but I figure it can't hurt either way.

As soon as I add a User-Agent to the $headers array in Api.php, requests start working again. I'd make a PR but I haven't updated my local fork yet since I'm unsure whether my other issue has been resolved in your copy.

How to get results in screen?

Hi,

I'm using your code but I can't get print results, How can do this? This is the code that I have:

use Cloudflare\Zone;
$client = new Cloudflare\Api('email', 'xxxxxx');
$result = new Cloudflare\Zone($client);
$result -> zones( 'domain.com', 'active', '1', '20', 'status', 'desc', 'all' );
echo $result;

nothing appears, it must present info about the zone.

Sorry for my english and than you,
Carlos

Unable to determine configuration for Firewall/AccessRules->create

I have several calls working, but am failing to get the format correct for the create access rule found at:
https://api.cloudflare.com/#firewall-access-rule-for-a-zone-create-access-rule

https://jamesryanbell.github.io/cloudflare/source-class-Cloudflare.Zone.Firewall.AccessRules.html#59-78

I expected the following to work, based on the cloudflare API docs

$firewall = new Cloudflare\Zone\Firewall\AccessRules($client);
$firewall->create('my_zone_id', 'whitelist', '{"target":"ip","value":"1.2.3.4"}', 'test from php api')

I however get back Missing configuration target.

I have tried various combinations but an unable to get this one working.

Trying to get property of non-object

Cloudflare returns invalid json response, might be caused by network or other issues.
https://github.com/jamesryanbell/cloudflare/blob/master/src/CloudFlare/Api.php#L237

ErrorException: Trying to get property of non-object
#50 vendor/jamesryanbell/cloudflare/src/CloudFlare/Api.php(238): handleError
#49 vendor/sentry/sentry/lib/Raven/Breadcrumbs/ErrorHandler.php(36): handleError
#48 vendor/jamesryanbell/cloudflare/src/CloudFlare/Api.php(238): request
#47 vendor/jamesryanbell/cloudflare/src/CloudFlare/Api.php(141): delete
#46 vendor/jamesryanbell/cloudflare/src/CloudFlare/Zone/Cache.php(50): purge_files
#45 app/Services/CloudFlare.php(28): clearFiles

Does the user section works correctly?

Hey.

Does the user section from new API works?

curl -X PATCH "https://api.cloudflare.com/client/v4/user" -H "X-Auth-Email: email" -H "X-Auth-Key: api key" --data '{"first_name":"firstname","last_name":"lastname","telephone":"phone","country":"country","zipcode":"zipcode"}'

Always returns "{"success":false,"errors":[{"code":1029,"message":"Unable to find a user property to update. Perhaps you are trying to update a readOnly setting?"}],"messages":[],"result":null}" nevermind of what do you send in data.

Does anyone able to success with that operation?

Detection of Free SSL status is missing

Would be good to implement ability to check the status of cloudflare's free ssl. The reason being that when you create a zone, the SSL may take some indeterminate amount of time to be ready. So before you enabled forced SSL, you have to check to see if its ready.

You can also tell cloudflare to retry the SSL which is can sometimes be useful.

Consider this patch to Zone/SSL.php

	/**
	 * Get SSL Verification Info for a Zone (permission needed: #ssl:read)
	 * https://api.cloudflare.com/#ssl-verification-properties
	 *
	 * @param string $zone_identifier API item identifier tag
	 */
	public function free_ssl_status($zone_identifier)
	{
		return $this->get('zones/'.$zone_identifier.'/ssl/verification');
	}

	/**
	 * Immediately retry SSL verification (permission needed: #ssl:edit)
	 * https://api.cloudflare.com/#ssl-verification-properties
	 *
	 * @param string $zone_identifier API item identifier tag
	 */
	public function free_ssl_retry($zone_identifier)
	{
		$data = [
			'retry' => true
		];

		return $this->get('zones/'.$zone_identifier.'/ssl/verification', $data);
	}

Cloudflare errors in drupal admin

Hello,

I am desperate here. My Drupal admin back-end is a mess after starting cloudflare.

I followed litterally every step on Cloudflare website.

I am seriously considering stopping my paid cloudflare account. After logging in, and clicking on an item on the main menu, you seem to be logged out. If however, you add a question mark at the end of the url, and you refresh, you see the admin page again !

Even when I try to logout, it doesn't work anymore, even when the user/logout should match the exception rule I provided (user*) !

Second problem: When I add a menu item to the site, it doesn't show on the 50.000 pages. I shouldn't clear the whole Cloudflare cache after I add one menu item ??

i have read on dozens of forums that Cloudflare has left Drupal users in the cold, and now I experience the same. I would rather prefer to add a positive comment to those forums, so I want to crack this nut ! :))

Thank you in advance

User permissions checking via organizations on non-enterprise accounts is unnecessary

I'm using this lib with a Pro account, and I'm getting a few errors. One such error occurs here: https://github.com/jamesryanbell/cloudflare/blob/master/src/Api.php#L129

It's trying to access ->organizations[0] despite organizations being null.

And then the bigger issue is that it's throwing an exception when attempting to use these organizations to check the permissions required to fire off the request: https://github.com/jamesryanbell/cloudflare/blob/master/src/Api.php#L154

For now, I've changed line 151 to if ( false && ... ) { to disable the permissions check and it seems to work okay, so I'm guessing it's just not necessary for Pro level accounts to perform this check. I wasn't sure how exactly you might want to approach disabling this check in the library so I figured an issue would be the best way to figure this out. For now I'm just going to fork and disable that block of code as I've done. Let me know if I can help

Inconsistency in method naming settings endpoint for 'always_online'

For the settings endpoint the following methods are typically available:

  • setting_name($zone_identifier)
  • change_setting_name($zone_identifier)

This allows to create a command which takes a setting name as parameter can then use:

  • $method = sprintf('change_%s', $settingName)

However, an inconsistency prevents this to work with the 'always online' setting:

Changing the name of this method to realize consistency would mean a BC-break. So an alias might be considered?

As far as I can see this is the only inconsistency. The following method seems missing:

  • change_email_obfuscation()

Type error: Argument 2 passed to Cloudflare\Api::request() must be of the type array, null given

This is a pretty major bug introduced in version 1.11.0 which has caused us to need to roll back and lock our version at 1.10.3.

It appears that with the new parameter defaults for the request() method in v1.11.0, several calls are broken from methods that pass in null for the data parameter. We are getting this for every request made to the activation_check() method, for example.

(new CloudFlareZone($this->cloudflare))->activation_check($external_id);

Obviously, you'd need to pass in values for the variables, but that is enough to throw an exception every time it is run. Several other methods are returning the same error. We're experiencing this while running PHP 7.1, though we have not tested with earlier versions.

I'd imagine that this bug is actually affecting all methods that don't pass in a data parameter to the request() method, so it seems pretty showstopping.

@jamesryanbell it seems like you'll need to simply update the default data parameter for the get(), patch(), put(), post(), delete()... etc methods in the Api class. It shouldn't be a difficult fix, I'd assume. Just an oversight when shipping the new version.

error Cloudflare\Zone\Dns

Strict Standards: Declaration of Cloudflare\Zone\Dns::create() should be compatible with Cloudflare\Zone::create($name, Cloudflare\bool $jump_start = NULL, Cloudflare\int $organization = NULL) in /home/abcdefg/public_html/vendor/jamesryanbell/cloudflare/src/CloudFlare/Zone/Dns.php on line 102

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.