first commit

This commit is contained in:
/usr/bin/nano
2017-04-15 01:34:36 +03:00
commit c715e2a604
5325 changed files with 329700 additions and 0 deletions
+92
View File
@@ -0,0 +1,92 @@
# Uploadcare CKEDITOR Plugin
This is a plugin for [CKEDITOR][4] to work with [Uploadcare][1].
It's based on a [uploadcare-php][3] library.
## Requirements
- CKEDITOR 4.0+
## Optional for PHP version.
- [iframedialog][5] plugin for CKEDITOR
- PHP 5.2+
- php-curl
**Note!** PHP implementation is optional by now and we higly recommend not to use it.
## Install
**Warning**: You **must** enable "Automatic file storing" in your account settings.
Please follow https://uploadcare.com/accounts/settings/ to enable feature.
Clone plugin from git to your plugins directory:
git clone git://github.com/uploadcare/uploadcare-ckeditor.git plugins/uploadcare --recursive
Initialize a CKEDITOR plugin with additional params:
<script>
UPLOADCARE_PUBLIC_KEY = "demopublickey"; //set publick key for Uploadcare
UPLOADCARE_LOCALE = 'ru'; //set locale if you wish
CKEDITOR.replace( 'editor1', {
extraPlugins: 'uploadcare', // this will enable plugin
toolbar: [
[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'Uploadcare' ]
]
});
</script>
## PHP (Optional)
Install iframedialog plugin.
Find a "config.php" file inside plugin directory and edit it:
<?php
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
Initialize a CKEDITOR plugin:
<script>
UPLOADCARE_PUBLIC_KEY = "demopublickey"; //set publick key for Uploadcare
UPLOADCARE_LOCALE = 'ru'; //set locale if you wish
CKEDITOR.replace( 'editor1', {
extraPlugins: 'uploadcare,iframedialog', // this will enable plugin. Iframedialog must be enabled in this case!
USE_PHP: true, //this will enable outdated PHP dialog
toolbar: [
[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'Uploadcare' ]
]
});
</script>
PHP Version provides an outdated custom dialog. This dialog is used to store files and images and
provides some additional image operations.
## Usage
### if USE_PHP = false
1. Press "Uploadcare" button.
2. Select a file to upload and press "Upload"
3. Wait for file to be uploaded.
4. Crop an image as you wish.
5. Press "Upload" again. A cropped image will be available inside editor.
### If USE_PHP = true
1. Press "Uploadcare" button.
2. Select a file to upload.
3. Wait for file to be uploaded. An "Uploadcare" icon will show upload progress.
4. Change any parameters you like.
5. Press "Insert" and an image will be available inside editor.
[1]: http://uploadcare.com/
[2]: https://uploadcare.com/documentation/reference/basic/cdn.html
[3]: https://github.com/uploadcare/uploadcare-php
[4]: http://www.ckeditor.com
[5]: http://www.ckeditor.com/addon/iframedialog
+3
View File
@@ -0,0 +1,3 @@
<?php
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
+222
View File
@@ -0,0 +1,222 @@
<?php
error_reporting(E_ERROR);
include dirname(__FILE__).'/config.php';
include dirname(__FILE__).'/uploadcare-php/uploadcare/lib/5.2/Uploadcare.php';
$public_key = UC_PUBLIC_KEY;
$secret_key = UC_SECRET_KEY;
$api = new Uploadcare_Api($public_key, $secret_key);
$editor_name = $_REQUEST['editor_name'];
//POST
$file = null;
$scale_crop_default_width = 800;
$scale_crop_default_height = 634;
if ($_POST['save']) {
$file_id = $_POST['file_id'];
$file = $api->getFile($file_id);
$file->scaleCrop($scale_crop_default_width, $scale_crop_default_height);
$file->op('stretch/off');
$file->store();
}
if ($_GET['file_id']) {
$file_id = $_GET['file_id'];
$file = $api->getFile($file_id);
$file->scaleCrop($scale_crop_default_width, $scale_crop_default_height);
$file->op('stretch/off');
$file->store();
}
$is_insert = false;
$is_preview = false;
if ($_POST['insert'] or $_POST['_preview']) {
$file_id = $_POST['file_id'];
$file = $api->getFile($file_id);
$original = clone $file;
if (isset($_POST['crop'])) {
$crop_width = $_POST['crop_width'];
$crop_height = $_POST['crop_height'];
$crop_center = isset($_POST['crop_center']) ? true : false;
$crop_fill_color = $_POST['crop_fill_color'];
$file = $file->crop($crop_width, $crop_height, $crop_center, $crop_fill_color);
}
if (isset($_POST['resize'])) {
$resize_width = $_POST['resize_width'];
$resize_height = $_POST['resize_height'];
$file = $file->resize($resize_width, $resize_height);
}
if (isset($_POST['scale_crop'])) {
$scale_crop_width = $_POST['scale_crop_width'];
$scale_crop_height = $_POST['scale_crop_height'];
$scale_crop_center = isset($_POST['scale_crop_center']) ? true : false;
$file = $file->scaleCrop($scale_crop_width, $scale_crop_height, $scale_crop_center);
} else {
$scale_crop_width = $scale_crop_default_width;
$scale_crop_height = $scale_crop_default_height;
$scale_crop_center = false;
}
if (isset($_POST['effect_flip'])) {
$file = $file->effect('flip');
}
if (isset($_POST['effect_grayscale'])) {
$file = $file->effect('grayscale');
}
if (isset($_POST['effect_invert'])) {
$file = $file->effect('invert');
}
if (isset($_POST['effect_mirror'])) {
$file = $file->effect('mirror');
}
if (isset($_POST['stretch_off'])) {
$file->op('stretch/off');
}
$is_insert = true;
if ($_POST['_preview']) {
$is_insert = false;
$is_preview = true;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Uploadcare</title>
</head>
<body>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.7");
</script>
<?php if ($is_preview): ?>
<?php echo $file->getImgTag($file->data['original_filename']); ?>
<?php die();?>
<?php endif;?>
<?php if ($is_insert): ?>
<script type="text/javascript">
/* <![CDATA[ */
window.parent.CKEDITOR.instances['<?php echo $editor_name; ?>'].insertHtml('<?php echo $file->getImgTag(); ?>');
window.parent.CKEDITOR.dialog.getCurrent().hide()
/* ]]> */
</script>
<?php die();?>
<?php endif;?>
<?php if ($file): ?>
<div id="media-items">
<div class="media-item">
<form enctype="multipart/form-data" method="post" action="" id="uploadcare_form">
<input type="hidden" name="file_id" id="file_id" value="<?php echo $file_id; ?>" />
<input type="hidden" name="editor_name" id="editor_name" value="<?php echo $editor_name; ?>" />
<table class="slidetoggle describe startclosed" style="display: table;">
<thead class="media-item-info">
<tr>
<td colspan="2">
<p><strong>File name:</strong> <?php echo $file->data['original_filename']; ?></p>
<p><strong>File type:</strong> <?php echo $file->data['mime_type']; ?></p>
<p><strong>Upload date:</strong> <?php echo $file->data['upload_date']; ?></p>
</td>
</tr>
</thead>
<tbody>
<tr align="left">
<td colspan="2"><input type="checkbox" name="crop" id="crop" />&nbsp;<strong><label for="crop">Crop</label></strong></td>
</tr>
<tr align="left"><th class="label"><label for="crop_width">Width:</label></th><td><input type="text" name="crop_width" id="crop_width" /></td></tr>
<tr align="left"><th class="label"><label for="crop_height">Height:</label></th><td><input type="text" name="crop_height" id="crop_height" /></td></tr>
<tr align="left"><th class="label"><label for="crop_center">Center:</label></th><td><input type="checkbox" name="crop_center" id="crop_center" /></td></tr>
<tr align="left"><th class="label"><label for="crop_fill_color">Fill color:</label></th><td><input type="text" name="crop_fill_color" id="crop_fill_color" /></td></tr>
<tr align="left">
<td colspan="2"><input type="checkbox" name="resize" id="resize" />&nbsp;<strong><label for="resize">Resize</label></strong></td>
</tr>
<tr align="left"><th class="label"><label for="resize_width">Width:</label></th><td><input type="text" name="resize_width" id="resize_width" /></td></tr>
<tr align="left"><th class="label"><label for="resize_height">Height:</label></th><td><input type="text" name="resize_height" id="resize_height" /></td></tr>
<tr align="left">
<td colspan="2"><input type="checkbox" name="scale_crop" checked="checked" id="scale_crop" />&nbsp;<strong><label for="scale_crop">Scale crop</label></strong></td>
</tr>
<tr align="left"><th class="label"><label for="scale_crop_width">Width:</label></th><td><input type="text" name="scale_crop_width" id="scale_crop_width" value="<?php echo $scale_crop_default_width;?>" /></td></tr>
<tr align="left"><th class="label"><label for="scale_crop_height">Height:</label></th><td><input type="text" name="scale_crop_height" id="scale_crop_height" value="<?php echo $scale_crop_default_height; ?>" /></td></tr>
<tr align="left"><th class="label"><label for="scale_crop_center">Center:</label></th><td><input type="checkbox" name="scale_crop_center" id="scale_crop_center" checked="checked"/></td></tr>
<tr align="left">
<td colspan="2"><strong>Effects</strong></td>
</tr>
<tr align="left"><th class="label" colspan="2"><input type="checkbox" name="effect_flip" id="effect_flip" />&nbsp;<label for="effect_flip">Flip</label></th></tr>
<tr align="left"><th class="label" colspan="2"><input type="checkbox" name="effect_grayscale" id="effect_grayscale" />&nbsp;<label for="effect_grayscale">Grayscale</label></th></tr>
<tr align="left"><th class="label" colspan="2"><input type="checkbox" name="effect_invert" id="effect_invert" />&nbsp;<label for="effect_invert">Invert</label></th></tr>
<tr align="left"><th class="label" colspan="2"><input type="checkbox" name="effect_mirror" id="effect_mirror" />&nbsp;<label for="effect_mirror">Mirror</label></th></tr>
<tr align="left"><th class="label" colspan="2"><input type="checkbox" name="stretch_off" id="stretch_off" checked="checked" />&nbsp;<label for="stretch">Stretch Off?</label></th></tr>
<tr valign="top">
<td class="A1B1" colspan="2">
<p><strong>Preview:</strong></p>
<div id="uploadcare_preview" style="width: 750px; overflow-x: scroll;">
<?php echo $file->getImgTag($file->data['original_filename']); ?>
</div>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Insert" name="insert" class="cke_dialog_ui_button" />
</form>
</div>
</div>
<script type="text/javascript">
jQuery(function() {
jQuery('#uploadcare_form :input').change(function() {
var form = jQuery('#uploadcare_form');
var data = form.serialize();
data += '&_preview=true';
jQuery.post(
form.attr('action'),
data,
function (html) {
jQuery('#uploadcare_preview').html(html);
}
);
return false;
});
});
</script>
<?php else: ?>
<?php echo $api->widget->getScriptTag(); ?>
<form enctype="multipart/form-data" method="post" action="" id="uploadcare_form">
<input type="hidden" name="editor_name" id="editor_name" value="<?php echo $editor_name; ?>" />
<h3 class="media-title">Use Uploadcare widget to upload file.</h3>
<?php echo $api->widget->getInputTag('file_id'); ?>
<p class="savebutton ml-submit">
<input type="submit" value="Store File" name="save" class="cke_dialog_ui_button" />
</p>
</form>
<script type="text/javascript">
jQuery(function() {
jQuery('#uploadcare_form').submit(function() {
var form = jQuery(this);
var file_id = form.find('input[name=file_id]').val();
if (!file_id) {
return false;
}
});
});
</script>
<?php endif; ?>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+74
View File
@@ -0,0 +1,74 @@
UPLOADCARE_CROP = true;
CKEDITOR.plugins.add('uploadcare', {
init : function(editor) {
var me = this;
var _file_id;
UPLOADCARE_CROP = !editor.config.USE_PHP;
UPLOADCARE_AUTOSTORE = !editor.config.USE_PHP;
CKEDITOR.scriptLoader.load('https://ucarecdn.com/widget/0.8.1.2/uploadcare/uploadcare-0.8.1.2.min.js');
editor.addCommand('uploadcareDialog', new CKEDITOR.dialogCommand('uploadcareDialog'));
editor.addCommand('showUploadcareDialog', {
allowedContent: 'img',
requiredContent: 'img',
exec : function() {
var dialog = uploadcare.openDialog().done(function(file) {
file.done(function(fileInfo) {
_file_id = fileInfo.uuid;
dialog_path = me.path + 'dialog.php?file_id=' + _file_id;
url = fileInfo.cdnUrl;
if (editor.config.USE_PHP) {
editor.execCommand('uploadcareDialog', true);
} else {
if (fileInfo.isImage) {
editor.insertHtml('<img src="'+url+'" />', 'unfiltered_html');
} else {
editor.insertHtml('<a href="'+url+'">'+fileInfo.name+'</a>', 'unfiltered_html');
}
}
});
});
}
});
editor.ui.addButton('Uploadcare', {
label : 'Uploadcare',
toolbar : 'insert',
command : 'showUploadcareDialog',
icon : this.path + 'images/logo.png',
allowedContent: 'img[alt,dir,id,lang,longdesc,!src,title]{*}(*)',
requiredContent: 'img[alt,src]'
});
CKEDITOR.dialog.add('uploadcareDialog', function() {
return {
title : 'Uploadcare',
minWidth : 800,
minHeight : 600,
onShow : function() {
document.getElementById(this.getButton('ok').domId).style.display = 'none';
},
contents : [ {
id : 'iframe',
label : 'Uploadcare',
expand : false,
elements : [ {
type : 'iframe',
src : me.path + 'dialog.php?file_id=' + _file_id,
width : '800',
height : '600',
onContentLoad : function() {
var iframe = document.getElementById(this._.frameId), iframeWindow = iframe.contentWindow;
if (iframeWindow.document.getElementById('editor_name')) {
iframeWindow.document.getElementById('editor_name').value = editor.name;
}
}
} ]
} ]
};
});
}
});
+374
View File
@@ -0,0 +1,374 @@
# Uploadcare PHP
This is a set of libraries to work with [Uploadcare][1].
## Install
**Note**: php-curl must be installed.
Just clone source code anywhere you like inside your project:
git clone git://github.com/uploadcare/uploadcare-php.git
If you like, define some constants with Public and Secret keys within your project:
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
If you are using PHP 5.3+ or 5.4+ it will be much better to use library with namespaces.
Just include one file to start using Uploadcare inside your PHP project and use namespace "\Uploadcare":
require_once '../uploadcare/lib/5.3-5.4/Uploadcare.php';
use \Uploadcare;
If you are using PHP 5.2+, then you should include Uploadcare PHP libraries like this:
require_once '../uploadcare/lib/5.2/Uploadcare.php';
Now, we are ready. Create an object of Uploadcare\Api class:
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
For PHP 5.2 it will be:
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
This is a main object your should work with. It has everything you need.
## Widgets and simple example
Let's start with widgets.
If you want to get Javascript's url for widget, just call:
print $api->widget->getScriptSrc()
You can easily get all contents and &lt;script&gt; sections to include in your HTML:
<head>
<?php print $api->widget->getScriptTag(); ?>
</head>
Create some form to use with widget:
<form method="POST" action="upload.php">
<?php echo $api->widget->getInputTag('qs-file'); ?>
<input type="submit" value="Save!" />
</form>
You will see an Uploadcare widget. After selecting file the "file_id" parameter will be set as value of hidden field.
The last thing left is to store file:
$file_id = $_POST['qs-file'];
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$file = $api->getFile($file_id);
$file->store();
Now you have an Uploadcare\File object to work with. You can show an image like this:
<img src="<?php echo $file->getUrl(); ?>" />
Or just:
<img src="<?php echo $file; ?>" />
Or you can even call a getImgTag method. This will return a prepared <img> tag:
echo $file->getImgTag('image.jpg', array('alt' => 'Image'));
## API and requests
You can do any simple request if you like by calling:
$api->request($method, $path, $data = array(), $headers = array());
Don't forget, that each API url has it's own allowed methods.
If method is not allowed exceptions will be thrown.
Ok, lets do some requests. This is request to index (http://api.uploadcare.com).
This will return an stdClass with information about urls you can request.
This is not really valuable data.
$data = $api->request('GET', '/');
Lets request account info.
This will return just some essential data inside stdClass such as: username, pub_key and email
$account_data = $api->request('GET', '/account/');
Now lets get file list.
This request will return stdClass with all files uploaded and some information about files.
Each files has:
- size
- upload_date
- last_keep_claim
- on_s3
- made_public
- url
- is_image
- file_id
- original_filename
- removed
- mime_type
- original_file_url
$files_raw = $api->request('GET', '/files/');
Previous request is just some raw request and it will return raw data from json.
There's a better way to handle all the files by using method below.
It will return an array of \Uploadcare\File objects to work with.
This objects provide ways to display the file and to use methods such as resize, crop, etc
$files = $api->getFileList();
getFileList called without any params will return just an array of first 20 files objects (first page).
But you can supply a page you want to see:
$page = 2;
$files = $api->getFileList($page);
You can get some information about pagination.
You will get an array with params:
- page: current page
- next: uri to request next page
- per_page: number of files per page
- pages: number of pages
- previous: uri to request previous page
Use "per_page" and "pages" information to create pagination inside your own project
$pagination_info = $api->getFilePaginationInfo();
If you have a file_id (for example, it's saved in your database) you can create object for file easily.
Just use request below:
$file_id = '5255b9dd-f790-425e-9fa9-8b49d4e64643';
$file = $api->getFile($file_id);
You can access raw data like this:
$file->data['size'];
Trying to access "data" parameter will fire GET request to get all that data once.
It will be a cached array if you will try to access "data" parameter again.
## File operations
Using object of \Uploadcare\File class we can get url for the file
echo $file->getUrl();
Now let's do some crop.
$width = 400;
$height = 400;
$is_center = true;
$fill_color = 'ff0000';
echo $file->crop($width, $height, $is_center, $fill_color)->getUrl();
And here's some resize with width and height
echo $file->resize($width, $height)->getUrl();
Width only
echo $file->resize($width)->getUrl();
Height only
echo $file->resize(false, $height)->getUrl();
We can also use scale crop
echo $file->scaleCrop($width, $height, $is_center)->getUrl();
And we can apply some effects.
echo $file->effect('flip')->getUrl();
echo $file->effect('grayscale')->getUrl();
echo $file->effect('invert')->getUrl();
echo $file->effect('mirror')->getUrl();
We can apply more than one effect!
echo $file->effect('flip')->effect('invert')->getUrl();
We can combine operations, not just effects.
Just chain methods and finish but calling "getUrl()".
echo $file->resize(false, $height)->crop(100, 100)->effect('flip')->effect('invert')->getUrl();
getUrl() returns a string with the resulting URL.
However, it's optional the object itself becomes a string when treated as such.
An example below will print an url too:
echo $file->resize(false, $height)->crop(100, 100)->effect('flip')->effect('invert');
The way you provide operations matters.
We can see the same operations below, but result will be a little bit different because of order:
echo $file->crop(100, 100)->resize(false, $height)->effect('flip')->effect('invert')->getUrl();
You can run any custom operations like this:
echo $file->op('effect/flip');
echo $file->op('resize/400x400')->op('effect/flip');
You can call getUrl with postfix parameter. This is will add some readable postfix.
echo $file->getUrl('image.jpg');
The result will be like this one:
http://ucarecdn.com/85b5644f-e692-4855-9db0-8c5a83096e25/-/crop/970x500/center/he.jpg
[More information on file operations can be found here][2]
## Uploading files
Let's have some fun with uploading files.
First of all, we can upload file from url. Just use construction below.
This will return Uploadcare\File instance.
$file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg');
$file->store();
By using default params of "fromUrl" method you tell Uploader to check file to be uploaded.
By default, Uploader will make 5 checks max with 1 second wait. You can change these params:
$file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg', true, $timeout, $max_attempts);
If file is not uploaded an Exception will be thrown.
You can just get token and check status manually later any time:
$token = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg', false);
$data = $api->uploader->status($token);
if ($data->status == 'success') {
$file_id = $data->file_id
// do smth with a file
}
You can do any operations with this file now.
echo $file->effect('flip')->getUrl();
You can upload file from path.
$file = $api->uploader->fromPath(dirname(__FILE__).'/test.jpg');
$file->store();
echo $file->effect('flip')->getUrl();
Or even just use a file pointer.
$fp = fopen(dirname(__FILE__).'/test.jpg', 'r');
$file = $api->uploader->fromResource($fp);
$file->store();
echo $file->effect('flip')->getUrl();
The last thing you can do is upload a file just from it's contents. But you will have to provide mime-type.
$content = "This is some text I want to upload";
$file = $api->uploader->fromContent($content, 'text/plain');
$file->store();
echo $file->getUrl();
If you want to delete file, just call delete() method on Uploadcare\File object.
$file->delete();
## Tests
Inside "tests" directory you can find test for PHP 5.2 and PHP 5.3.
This tests are based on PHPUnit, so you must have PHPUnit installed on your system to use them.
To execute tests just run this for PHP 5.3:
cd tests/5.3/
phpunit ApiTest.php
or for PHP 5.2:
cd tests/5.2/
phpunit ApiTest.php
ApiTest is divided is sections/methods.
Here's descriptions of methods:
### testConstantValid
Just some basic unit test to test, that constants are not misspelled.
### testChildObjectsValid
Test that Api object has proper child objects.
### testPublicKeyValid
Test for public key is correct.
### testFileList
Test that getFilesList mehtod returns array and each item of array is an object of Uploadcare\File class
### testRequestsRaw
Test different request types to url https://api.uploadcare.com/.
Some requests must throw an exception, some must not.
Checks for some result returned.
### testRequestsAccount
The same as "testRequestsRaw" but with https://api.uploadcare.com/account/ url.
### testRequestsFiles
Makes raw request to get an array of files.
Check's if each file has essentials parameters.
### testFile
Tests Uploadcare\File object to work correctly.
Test runs different operations and checks url is returned correctly for each of them.
### testUploadAndDelete
Tests all four types of uploading.
None of them should throw exception while uplaoding and storing.
Checks text file is uploaded correctly.
Checks for file deletions. No exceptions must be thrown.
[1]: https://uploadcare.com/
[2]: https://uploadcare.com/documentation/reference/basic/cdn.html
@@ -0,0 +1,3 @@
<?php
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
@@ -0,0 +1,225 @@
<?php
/**
* Examples
*/
// This is just some config with public and secret keys for UC.
require_once 'config.php';
// requesting lib for PHP 5.3/5.4
require_once '../uploadcare/lib/5.3-5.4/Uploadcare.php';
// using namespace
use \Uploadcare;
// create object istance for Api.
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
/**
* Let's start with widgets.
* You can get widget url by using this:
* */
print $api->widget->getScriptSrc()."\n";
/**
* You can just use method below to get all the code to insert widget
*/
print $api->widget->getScriptTag()."\n";
/**
* Ok, lets do some requests. This is request to index (http://api.uploadcare.com).
* This will return an stdClass with information about urls you can request.
*/
$data = $api->request('GET', '/');
/**
* Ok, now lets get file list.
* This request will return stdClass with all files uploaded and some information about files.
* Each files has:
* - size
* - upload_date
* - last_keep_claim
* - on_s3
* - made_public
* - url
* - is_image
* - file_id
* - original_filename
* - removed
* - mime_type
* - original_file_url
*
*/
$files_raw = $api->request('GET', '/files/');
/**
* Previous request is just some raw request and it will return raw data from json.
* There's a better way to handle all the files by using method below.
* It will return an array of \Uploadcare\File objects to work with.
*
* This objects don't provide all the data like in previous request, but provides ways to display the file
* and to use methods such as resize, crop, etc
*/
$files = $api->getFileList();
/**
* getFileList called without any params will return just an array of first 20 files objects (first page).
*
* But you can supply a page you want to see:
*/
$page = 2;
$files = $api->getFileList($page);
/**
* You can get some information about pagination.
*
* You will get an array with params:
* - page: current page
* - next: uri to request next page
* - per_page: number of files per page
* - pages: number of pages
* - previous: uri to request previous page
*
* Use "per_page" and "pages" information to create pagination inside your own project
*/
$pagination_info = $api->getFilePaginationInfo();
/**
* If you have a file_id (for example, it's saved in your database) you can create object for file easily.
* Just user request below
*/
$file_id = '5255b9dd-f790-425e-9fa9-8b49d4e64643';
$file = $api->getFile($file_id);
/**
* Ok, using object of \Uploadcare\File class we can get url for the file
*/
echo $file->getUrl()."\n";
/**
* Or even get an image tag
*/
echo $file->getImgTag('image.jpg', array('alt' => 'Somealt'))."\n";
/**
* Now let's do some crop.
*/
$width = 400;
$height = 400;
$is_center = true;
$fill_color = 'ff0000';
echo $file->crop($width, $height, $is_center, $fill_color)->getUrl()."\n";
/**
* And here's some resize with width and height
* */
echo $file->resize($width, $height)->getUrl()."\n";
/**
* Width only
*/
echo $file->resize($width)->getUrl()."\n";
/**
* Height only
*/
echo $file->resize(false, $height)->getUrl()."\n";
/**
* We can also use scale crop
*/
echo $file->scaleCrop($width, $height, $is_center)->getUrl()."\n";
/**
* And we can apply some effects.
*/
echo $file->effect('flip')->getUrl()."\n";
echo $file->effect('grayscale')->getUrl()."\n";
echo $file->effect('invert')->getUrl()."\n";
echo $file->effect('mirror')->getUrl()."\n";
/**
* We can apply more that one effect!
* */
echo $file->effect('flip')->effect('invert')->getUrl()."\n";
/**
* We can combine operations, not just effects.
*
* Just chain methods and finish but calling "getUrl()".
*
* */
echo $file->resize(false, $height)->crop(100, 100)->effect('flip')->effect('invert')->getUrl()."\n";
/**
* The way you provide operations matters.
* We can see the same operations below, but result will be a little bit different.
*/
echo $file->crop(100, 100)->resize(false, $height)->effect('flip')->effect('invert')->getUrl()."\n";
/**
* You can run any custom operations like this:
*/
echo $file->op('effect/flip')."\n";
echo $file->op('resize/400x400')->op('effect/flip')."\n";
/**
* You can call getUrl with postfix parameter. This is will add some readable postfix.
*/
echo $file->getUrl('image.jpg')."\n";
/**
* You can find more about operations here:
* https://uploadcare.com/documentation/reference/basic/cdn.html
*/
/**
* Ok, it's everything with operations.
* Let's have some fun with uploading files.
* First of all, we can upload file from url. Just use construction below.
* This will return File instance.
*/
$file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg');
/**
* File must be uploaded, but it's not stored yet.
* Let's store it.
* We user true flag to be sure that file is uploaded.
**/
try {
$file->store(true);
} catch (Exception $e) {
echo $e->getMessage()."\n";
echo nl2br($e->getTraceAsString())."\n";
}
/**
* We can do any operations with this file now.
**/
echo $file->effect('flip')->getUrl()."\n";
/**
* We can upload file from path
* */
$file = $api->uploader->fromPath(dirname(__FILE__).'/test.jpg');
$file->store();
echo $file->effect('flip')->getUrl()."\n";
/**
* Or even just use a file pointer.
**/
$fp = fopen(dirname(__FILE__).'/test.jpg', 'r');
$file = $api->uploader->fromResource($fp);
$file->store();
echo $file->effect('flip')->getUrl()."\n";
/**
* The last thing you can do is upload a file just from it's contents. But you will have to provide
* mime-type.
*/
$content = "This is some text I want to upload";
$file = $api->uploader->fromContent($content, 'text/plain');
$file->store();
echo $file->getUrl()."\n";
/**
* Lets delete the last file.
*/
$file->delete();
@@ -0,0 +1,221 @@
<?php
// This is just some config with public and secret keys for UC.
require_once 'config.php';
// requesting lib for PHP 5.2
require_once '../uploadcare/lib/5.2/Uploadcare.php';
// using namespace
// create object istance for Api.
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
/**
* Let's start with widgets.
* You can get widget url by using this:
* */
print $api->widget->getScriptSrc()."\n";
/**
* You can just use method below to get all the code to insert widget
*/
print $api->widget->getScriptTag()."\n";
/**
* Ok, lets do some requests. This is request to index (http://api.uploadcare.com).
* This will return an stdClass with information about urls you can request.
*/
$data = $api->request('GET', '/');
/**
* Ok, now lets get file list.
* This request will return stdClass with all files uploaded and some information about files.
* Each files has:
* - size
* - upload_date
* - last_keep_claim
* - on_s3
* - made_public
* - url
* - is_image
* - file_id
* - original_filename
* - removed
* - mime_type
* - original_file_url
*
*/
$files_raw = $api->request('GET', '/files/');
/**
* Previous request is just some raw request and it will return raw data from json.
* There's a better way to handle all the files by using method below.
* It will return an array of \Uploadcare\File objects to work with.
*
* This objects don't provide all the data like in previous request, but provides ways to display the file
* and to use methods such as resize, crop, etc
*/
$files = $api->getFileList();
/**
* getFileList called without any params will return just an array of first 20 files objects (first page).
*
* But you can supply a page you want to see:
*/
$page = 2;
$files = $api->getFileList($page);
/**
* You can get some information about pagination.
*
* You will get an array with params:
* - page: current page
* - next: uri to request next page
* - per_page: number of files per page
* - pages: number of pages
* - previous: uri to request previous page
*
* Use "per_page" and "pages" information to create pagination inside your own project
*/
$pagination_info = $api->getFilePaginationInfo();
/**
* If you have a file_id (for example, it's saved in your database) you can create object for file easily.
* Just user request below
*/
$file_id = '5255b9dd-f790-425e-9fa9-8b49d4e64643';
$file = $api->getFile($file_id);
/**
* Ok, using object of \Uploadcare\File class we can get url for the file
*/
echo $file->getUrl()."\n";
/**
* Or even get an image tag
*/
echo $file->getImgTag('image.jpg', array('alt' => 'Somealt'))."\n";
/**
* Now let's do some crop.
*/
$width = 400;
$height = 400;
$is_center = true;
$fill_color = 'ff0000';
echo $file->crop($width, $height, $is_center, $fill_color)->getUrl()."\n";
/**
* And here's some resize with width and height
* */
echo $file->resize($width, $height)->getUrl()."\n";
/**
* Width only
*/
echo $file->resize($width)->getUrl()."\n";
/**
* Height only
*/
echo $file->resize(false, $height)->getUrl()."\n";
/**
* We can also use scale crop
*/
echo $file->scaleCrop($width, $height, $is_center)->getUrl()."\n";
/**
* And we can apply some effects.
*/
echo $file->effect('flip')->getUrl()."\n";
echo $file->effect('grayscale')->getUrl()."\n";
echo $file->effect('invert')->getUrl()."\n";
echo $file->effect('mirror')->getUrl()."\n";
/**
* We can apply more that one effect!
* */
echo $file->effect('flip')->effect('invert')->getUrl()."\n";
/**
* We can combine operations, not just effects.
*
* Just chain methods and finish but calling "getUrl()".
*
* */
echo $file->resize(false, $height)->crop(100, 100)->effect('flip')->effect('invert')->getUrl()."\n";
/**
* The way you provide operations matters.
* We can see the same operations below, but result will be a little bit different.
*/
echo $file->crop(100, 100)->resize(false, $height)->effect('flip')->effect('invert')->getUrl()."\n";
/**
* You can run any custom operations like this:
*/
echo $file->op('effect/flip')."\n";
echo $file->op('resize/400x400')->op('effect/flip')."\n";
/**
* You can call getUrl with postfix parameter. This is will add some readable postfix.
*/
echo $file->getUrl('image.jpg')."\n";
/**
* You can find more about operations here:
* https://uploadcare.com/documentation/reference/basic/cdn.html
*/
/**
* Ok, it's everything with operations.
* Let's have some fun with uploading files.
* First of all, we can upload file from url. Just use construction below.
* This will return File instance.
*/
$file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg');
/**
* File must be uploaded, but it's not stored yet.
* Let's store it.
* We user true flag to be sure that file is uploaded.
*/
try {
$file->store(true);
} catch (Exception $e) {
echo $e->getMessage()."\n";
echo nl2br($e->getTraceAsString())."\n";
}
/**
* We can do any operations with this file now.
*/
echo $file->effect('flip')->getUrl()."\n";
/**
* We can upload file from path
* */
$file = $api->uploader->fromPath(dirname(__FILE__).'/test.jpg');
$file->store();
echo $file->effect('flip')->getUrl()."\n";
/**
* Or even just use a file pointer.
*/
$fp = fopen(dirname(__FILE__).'/test.jpg', 'r');
$file = $api->uploader->fromResource($fp);
$file->store();
echo $file->effect('flip')->getUrl()."\n";
/**
* The last thing you can do is upload a file just from it's contents. But you will have to provide
* mime-type.
*/
$content = "This is some text I want to upload";
$file = $api->uploader->fromContent($content, 'text/plain');
$file->store();
echo $file->getUrl()."\n";
/**
* Lets delete the last file.
*/
$file->delete();
@@ -0,0 +1,81 @@
<?php
require_once 'config.php';
require_once '../uploadcare/lib/5.3-5.4/Uploadcare.php';
use \Uploadcare;
$uc_handler = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
?>
<!DOCTYPE html>
<html>
<head>
<meta encoding='utf-8'>
<title>Uploadcare</title>
<link
href="// ucarecdn.com/assets/application-68fbe95c430b7646b16aef33e1ad2824.css"
media="screen" rel="stylesheet" type="text/css" />
<link
href="https://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic|PT+Sans+Caption&amp;subset=latin,cyrillic"
media="screen" rel="stylesheet" type="text/css" />
<script
src="// ucarecdn.com/assets/application-241564109602bb3ae298c344abff83a7.js"
type="text/javascript"></script>
<?php echo $uc_handler->widget->getScriptTag(); ?>
</head>
<body class='welcome quick_start docs'>
<div class='wrap'>
<header class='header'>
<div class='logo hide-till-loaded'>
<a href="/" class="pic"><img alt="Logo"
src="// ucarecdn.com/assets/logo-07ad940955c42489ffac0a2c2f0c5d62.png" />
</a> <a href="/">Uploadcare</a>
</div>
<div class='logo logo-animated show-till-loaded'>
<a href="/" class="pic"><img alt="Loading"
src="// ucarecdn.com/assets/loading-04f291b2aa39cf277186c36d18d9217f.png" />
</a> <a href="/">Uploadcare</a>
</div>
</header>
<div class='page-content-placeholder'></div>
<div class='page-content'>
<section class='content text-content' style="width: 100%;">
<article class='content-block'>
<ul class="instructions" style="list-style-type: none;">
<li id="step1">
<div class="item-header" role="foldable-folder">
<h2 class="upload">Use Uploadcare widget to upload any image.</h2>
</div>
<div class="hinted">
<form method="POST" action="upload.php" id="uc_form">
<?php echo $uc_handler->widget->getInputTag('qs-file', array('attr' => 1)); ?>
<input type="submit" value="Save!" />
</form>
<p id="uc_form_nofile_hint"
style="display: none; margin-top: 20px; color: #ff0033;">
<img src="img/warning.jpg" alt="" /> Please, upload any image
using Uploadcare widget.
</p>
</div>
</li>
</ul>
</article>
</section>
</div>
</div>
</body>
<script type="text/javascript">
$(function() {
handleUCForm = function() {
if (!$('#uc_form input[name=qs-file]').val()) {
$('#uc_form_nofile_hint').slideDown();
setTimeout('hideNoFileHint()', '1500');
return false;
}
};
hideNoFileHint = function() {
$('#uc_form_nofile_hint').slideUp();
}
$('#uc_form').submit(handleUCForm);
});
</script>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

@@ -0,0 +1,71 @@
<?php
require_once 'config.php';
require_once '../uploadcare/lib/5.3-5.4/Uploadcare.php';
use \Uploadcare;
$file_id = $_POST['qs-file'];
$uc_handler = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$file = $uc_handler->getFile($file_id);
try {
$file->store();
} catch (Exception $e) {
echo $e->getMessage()."<br />";
echo nl2br($e->getTraceAsString());
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta encoding='utf-8'>
<title>Uploadcare</title>
<link
href="// ucarecdn.com/assets/application-68fbe95c430b7646b16aef33e1ad2824.css"
media="screen" rel="stylesheet" type="text/css" />
<link
href="https://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic|PT+Sans+Caption&amp;subset=latin,cyrillic"
media="screen" rel="stylesheet" type="text/css" />
<script
src="// ucarecdn.com/assets/application-241564109602bb3ae298c344abff83a7.js"
type="text/javascript"></script>
</head>
<body class='welcome quick_start docs'>
<div class='wrap'>
<header class='header'>
<div class='logo hide-till-loaded'>
<a href="/" class="pic"><img alt="Logo"
src="// ucarecdn.com/assets/logo-07ad940955c42489ffac0a2c2f0c5d62.png" />
</a> <a href="/">Uploadcare</a>
</div>
<div class='logo logo-animated show-till-loaded'>
<a href="/" class="pic"><img alt="Loading"
src="// ucarecdn.com/assets/loading-04f291b2aa39cf277186c36d18d9217f.png" />
</a> <a href="/">Uploadcare</a>
</div>
</header>
<div class='page-content-placeholder'></div>
<div class='page-content'>
<section class='content text-content' style="width: 100%;">
<article class='content-block'>
<ul class="instructions" style="list-style-type: none;">
<li id="step1">
<div class="item-header" role="foldable-folder">
<h2 class="upload">Here is a cropped image size 400x400. Click
cropped image to see original one.</h2>
<p>
Would you like to <a href="../sample-project">upload more</a>?
</p>
</div>
<div class="hinted">
<a href="<?php echo $file->getUrl(); ?>" target="_blank"><img
src="<?php print $file->resize(400, 400)->getUrl(); ?>" /> </a>
</div>
</li>
</ul>
</article>
</section>
</div>
</div>
</body>
</html>
@@ -0,0 +1,311 @@
<?php
require_once dirname(__FILE__).'/config.php';
require_once dirname(__FILE__).'/../../uploadcare/lib/5.2/Uploadcare.php';
class ApiTest extends PHPUnit_Framework_TestCase
{
/**
* Setup test
* @return void
*/
public function setUp() {
}
/**
* Tear down
* @return void
*/
public function tearDown() {
}
/**
* Test for constants not to be misspelled
*/
public function testConstantValid()
{
$this->assertTrue(API_TYPE_RAW == 'raw');
$this->assertTrue(API_TYPE_ACCOUNT == 'account');
$this->assertTrue(API_TYPE_STORE == 'store');
$this->assertTrue(API_TYPE_FILES == 'files');
$this->assertTrue(API_TYPE_FILE == 'file');
$this->assertTrue(REQUEST_TYPE_POST == 'post');
$this->assertTrue(REQUEST_TYPE_PUT == 'put');
$this->assertTrue(REQUEST_TYPE_DELETE == 'delete');
$this->assertTrue(REQUEST_TYPE_GET == 'get');
$this->assertTrue(REQUEST_TYPE_HEAD == 'head');
$this->assertTrue(REQUEST_TYPE_OPTIONS == 'options');
$this->assertTrue(UC_PARAM_FILE_ID == 'file_id');
}
/**
* This is just some simple test to check that classes are right.
*/
public function testChildObjectsValid()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$this->assertTrue(get_class($api->widget) == 'Uploadcare_Widget');
$this->assertTrue(get_class($api->uploader) == 'Uploadcare_Uploader');
}
/**
* Is public key valid?
*/
public function testPublicKeyValid()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$this->assertTrue($api->getPublicKey() == 'demopublickey', 'This is true');
}
/**
* Test that getFilesList mehtod returns array
* and each item of array is an object of Uploadcare_File class
*/
public function testFileList()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$files = $api->getFileList();
$this->assertTrue(is_array($files));
foreach ($files as $file) {
$this->assertTrue(get_class($file) == 'Uploadcare_File');
}
}
/**
* Test requests for exceptions to "raw" url
*/
public function testRequestsRaw()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// this are request to https://api.uploadcare.com/ url.
// no exceptions should be thrown
try {
$result = $api->request('GET', '/');
$api->request('HEAD', '/');
$api->request('OPTIONS', '/');
} catch (Exception $e) {
$this->fail('An unexpected exception thrown');
}
// let's check we have a "resources"
$this->assertTrue(is_array($result->resources));
// this are requests to https://api.uploadcare.com/ url.
// But this requests are now allowed but this url and we must have an exception
try {
$api->request('POST', '/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('PUT', '/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('DELETE', '/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
}
/**
* Test requests to "account" url
*/
public function testRequestsAccount()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// this are request to https://api.uploadcare.com/account/ url.
// no exceptions should be thrown
try {
$result = $api->request('GET', '/account/');
$api->request('HEAD', '/account/');
$api->request('OPTIONS', '/account/');
} catch (Exception $e) {
$this->fail('An unexpected exception thrown');
}
// we have some data, let's check it
$this->assertEquals($result->username, 'demo');
$this->assertEquals($result->pub_key, 'demopublickey');
$this->assertEquals($result->email, 'demo@uploadcare.com');
// this are requests to https://api.uploadcare.com/account/ url.
// But this requests are now allowed but this url and we must have an exception
try {
$api->request('POST', '/account/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('PUT', '/account/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('DELETE', '/account/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
}
/**
* Test request to "files"
*/
public function testRequestsFiles()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// this are request to https://api.uploadcare.com/files/ url.
// no exceptions should be thrown
try {
$result = $api->request('GET', '/files/');
$api->request('HEAD', '/files/');
$api->request('OPTIONS', '/files/');
} catch (Exception $e) {
$this->fail('An unexpected exception thrown');
}
// let's check we have an array of raw file data
$this->assertTrue(is_array($result->results));
$this->assertGreaterThan(0, count($result->results));
$file_raw = (array)$result->results[0];
$this->assertArrayHasKey('size', $file_raw);
$this->assertArrayHasKey('upload_date', $file_raw);
$this->assertArrayHasKey('is_image', $file_raw);
$this->assertArrayHasKey('file_id', $file_raw);
$this->assertArrayHasKey('original_filename', $file_raw);
$this->assertArrayHasKey('mime_type', $file_raw);
// this are requests to https://api.uploadcare.com/files/ url.
// But this requests are now allowed but this url and we must have an exception
try {
$api->request('POST', '/files/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('PUT', '/files/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('DELETE', '/files/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
}
/**
* Let's check the file operations and check for correct urls
*/
public function testFile()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$file = $api->getFile('4bd3a897-f489-4b9f-b643-961b1c9f657e');
$this->assertEquals(get_class($file), 'Uploadcare_File');
$this->assertEquals($file->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/');
$this->assertEquals($file->resize(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x400/');
$this->assertEquals($file->resize(400, false)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x/');
$this->assertEquals($file->resize(false, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/x400/');
$this->assertEquals($file->crop(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/');
$this->assertEquals($file->crop(400, 400, true)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/center/');
$this->assertEquals($file->crop(400, 400, true, 'ff0000')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/center/ff0000/');
$this->assertEquals($file->crop(400, 400, false, 'ff0000')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/ff0000/');
$this->assertEquals($file->scaleCrop(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/scale_crop/400x400/');
$this->assertEquals($file->scaleCrop(400, 400, true)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/scale_crop/400x400/center/');
$this->assertEquals($file->effect('flip')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/flip/');
$this->assertEquals($file->effect('grayscale')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/grayscale/');
$this->assertEquals($file->effect('invert')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/invert/');
$this->assertEquals($file->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/mirror/');
$this->assertEquals($file->effect('flip')->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/flip/-/effect/mirror/');
$this->assertEquals($file->effect('mirror')->effect('flip')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/mirror/-/effect/flip/');
$this->assertEquals($file->resize(400, 400)->scaleCrop(200, 200, true)->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x400/-/scale_crop/200x200/center/-/effect/mirror/');
}
/**
* Test uploading and deleting
*/
public function testUploadAndDelete()
{
$api = new Uploadcare_Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// upload form url
try {
$file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg');
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from url '.$e->getMessage());
}
$this->assertEquals(get_class($file), 'Uploadcare_File');
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from url'.$e->getMessage());
}
// upload from path
try {
$file = $api->uploader->fromPath(dirname(__FILE__).'/test.jpg');
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from path');
}
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from path'.$e->getMessage());
}
// upload from resource
try {
$fp = fopen(dirname(__FILE__).'/test.jpg', 'r');
$file = $api->uploader->fromResource($fp);
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from resource'.$e->getMessage());
}
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from resource'.$e->getMessage());
}
// upload from raw
try {
$content = "This is some text I want to upload";
$file = $api->uploader->fromContent($content, 'text/plain');
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from contents'.$e->getMessage());
}
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from contents'.$e->getMessage());
}
$text = file_get_contents($file->getUrl());
$this->assertEquals($text, "This is some text I want to upload");
// test file delete
try {
$file->delete();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to delete file'.$e->getMessage());
}
}
}
@@ -0,0 +1,3 @@
<?php
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

@@ -0,0 +1,313 @@
<?php
error_reporting(E_ERROR);
require_once dirname(__FILE__).'/config.php';
require_once dirname(__FILE__).'/../../uploadcare/lib/5.3-5.4/Uploadcare.php';
use \Uploadcare;
class ApiTest extends PHPUnit_Framework_TestCase
{
/**
* Setup test
* @return void
*/
public function setUp() {
}
/**
* Tear down
* @return void
*/
public function tearDown() {
}
/**
* Test for constants not to be misspelled
*/
public function testConstantValid()
{
$this->assertTrue(API_TYPE_RAW == 'raw');
$this->assertTrue(API_TYPE_ACCOUNT == 'account');
$this->assertTrue(API_TYPE_STORE == 'store');
$this->assertTrue(API_TYPE_FILES == 'files');
$this->assertTrue(API_TYPE_FILE == 'file');
$this->assertTrue(REQUEST_TYPE_POST == 'post');
$this->assertTrue(REQUEST_TYPE_PUT == 'put');
$this->assertTrue(REQUEST_TYPE_DELETE == 'delete');
$this->assertTrue(REQUEST_TYPE_GET == 'get');
$this->assertTrue(REQUEST_TYPE_HEAD == 'head');
$this->assertTrue(REQUEST_TYPE_OPTIONS == 'options');
$this->assertTrue(UC_PARAM_FILE_ID == 'file_id');
}
/**
* This is just some simple test to check that classes are right.
*/
public function testChildObjectsValid()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$this->assertTrue(get_class($api->widget) == 'Uploadcare\Widget');
$this->assertTrue(get_class($api->uploader) == 'Uploadcare\Uploader');
}
/**
* Is public key valid?
*/
public function testPublicKeyValid()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$this->assertTrue($api->getPublicKey() == 'demopublickey', 'This is true');
}
/**
* Test that getFilesList mehtod returns array
* and each item of array is an object of Uploadcare\File class
*/
public function testFileList()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$files = $api->getFileList();
$this->assertTrue(is_array($files));
foreach ($files as $file) {
$this->assertTrue(get_class($file) == 'Uploadcare\File');
}
}
/**
* Test requests for exceptions to "raw" url
*/
public function testRequestsRaw()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// this are request to https://api.uploadcare.com/ url.
// no exceptions should be thrown
try {
$result = $api->request('GET', '/');
$api->request('HEAD', '/');
$api->request('OPTIONS', '/');
} catch (Exception $e) {
$this->fail('An unexpected exception thrown');
}
// let's check we have a "resources"
$this->assertTrue(is_array($result->resources));
// this are requests to https://api.uploadcare.com/ url.
// But this requests are now allowed but this url and we must have an exception
try {
$api->request('POST', '/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('PUT', '/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('DELETE', '/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
}
/**
* Test requests to "account" url
*/
public function testRequestsAccount()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// this are request to https://api.uploadcare.com/account/ url.
// no exceptions should be thrown
try {
$result = $api->request('GET', '/account/');
$api->request('HEAD', '/account/');
$api->request('OPTIONS', '/account/');
} catch (Exception $e) {
$this->fail('An unexpected exception thrown');
}
// we have some data, let's check it
$this->assertEquals($result->username, 'demo');
$this->assertEquals($result->pub_key, 'demopublickey');
$this->assertEquals($result->email, 'demo@uploadcare.com');
// this are requests to https://api.uploadcare.com/account/ url.
// But this requests are now allowed but this url and we must have an exception
try {
$api->request('POST', '/account/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('PUT', '/account/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('delete', '/account/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
}
/**
* Test request to "files"
*/
public function testRequestsFiles()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// this are request to https://api.uploadcare.com/files/ url.
// no exceptions should be thrown
try {
$result = $api->request('GET', '/files/');
$api->request('HEAD', '/files/');
$api->request('OPTIONS', '/files/');
} catch (Exception $e) {
$this->fail('An unexpected exception thrown');
}
// let's check we have an array of raw file data
$this->assertTrue(is_array($result->results));
$this->assertGreaterThan(0, count($result->results));
$file_raw = (array)$result->results[0];
$this->assertArrayHasKey('size', $file_raw);
$this->assertArrayHasKey('upload_date', $file_raw);
$this->assertArrayHasKey('is_image', $file_raw);
$this->assertArrayHasKey('file_id', $file_raw);
$this->assertArrayHasKey('original_filename', $file_raw);
$this->assertArrayHasKey('mime_type', $file_raw);
// this are requests to https://api.uploadcare.com/files/ url.
// But this requests are now allowed but this url and we must have an exception
try {
$api->request('POST', '/files/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('PUT', '/files/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
try {
$api->request('DELETE', '/files/');
$this->fail('We must get an exception but everything worked fine!');
} catch (Exception $e) {
}
}
/**
* Let's check the file operations and check for correct urls
*/
public function testFile()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
$file = $api->getFile('4bd3a897-f489-4b9f-b643-961b1c9f657e');
$this->assertEquals(get_class($file), 'Uploadcare\File');
$this->assertEquals($file->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/');
$this->assertEquals($file->resize(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x400/');
$this->assertEquals($file->resize(400, false)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x/');
$this->assertEquals($file->resize(false, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/x400/');
$this->assertEquals($file->crop(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/');
$this->assertEquals($file->crop(400, 400, true)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/center/');
$this->assertEquals($file->crop(400, 400, true, 'ff0000')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/center/ff0000/');
$this->assertEquals($file->crop(400, 400, false, 'ff0000')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/crop/400x400/ff0000/');
$this->assertEquals($file->scaleCrop(400, 400)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/scale_crop/400x400/');
$this->assertEquals($file->scaleCrop(400, 400, true)->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/scale_crop/400x400/center/');
$this->assertEquals($file->effect('flip')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/flip/');
$this->assertEquals($file->effect('grayscale')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/grayscale/');
$this->assertEquals($file->effect('invert')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/invert/');
$this->assertEquals($file->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/mirror/');
$this->assertEquals($file->effect('flip')->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/flip/-/effect/mirror/');
$this->assertEquals($file->effect('mirror')->effect('flip')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/effect/mirror/-/effect/flip/');
$this->assertEquals($file->resize(400, 400)->scaleCrop(200, 200, true)->effect('mirror')->getUrl(), 'https://ucarecdn.com/4bd3a897-f489-4b9f-b643-961b1c9f657e/-/resize/400x400/-/scale_crop/200x200/center/-/effect/mirror/');
}
/**
* Test uploading and deleting
*/
public function testUploadAndDelete()
{
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);
// upload form url
try {
$file = $api->uploader->fromUrl('http://www.baysflowers.co.nz/Images/tangerine-delight.jpg');
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from url '.$e->getMessage());
}
$this->assertEquals(get_class($file), 'Uploadcare\File');
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from url'.$e->getMessage());
}
// upload from path
try {
$file = $api->uploader->fromPath(dirname(__FILE__).'/test.jpg');
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from path');
}
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from path'.$e->getMessage());
}
// upload from resource
try {
$fp = fopen(dirname(__FILE__).'/test.jpg', 'r');
$file = $api->uploader->fromResource($fp);
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from resource'.$e->getMessage());
}
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from resource'.$e->getMessage());
}
// upload from raw
try {
$content = "This is some text I want to upload";
$file = $api->uploader->fromContent($content, 'text/plain');
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to upload from contents'.$e->getMessage());
}
try {
$file->store();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to store uploaded file from contents'.$e->getMessage());
}
$text = file_get_contents($file->getUrl());
$this->assertEquals($text, "This is some text I want to upload");
// test file delete
try {
$file->delete();
} catch (Exception $e) {
$this->fail('We get an unexpected exception trying to delete file'.$e->getMessage());
}
}
}
@@ -0,0 +1,3 @@
<?php
define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demoprivatekey');
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

@@ -0,0 +1,302 @@
<?php
/**
* @file
*
* Uploadcare_Api
*/
class Uploadcare_Api
{
/**
* Uploadcare public key
*
* @var string
**/
private $public_key = null;
/**
* Uploadcare secret key
*
* @var string
**/
private $secret_key = null;
/**
* API host for requests
*
* @var string
**/
private $api_host = 'api.uploadcare.com';
/**
* Uploadcare_Widget instance.
*
* @var Uploadcare_Widget
**/
public $widget = null;
/**
* Uploadcare_Uploader instance
*
* @var Uploadcare_Uploader
**/
public $uploader = null;
/**
* Uploadcare library version
*
* @var string
**/
public $version = '1.0.2/5.3';
/**
* Constructor
*
* @param string $public_key A public key given by Uploadcare.com
* @param string $secret_key A private (secret) key given by Uploadcare.com
* @return void
**/
public function __construct($public_key, $secret_key)
{
$this->public_key = $public_key;
$this->secret_key = $secret_key;
$this->widget = new Uploadcare_Widget($this);
$this->uploader = new Uploadcare_Uploader($this);
}
/**
* Returns public key
*
* @return string
**/
public function getPublicKey()
{
return $this->public_key;
}
/**
* Return an array of File objects to work with.
*
* @param integer $page Page to be shown.
* @return array
**/
public function getFileList($page = 1)
{
$data = $this->__preparedRequest(API_TYPE_FILES, REQUEST_TYPE_GET, array('page' => $page));
$files_raw = (array)$data->results;
$result = array();
foreach ($files_raw as $file_raw) {
$result[] = new Uploadcare_File($file_raw->file_id, $this);
}
return $result;
}
/**
* Get info about pagination.
*
* @param integer $page
* @return array
**/
public function getFilePaginationInfo($page = 1)
{
$data = (array)$this->__preparedRequest(API_TYPE_FILES, REQUEST_TYPE_GET, array('page' => $page));
unset($data['results']);
return $data;
}
/**
* Run raw request to REST.
*
* @param string $method Request method: GET, POST, HEAD, OPTIONS, PUT, etc
* @param string $path Path to request
* @param string $data Array of data to send.
* @param string $headers Additonal headers.
* @return array
**/
public function request($method, $path, $data = array(), $headers = array())
{
$ch = curl_init(sprintf('https://%s%s', $this->api_host, $path));
$this->__setRequestType($ch, $method);
$this->__setHeaders($ch, $headers, $data);
$data = curl_exec($ch);
if ($data === false) {
throw new Exception(curl_error($ch));
}
$ch_info = curl_getinfo($ch);
if ($method == REQUEST_TYPE_DELETE) {
if ($ch_info['http_code'] != 204) {
throw new Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
} else {
if ($ch_info['http_code'] != 200) {
throw new Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
}
curl_close($ch);
if ($this->public_key == 'demopublickey' || $this->secret_key == 'demoprivatekey') {
trigger_error('You are using the demo account. Please get an Uploadcare account at https://uploadcare.com/accounts/create/', E_USER_WARNING);
}
return json_decode($data);
}
/**
* Make request to API.
* Throws Exception if not http code 200 was returned.
* If http code 200 it will parse returned data form request as JSON.
*
* @param string $type Construct type. Url will be generated using this params. Options: store
* @param string $request_type Request type. Options: get, post, put, delete.
* @param array $params Additional parameters for requests as array.
* @throws Exception
* @return array
**/
public function __preparedRequest($type, $request_type = REQUEST_TYPE_GET, $params = array())
{
$url = $this->__getUrl($type, $params);
$ch = $this->__initRequest($type, $params);
$this->__setRequestType($ch, $request_type);
$this->__setHeaders($ch);
$data = curl_exec($ch);
$ch_info = curl_getinfo($ch);
if ($request_type == REQUEST_TYPE_DELETE) {
if ($ch_info['http_code'] != 204) {
throw new Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
} else {
if ($ch_info['http_code'] != 200) {
throw new Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
}
curl_close($ch);
if ($this->public_key == 'demopublickey' || $this->secret_key == 'demoprivatekey') {
trigger_error('You are using the demo account. Please get an Uploadcare account at https://uploadcare.com/accounts/create/', E_USER_WARNING);
}
return json_decode($data);
}
/**
* Inits curl request and rerturn handler
*
* @param string $type Construct type. Url will be generated using this params. Options: store
* @param array $params Additional parameters for requests as array.
* @return resource
**/
private function __initRequest($type, $params = array())
{
$url = $this->__getUrl($type, $params);
return $ch = curl_init($url);
}
/**
* Return url to send request to.
* Throws Exception if wrong type is provided or parameters missing.
*
* @param string $type Construct type.
* @param array $params Additional parameters for requests as array.
* @throws Exception
* @return string
**/
private function __getUrl($type, $params = array())
{
switch ($type) {
case API_TYPE_RAW:
return sprintf('https://%s/', $this->api_host);
case API_TYPE_ACCOUNT:
return sprintf('https://%s/account/', $this->api_host);
case API_TYPE_FILES:
return sprintf('https://%s/files/?page=%s', $this->api_host, $params['page']);
case API_TYPE_STORE:
if (array_key_exists(UC_PARAM_FILE_ID, $params) == false) {
throw new Exception('Please provide "store_id" param for request');
}
return sprintf('https://%s/files/%s/storage/', $this->api_host, $params['file_id']);
case API_TYPE_FILE:
if (array_key_exists(UC_PARAM_FILE_ID, $params) == false) {
throw new Exception('Please provide "store_id" param for request');
}
return sprintf('https://%s/files/%s/', $this->api_host, $params['file_id']);
default:
throw new Exception('No api url type is provided for request. Use store, or appropriate constants.');
}
}
/**
* Set request type.
* If request type is wrong an Exception will be thrown.
*
* @param resource $ch. Curl resource.
* @param string $type Request type. Options: get, post, put, delete.
* @throws Exception
* @return void
**/
private function __setRequestType($ch, $type = REQUEST_TYPE_GET)
{
switch ($type) {
case REQUEST_TYPE_GET:
case 'GET':
break;
case REQUEST_TYPE_POST:
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
break;
case REQUEST_TYPE_PUT:
case 'PUT':
curl_setopt($ch, CURLOPT_PUT, true);
break;
case REQUEST_TYPE_DELETE:
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case REQUEST_TYPE_HEAD:
case 'HEAD':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
break;
case REQUEST_TYPE_OPTIONS:
case 'OPTIONS':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'OPTIONS');
break;
default:
throw new Exception('No request type is provided for request. Use post, put, delete, get or appropriate constants.');
}
}
/**
* Set all the headers for request and set returntrasfer.
*
* @param resource $ch. Curl resource.
* @param array $headers additional headers.
* @param array $data Data array.
* @return void
**/
private function __setHeaders($ch, $add_headers = array(), $data = array())
{
$content_length = 0;
if (count($data)) {
$content_length = strlen(http_build_query($data));
}
$headers = array(
sprintf('Host: %s', $this->api_host),
sprintf('Authorization: Uploadcare.Simple %s:%s', $this->public_key, $this->secret_key),
'Content-Type: application/json',
'Content-Length: '.$content_length,
'User-Agent: PHP Uploadcare Module '.$this->version,
sprintf('Date: %s', date('Y-m-d H:i:s')),
) + $add_headers;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
/**
* Get object of Uploadcare_File class by file_id
*
* @param string $file_id Uploadcare file_id
* @return Uploadcare_File
**/
public function getFile($file_id)
{
return new Uploadcare_File($file_id, $this);
}
}
@@ -0,0 +1,320 @@
<?php
/**
* @file
*
* Uploadcare_File
*/
class Uploadcare_File
{
/**
* Uploadcare cdn host
*
* @var string
*/
private $cdn_host = 'ucarecdn.com';
/**
* Uploadcare file id
*
* @var string
*/
private $file_id = null;
/**
* Operations and params for operations: crop, resize, scale_crop, effect.
*
* @var array
*/
private $operations = array();
/**
* Uploadcare class instance.
*
* @var Uploadcare_Api
*/
private $api = null;
/**
* Operations list
*/
private $operation_list = array('crop', 'resize', 'scale_crop', 'effect');
/**
* Cached data
*
* @var array
*/
private $cached_data = null;
/**
* Constructs an object for CDN file with specified ID
*
* @param string $file_id Uploadcare file_id
* @param Uploadcare_Uploadcare $api Uploadcare class instance
*/
public function __construct($file_id, Uploadcare_Api $api)
{
$this->file_id = $file_id;
$this->api = $api;
}
public function __get($name)
{
if ($name == 'data') {
if (!$this->cached_data) {
$this->cached_data = (array)$this->api->__preparedRequest(API_TYPE_FILE, REQUEST_TYPE_GET, array('file_id' => $this->file_id));
}
return $this->cached_data;
}
}
/**
* @return string
*/
public function __toString()
{
return $this->getUrl();
}
/**
* Return file_id for this file
*
* @return string
*/
public function getFileId()
{
return $this->file_id;
}
/**
* Try to store file.
*
* @param boolean $check_status Check upload status?
* @return array
*/
public function store()
{
return $this->api->__preparedRequest(API_TYPE_STORE, REQUEST_TYPE_POST, array('file_id' => $this->file_id));
}
/**
* Delete file
*
* @return array
*/
public function delete()
{
return $this->api->__preparedRequest(API_TYPE_FILE, REQUEST_TYPE_DELETE, array('file_id' => $this->file_id));
}
/**
* Get url of original image
*
* @param string $postfix
* @return string
*/
public function getUrl($postfix = null)
{
$url = sprintf('https://%s/%s/', $this->cdn_host, $this->file_id);
$operations = array();
foreach ($this->operations as $i => $operation_item) {
$part = array();
foreach (array_keys($operation_item) as $operation_type) {
$operation_params = $operation_item[$operation_type];
$part[] = $operation_type;
switch ($operation_type) {
case 'crop':
$part = $this->__addPartSize($part, $operation_params);
$part = $this->__addPartCenter($part, $operation_params);
$part = $this->__addPartFillColor($part, $operation_params);
break;
case 'resize':
$part = $this->__addPartSize($part, $operation_params);
break;
case 'scale_crop':
$part = $this->__addPartSize($part, $operation_params);
$part = $this->__addPartCenter($part, $operation_params);
break;
case 'effect':
$part = $this->__addPartEffect($part, $operation_params);
break;
case 'custom':
$part = array($operation_params);
break;
}
$part_str = join('/', $part);
$operations[] = $part_str;
}
}
if (count($operations)) {
$operations_part = join('/-/', $operations);
return $url.'-/'.$operations_part.'/'.$postfix;
} else {
return $url.$postfix;
}
}
/**
* Get image tag
*
* @param string $postfix File path postfix
* @param array $attrs additional attributes
* @return string
*/
public function getImgTag($postfix = null, $attribs = array())
{
$to_compile = array();
foreach ($attribs as $key => $value) {
$to_compile[] = sprintf('%s="%s"', $key, $value);
}
return sprintf('<img src="%s" %s />', $this->getUrl(), join(' ', $to_compile));
}
/**
* Get object with cropped parameters.
*
* @param integer $width Crop width
* @param integer $height Crop height
* @param boolean $center Center crop? true or false (default false).
* @param string $fill_color Fill color. If nothig is provided just use false (default false).
* @return Uploadcare_File
*/
public function crop($width, $height, $center = false, $fill_color = false)
{
$result = clone $this;
$result->operations[]['crop'] = array(
'width' => $width,
'height' => $height,
'center' => $center,
'fill_color' => $fill_color,
);
return $result;
}
/**
* Get object with resized parameters.
* Provide width or height or both.
* If not width or height are provided exceptions will be thrown!
*
* @param integer $width Resized image width. Provide false if you resize proportionally.
* @param integer $height Resized image height. Provide false if you resize proportionally.
* @throws Exception
* @return Uploadcare_File
*/
public function resize($width = false, $height = false)
{
$result = clone $this;
if (!$width && !$height) {
throw new Exception('Please, provide at least width or height for resize');
}
$result->operations[]['resize'] = array(
'width' => $width,
'height' => $height,
);
return $result;
}
/**
* Get object with cropped parameters.
*
* @param integer $width Crop width
* @param integer $height Crop height
* @param boolean $center Center crop? true or false (default false).
* @return Uploadcare_File
*/
public function scaleCrop($width, $height, $center = false)
{
$result = clone $this;
$result->operations[]['scale_crop'] = array(
'width' => $width,
'height' => $height,
'center' => $center,
);
return $result;
}
/**
* Apply effect
*
* @param string $effect Effect name
* @return File
*/
public function effect($effect)
{
$result = clone $this;
$result->operations[]['effect'] = $effect;
return $result;
}
/**
* Add any custom operation.
*
* @param string $operation
*/
public function op($operation)
{
$result = clone $this;
$result->operations[]['custom'] = $operation;
return $result;
}
/**
* Adds part with size for operations
*
* @param array $part
* @param array $params
* @return array
*/
private function __addPartSize($part, $params)
{
$part[] = sprintf('%sx%s', $params['width'], $params['height']);
return $part;
}
/**
* Adds part with center for operations
*
* @param array $part
* @param array $params
* @return array
*/
private function __addPartCenter($part, $params)
{
if ($params['center'] !== false) {
$part[] = 'center';
}
return $part;
}
/**
* Adds part with fill color for operations
*
* @param array $part
* @param array $params
* @return array
*/
private function __addPartFillColor($part, $params)
{
if ($params['fill_color'] !== false) {
$part[] = $params['fill_color'];
}
return $part;
}
/**
* Adds part with effect for operations
*
* @param array $part
* @param string $effect
* @return array
*/
private function __addPartEffect($part, $effect)
{
$part[] = $effect;
return $part;
}
}
@@ -0,0 +1,26 @@
<?php
/**
* @file
*
* Uploadcare Constants
*/
define('API_TYPE_RAW', 'raw');
define('API_TYPE_ACCOUNT', 'account');
define('API_TYPE_FILES', 'files');
define('API_TYPE_FILE', 'file');
define('API_TYPE_STORE', 'store');
define('REQUEST_TYPE_POST', 'post');
define('REQUEST_TYPE_PUT', 'put');
define('REQUEST_TYPE_DELETE', 'delete');
define('REQUEST_TYPE_GET', 'get');
define('REQUEST_TYPE_HEAD', 'head');
define('REQUEST_TYPE_OPTIONS', 'options');
define('UC_PARAM_FILE_ID', 'file_id');
require_once dirname(__FILE__).'/Api.php';
require_once dirname(__FILE__).'/File.php';
require_once dirname(__FILE__).'/Widget.php';
require_once dirname(__FILE__).'/Uploader.php';
@@ -0,0 +1,230 @@
<?php
/**
* @file
*
* Uploadcare_Uploader
*/
class Uploadcare_Uploader {
/**
* Base upload host
*
* @var string
*/
private $host = 'upload.uploadcare.com';
/**
* Api instance
*
* @var Uploadcare_Api
*/
private $api = null;
/**
* Constructor
*/
public function __construct(Uploadcare_Api $api) {
$this->api = $api;
}
/**
* Check file status.
* Return array of json data
*
* @param string $file_id
* @return array
*/
public function status($token) {
$data = array(
'token' => $token,
);
$ch = $this->__initRequest('status', $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
return $data;
}
/**
* Upload file from url and get Uploadcare_File instance
*
* @param string $url An url of file to be uploaded.
* @return Uploadcare_File
*/
public function fromUrl($url, $check_status = true, $timeout = 1, $max_attempts = 5) {
$data = array(
'_' => time(),
'source_url' => $url,
'pub_key' => $this->api->getPublicKey(),
);
$ch = $this->__initRequest('from_url', $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$token = $data->token;
if ($check_status) {
$success = false;
$attempts = 0;
while (!$success) {
$data = $this->status($token);
if ($data->status == 'success') {
$success = true;
}
if ($attempts == $max_attempts) {
throw new Exception('Cannot store file, max attempts reached, upload is not successful');
}
sleep($timeout);
$attempts++;
}
} else {
return $token;
}
$file_id = $data->file_id;
return new Uploadcare_File($file_id, $this->api);
}
/**
* Upload file from local path.
*
* @param string $path
* @return Uploadcare_File
*/
public function fromPath($path) {
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => '@'.$path,
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$file_id = $data->file;
return new Uploadcare_File($file_id, $this->api);
}
/**
* Upload file from file pointer
*
* @param resourse $fp
* @return Uploadcare_File
*/
public function fromResource($fp) {
$tmpfile = tempnam(sys_get_temp_dir(), 'ucr');
$temp = fopen($tmpfile, 'w');
while (!feof($fp)) {
fwrite($temp, fread($fp, 8192));
}
fclose($temp);
fclose($fp);
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => '@'.$tmpfile,
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$file_id = $data->file;
return new Uploadcare_File($file_id, $this->api);
}
/**
* Upload file from string using mime-type.
*
* @param string $content
* @param string $mime_type
* @return Uploadcare_File
*/
public function fromContent($content, $mime_type) {
$tmpfile = tempnam(sys_get_temp_dir(), 'ucr');
$temp = fopen($tmpfile, 'w');
fwrite($temp, $content);
fclose($temp);
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => sprintf('@%s;type=%s', $tmpfile, $mime_type),
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$file_id = $data->file;
return new Uploadcare_File($file_id, $this->api);
}
/**
* Init upload request and return curl resource
*
* @param array $data
* @return resource
*/
private function __initRequest($type, $data = null) {
$url = sprintf('https://%s/%s/', $this->host, $type);
if (is_array($data)) {
$url = sprintf('%s?%s', $url, http_build_query($data));
}
$ch = curl_init($url);
return $ch;
}
/**
* Set request type for curl resrouce
*
* @param resource $ch
* @return void
*/
private function __setRequestType($ch) {
curl_setopt($ch, CURLOPT_POST, true);
}
/**
* Set all the headers for request and set returntrasfer.
*
* @param resource $ch. Curl resource.
* @return void
*/
private function __setHeaders($ch) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'User-Agent: PHP Uploadcare Module '.$this->api->version,
));
}
/**
* Set data to be posted on request
*
* @param resource $ch. Curl resource
* @param array $data
* @return void
*/
private function __setData($ch, $data = array()) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
/**
* Run prepared curl request.
* Throws Exception of not 200 http code
*
* @param resource $ch. Curl resource
* @throws Exception
* @return array
*/
private function __runRequest($ch) {
$data = curl_exec($ch);
$ch_info = curl_getinfo($ch);
if ($ch_info['http_code'] != 200) {
throw new Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
curl_close($ch);
return json_decode($data);
}
}
@@ -0,0 +1,71 @@
<?php
/**
* @file
*
* Uploadcare_Widget
*/
class Uploadcare_Widget {
/**
* Uploadcare_Api instance
*
* @var Uploadcare_Api
*/
private $api = null;
/**
* Uploadcare widget version
* @var string
*/
private $version = '0.6.3';
/**
* Constructor
*
* @param Uploadcare_Api $api
*/
public function __construct(Uploadcare_Api $api) {
$this->api = $api;
}
/**
* Returns <script> sections to include Uploadcare widget
*
* @param string $version Uploadcare version
* @return string
*/
public function getScriptTag($version = null) {
$result = sprintf('<script>UPLOADCARE_PUBLIC_KEY = "%s";</script>', $this->api->getPublicKey());
$result .= sprintf('<script async="async" src="%s"></script>', $this->getScriptSrc($version));
return $result;
}
/**
* Return url for javascript widget.
* If no version is provided method will use default(current) version
*
* @param string $version Version of Uploadcare.com widget
* @return string
*/
public function getScriptSrc($version = null) {
if (!$version) {
$version = $this->version;
}
return sprintf('https://ucarecdn.com/widget/%s/uploadcare/uploadcare-%s.min.js', $version, $version);
}
/**
* Gets input tag to use with widget
*
* @param string $name Input name
* @param array $attribs Custom attributes to include
* @return string
*/
public function getInputTag($name, $attribs = array()) {
$to_compile = array();
foreach ($attribs as $key => $value) {
$to_compile[] = sprintf('%s="%s"', $key, $value);
}
return sprintf('<input type="hidden" role="uploadcare-uploader" name="%s" data-upload-url-base="" %s />', $name, join(' ', $to_compile));
}
}
@@ -0,0 +1,298 @@
<?php
namespace Uploadcare;
class Api
{
/**
* Uploadcare public key
*
* @var string
*/
private $public_key = null;
/**
* Uploadcare secret key
*
* @var string
*/
private $secret_key = null;
/**
* API host for requests
*
* @var string
*/
private $api_host = 'api.uploadcare.com';
/**
* Widget instance.
*
* @var Widget
*/
public $widget = null;
/**
* Uploader instance
*
* @var Uploader
*/
public $uploader = null;
/**
* Uploadcare library version
*
* @var string
*/
public $version = '1.0.2/5.3';
/**
* Constructor
*
* @param string $public_key A public key given by Uploadcare.com
* @param string $secret_key A private (secret) key given by Uploadcare.com
* @return void
*/
public function __construct($public_key, $secret_key)
{
$this->public_key = $public_key;
$this->secret_key = $secret_key;
$this->widget = new Widget($this);
$this->uploader = new Uploader($this);
}
/**
* Returns public key
*
* @return string
*/
public function getPublicKey()
{
return $this->public_key;
}
/**
* Return an array of File objects to work with.
*
* @param integer $page Page to be shown.
* @return array
*/
public function getFileList($page = 1)
{
$data = $this->__preparedRequest(API_TYPE_FILES, REQUEST_TYPE_GET, array('page' => $page));
$files_raw = (array)$data->results;
$result = array();
foreach ($files_raw as $file_raw) {
$result[] = new File($file_raw->file_id, $this);
}
return $result;
}
/**
* Get info about pagination.
*
* @param integer $page
* @return array
*/
public function getFilePaginationInfo($page = 1)
{
$data = (array)$this->__preparedRequest(API_TYPE_FILES, REQUEST_TYPE_GET, array('page' => $page));
unset($data['results']);
return $data;
}
/**
* Run raw request to REST.
*
* @param string $method Request method: GET, POST, HEAD, OPTIONS, PUT, etc
* @param string $path Path to request
* @param string $data Array of data to send.
* @param string $headers Additonal headers.
* @return array
*/
public function request($method, $path, $data = array(), $headers = array())
{
$ch = curl_init(sprintf('https://%s%s', $this->api_host, $path));
$this->__setRequestType($ch, $method);
$this->__setHeaders($ch, $headers, $data);
$data = curl_exec($ch);
if ($data === false) {
throw new \Exception(curl_error($ch));
}
$ch_info = curl_getinfo($ch);
if ($method == REQUEST_TYPE_DELETE) {
if ($ch_info['http_code'] != 204) {
throw new \Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
} else {
if ($ch_info['http_code'] != 200) {
throw new \Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
}
curl_close($ch);
if ($this->public_key == 'demopublickey' || $this->secret_key == 'demoprivatekey') {
trigger_error('You are using the demo account. Please get an Uploadcare account at https://uploadcare.com/accounts/create/', E_USER_WARNING);
}
return json_decode($data);
}
/**
* Make request to API.
* Throws Exception if not http code 200 was returned.
* If http code 200 it will parse returned data form request as JSON.
*
* @param string $type Construct type. Url will be generated using this params. Options: store
* @param string $request_type Request type. Options: get, post, put, delete.
* @param array $params Additional parameters for requests as array.
* @throws Exception
* @return array
*/
public function __preparedRequest($type, $request_type = REQUEST_TYPE_GET, $params = array())
{
$url = $this->__getUrl($type, $params);
$ch = $this->__initRequest($type, $params);
$this->__setRequestType($ch, $request_type);
$this->__setHeaders($ch);
$data = curl_exec($ch);
$ch_info = curl_getinfo($ch);
if ($request_type == REQUEST_TYPE_DELETE) {
if ($ch_info['http_code'] != 204) {
throw new \Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
} else {
if ($ch_info['http_code'] != 200) {
throw new \Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
}
curl_close($ch);
if ($this->public_key == 'demopublickey' || $this->secret_key == 'demoprivatekey') {
trigger_error('You are using the demo account. Please get an Uploadcare account at https://uploadcare.com/accounts/create/', E_USER_WARNING);
}
return json_decode($data);
}
/**
* Inits curl request and rerturn handler
*
* @param string $type Construct type. Url will be generated using this params. Options: store
* @param array $params Additional parameters for requests as array.
* @return resource
*/
private function __initRequest($type, $params = array())
{
$url = $this->__getUrl($type, $params);
return $ch = curl_init($url);
}
/**
* Return url to send request to.
* Throws Exception if wrong type is provided or parameters missing.
*
* @param string $type Construct type.
* @param array $params Additional parameters for requests as array.
* @throws Exception
* @return string
*/
private function __getUrl($type, $params = array())
{
switch ($type) {
case API_TYPE_RAW:
return sprintf('https://%s/', $this->api_host);
case API_TYPE_ACCOUNT:
return sprintf('https://%s/account/', $this->api_host);
case API_TYPE_FILES:
return sprintf('https://%s/files/?page=%s', $this->api_host, $params['page']);
case API_TYPE_STORE:
if (array_key_exists(UC_PARAM_FILE_ID, $params) == false) {
throw new \Exception('Please provide "store_id" param for request');
}
return sprintf('https://%s/files/%s/storage/', $this->api_host, $params['file_id']);
case API_TYPE_FILE:
if (array_key_exists(UC_PARAM_FILE_ID, $params) == false) {
throw new \Exception('Please provide "store_id" param for request');
}
return sprintf('https://%s/files/%s/', $this->api_host, $params['file_id']);
default:
throw new \Exception('No api url type is provided for request. Use store, or appropriate constants.');
}
}
/**
* Set request type.
* If request type is wrong an Exception will be thrown.
*
* @param resource $ch. Curl resource.
* @param string $type Request type. Options: get, post, put, delete.
* @throws Exception
* @return void
*/
private function __setRequestType($ch, $type = REQUEST_TYPE_GET)
{
switch ($type) {
case REQUEST_TYPE_GET:
case 'GET':
break;
case REQUEST_TYPE_POST:
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
break;
case REQUEST_TYPE_PUT:
case 'PUT':
curl_setopt($ch, CURLOPT_PUT, true);
break;
case REQUEST_TYPE_DELETE:
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case REQUEST_TYPE_HEAD:
case 'HEAD':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
break;
case REQUEST_TYPE_OPTIONS:
case 'OPTIONS':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'OPTIONS');
break;
default:
throw new \Exception('No request type is provided for request. Use post, put, delete, get or appropriate constants.');
}
}
/**
* Set all the headers for request and set returntrasfer.
*
* @param resource $ch. Curl resource.
* @param array $headers additional headers.
* @param array $data Data array.
* @return void
*/
private function __setHeaders($ch, $add_headers = array(), $data = array())
{
$content_length = 0;
if (count($data)) {
$content_length = strlen(http_build_query($data));
}
$headers = array(
sprintf('Host: %s', $this->api_host),
sprintf('Authorization: Uploadcare.Simple %s:%s', $this->public_key, $this->secret_key),
'Content-Type: application/json',
'Content-Length: '.$content_length,
'User-Agent: PHP Uploadcare Module '.$this->version,
sprintf('Date: %s', date('Y-m-d H:i:s')),
) + $add_headers;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
/**
* Get object of File class by file_id
*
* @param string $file_id Uploadcare file_id
* @return File
*/
public function getFile($file_id)
{
return new File($file_id, $this);
}
}
@@ -0,0 +1,316 @@
<?php
namespace Uploadcare;
class File
{
/**
* Uploadcare cdn host
*
* @var string
*/
private $cdn_host = 'ucarecdn.com';
/**
* Uploadcare file id
*
* @var string
*/
private $file_id = null;
/**
* Operations and params for operations: crop, resize, scale_crop, effect.
*
* @var array
*/
private $operations = array();
/**
* Uploadcare class instance.
*
* @var Api
*/
private $api = null;
/**
* Operations list
*/
private $operation_list = array('crop', 'resize', 'scale_crop', 'effect');
/**
* Cached data
*
* @var array
*/
private $cached_data = null;
/**
* Constructs an object for CDN file with specified ID
*
* @param string $file_id Uploadcare file_id
* @param Uploadcare $api Uploadcare class instance
*/
public function __construct($file_id, Api $api)
{
$this->file_id = $file_id;
$this->api = $api;
}
public function __get($name)
{
if ($name == 'data') {
if (!$this->cached_data) {
$this->cached_data = (array)$this->api->__preparedRequest(API_TYPE_FILE, REQUEST_TYPE_GET, array('file_id' => $this->file_id));
}
return $this->cached_data;
}
}
/**
* @return string
*/
public function __toString()
{
return $this->getUrl();
}
/**
* Return file_id for this file
*
* @return string
*/
public function getFileId()
{
return $this->file_id;
}
/**
* Try to store file.
*
* @param boolean $check_status Check upload status?
* @return array
*/
public function store()
{
return $this->api->__preparedRequest(API_TYPE_STORE, REQUEST_TYPE_POST, array('file_id' => $this->file_id));
}
/**
* Delete file
*
* @return array
*/
public function delete()
{
return $this->api->__preparedRequest(API_TYPE_FILE, REQUEST_TYPE_DELETE, array('file_id' => $this->file_id));
}
/**
* Get url of original image
*
* @param string $postfix
* @return string
*/
public function getUrl($postfix = null)
{
$url = sprintf('https://%s/%s/', $this->cdn_host, $this->file_id);
$operations = array();
foreach ($this->operations as $i => $operation_item) {
$part = array();
foreach (array_keys($operation_item) as $operation_type) {
$operation_params = $operation_item[$operation_type];
$part[] = $operation_type;
switch ($operation_type) {
case 'crop':
$part = $this->__addPartSize($part, $operation_params);
$part = $this->__addPartCenter($part, $operation_params);
$part = $this->__addPartFillColor($part, $operation_params);
break;
case 'resize':
$part = $this->__addPartSize($part, $operation_params);
break;
case 'scale_crop':
$part = $this->__addPartSize($part, $operation_params);
$part = $this->__addPartCenter($part, $operation_params);
break;
case 'effect':
$part = $this->__addPartEffect($part, $operation_params);
break;
case 'custom':
$part = array($operation_params);
break;
}
$part_str = join('/', $part);
$operations[] = $part_str;
}
}
if (count($operations)) {
$operations_part = join('/-/', $operations);
return $url.'-/'.$operations_part.'/'.$postfix;
} else {
return $url.$postfix;
}
}
/**
* Get image tag
*
* @param string $postfix File path postfix
* @param array $attrs additional attributes
* @return string
*/
public function getImgTag($postfix = null, $attribs = array())
{
$to_compile = array();
foreach ($attribs as $key => $value) {
$to_compile[] = sprintf('%s="%s"', $key, $value);
}
return sprintf('<img src="%s" %s />', $this->getUrl(), join(' ', $to_compile));
}
/**
* Get object with cropped parameters.
*
* @param integer $width Crop width
* @param integer $height Crop height
* @param boolean $center Center crop? true or false (default false).
* @param string $fill_color Fill color. If nothig is provided just use false (default false).
* @return File
*/
public function crop($width, $height, $center = false, $fill_color = false)
{
$result = clone $this;
$result->operations[]['crop'] = array(
'width' => $width,
'height' => $height,
'center' => $center,
'fill_color' => $fill_color,
);
return $result;
}
/**
* Get object with resized parameters.
* Provide width or height or both.
* If not width or height are provided exceptions will be thrown!
*
* @param integer $width Resized image width. Provide false if you resize proportionally.
* @param integer $height Resized image height. Provide false if you resize proportionally.
* @throws \Exception
* @return File
*/
public function resize($width = false, $height = false)
{
$result = clone $this;
if (!$width && !$height) {
throw new \Exception('Please, provide at least width or height for resize');
}
$result->operations[]['resize'] = array(
'width' => $width,
'height' => $height,
);
return $result;
}
/**
* Get object with cropped parameters.
*
* @param integer $width Crop width
* @param integer $height Crop height
* @param boolean $center Center crop? true or false (default false).
* @return File
*/
public function scaleCrop($width, $height, $center = false)
{
$result = clone $this;
$result->operations[]['scale_crop'] = array(
'width' => $width,
'height' => $height,
'center' => $center,
);
return $result;
}
/**
* Apply effect
*
* @param string $effect Effect name
* @return File
*/
public function effect($effect)
{
$result = clone $this;
$result->operations[]['effect'] = $effect;
return $result;
}
/**
* Add any custom operation.
*
* @param string $operation
*/
public function op($operation)
{
$result = clone $this;
$result->operations[]['custom'] = $operation;
return $result;
}
/**
* Adds part with size for operations
*
* @param array $part
* @param array $params
* @return array
*/
private function __addPartSize($part, $params)
{
$part[] = sprintf('%sx%s', $params['width'], $params['height']);
return $part;
}
/**
* Adds part with center for operations
*
* @param array $part
* @param array $params
* @return array
*/
private function __addPartCenter($part, $params)
{
if ($params['center'] !== false) {
$part[] = 'center';
}
return $part;
}
/**
* Adds part with fill color for operations
*
* @param array $part
* @param array $params
* @return array
*/
private function __addPartFillColor($part, $params)
{
if ($params['fill_color'] !== false) {
$part[] = $params['fill_color'];
}
return $part;
}
/**
* Adds part with effect for operations
*
* @param array $part
* @param string $effect
* @return array
*/
private function __addPartEffect($part, $effect)
{
$part[] = $effect;
return $part;
}
}
@@ -0,0 +1,20 @@
<?php
define('API_TYPE_RAW', 'raw');
define('API_TYPE_ACCOUNT', 'account');
define('API_TYPE_FILES', 'files');
define('API_TYPE_FILE', 'file');
define('API_TYPE_STORE', 'store');
define('REQUEST_TYPE_POST', 'post');
define('REQUEST_TYPE_PUT', 'put');
define('REQUEST_TYPE_DELETE', 'delete');
define('REQUEST_TYPE_GET', 'get');
define('REQUEST_TYPE_HEAD', 'head');
define('REQUEST_TYPE_OPTIONS', 'options');
define('UC_PARAM_FILE_ID', 'file_id');
require_once dirname(__FILE__).'/Api.php';
require_once dirname(__FILE__).'/File.php';
require_once dirname(__FILE__).'/Widget.php';
require_once dirname(__FILE__).'/Uploader.php';
@@ -0,0 +1,238 @@
<?php
namespace Uploadcare;
class Uploader
{
/**
* Base upload host
*
* @var string
*/
private $host = 'upload.uploadcare.com';
/**
* Api instance
*
* @var Api
*/
private $api = null;
/**
* Constructor
*/
public function __construct(Api $api)
{
$this->api = $api;
}
/**
* Check file status.
* Return array of json data
*
* @param string $file_id
* @return array
*/
public function status($token)
{
$data = array(
'token' => $token,
);
$ch = $this->__initRequest('status', $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
return $data;
}
/**
* Upload file from url and get File instance
*
* @param string $url An url of file to be uploaded.
* @return File
*/
public function fromUrl($url, $check_status = true, $timeout = 1, $max_attempts = 5)
{
$data = array(
'_' => time(),
'source_url' => $url,
'pub_key' => $this->api->getPublicKey(),
);
$ch = $this->__initRequest('from_url', $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$token = $data->token;
if ($check_status) {
$success = false;
$attempts = 0;
while (!$success) {
$data = $this->status($token);
if ($data->status == 'success') {
$success = true;
}
if ($attempts == $max_attempts) {
throw new \Exception('Cannot store file, max attempts reached, upload is not successful');
}
sleep($timeout);
$attempts++;
}
} else {
return $token;
}
$file_id = $data->file_id;
return new File($file_id, $this->api);
}
/**
* Upload file from local path.
*
* @param string $path
* @return File
*/
public function fromPath($path)
{
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => '@'.$path,
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$file_id = $data->file;
return new File($file_id, $this->api);
}
/**
* Upload file from file pointer
*
* @param resourse $fp
* @return File
*/
public function fromResource($fp)
{
$tmpfile = tempnam(sys_get_temp_dir(), 'ucr');
$temp = fopen($tmpfile, 'w');
while (!feof($fp)) {
fwrite($temp, fread($fp, 8192));
}
fclose($temp);
fclose($fp);
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => '@'.$tmpfile,
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$file_id = $data->file;
return new File($file_id, $this->api);
}
/**
* Upload file from string using mime-type.
*
* @param string $content
* @param string $mime_type
* @return File
*/
public function fromContent($content, $mime_type)
{
$tmpfile = tempnam(sys_get_temp_dir(), 'ucr');
$temp = fopen($tmpfile, 'w');
fwrite($temp, $content);
fclose($temp);
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => sprintf('@%s;type=%s', $tmpfile, $mime_type),
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$file_id = $data->file;
return new File($file_id, $this->api);
}
/**
* Init upload request and return curl resource
*
* @param array $data
* @return resource
*/
private function __initRequest($type, $data = null)
{
$url = sprintf('https://%s/%s/', $this->host, $type);
if (is_array($data)) {
$url = sprintf('%s?%s', $url, http_build_query($data));
}
$ch = curl_init($url);
return $ch;
}
/**
* Set request type for curl resrouce
*
* @param resource $ch
* @return void
*/
private function __setRequestType($ch)
{
curl_setopt($ch, CURLOPT_POST, true);
}
/**
* Set all the headers for request and set returntrasfer.
*
* @param resource $ch. Curl resource.
* @return void
*/
private function __setHeaders($ch)
{
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'User-Agent: PHP Uploadcare Module '.$this->api->version,
));
}
/**
* Set data to be posted on request
*
* @param resource $ch. Curl resource
* @param array $data
* @return void
*/
private function __setData($ch, $data = array())
{
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
/**
* Run prepared curl request.
* Throws Exception of not 200 http code
*
* @param resource $ch. Curl resource
* @throws Exception
* @return array
*/
private function __runRequest($ch)
{
$data = curl_exec($ch);
$ch_info = curl_getinfo($ch);
if ($ch_info['http_code'] != 200) {
throw new \Exception('Request returned unexpected http code '.$ch_info['http_code'].'. '.$data);
}
curl_close($ch);
return json_decode($data);
}
}
@@ -0,0 +1,72 @@
<?php
namespace Uploadcare;
class Widget
{
/**
* Api instance
*
* @var Api
*/
private $api = null;
/**
* Uploadcare widget version
* @var string
*/
private $version = '0.6.3';
/**
* Constructor
*
* @param Api $api
*/
public function __construct(Api $api)
{
$this->api = $api;
}
/**
* Returns <script> sections to include Uploadcare widget
*
* @param string $version Uploadcare version
* @return string
*/
public function getScriptTag($version = null)
{
$result = sprintf('<script>UPLOADCARE_PUBLIC_KEY = "%s";</script>', $this->api->getPublicKey());
$result .= sprintf('<script async="async" src="%s"></script>', $this->getScriptSrc($version));
return $result;
}
/**
* Return url for javascript widget.
* If no version is provided method will use default(current) version
*
* @param string $version Version of Uploadcare.com widget
* @return string
*/
public function getScriptSrc($version = null)
{
if (!$version) {
$version = $this->version;
}
return sprintf('https://ucarecdn.com/widget/%s/uploadcare/uploadcare-%s.min.js', $version, $version);
}
/**
* Gets input tag to use with widget
*
* @param string $name Input name
* @param array $attribs Custom attributes to include
* @return string
*/
public function getInputTag($name, $attribs = array())
{
$to_compile = array();
foreach ($attribs as $key => $value) {
$to_compile[] = sprintf('%s="%s"', $key, $value);
}
return sprintf('<input type="hidden" role="uploadcare-uploader" name="%s" data-upload-url-base="" %s />', $name, join(' ', $to_compile));
}
}