Giter Site home page Giter Site logo

unsplash-php's Introduction

PHP Unsplash Wrapper

Build Status

A PHP client for the Unsplash API.

Quick links to methods you're likely to care about:

Note: Every application must abide by the API Guidelines. Specifically, remember to hotlink images and trigger a download when appropriate.

Installation

unsplash-php uses Composer. To use it, require the library

composer require unsplash/unsplash

Usage

Configuration

Before using, configure the client with your access key and secret. If you don't have an access key and secret, follow the steps from the Unsplash API to register your application.

Note: if you're just using actions that require the public permission scope, only the access key is required. Access key is entered as applicationId due to legacy reasons.

Note: if utmSource is omitted from $credentials a notice will be raised.

Unsplash\HttpClient::init([
	'applicationId'	=> 'YOUR ACCESS KEY',
	'secret'	=> 'YOUR APPLICATION SECRET',
	'callbackUrl'	=> 'https://your-application.com/oauth/callback',
	'utmSource' => 'NAME OF YOUR APPLICATION'
]);

User Authorization workflow

If you need to access actions that are non-public on behalf of the user (i.e. uploading a photo to a specific account), you'll need to follow the user authentication workflow to access their data.

An example of this flow can be found in /examples/oauth-flow.php

Direct them to an authorization URL (configuring any scopes before generating the authorization URL):

$scopes = ['public', 'write_user'];
Unsplash\HttpClient::$connection->getConnectionUrl($scopes);

Upon authorization, Unsplash will return to you an authentication code via your OAuth callback handler. Use it to generate an access token:

Unsplash\HttpClient::$connection->generateToken($code);

With the token you can now access any additional non-public actions available for the authorized user.

Permission Scopes

The current permission scopes defined by the Unsplash API are:

  • public (Access a user's public data)
  • read_user (Access a user's private data)
  • write_user (Edit and create user data)
  • read_photos (Access private information from a user's photos)
  • write_photos (Post and edit photos for a user)
  • write_likes (Like a photo for a user)
  • read_collections (View a user’s private collections)
  • write_collections (Create and update a user’s collections)

API methods

For more information about the responses for each call, refer to the official documentation.

Some parameters are identical across all methods:

param Description
$per_page Defines the number of objects per page. Default 10
$page Defines the offset page. Default 1

Note: The methods that return multiple objects return an ArrayObject, which acts like a normal stdClass.


Search

Photos

Retrieve a single page of photo results depending on search results.

Arguments

Argument Type Opt/Required
$search string Required
$page int Opt (Default: 1)
$per_page int Opt (Default: 10 / Maximum: 30)
$orientation string Opt (Default: null / Available: "landscape", "portrait", "squarish")
$collections string Opt (Default: null / If multiple, comma-separated)
$order_by string How to sort the photos. (Optional; default: relevant). Valid values are latest and relevant.

Example

$search = 'forest';
$page = 3;
$per_page = 15;
$orientation = 'landscape';

Unsplash\Search::photos($search, $page, $per_page, $orientation);

Collections

Retrieve a single page of collection results depending on search results.

Arguments

Argument Type Opt/Required
$search string Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)

Example

Unsplash\Search::collections($search, $page, $per_page);

Users

Retrieve a single page of user results depending on search results.

Arguments

Argument Type Opt/Required
$search string Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)

Example

Unsplash\Search::users($search, $page, $per_page);

Collections

Retrieve the list of collections.

Arguments

Argument Type Opt/Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)

Example

Unsplash\Collection::all($page, $per_page);

Unsplash\Collection::photos($page, $per_page)

Retrieve photos from a collection.

Note: You need to instantiate a collection object first.

Arguments

Argument Type Opt/Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)

Example

$collection = Unsplash\Collection::find(integer $id);
$photos = $collection->photos($page, $per_page);

Unsplash\Collection::related($page, $per_page)

Retrieve list of featured collections.

Note You must instantiate a collection first

Arguments

Argument Type Opt/Required

Example

$collection = Unsplash\Collection::find($id);
$collection->related();

Unsplash\Collection::create($title, $description, $private)

Create a collection on the user's behalf.

Note: You need the write_collections permission scope

Arguments

Argument Type Opt/Required
$title string Required
$description string Opt (Default: '')
$private boolean Opt (Default: false)

Example

$collection = Unsplash\Collection::create($title);

Unsplash\Collection::update($parameters)

Update a collection on the user's behalf.

Note: You need to instantiate a collection object first

Note: You need the write_collections permission scope

Arguments

Argument | Type | Opt/Required | Note ---------------|---------|---------------------- $parameters | array | Required | The following keys can be set in the array : title, description, private

Example

$collection = Unsplash\Collection::find(int $id);
$collection->update(['private' => true])

Unsplash\Collection::destroy()

Delete a collection on the user's behalf.

Note: You need to instantiate a collection object first

Note: You need the write_collections permission scope

Example

$collection = Unsplash\Collection::find(int $id);
$collection->destroy()

Unsplash\Collection::add($photo_id)

Add a photo in the collection on the user's behalf.

Note: You need to instantiate a collection object first

Note: You need the write_collections permission scope

Arguments

Argument Type Opt/Required
$photo_id integer Required

Example

$collection = Unsplash\Collection::find(int $id);
$collection->add(int $photo_id)

Unsplash\Collection::remove($photo_id)

Remove a photo from the collection on the user's behalf.

Note: You need to instantiate a collection object first

Note: You need the write_collections permission scope

Arguments

Argument Type Opt/Required
$photo_id integer Required

Example

$collection = Unsplash\Collection::find(int $id);
$collection->remove(int $photo_id)

Photo

Unsplash\Photo::all($page, $per_page, $order_by)

Retrieve a list of photos.

Arguments

Argument Type Opt/Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)
$order_by string Opt (Default: latest / Available: oldest, popular)

Example

Unsplash\Photo::all($page, $per_page, $order_by);

Unsplash\Photo::find($id)

Retrieve a specific photo.

Arguments

Argument Type Opt/Required
$id int Required

Example

Unsplash\Photo::find($id);

Unsplash\Photo::update($parameters = [])

Post a photo on the user's behalf.

Note: You need the write_photos permission scope You need to instantiate the Photo object first

Arguments

Argument Type Opt/Required
$parameters array Required

Example

$photo = Unsplash\Photo::find(string $id)
$photo->update(array $parameters);

Unsplash\Photo::photographer()

Retrieve the photo's photographer.

Note: You need to instantiate a photo object first

Arguments

N/A

Example

$photo = Unsplash\Photo::find(string $id);
$photo->photographer();

Unsplash\Photo::random([featured => $value, username => $value, query => $value, w => $value, h => $value])

Retrieve a random photo from specified filters. For more information regarding filtering, refer to the Offical documentation.

Note: An array needs to be passed as a parameter.

Arguments

Argument Type Opt/Required
featured boolean Opt (Limit selection to featured photos)
username string Opt (Limit selection to a single user)
query string Opt (Limit selection to photos matching a search term)
w int Opt (Image width in pixels)
h int Opt (Image height in pixels)

Example

// Or apply some optional filters by passing a key value array of filters
$filters = [
    'username' => 'andy_brunner',
    'query'    => 'coffee',
    'w'        => 100,
    'h'        => 100
];
Unsplash\Photo::random($filters);

Unsplash\Photo::like()

Like a photo on the user's behalf.

Note: You need to instantiate a photo object first

Note: You need the like_photos permission scope

Arguments

N/A

Example

$photo = Unsplash\Photo::find(string $id);
$photo->like();

Unsplash\Photo::unlike()

Unlike a photo on the user's behalf.

Note: You need to instantiate a photo object first

Note: You need the like_photos permission scope

Arguments

N/A

Example

$photo = Unsplash\Photo::find(string $id);
$photo->unlike();

Unsplash\Photo::statistics(string $resolution, int $quantity)

Retrieve total number of downloads, views and likes of a single photo, as well as the historical breakdown of these stats in a specific timeframe (default is 30 days).

Note: You must instantiate a Photo object first

Arguments

Argument Type Opt/Required
resolution string Opt (Accepts only days currently)
quantity int Opt (Defaults to 30, can be between 1 and 30)

Example

$photo = Unsplash\Photo::find($id);
$photo->statistics('days', 7);

Unsplash\Photo::download()

Trigger a download for a photo. This is needed to follow the 'trigger a download' API Guideline.

Note: You must instantiate a Photo object first

Arguments

Argument Type Opt/Required

Example

$photo = Unsplash\Photo::find();
$photo->download();

User

Unsplash\User::find($username)

Retrieve a user's information.

Arguments

Argument Type Opt/Required
$username string Required

Example

Unsplash\User::find($username)

Unsplash\User::portfolio($username)

Retrieve a link to the user's portfolio page.

Arguments

Argument Type Opt/Required
$username string Required

Example

Unsplash\User::portfolio($username)

Unsplash\User::current()

Retrieve the user's private information.

Note: You need the read_user permission scope

Arguments

N/A

Example

$user = Unsplash\User::current();

Unsplash\User::photos($page, $per_page, $order_by)

Retrieve user's photos.

Note: You need to instantiate a user object first

Arguments

Argument Type Opt/Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)
$order_by string Opt (Default: latest / Available: oldest, popular)

Example

$user = Unsplash\User::find($username);
$user->photos($page, $per_page);

Unsplash\User::collections($page, $per_page)

Retrieve user's collections.

Note: You need to instantiate a user object first Note: You need the read_collections permission scope to retrieve user's private collections

Arguments

Argument Type Opt/Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)

Example

$user = Unsplash\User::find($username);
$user->collections($page, $per_page);

Unsplash\User::likes($page, $per_page, $order_by)

Retrieve user's collections.

Note: You need to instantiate a user object first

Arguments

Argument Type Opt/Required
$per_page int Opt (Default: 10 / Maximum: 30)
$page int Opt (Default: 1)
$order_by string Opt (Default: latest / Available: oldest, popular)

Example

$user = Unsplash\User::find($username);
$user->likes($page, $per_page, $order_by);

Unsplash\User::update([$key => value])

Update current user's fields. Multiple fields can be passed in the array.

Note: You need to instantiate a user object first

Note: You need the write_user permission scope.

Arguments

Argument Type Opt/Required Note
$key string Required The following keys are accepted: username, first_name, last_name, email, url, location, bio, instagram_username
$value mixed required
$user = Unsplash\User::current();
$user->update(['first_name' => 'Elliot', 'last_name' => 'Alderson']);

Unsplash\User::statistics(string $resolution, int $quantity)

Retrieve total number of downloads, views and likes for a user, as well as the historical breakdown of these stats in a specific timeframe (default is 30 days).

Note: You must instantiate the User object first

Arguments

Argument Type Opt/Required
resolution string Opt (Accepts only days currently)
quantity int Opt (Defaults to 30, can be between 1 and 30)

Example

$user = Unsplash\User::find($id);
$user->statistics('days', 7);

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/unsplash/unsplash-php. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

unsplash-php's People

Contributors

aaronklaassen avatar ams777 avatar anzoel avatar benmorel avatar dannyweeks avatar dechuck avatar dependabot[bot] avatar dioncodes avatar freezy-sk avatar harriescc avatar hughbertd avatar janhenckens avatar joshbmarshall avatar kevinbatdorf avatar lukechesser avatar petewalker avatar pvessel avatar seojtix avatar sirodiaz avatar spekulatius avatar tommienu avatar zembrowski 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unsplash-php's Issues

Issue with ArrayObject and private $parameters within Endpoint

Hello,

I'm creating an API layer using unsplash-php package and our CMS frontend / backend and found it impossible to return a json string.

I've got some issues trying to json_encode the ArrayObject object. I've tried using ArrayObject::getArrayCopy(); but it still returns Crew\Unsplash\Photo which is impossible to json_encode as the $parameters attribute is private.

Of course I could format the objects myself, but then I might run into issues later on trying to retrieve attributes that no longer exist, or new attributes.

I'd like to see some sort of toArray() method within ArrayObject which returns an array of Crew\Unsplash\EndPoint::$parameters values.

Would you like me to draft a PR?

Thanks in advance.

Are there any plans to add a proxy option to this?

Hi

Problems

My school has a proxy server, and when I try to use this library there, I get the following error.

PHP Fatal error:  Uncaught GuzzleHttp\\Exception\\ConnectException: cURL error 28: Failed to connect to api.unsplash.com port 443: Connection timed out (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.unsplash.com/photos/random?query=snow&w=600&h=400

In the .bashrc, I have written http_proxy and https_proxy, and when I access the API with cURL in the CLI, I can access it successfully.

Solved method

I was able to solve this problem by adding a proxy option to __construct() in HttpClient.php, referring to the Guzzle document.

$this->httpClient = new Client(['handler' => $this->setHandler(self::$connection->getAuthorizationToken()), 'proxy' => 'http://hostname:port');

I don't know much about PHP, so I can't modify the code and submit a pull request.
I would like to know if there is a way to add a proxy option to this library or any other way to solve this problem.
I'm sorry for my poor English.

Development Environment

  • Ubuntu Server 20.04
  • PHP 7.4
  • Apache 2.4

Add test coverage badge

Setup codeship to run tests automatically when pushed and add the codeship badge to the README.

Add documentation for Search::X methods

Since Crew\Unsplash\Photo::search is deprecated, we need to add documentation for the Search methods:

Search::photos()
Search::collections()
Search::users()

Doubt in the Endpoint class

Should the parameter attribute in the class Endpoint be private anyway? If yes, which method returns the list of photos?

fresh up the doc

If you use magic methods in your "Endpoint" class, please add some info about which parameters are available.

thank you.

Download endpoint not called async

In the medium post I read:

We’ve found that it’s best to trigger the endpoint asynchronously to make sure that it doesn’t slow down your user’s interactions.

However the download endpoint is not async. See: https://github.com/unsplash/unsplash-php/blob/master/src/Photo.php#L204. In fact: it has a return value. Thus if I would add this call; this would now indeed slow down the user experience a little bit.

Is the behaviour in this repo intended? I would suggest introducing a new method asyncDownload that does precisely that. We could use Guzzle's async mechanism: http://docs.guzzlephp.org/en/stable/faq.html#can-guzzle-send-asynchronous-requests.

Having installation problem with composer because of guzzlehttp/guzzle version

Here is the output

Problem 1
- Installation request for crewlabs/unsplash ^2.0 -> satisfiable by crewlabs/unsplash[2.0.0].
- Conclusion: remove guzzlehttp/guzzle 6.2.0
- Conclusion: don't install guzzlehttp/guzzle 6.2.0
- crewlabs/unsplash 2.0.0 requires guzzlehttp/guzzle ~6.1.0 -> satisfiable by guzzlehttp/guzzle[6.1.0, 6.1.1].
- Can only install one of: guzzlehttp/guzzle[6.1.0, 6.2.0].
- Can only install one of: guzzlehttp/guzzle[6.1.1, 6.2.0].
- Installation request for guzzlehttp/guzzle (locked at 6.2.0) -> satisfiable by guzzlehttp/guzzle[6.2.0].

Installation failed, reverting ./composer.json to its original content.

Search results different from the website

Hello,

We're having some issues with the search result for specific keywords. When queried for "digital marketing", for example, the returned images are completely different from the website result or the keywords context.
I've tried to replace its space for "-", "+", "_", but the result set was the same.

Is there any parameter that I can send to get the result set like if I was searching in the website?

Thanks

Improve test coverage

Some functions are not tested properly.

  • User::update (due to an issue with VCR)
  • Photo::create
  • AuthorizationUrl with scopes

Fix test in codeship

Even if my cassette are present, codeship seems to want to do the request.

If I'm change my testing variable that set the api url from api.lvh.me to api.staging.unsplash.com my test seems to work, but codeship run the API call on his side, since the request uri change.

Error message missing

Hey there

From time to time we are getting bad responses when doing

\Crew\Unsplash\Search::photos('life', 1, 20);

And we are getting status code out of this range

return $response->getstatusCode() >= 200 && $response->getstatusCode() < 300;

so we are getting an exception, but when we log it, we see the following

Crew\Unsplash\Exception: [] in /app/vendor/crewlabs/unsplash/src/Endpoint.php:87

Seems like the error message is missing and we don't know which part we are doing wrong, any idea why empty message ?

The path of a URI with an authority must start with a slash "/" or be empty

Hi, I got InvalidArgumentException in Uri.php line 693:
The path of a URI with an authority must start with a slash "/" or be empty

This is my code:

        \Crew\Unsplash\HttpClient::init([
            'applicationId' => 'appId'
        ]);

        $photos = \Crew\Unsplash\Photo::all();

        var_dump($photos);

This is composer.json:

    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.3.*",
        "crewlabs/unsplash": "^2.2",
        "guzzlehttp/guzzle": "^6.2"
    },

PHP -v:
PHP 7.0.9 (cli) (built: Aug 26 2016 06:17:04) ( NTS )

And the error stack:

in Uri.php line 693
at Uri->validateState() in Uri.php line 471
at Uri->withHost('api.unsplash.com') in HttpClient.php line 140
at HttpClient->Crew\Unsplash\{closure}(object(Request)) in Middleware.php line 233
at Middleware::GuzzleHttp\{closure}(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Middleware.php line 233
at Middleware::GuzzleHttp\{closure}(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in HandlerStack.php line 67
at HandlerStack->__invoke(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Client.php line 275
at Client->transfer(object(Request), array('synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false)) in Client.php line 96
at Client->sendAsync(object(Request), array('query' => array('page' => '1', 'per_page' => '10'), 'synchronous' => true, 'handler' => object(HandlerStack), 'allow_redirects' => array('max' => '5', 'protocols' => array('http', 'https'), 'strict' => false, 'referer' => false, 'track_redirects' => false), 'http_errors' => true, 'decode_content' => true, 'verify' => true, 'cookies' => false, '_conditional' => array('User-Agent' => 'GuzzleHttp/6.2.1 curl/7.45.0 PHP/7.0.9'))) in Client.php line 104
at Client->send(object(Request), array('query' => array('page' => '1', 'per_page' => '10'), 'synchronous' => true)) in HttpClient.php line 111
at HttpClient->send('get', array('photos', array('query' => array('page' => '1', 'per_page' => '10')))) in Endpoint.php line 74
at Endpoint::__callStatic('get', array('photos', array('query' => array('page' => '1', 'per_page' => '10')))) in Photo.php line 32
at Photo::all() in UtilController.php line 23
at UtilController->getFreeImages(object(Request))

Is my implementation wrong?

How to get photo API url by its download name?

Sorry if I am posting in a wrong git but cant seem to find a place to ask this.
It is a great API but a huge thing has been missed by the devs.
When you click on download image you get the image with a name that is mixed with user real name and some ID ,

for example if you go here https://unsplash.com/photos/pTgMXg2WrHY
and click on download

you get image by name nathan-anderson-268995.jpg

now you dont have one reference in that image name that you could use with the API.
No image ID , no actual username, nothing.

We developed a WP theme with actual download names , now we are exporting a demo and would like to bulk replace image names URL with a API url. No way we can do that now unless we go back , change all image names with image id from the URL.

Photo::search using deprecated endpoint

I'm seeing a warning that says:

The photo search endpoint is deprecated. Use the new search endpoint instead. See: https://unsplash.com/documentation#search

Still getting results though.

league/oauth2-client ~1.0

Dear Crew-Team,

when is league/oauth2-client ~1.0 support planned?

I've got another composer package that requires league/oauth2-client in ~1.0 version and both 0.12 and ~1.0 can't be installed at the same time.

I started to define the missing abstract functions which was not difficult, but get stuck with the following error: Cannot access protected property Crew\Unsplash\Provider::$clientId in /vendor/crewlabs/unsplash/src/Connection.php on line 94

Would appreciate an answer.

Thanks in advance.

Best regards,
Krzysztof

Send UTM params

@lukechesser @HughbertD

These days the API terms have this requirement: https://community.unsplash.com/developersblog/unsplash-api-terms-explained#block-yui_3_17_2_1_1490972762425_202608

But without being able to send arbitrary query params via the lib, clients can't do that. Since it should be attached to every request anyway, maybe the best way to do this is to make the utm_source value part of the lib config, and everything just gets attached automatically. i.e.,

Crew\Unsplash\HttpClient::init([
	'applicationId'	=> 'YOUR APPLICATION ID',
        'secret'        => 'YOUR APPLICATION SECRET',
	'callbackUrl'	=> 'https://your-application.com/oauth/callback',
        'utmSource'     => 'my sweet app'
]);

or whatever.

For backwards compatibility, I'd log a warning if that value is missing from the config, but not fail outright.

New to composer install - having problems

1st time doing a composer install. Shared hosting environment. I got the following message and cruising forums about composer installs and modifying composer.json didn't really help me - probably because I'm a newbie. So with the following message what should I do next?

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package crewlabs/unsplash No version set (parsed as 1.0.0) is satisfiable by crewlabs/unsplash[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.

Wrong rate limit values

Hi, I'm getting some odd values when checking my rate limits in PHP.
bildschirmfoto 2017-01-09 um 10 44 38

These are the functions I am using:

public function rateLimitTotal()
    {
        $limit = 50;
        if (!empty($this->headers[self::X_Ratelimit_Limit]) && is_array($this->headers[self::X_Ratelimit_Limit])) {
            $limit = (int) $this->headers[self::X_Ratelimit_Limit][0];
        }

        return $limit;
    }
    public function rateLimitRemaining()
    {
        $limit = 0;
        if (!empty($this->headers[self::X_Ratelimit_Remaining]) && is_array($this->headers[self::X_Ratelimit_Remaining])) {
            $limit = (int) $this->headers[self::X_Ratelimit_Remaining][0];
        }

        return $limit;
    }

Any idea on what's going wrong?

Collection Retrieve Photos

$collection = Crew\Unsplash\Collection::find(integer $id);
$photos = $collection->photos($page, $per_page);

The retrieve photos of a collection returns an ArrayObject. Please make it to return a PageResult as you have at Search::photos as an example

2.4 requires packages of state dev-master

The first problem is that I cannot update without changing the minimum stability.

The second problem is that every download of this repo will potentially result in a different version of that dev-master library. That is because libraries do not utilize a lock-file.

Error breakdown on my project:

$ composer update crewlabs/unsplash
Loading composer repositories with package information
Updating dependencies (including require-dev)                                  
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for crewlabs/unsplash ^2.4 -> satisfiable by crewlabs/unsplash[2.4.0].
    - crewlabs/unsplash 2.4.0 requires hughbertd/oauth2-unsplash dev-master -> satisfiable by hughbertd/oauth2-unsplash[dev-master] but these conflict with your requirements or minimum-stability.

I'll stick on 2.3 for now :). Thanks for the lib!

Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.

When i'm trying to use oath authentication I keep getting this error.
I have really no clue what is going wrong.

Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.

I'm using the script mentioned in the example folder. Specified:

require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
session_start();
// Landing on the page for the first time, setup connection with private application details registered with unsplash and redirect user to authenticate
if (!isset($_GET['code']) && !isset($_SESSION['token'])) {
    \Crew\Unsplash\HttpClient::init([
        'applicationId'	=> 'XXXXX',
        'secret'		=> 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'callbackUrl'	=> 'http://unsplash-api.dev'
    ]);
    $httpClient = new \Crew\Unsplash\HttpClient();
    $scopes = ['write_user', 'public'];
    //echo $httpClient::$connection->getConnectionUrl($scopes);
    header("Location: ". $httpClient::$connection->getConnectionUrl($scopes));
    exit;
}

// Unsplash sends user back with ?code=XXX, use this code to generate AccessToken
if (isset($_GET['code']) && !isset($_SESSION['token'])) {
    \Crew\Unsplash\HttpClient::init([
        'applicationId' => 'XXXXX',
        'secret'        => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'callbackUrl'   => 'http://unsplash-api.dev'
    ]);

    try {
        $token = \Crew\Unsplash\HttpClient::$connection->generateToken($_GET['code']);
    } catch (Exception $e) {
        print("Failed to generate access token: {$e->getMessage()}");
        exit;
    }

    // Store the access token, use this for future requests
    $_SESSION['token'] = $token;
}

// Send requests to Unsplash
\Crew\Unsplash\HttpClient::init([
        'applicationId' => 'XXXXX',
        'secret'        => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'callbackUrl'   => 'http://unsplash-api.dev'
], [
    'access_token' => $_SESSION['token']->getToken(),
    'expires_in' => 30000,
    'refresh_token' => $_SESSION['token']->getRefreshToken()
]);

$httpClient = new \Crew\Unsplash\HttpClient();
$owner = $httpClient::$connection->getResourceOwner();

print("Hello {$owner->getName()}, you have authenticated successfully");

Is Crew\Unsplash\Photo::create($file_path) still supported?

I'm trying to upload an image from my laravel app! But I get the following error:

OAuth error: missing permissions 403

I have set 'write_photos'! So, probably I have the permissions!
I can use the others endpoints! This is the only one I can't!

Bad error message when photo ID is missing

If you do the following code:

$photo = \Crew\Unsplash\Photo::find(null);
$download_url = $photo->download();

This is of course a bad ID argument for the find() method but I did this by mistake and it took a while before I realized the issue because the only error message I got was this:

EXCEPTION

[]

File: .../vendor/crewlabs/unsplash/src/Endpoint.php
Line: 87
#0 .../vendor/crewlabs/unsplash/src/Photo.php(208): Crew\Unsplash\Endpoint::__callStatic('get', Array)
#1 .../models/Unsplash.php(88): Crew\Unsplash\Photo->download()

Would be nice if this could be caught and notified clearly.

Everything is Private

After authenticating and running Unsplash\Photo::all(1, 30) it returns an ArrayObject in which everything is private. Can't access any of the properties.

Crew\Unsplash\Exception with error message: []

Hi, I'm (still) getting a lot of Exceptions with an empty error message from the api. I've already had over 130 of these errors this month. Here is the error information I get:

2017-01-09 21:50:05.402  :  Error caller: functions at line 1212
2017-01-09 21:50:05.402  :  Error class: Crew\Unsplash\Exception
2017-01-09 21:50:05.402  :  Error message: []
2017-01-09 21:50:05.402  :  In: /path/php/vendor/crewlabs/unsplash/src/Endpoint.php(78)
2017-01-09 21:50:05.402  :  Stack trace:
2017-01-09 21:50:05.402  :  #0 /path/php/vendor/crewlabs/unsplash/src/User.php(19): Crew\Unsplash\Endpoint::__callStatic('get', Array)
2017-01-09 21:50:05.402  :  #1 /path/php/functions.php(1205): Crew\Unsplash\User::find('zimsurfa')
2017-01-09 21:50:05.402  :  #2 /path/php/get-liked.php(317): getUnsplashPhotoInfo('liked', '1', 25, 'oldest', 'zimsurfa')
2017-01-09 21:50:05.402  :  #3 {main}

I'm using a modified $user->likes function that allows me to use the 'order_by' parameter:

public function likes($page = 1, $per_page = 10, $order_by = 'latest')
    {
        if (! isset($this->likes["{$page}-{$per_page}-{$order_by}"])) {
            $likes = self::get("users/{$this->username}/likes", ['query' => ['page' => $page, 'per_page' => $per_page, 'order_by' => $order_by]]);

            $this->likes["{$page}-{$per_page}-{$order_by}"] = [
                'body' => self::getArray($likes->getBody(), __NAMESPACE__.'\\Photo'),
                'headers' => $likes->getHeaders()
            ];
        }

        return new ArrayObject(
            $this->likes["{$page}-{$per_page}-{$order_by}"]['body'],
            $this->likes["{$page}-{$per_page}-{$order_by}"]['headers']
        );
    }

And here is the function that is using this modified $user->likes function:

function getUnsplashPhotoInfo($syncmode,$page,$per_page='1',$order_by='latest',$username='') {
  if ($syncmode == 'featured') {
    UnsplashInit();
    try {
      $collectionData = Unsplash\CuratedCollection::find($page);
      $requestData = $collectionData->photos(1,1);
    } catch (Unsplash\Exception $e) {
      writeErrorLogEntry(basename(__FILE__,'.php'),__LINE__,$e);
    }
  } else if ($syncmode == 'liked') {
    UnsplashInit();
    try {
      $userData = Unsplash\User::find($username);
      $requestData = $userData->likes($page,$per_page,$order_by);
    } catch (Unsplash\Exception $e) {
      if ($e->getMessage() == '["Couldn\'t find User"]') {
        setErrUnsplashuser($username);
      }
      writeErrorLogEntry(basename(__FILE__,'.php'),__LINE__,$e);
    }
  }
  // Build photos array with required info
  foreach ($requestData as $photo) {
      $photos[] = array(
        'id' => $photo->id,
        'url' => $photo->urls['full'],
        'username' => strtolower($photo->user['username'])
      );
  }
  // Add filename to photos array
  foreach ($photos as $key => $value) {
    $photos[$key]['filename'] = buildUnsplashFilename($value);
  }
  if (!empty_array($photos)) {
    return $photos;
  } else {
    return false;
  }
}

The last piece of the puzzle is establishing the connection to the API:

function UnsplashInit($app_id) {
  if ($app_id !== false) {
    try {
      Unsplash\HttpClient::init(['applicationId' => $app_id]);
    } catch (Unsplash\Exception $e) {
      writeErrorLogEntry(basename(__FILE__,'.php'),__LINE__,$e);
    }
  }
}

I've tested this code on multiple servers, different versions of PHP and in different variants. Any idea on what is causing this issue and how to fix it?

Edit no. 1: The error log shows the $page being passed as a string ('1'). I've fixed that, but I'm still getting the error.

Edit no. 2: I ran a test with a simple GET request via Guzzle in order to find out whether this is a problem with the PHP client or the API itself. Looks like it is the client: not a single error in 8+ hours.

$client = new Client();
  $res = $client->request('GET', $api_url.'/users/'.$users[$choice].'/likes', [
    'headers' => ['Authorization'      => 'Client-ID '.$app_id],
    'query' => ['page' => 1, 'per_page' => 30, 'order_by' => 'oldest']
  ]);
$status = $res->getStatusCode();
$photos = json_decode($res->getBody(),true);

Curl Error 35

When searching for some photos using
$photos = \Crew\Unsplash\Search::photos('Love', 1, 30);
i receive following error on my local mamp server:

Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 35: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /Users/julian-weiland/instabot/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:186 Stack trace: #0 /Users/julian-weiland/instabot/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 /Users/julian-weiland/instabot/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 /Users/julian-weiland/instabot/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #3 /Users/julian-weiland/ins in /Users/julian-weiland/instabot/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 186

Search options missing from /search/photos

Now that /photos/search has been deprecated in favour of /search/photos, I was wondering if there are any plans on adding the existing parameters to the new endpoint. (in particular the orientation and category options)

Thanks
(Already working on a PR to add the new search endpoint to this library so wanted to ask before I submit the PR)

PHP 5.4

Hi
Are you planning to use some features introduced in PHP 5.5?
If not, what about lowering required version from "php": ">=5.5.0" to "php": ">=5.4.0" ?

Cannot search only within collection

I'm trying to figure out how to search my personal collection for images, and only return results within my collection. However, I keep getting images that I definitely don't have within my collection. My collection ID is _3ibhbq0WTE.

image

How to find the information for the attribution

Hi!

I'm not sure if I'm missing something, but I'm not able to find the information of the photographer for the attribution.

WHen getting a random photo, I call photo->download() and with that I get a download link. Thats fine. When calling photo->photographer(), the only information insider is the username.

I used the username to retrieve the User object, but again, inside there is not information for the attribution (Firstname, Lastname).

What I'm doing wrong?

Thanks.

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.