This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1 @@
/example export-ignore

3
vendor/angelfqc/vimeo-api/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
composer.lock
reports/
vendor/

19
vendor/angelfqc/vimeo-api/.styleci.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
preset: psr2
enabled:
- combine_consecutive_unsets
- newline_after_open_tag
- no_php4_constructor
- no_useless_else
- ordered_class_elements
- ordered_use
- strict
- strict_param
- php_unit_construct
- php_unit_strict
finder:
exclude:
- 'example'
name:
- '*.php'

27
vendor/angelfqc/vimeo-api/.travis.yml vendored Normal file
View File

@@ -0,0 +1,27 @@
language: php
php:
- '5.4'
- '5.5'
- '5.6'
- '7.0'
- '7.1'
- '7.2'
matrix:
include:
- php: 5.3
dist: precise
cache:
directories:
- ./vendor
install:
- composer install
script:
- vendor/bin/phpunit --coverage-clover build/logs/clover.xml
after_success:
- travis_retry vendor/bin/coveralls -v

106
vendor/angelfqc/vimeo-api/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,106 @@
# Changelog
## [2.0.5] - 2018-04-27
### Changed
- Updating the user agent version string to match the library version.
## [2.0.4] - 2018-04-24
### Added
- Support for passing your own `Authorization` header on API requests. ([#166](https://github.com/vimeo/vimeo.php/pull/166))
## [2.0.3] - 2018-04-02
### Changed
- Uploads no longer make a pre-emptive request to check the user's quota. This check is done automatically when making a POST to `/me/videos`. ([#163](https://github.com/vimeo/vimeo.php/pull/163))
## [2.0.2] - 2018-03-20
### Added
- Support for passing API requests through a custom proxy. ([#161](https://github.com/vimeo/vimeo.php/pull/161), [@MichalMMac](https://github.com/MichalMMac))
## [2.0.1] - 2018-03-07
### Added
- Initializing a unit test environment. ([#143](https://github.com/vimeo/vimeo.php/pull/143), [@peter279k](https://github.com/peter279k))
- Support for making `HEAD` requests. ([#160](https://github.com/vimeo/vimeo.php/pull/160))
## [2.0.0] - 2018-02-06
### Changed
- Moving API requests over to use API v3.4. ([#144](https://github.com/vimeo/vimeo.php/pull/144))
- Moving uploads over to using the new tus protocol. ([#144](https://github.com/vimeo/vimeo.php/pull/144))
## [1.3.0] - 2017-10-25
### Changed
- Deprecating the `upgrade_to_1080` option on video uploads. ([#140](https://github.com/vimeo/vimeo.php/pull/140))
## [1.2.7] - 2017-10-04
### Added
- Support for supplying custom HTTP headers. ([#136](https://github.com/vimeo/vimeo.php/pull/136), [@davekiss](https://github.com/davekiss))
### Fixed
- Updated some bad PHPDoc comments on the upload methods. ([#129](https://github.com/vimeo/vimeo.php/pull/129), [@hluup](https://github.com/hluup))
### Changed
- PSR-2 code style. ([#117](https://github.com/vimeo/vimeo.php/pull/117), [@peter279k](https://github.com/peter279k))
## [1.2.6] - 2016-12-02
### Fixed
- Updating the user agent so it matches the current release.
## [1.2.5] - 2016-10-13
### Fixed
- Some namespace gremlins. ([#112](https://github.com/vimeo/vimeo.php/pull/112), [@Spudley](https://github.com/Spudley))
## [1.2.4] - 2016-09-13
### Added
- Changelog (@vinkla)
- Added a new search example. ([@greedo](https://github.com/greedo))
- Support for lowercase HTTP verbs. ([#108](https://github.com/vimeo/vimeo.php/issues/108))
### Changed
- Updated some examples to match the new example format.
### Fixed
- Fixed some bad documentation in the README.
- Fixed a bad VOD example. ([#76](https://github.com/vimeo/vimeo.php/issues/76))
- Correctly handing headers when parsing them. ([#110](https://github.com/vimeo/vimeo.php/pull/110), [@qzminski](https://github.com/qzminski))
## [1.2.3] - 2015-06-02
### Added
- Handling timeouts for large files.
## [1.2.2] - 2015-05-11
### Fixed
- Reinstating the upload request. ([#72](https://github.com/vimeo/vimeo.php/pull/72))
## [1.2.1] - 2015-05-07
### Changed
- Move from pem to cer
## [1.2.0] - 2015-05-01
### Changed
- Better error messages when uploading ([#66](https://github.com/vimeo/vimeo.php/pull/66))
- Better error messages when curl errors ([#68](https://github.com/vimeo/vimeo.php/pull/68))
- Root cert is included to help with curl errors ([#69](https://github.com/vimeo/vimeo.php/pull/69))
## [1.1.0] - 2014-10-23
### Added
- Added composer support ([#6](https://github.com/vimeo/vimeo.php/pull/6))
## 1.0.0 - 2014-09-26
### Added
- This is the Vimeo library for version 3 of the Vimeo API.
[2.0.5]: https://github.com/vimeo/vimeo.php/compare/2.0.4...2.0.5
[2.0.4]: https://github.com/vimeo/vimeo.php/compare/2.0.3...2.0.4
[2.0.3]: https://github.com/vimeo/vimeo.php/compare/2.0.2...2.0.3
[2.0.2]: https://github.com/vimeo/vimeo.php/compare/2.0.1...2.0.2
[2.0.1]: https://github.com/vimeo/vimeo.php/compare/2.0.0...2.0.1
[2.0.0]: https://github.com/vimeo/vimeo.php/compare/1.3.0...2.0.0
[1.3.0]: https://github.com/vimeo/vimeo.php/compare/1.2.7...1.3.0
[1.2.7]: https://github.com/vimeo/vimeo.php/compare/1.2.6...1.2.7
[1.2.6]: https://github.com/vimeo/vimeo.php/compare/1.2.5...1.2.6
[1.2.4]: https://github.com/vimeo/vimeo.php/compare/1.2.5...1.2.6
[1.2.5]: https://github.com/vimeo/vimeo.php/compare/1.2.4...1.2.5
[1.2.4]: https://github.com/vimeo/vimeo.php/compare/1.2.3...1.2.4
[1.2.3]: https://github.com/vimeo/vimeo.php/compare/1.2.2...1.2.3
[1.2.2]: https://github.com/vimeo/vimeo.php/compare/1.2.1...1.2.2
[1.2.1]: https://github.com/vimeo/vimeo.php/compare/1.2.0...1.2.1
[1.2.0]: https://github.com/vimeo/vimeo.php/compare/1.1.0...1.2.0
[1.1.0]: https://github.com/vimeo/vimeo.php/compare/1.0.0...1.1.0

View File

@@ -0,0 +1,28 @@
Contributing
===
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/vimeo/vimeo.php).
## Pull Requests
- We try to follow the **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)**.
- **Document any change in behaviour** - Make sure the `README.md`, [wiki](https://github.com/vimeo/vimeo.php/wiki), and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
## Running Tests
```bash
$ composer test
```
**Happy coding**!

177
vendor/angelfqc/vimeo-api/LICENSE vendored Normal file
View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

255
vendor/angelfqc/vimeo-api/README.md vendored Normal file
View File

@@ -0,0 +1,255 @@
# <img src="https://user-images.githubusercontent.com/33762/33720344-abc20bb8-db31-11e7-8362-59a4985aeff0.png" width="250" />
[![Packagist](https://img.shields.io/packagist/v/vimeo/vimeo-api.svg?style=flat-square)](https://packagist.org/packages/vimeo/vimeo-api)
[![License](https://img.shields.io/packagist/l/vimeo/vimeo-api.svg?style=flat-square)](https://packagist.org/packages/vimeo/vimeo-api)
[![Travis CI](https://img.shields.io/travis/vimeo/vimeo.php.svg?style=flat-square)](https://travis-ci.org/vimeo/vimeo.php)
[![StyleCI](https://styleci.io/repos/9654006/shield?style=flat-square)](https://styleci.io/repos/9654006/)
This is a simple PHP library for interacting with the [Vimeo API](https://developers.vimeo.com).
- [Get Started](#get-started-with-the-vimeo-api)
- [Help](#direct-help)
- [Troubleshooting](#troubleshooting)
- [Installation](#installation)
- [Usage](#usage)
- [Authentication and access tokens](#generate-your-access-token)
- [Unauthenticated tokens](#unauthenticated)
- [Authenticated tokens](#authenticated)
- [Make requests](#make-requests)
- [Uploading videos](#uploading-videos)
- [Upload videos from a server](#upload-videos-from-the-server)
- [Replace videos from a server](#replace-videos-from-the-server)
- [Client side uploads](#upload-or-replace-videos-from-the-client)
- [Upload videos from a URL](#upload-videos-from-a-url)
- [Upload images](#upload-images)
- [Framework integrations](#framework-integrations)
## Get started with the Vimeo API
There is a lot of information about the Vimeo API at <https://developer.vimeo.com/api/start>. Most of your questions are answered there!
## Direct Help
* [Stack Overflow](http://stackoverflow.com/questions/tagged/vimeo-api)
* [Vimeo Support](https://vimeo.com/help/contact)
#### NOTE: How to use the PHP library with Vimeo dot notation documentation.
The API docs often uses dot notation to represent a hierarchy of data, like this: `privacy.view`. Because this library sends all data using JSON, you must use nested associative arrays, not dot notation.
```php
// The documentation refers to the following as `privacy.view`
$params = ['privacy' => ['view' => 'disable']];
```
## Installation
### Composer
1. Require this package, with [Composer](https://getcomposer.org/), in the root directory of your project.
```bash
composer require vimeo/vimeo-api
```
2. Use the library `$lib = new \Vimeo\Vimeo($client_id, $client_secret)`.
### Manual
1. Download the latest release: [v2.0.3](https://github.com/vimeo/vimeo.php/archive/2.0.3.zip).
2. Include the autoloader `require("/path/to/vimeo.php/autoload.php");`.
3. Use the library `$lib = new \Vimeo\Vimeo($client_id, $client_secret)`.
## Usage
### Generate your access token
All requests require access tokens. There are two types of access tokens:
- [Unauthenticated](#unauthenticated) - Access tokens without a user. These tokens can view only public data.
- [Authenticated](#authenticated) - Access tokens with a user. These tokens interact on behalf of the authenticated user.
#### Unauthenticated
Unauthenticated API requests must generate an access token. You should not generate a new access token for each request. Instead, request an access token once and use it forever.
```php
// `scope` is an array of permissions your token needs to access.
// You can read more at https://developer.vimeo.com/api/authentication#supported-scopes
$token = $lib->clientCredentials(scope);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
```
#### Authenticated
1. Build a link to Vimeo so your users can authorize your app.
```php
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state)
```
Name | Type | Description
---------------|----------|------------
`redirect_uri` | string | The URI the user is redirected to in Step 3. This value must be provided to every step of the authorization process, including creating your app, building your authorization endpoint, and exchanging your authorization code for an access token.
`scope` | array | An array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#supported-scopes.
`state` | string | A value unique to this authorization request. You should generate it randomly and validate it in Step 3.
2. Your user needs to access the authorization endpoint (either by clicking the link or through a redirect). On the authorization endpoint, the user will have the option to deny your app any scopes you have requested. If they deny your app, they are redirected back to your `redirect_url` with an `error` parameter.
3. If the user accepts your app, they are redirected back to your `redirect_uri` with a `code` and `state` query parameter (eg. http://yourredirect.com?code=abc&state=xyz).
1. You must validate that the `state` matches your state from Step 1.
2. If the state is valid, you can exchange your code and `redirect_uri` for an access token.
```php
// `redirect_uri` must be provided, and must match your configured URI
$token = $lib->accessToken(code, redirect_uri);
// Usable access token
var_dump($token['body']['access_token']);
// Accepted scopes
var_dump($token['body']['scope']);
// Set the token
$lib->setToken($token['body']['access_token']);
```
For additional information, check out the [example](https://github.com/vimeo/vimeo.php/blob/master/example/auth.php).
### Make requests
The API library has a `request` method that takes three parameters. It returns an associative array containing all of the relevant request information.
#### Usage
Name | Type | Description
----------|----------|------------
`url` | string | The URL path (e.g.: `/users/dashron`).
`params` | string | An object containing all of your parameters (e.g.: `{ "per_page": 5, "filter" : "featured"}` ).
`method` | string | The HTTP method (e.g.: `GET`).
```php
$response = $lib->request('/me/videos', ['per_page' => 2], 'GET');
```
#### Response
The response array contains three keys.
Name | Type | Description
-----------|--------|------------
`body` | array | The parsed request body. All responses are JSON, so we parse this for you and give you the result.
`status` | number | The HTTP status code of the response. This partially informs you about the success of your API request.
`headers` | array | An associative array containing all of the response headers.
```php
$response = $lib->request('/me/videos', ['per_page' => 2], 'GET');
var_dump($response['body']);
```
### Uploading videos
#### Upload videos from the server
To upload videos, you must call the `upload` method. It accepts two parameters. It returns the URI of the new video.
Internally, this library executes a `tus` upload approach and sends a file to the server with the [tus](https://tus.io/) upload protocol.
For more information, check out the [example](https://github.com/vimeo/vimeo.php/blob/master/example/upload.php)
Name | Type | Description
---------|---------|------------
`file` | string | Full path to the upload file on the local system.
`params` | array | Parameters to send when creating a new video (name, privacy restrictions, etc.). See the [`/me/videos` documentation](https://developer.vimeo.com/api/endpoints/videos#POST/users/{user_id}/videos) for supported parameters.
```php
$response = $lib->upload('/home/aaron/Downloads/ada.mp4')
// With parameters.
$response = $lib->upload('/home/aaron/Downloads/ada.mp4', [
'name' => 'Ada',
'privacy' => [
'view' => 'anybody'
]
])
```
#### Replace videos from the server
To replace the source file of a video, you must call the `replace` method. It accepts two parameters. It returns the URI of the replaced video.
Name | Type | Description
------------|----------|------------
`video_uri` | string | The URI of the original video. Once uploaded and successfully transcoded, your source video file is swapped with this new video file.
`file` | string | Full path to the upload file on the local system.
```php
$response = $lib->replace('/videos/12345', '/home/aaron/Downloads/ada-v2.mp4')
```
#### Upload or replace videos from the client
To upload from the client, you must mix some server-side and client-side API requests. We support two workflows, the first of which is much easier than the second.
##### Simple POST uploads
This workflow is well documented on Vimeo's developer site. You can read more here: <https://developer.vimeo.com/api/upload/videos#simple-upload>.
##### Streaming uploads
Streaming uploads support progress bars and resumable uploading. If you want to perform these uploads client-side, you need to start with some server-side requests.
Read through the [Vimeo documentation](https://developer.vimeo.com/api/upload/videos#resumable-upload) first. Steps 1 and 4 should be performed on the server, while Steps 2 and 3 can be performed on the client. With this workflow, the video is never transferred to your servers.
#### Upload videos from a URL
Uploading videos from a public URL (also called "pull uploads") uses a single, simple API call.
```php
$video_response = $lib->request(
'/me/videos',
[
'upload' => [
'approach' => 'pull',
'link' => $url
],
],
'POST'
);
```
### Upload images
To upload an image, call the `uploadImage` method. It takes three parameters.
For more information check out the [example](https://github.com/vimeo/vimeo.php/blob/master/example/upload_image.php).
Name | Type | Description
---------------|----------|------------
`pictures_uri` | string | The URI to the pictures collection for a single resource, such as `/videos/12345/pictures`. You can always find this in the resource representation.
`file` | string | Full path to the upload file on the local system.
`activate` | boolean | (Optional) Defaults to `false`. If true, this picture will become the default picture for the associated resource.
```php
$response = $lib->uploadImage('/videos/12345/pictures', '/home/aaron/Downloads/ada.png', true)
```
## Troubleshooting
If you have any questions or problems, create a [ticket](https://github.com/vimeo/vimeo.php/issues) or [contact us](https://vimeo.com/help/contact).
## Framework integrations
- **WordPress** - <http://vimeography.com/>
- **Laravel** - <https://github.com/vimeo/laravel>
If you have integrated Vimeo into a popular PHP framework, let us know!
## Contributors
To see the contributors, please visit the [contributors graph](https://github.com/vimeo/vimeo.php/graphs/contributors).

29
vendor/angelfqc/vimeo-api/autoload.php vendored Normal file
View File

@@ -0,0 +1,29 @@
<?php
/**
* Copyright 2014 Vimeo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
spl_autoload_register(function ($class) {
// Make sure that the class being loaded is in the vimeo namespace
if (substr(strtolower($class), 0, 6) !== 'vimeo\\') {
return;
}
// Locate and load the file that contains the class
$path = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($path)) {
require($path);
}
});

View File

@@ -0,0 +1,47 @@
-----BEGIN CERTIFICATE-----
MIIElDCCA3ygAwIBAgIQAf2j627KdciIQ4tyS8+8kTANBgkqhkiG9w0BAQsFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0xMzAzMDgxMjAwMDBaFw0yMzAzMDgxMjAwMDBaME0xCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxJzAlBgNVBAMTHkRpZ2lDZXJ0IFNIQTIg
U2VjdXJlIFNlcnZlciBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
ANyuWJBNwcQwFZA1W248ghX1LFy949v/cUP6ZCWA1O4Yok3wZtAKc24RmDYXZK83
nf36QYSvx6+M/hpzTc8zl5CilodTgyu5pnVILR1WN3vaMTIa16yrBvSqXUu3R0bd
KpPDkC55gIDvEwRqFDu1m5K+wgdlTvza/P96rtxcflUxDOg5B6TXvi/TC2rSsd9f
/ld0Uzs1gN2ujkSYs58O09rg1/RrKatEp0tYhG2SS4HD2nOLEpdIkARFdRrdNzGX
kujNVA075ME/OV4uuPNcfhCOhkEAjUVmR7ChZc6gqikJTvOX6+guqw9ypzAO+sf0
/RR3w6RbKFfCs/mC/bdFWJsCAwEAAaOCAVowggFWMBIGA1UdEwEB/wQIMAYBAf8C
AQAwDgYDVR0PAQH/BAQDAgGGMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYY
aHR0cDovL29jc3AuZGlnaWNlcnQuY29tMHsGA1UdHwR0MHIwN6A1oDOGMWh0dHA6
Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEdsb2JhbFJvb3RDQS5jcmwwN6A1
oDOGMWh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEdsb2JhbFJvb3RD
QS5jcmwwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8v
d3d3LmRpZ2ljZXJ0LmNvbS9DUFMwHQYDVR0OBBYEFA+AYRyCMWHVLyjnjUY4tCzh
xtniMB8GA1UdIwQYMBaAFAPeUDVW0Uy7ZvCj4hsbw5eyPdFVMA0GCSqGSIb3DQEB
CwUAA4IBAQAjPt9L0jFCpbZ+QlwaRMxp0Wi0XUvgBCFsS+JtzLHgl4+mUwnNqipl
5TlPHoOlblyYoiQm5vuh7ZPHLgLGTUq/sELfeNqzqPlt/yGFUzZgTHbO7Djc1lGA
8MXW5dRNJ2Srm8c+cftIl7gzbckTB+6WohsYFfZcTEDts8Ls/3HB40f/1LkAtDdC
2iDJ6m6K7hQGrn2iWZiIqBtvLfTyyRRfJs8sjX7tN8Cp1Tm5gr8ZDOo0rwAhaPit
c+LJMto4JQtV05od8GiG7S5BNO98pVAdvzr508EIDObtHopYJeS4d60tbvVS3bR0
j6tJLp07kzQoH3jOlOrHvdPJbRzeXDLz
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG
EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw
HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw
MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3
dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq
hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn
TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5
BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H
4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y
7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB
o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm
8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF
BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr
EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt
tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886
UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----

37
vendor/angelfqc/vimeo-api/composer.json vendored Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "angelfqc/vimeo-api",
"description": "Official PHP library for the Vimeo API.",
"homepage": "https://github.com/vimeo/vimeo.php",
"keywords": ["vimeo", "video"],
"license": "Apache-2.0",
"authors": [
{
"name": "Vimeo",
"homepage": "http://vimeo.com"
}
],
"minimum-stability": "stable",
"require": {
"php": ">=5.3.0",
"ext-curl": "*",
"ext-json":"*"
},
"autoload": {
"psr-4": {
"Vimeo\\": "src/Vimeo"
}
},
"autoload-dev": {
"psr-4": {
"Vimeo\\": "tests/Vimeo"
}
},
"require-dev": {
"phpunit/phpunit": "^4.8 || ^6.5",
"php-coveralls/php-coveralls": "^1.0"
},
"scripts": {
"coverage": "phpunit --coverage-html reports/",
"tests": "phpunit"
}
}

23
vendor/angelfqc/vimeo-api/phpunit.xml vendored Normal file
View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="Vimeo PHP SDK">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>src/</directory>
</whitelist>
</filter>
</phpunit>

View File

@@ -0,0 +1,9 @@
<?php
namespace Vimeo\Exceptions;
/**
* ExceptionInterface
*/
interface ExceptionInterface
{
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Vimeo\Exceptions;
/**
* VimeoRequestException class for failure to make request.
*/
class VimeoRequestException extends \Exception implements ExceptionInterface
{
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Vimeo\Exceptions;
/**
* VimeoUploadException class for failure to upload to the server.
*/
class VimeoUploadException extends \Exception implements ExceptionInterface
{
}

View File

@@ -0,0 +1,627 @@
<?php
namespace Vimeo;
use Vimeo\Exceptions\VimeoRequestException;
use Vimeo\Exceptions\VimeoUploadException;
/**
* Copyright 2013 Vimeo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!function_exists('json_decode')) {
throw new \Exception('We could not find json_decode. json_decode is found in php 5.2 and up, but may be missing on some Linux systems due to licensing conflicts. If you are running ubuntu try "sudo apt-get install php5-json".');
}
class Vimeo
{
const ROOT_ENDPOINT = 'https://api.vimeo.com';
const AUTH_ENDPOINT = 'https://api.vimeo.com/oauth/authorize';
const ACCESS_TOKEN_ENDPOINT = '/oauth/access_token';
const CLIENT_CREDENTIALS_TOKEN_ENDPOINT = '/oauth/authorize/client';
const VERSIONS_ENDPOINT = '/versions';
const VERSION_STRING = 'application/vnd.vimeo.*+json; version=3.4';
const USER_AGENT = 'vimeo.php 2.0.5; (http://developer.vimeo.com/api/docs)';
const CERTIFICATE_PATH = '/certificates/vimeo-api.pem';
protected $_curl_opts = array();
protected $CURL_DEFAULTS = array();
private $_client_id = null;
private $_client_secret = null;
private $_access_token = null;
/**
* Creates the Vimeo library, and tracks the client and token information.
*
* @param string $client_id Your applications client id. Can be found on developer.vimeo.com/apps
* @param string $client_secret Your applications client secret. Can be found on developer.vimeo.com/apps
* @param string $access_token Your access token. Can be found on developer.vimeo.com/apps or generated using OAuth 2.
*/
public function __construct($client_id, $client_secret, $access_token = null)
{
$this->_client_id = $client_id;
$this->_client_secret = $client_secret;
$this->_access_token = $access_token;
$this->CURL_DEFAULTS = array(
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
//Certificate must indicate that the server is the server to which you meant to connect.
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => realpath(__DIR__ .'/../..') . self::CERTIFICATE_PATH
);
}
/**
* Make an API request to Vimeo.
*
* @param string $url A Vimeo API Endpoint. Should not include the host
* @param array $params An array of parameters to send to the endpoint. If the HTTP method is GET, they will be added to the url, otherwise they will be written to the body
* @param string $method The HTTP Method of the request
* @param bool $json_body
* @param array $headers An array of HTTP headers to pass along with the request.
* @return array This array contains three keys, 'status' is the status code, 'body' is an object representation of the json response body, and headers are an associated array of response headers
* @throws VimeoRequestException
*/
public function request($url, $params = array(), $method = 'GET', $json_body = true, array $headers = array())
{
$headers = array_merge(array(
'Accept' => self::VERSION_STRING,
'User-Agent' => self::USER_AGENT,
), $headers);
$method = strtoupper($method);
// If a pre-defined `Authorization` header isn't present, then add a bearer token or client information.
if (!isset($headers['Authorization'])) {
if (!empty($this->_access_token)) {
$headers['Authorization'] = 'Bearer ' . $this->_access_token;
} else {
// this may be a call to get the tokens, so we add the client info.
$headers['Authorization'] = 'Basic ' . $this->_authHeader();
}
}
// Set the methods, determine the URL that we should actually request and prep the body.
$curl_opts = array();
switch ($method) {
case 'GET':
case 'HEAD':
if (!empty($params)) {
$query_component = '?' . http_build_query($params, '', '&');
} else {
$query_component = '';
}
$curl_url = self::ROOT_ENDPOINT . $url . $query_component;
break;
case 'POST':
case 'PATCH':
case 'PUT':
case 'DELETE':
if ($json_body && !empty($params)) {
$headers['Content-Type'] = 'application/json';
$body = json_encode($params);
} else {
$body = http_build_query($params, '', '&');
}
$curl_url = self::ROOT_ENDPOINT . $url;
$curl_opts = array(
CURLOPT_POST => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $body
);
break;
}
// Set the headers
foreach ($headers as $key => $value) {
$curl_opts[CURLOPT_HTTPHEADER][] = sprintf('%s: %s', $key, $value);
}
$response = $this->_request($curl_url, $curl_opts);
$response['body'] = json_decode($response['body'], true);
return $response;
}
/**
* Request the access token associated with this library.
*
* @return string
*/
public function getToken()
{
return $this->_access_token;
}
/**
* Assign a new access token to this library.
*
* @param string $access_token the new access token
*/
public function setToken($access_token)
{
$this->_access_token = $access_token;
}
/**
* Gets custom cURL options.
*
* @return string
*/
public function getCURLOptions()
{
return $this->_curl_opts;
}
/**
* Sets custom cURL options.
*
* @param array $curl_opts An associative array of cURL options.
*/
public function setCURLOptions($curl_opts = array())
{
$this->_curl_opts = $curl_opts;
}
/**
* Set a proxy to pass all API requests through.
*
* @param string $proxy_address Mandatory address of proxy.
* @param string|null $proxy_port Optional number of port.
* @param string|null $proxy_userpwd Optional `user:password` authentication.
*/
public function setProxy($proxy_address, $proxy_port = null, $proxy_userpwd = null)
{
$this->CURL_DEFAULTS[CURLOPT_PROXY] = $proxy_address;
if ($proxy_port) {
$this->CURL_DEFAULTS[CURLOPT_PROXYPORT] = $proxy_port;
}
if ($proxy_userpwd) {
$this->CURL_DEFAULTS[CURLOPT_PROXYUSERPWD] = $proxy_userpwd;
}
}
/**
* Convert the raw headers string into an associated array
*
* @param string $headers
* @return array
*/
public static function parse_headers($headers)
{
$final_headers = array();
$list = explode("\n", trim($headers));
$http = array_shift($list);
foreach ($list as $header) {
$parts = explode(':', $header, 2);
$final_headers[trim($parts[0])] = isset($parts[1]) ? trim($parts[1]) : '';
}
return $final_headers;
}
/**
* Request an access token. This is the final step of the
* OAuth 2 workflow, and should be called from your redirect url.
*
* @param string $code The authorization code that was provided to your redirect url
* @param string $redirect_uri The redirect_uri that is configured on your app page, and was used in buildAuthorizationEndpoint
* @return array This array contains three keys, 'status' is the status code, 'body' is an object representation of the json response body, and headers are an associated array of response headers
*/
public function accessToken($code, $redirect_uri)
{
return $this->request(self::ACCESS_TOKEN_ENDPOINT, array(
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $redirect_uri
), "POST", false);
}
/**
* Get client credentials for requests.
*
* @param mixed $scope Scopes to request for this token from the server.
* @return array Response from the server with the tokens, we also set it into this object.
*/
public function clientCredentials($scope = 'public')
{
if (is_array($scope)) {
$scope = implode(' ', $scope);
}
$token_response = $this->request(self::CLIENT_CREDENTIALS_TOKEN_ENDPOINT, array(
'grant_type' => 'client_credentials',
'scope' => $scope
), "POST", false);
return $token_response;
}
/**
* Build the url that your user.
*
* @param string $redirect_uri The redirect url that you have configured on your app page
* @param string $scope An array of scopes that your final access token needs to access
* @param string $state A random variable that will be returned on your redirect url. You should validate that this matches
* @return string
*/
public function buildAuthorizationEndpoint($redirect_uri, $scope = 'public', $state = null)
{
$query = array(
"response_type" => 'code',
"client_id" => $this->_client_id,
"redirect_uri" => $redirect_uri
);
$query['scope'] = $scope;
if (empty($scope)) {
$query['scope'] = 'public';
} elseif (is_array($scope)) {
$query['scope'] = implode(' ', $scope);
}
if (!empty($state)) {
$query['state'] = $state;
}
return self::AUTH_ENDPOINT . '?' . http_build_query($query);
}
/**
* Upload a file.
*
* This should be used to upload a local file. If you want a form for your site to upload direct to Vimeo, you
* should look at the `POST /me/videos` endpoint.
*
* @link https://developer.vimeo.com/api/endpoints/videos#POST/users/{user_id}/videos
* @param string $file_path Path to the video file to upload.
* @param array $params Parameters to send when creating a new video (name, privacy restrictions, etc.).
* @return string Video URI
* @throws VimeoRequestException
* @throws VimeoUploadException
*/
public function upload($file_path, array $params = array())
{
// Validate that our file is real.
if (!is_file($file_path)) {
throw new VimeoUploadException('Unable to locate file to upload.');
}
$file_size = filesize($file_path);
// Ignore any specified upload approach and size.
$params['upload']['approach'] = 'tus';
$params['upload']['size'] = $file_size;
// Use JSON filtering so we only receive the data that we need to make an upload happen.
$uri = '/me/videos?fields=uri,upload';
$attempt = $this->request($uri, $params, 'POST');
if ($attempt['status'] !== 200) {
$attempt_error = !empty($attempt['body']['error']) ? ' [' . $attempt['body']['error'] . ']' : '';
throw new VimeoUploadException('Unable to initiate an upload.' . $attempt_error);
}
return $this->perform_upload_tus($file_path, $file_size, $attempt);
}
/**
* Replace the source of a single Vimeo video.
*
* @link https://developer.vimeo.com/api/endpoints/videos#POST/videos/{video_id}/versions
* @param string $video_uri Video uri of the video file to replace.
* @param string $file_path Path to the video file to upload.
* @return string Video URI
* @throws VimeoRequestException
* @throws VimeoUploadException
*/
public function replace($video_uri, $file_path, array $params = array())
{
// Validate that our file is real.
if (!is_file($file_path)) {
throw new VimeoUploadException('Unable to locate file to upload.');
}
$file_size = filesize($file_path);
// Use JSON filtering so we only receive the data that we need to make an upload happen.
$uri = $video_uri . self::VERSIONS_ENDPOINT . '?fields=upload';
// Ignore any specified upload approach and size.
$params['file_name'] = basename($file_path);
$params['upload']['approach'] = 'tus';
$params['upload']['size'] = $file_size;
$attempt = $this->request($uri, $params, 'POST');
if ($attempt['status'] !== 201) {
$attempt_error = !empty($attempt['body']['error']) ? ' [' . $attempt['body']['error'] . ']' : '';
throw new VimeoUploadException('Unable to initiate an upload.' . $attempt_error);
}
// `uri` doesn't come back from `/videos/:id/versions` so we need to manually set it here for uploading.
$attempt['body']['uri'] = $video_uri;
return $this->perform_upload_tus($file_path, $file_size, $attempt);
}
/**
* Uploads an image to an individual picture response.
*
* @link https://developer.vimeo.com/api/upload/pictures
* @param string $pictures_uri The pictures endpoint for a resource that allows picture uploads (eg videos and users)
* @param string $file_path The path to your image file
* @param boolean $activate Activate image after upload
* @return string The URI of the uploaded image.
* @throws VimeoRequestException
* @throws VimeoUploadException
*/
public function uploadImage($pictures_uri, $file_path, $activate = false)
{
// Validate that our file is real.
if (!is_file($file_path)) {
throw new VimeoUploadException('Unable to locate file to upload.');
}
$pictures_response = $this->request($pictures_uri, array(), 'POST');
if ($pictures_response['status'] !== 201) {
throw new VimeoUploadException('Unable to request an upload url from vimeo');
}
$upload_url = $pictures_response['body']['link'];
$image_resource = fopen($file_path, 'r');
$curl_opts = array(
CURLOPT_TIMEOUT => 240,
CURLOPT_UPLOAD => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_READDATA => $image_resource
);
$curl = curl_init($upload_url);
// Merge the options
curl_setopt_array($curl, $curl_opts + $this->CURL_DEFAULTS);
$response = curl_exec($curl);
$curl_info = curl_getinfo($curl);
if (!$response) {
$error = curl_error($curl);
throw new VimeoUploadException($error);
}
curl_close($curl);
if ($curl_info['http_code'] !== 200) {
throw new VimeoUploadException($response);
}
// Activate the uploaded image
if ($activate) {
$completion = $this->request($pictures_response['body']['uri'], array('active' => true), 'PATCH');
}
return $pictures_response['body']['uri'];
}
/**
* Uploads a text track.
*
* @link https://developer.vimeo.com/api/upload/texttracks
* @param string $texttracks_uri The text tracks uri that we are adding our text track to
* @param string $file_path The path to your text track file
* @param string $track_type The type of your text track
* @param string $language The language of your text track
* @return string The URI of the uploaded text track.
* @throws VimeoRequestException
* @throws VimeoUploadException
*/
public function uploadTexttrack($texttracks_uri, $file_path, $track_type, $language)
{
// Validate that our file is real.
if (!is_file($file_path)) {
throw new VimeoUploadException('Unable to locate file to upload.');
}
// To simplify the script we provide the filename as the text track name, but you can provide any value you want.
$name = array_slice(explode("/", $file_path), -1);
$name = $name[0];
$texttrack_response = $this->request($texttracks_uri, array('type' => $track_type, 'language' => $language, 'name' => $name), 'POST');
if ($texttrack_response['status'] !== 201) {
throw new VimeoUploadException('Unable to request an upload url from vimeo');
}
$upload_url = $texttrack_response['body']['link'];
$texttrack_resource = fopen($file_path, 'r');
$curl_opts = array(
CURLOPT_TIMEOUT => 240,
CURLOPT_UPLOAD => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_READDATA => $texttrack_resource
);
$curl = curl_init($upload_url);
// Merge the options
curl_setopt_array($curl, $curl_opts + $this->CURL_DEFAULTS);
$response = curl_exec($curl);
$curl_info = curl_getinfo($curl);
if (!$response) {
$error = curl_error($curl);
throw new VimeoUploadException($error);
}
curl_close($curl);
if ($curl_info['http_code'] !== 200) {
throw new VimeoUploadException($response);
}
return $texttrack_response['body']['uri'];
}
/**
* Internal function to handle requests, both authenticated and by the upload function.
*
* @param string $url
* @param array $curl_opts
* @return array
* @throws VimeoRequestException
*/
private function _request($url, $curl_opts = array())
{
// Merge the options (custom options take precedence).
$curl_opts = $this->_curl_opts + $curl_opts + $this->CURL_DEFAULTS;
// Call the API.
$curl = curl_init($url);
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
$curl_info = curl_getinfo($curl);
if (isset($curl_info['http_code']) && $curl_info['http_code'] === 0) {
$curl_error = curl_error($curl);
$curl_error = !empty($curl_error) ? ' [' . $curl_error .']' : '';
throw new VimeoRequestException('Unable to complete request.' . $curl_error);
}
curl_close($curl);
// Retrieve the info
$header_size = $curl_info['header_size'];
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
// Return it raw.
return array(
'body' => $body,
'status' => $curl_info['http_code'],
'headers' => self::parse_headers($headers)
);
}
/**
* Get authorization header for retrieving tokens/credentials.
*
* @return string
*/
private function _authHeader()
{
return base64_encode($this->_client_id . ':' . $this->_client_secret);
}
/**
* Take an upload attempt and perform the actual upload via tus.
*
* @link https://tus.io/
* @param string $file_path Path to the video file to upload
* @param int $file_size Size of the video file.
* @param array $attempt Upload attempt data.
* @return mixed
* @throws VimeoRequestException
* @throws VimeoUploadException
*/
private function perform_upload_tus($file_path, $file_size, $attempt)
{
$url = $attempt['body']['upload']['upload_link'];
// We need a handle on the input file since we may have to send segments multiple times.
$file = fopen($file_path, 'r');
$curl_opts = array(
CURLOPT_POST => true,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_INFILE => $file,
CURLOPT_INFILESIZE => filesize($file_path),
CURLOPT_UPLOAD => true,
CURLOPT_HTTPHEADER => array(
'Expect: ',
'Content-Type: application/offset+octet-stream',
'Tus-Resumable: 1.0.0',
'upload-offset: {placeholder}',
)
);
// Perform the upload by sending as much to the server as possible and ending when we reach the file size on
// the server.
$failures = 0;
$server_at = 0;
do {
// The last HTTP header we set has to be `upload-offset`, since for resumable uploading to work properly,
// we'll need to alter the content of the header for each upload segment request.
array_pop($curl_opts[CURLOPT_HTTPHEADER]);
$curl_opts[CURLOPT_HTTPHEADER][] = 'upload-offset: ' . $server_at;
fseek($file, $server_at);
try {
$response = $this->_request($url, $curl_opts);
// Successful upload, so reset the failure counter.
$failures = 0;
if ($response['status'] === 204) {
// If the `upload-offset` returned is equal to the size of the video we want to upload, then we've
// fully uploaded the video. If not, continue uploading.
if ($response['headers']['upload-offset'] === $file_size) {
break;
}
$server_at = $response['headers']['upload-offset'];
continue;
}
// If we didn't receive a 204 response from the tus server, then we should verify what's going on before
// proceeding to upload more pieces.
$verify_response = $this->request($url, array(), 'HEAD');
if ($verify_response['status'] !== 200) {
$verify_error = !empty($ticket['body']) ? ' [' . $ticket['body'] . ']' : '';
throw new VimeoUploadException('Unable to verify upload' . $verify_error);
}
if ($verify_response['headers']['upload-offset'] === $file_size) {
break;
}
$server_at = $verify_response['headers']['upload-offset'];
} catch (VimeoRequestException $exception) {
// We likely experienced a timeout, but if we experience three in a row, then we should back off and
// fail so as to not overwhelm servers that are, probably, down.
if ($failures >= 3) {
throw $exception;
}
$failures++;
sleep(pow(4, $failures)); // sleep 4, 16, 64 seconds (based on failure count)
} catch (VimeoUploadException $exception) {
throw $exception;
}
} while ($server_at < $file_size);
return $attempt['body']['uri'];
}
}

View File

@@ -0,0 +1,253 @@
<?php
namespace Vimeo;
use PHPUnit\Framework\TestCase;
use Vimeo\Vimeo;
class VimeoTest extends TestCase
{
protected $clientId = 'client_id';
protected $clientSecret = 'client_secret';
public function testRequestGetUserInformation()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->request('/users/userwillnotbefound');
// Assert
$this->assertSame('You must provide a valid authenticated access token.', $result['body']['error']);
}
public function testRequestGetUserInformationWithAccessToken()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret, 'fake_access_token');
// Act
$result = $vimeo->request('/users/userwillnotbefound');
// Assert
$this->assertSame('You must provide a valid authenticated access token.', $result['body']['error']);
}
public function testRequestGetUserInformationWithParams()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->request('/users/userwillnotbefound', array('fake_key=fake_value'));
// Assert
$this->assertSame('You must provide a valid authenticated access token.', $result['body']['error']);
}
public function testGetToken()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$vimeo->setToken('fake_access_token');
// Assert
$this->assertSame('fake_access_token', $vimeo->getToken());
}
public function testGetCurlOptions()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$vimeo->setCurlOptions(array('custom_name' => 'custom_value'));
$result = $vimeo->getCurlOptions();
// Assert
$this->assertInternalType('array', $result);
$this->assertSame('custom_value', $result['custom_name']);
}
public function testAccessTokenWithCallingFakeRedirectUri()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->accessToken('fake_auth_code', 'https://fake.redirect.uri');
// Assert
$this->assertSame('invalid_client', $result['body']['error']);
}
public function testClientCredentialsWithDefaultScope()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->clientCredentials();
// Assert
$this->assertSame('You must provide a valid authenticated access token.', $result['body']['error']);
}
public function testClientCredentialsWithArrayScope()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->clientCredentials(array('public'));
// Assert
$this->assertSame('You must provide a valid authenticated access token.', $result['body']['error']);
}
public function testBuildAuthorizationEndpointWithDefaultScopeAndNullState()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->buildAuthorizationEndpoint('https://fake.redirect.uri');
// Assert
$this->assertSame('https://api.vimeo.com/oauth/authorize?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Ffake.redirect.uri&scope=public', $result);
}
public function testBuildAuthorizationEndpointWithNullScopeAndNullState()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->buildAuthorizationEndpoint('https://fake.redirect.uri', null);
// Assert
$this->assertSame('https://api.vimeo.com/oauth/authorize?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Ffake.redirect.uri&scope=public', $result);
}
public function testBuildAuthorizationEndpointWithArrayScopeAndNullState()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->buildAuthorizationEndpoint('https://fake.redirect.uri', array('public', 'private'));
// Assert
$this->assertSame('https://api.vimeo.com/oauth/authorize?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Ffake.redirect.uri&scope=public+private', $result);
}
public function testBuildAuthorizationEndpointWithArrayScopeAndState()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->buildAuthorizationEndpoint('https://fake.redirect.uri', array('public'), 'fake_state');
// Assert
$this->assertSame('https://api.vimeo.com/oauth/authorize?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Ffake.redirect.uri&scope=public&state=fake_state', $result);
}
/**
* @expectedException Vimeo\Exceptions\VimeoUploadException
*/
public function testUploadWithNonExistedFile()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->upload('./the_file_is_invalid');
}
/**
* @expectedException Vimeo\Exceptions\VimeoUploadException
*/
public function testUploadWithInvalidParamShouldReturnVimeoRequestException()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->upload(__DIR__.'/../../composer.json', array('invalid_param'));
}
/**
* @expectedException Vimeo\Exceptions\VimeoUploadException
*/
public function testReplaceWithNonExistedFile()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->replace('https://vimeo.com/241711006', './the_file_is_invalid');
}
/**
* @expectedException Vimeo\Exceptions\VimeoUploadException
*/
public function testUploadImageWithNonExistedFile()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->uploadImage('https://vimeo.com/241711006', './the_file_is_invalid');
}
/**
* @expectedException Vimeo\Exceptions\VimeoUploadException
*/
public function testUploadTexttrackWithNonExistedFile()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->uploadTexttrack('https://vimeo.com/241711006', './the_file_is_invalid', 'fake_track_type', 'zh_TW');
}
/**
* @expectedException Vimeo\Exceptions\VimeoRequestException
*/
public function testReplaceWithVideoUriShouldReturnVimeoRequestException()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->replace('https://vimeo.com/241711006', __DIR__.'/../../composer.json');
}
/**
* @expectedException Vimeo\Exceptions\VimeoRequestException
*/
public function testUploadImageWithPictureUriShouldReturnVimeoRequestException()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->uploadImage('https://vimeo.com/user59081751', __DIR__.'/../../composer.json');
}
/**
* @expectedException Vimeo\Exceptions\VimeoRequestException
*/
public function testUploadTexttrackWithPictureUriAndInvalidParamShouldReturnVimeoRequestException()
{
// Arrange
$vimeo = new Vimeo($this->clientId, $this->clientSecret);
// Act
$result = $vimeo->uploadTexttrack('https://vimeo.com/user59081751', __DIR__.'/../../composer.json', 'fake_track_type', 'zh_TW');
}
}