This repository was archived by the owner on Apr 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConvertAPI.php
More file actions
212 lines (182 loc) · 6.46 KB
/
ConvertAPI.php
File metadata and controls
212 lines (182 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<?php
#
# ConvertAPI.php
#
# Copyright 2014, Jonathon Wardman. All rights reserved.
# Contact: jonathon@flutt.co.uk / flutt.co.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
namespace ConvertAPI;
/**
* Abstract class for interacting with the convertapi.com APIs. Should be
* extended in order to support each of the available convertapi.com conversion
* methods.
*
* @see http://convertapi.com/
*/
abstract class ConvertAPI {
/**
* API key to use when making requests to convertapi.com APIs.
*/
public $apiKey = null;
/**
* Additional parameters to send to convertapi.com when carrying out a Word to
* PDF conversion.
*/
protected $_additionalParameters = array();
/**
* An array of valid input file formats, or a string representing a URL. Will
* be checked before conversion and therefore must be populated by concrete
* classes.
*/
protected $_validInputFormats = array();
/* Magic methods. */
/**
* Constructor. Optionally sets the API key to use for calls to convertapi.com.
*
* @param string $apiKey Optional convertapi.com API key to use.
*/
public function __construct($apiKey = null) {
if (!isset($this->_apiUrl)) {
throw new \Exception('Child classes of ConvertAPI must specify a value for $this->_apiUrl.');
}
if ($apiKey != null) {
$this->apiKey = $apiKey;
}
}
/* Public methods. */
/**
* Concrete classes must provide a convert method: a method which sends the
* request to convertapi.com and deals with the response.
*
* @param string $inputFilename Full path of file to convert.
* @param string $outputFilename Full path of file to write with converted document.
*/
public function convert($inputFilename, $outputFilename = null) {
// Check input file (if it's an array of local file extensions)...
$urlInput = false;
if (is_array($this->_validInputFormats)) {
$inputFilenameChunks = explode('.', $inputFilename);
if (in_array(array_pop($inputFilenameChunks), $this->_validInputFormats)) {
if (!is_readable($inputFilename)) {
throw new \Exception('Input file is not readable.');
}
} else {
throw new \Exception('Invalid input file type.');
}
} else if ($this->_validInputFormats == 'url') {
if (preg_match('/^https?:\/\//', $inputFilename)) {
$urlInput = true;
} else {
throw new \Exception('Invalid input URL.');
}
} else {
throw new \Exception('Invalid input format identifier.');
}
// Check output file...
if ($outputFilename !== null) {
if (!((file_exists($outputFilename) && is_writable($outputFilename)) || is_writable(dirname($outputFilename)))) {
throw new \Exception('Output file target is not writable.');
}
}
// Do conversion...
try {
$convertResponse = $this->_apiRequest($inputFilename, $urlInput);
if ($outputFilename !== null) {
if (file_put_contents($outputFilename, $convertResponse['document'])) {
unset($convertResponse['document']);
return $convertResponse;
} else {
throw new \Exception('Error writing output file.');
}
} else {
return $convertResponse['document'];
}
} catch (\Exception $e) {
throw $e;
}
}
/* Protected methods. */
/**
* Send a request to the API.
*
* @param string $filename Full path of file to convert.
* @return array Array containing request details and binary data. See above.
*/
protected function _apiRequest($filename, $urlInput = false) {
if (function_exists('curl_init')) {
// Set the source filename or URL...
if ($urlInput == true) {
$postFields = array('CUrl' => $filename);
} else {
if (is_readable($filename)) {
$postFields = array('File' => '@'.$filename);
} else {
throw new \Exception('File does not exist or is not readable.');
}
}
// Build the rest of the post fields array...
if ($this->apiKey !== null) {
$postFields['ApiKey'] = $this->apiKey;
}
if (isset($this->_additionalParameters) && is_array($this->_additionalParameters)) {
foreach ($this->_additionalParameters AS $key => $value) {
if ($value !== null) {
$postFields[$key] = $value;
}
}
}
// Carry out the cURL request...
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curlHandle, CURLOPT_URL, $this->_apiUrl);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
$curlReturn = curl_exec($curlHandle);
// Split the response into headers and body (usually document)...
$curlReturnArray = explode("\r\n\r\n", $curlReturn);
// Check headers and return the document...
$headers = explode("\r\n", $curlReturnArray[1]);
if ($headers[0] == 'HTTP/1.1 200 OK') {
$returnArray = array('document' => $curlReturnArray[2]);
foreach ($headers AS $headerLine) {
$headerParts = explode(': ', $headerLine);
switch ($headerParts[0]) {
case 'InputFormat': $returnArray['input'] = $headerParts[1]; break;
case 'OutputFormat': $returnArray['output'] = $headerParts[1]; break;
case 'CreditsCost': $returnArray['cost'] = $headerParts[1]; break;
case 'FileSize': $returnArray['size'] = $headerParts[1]; break;
}
}
return $returnArray;
} else {
throw new \Exception('Error converting document: '.trim(array_shift(explode("\n", $curlReturnArray[1]))));
}
} else {
throw new \Exception('Unable to init cURL. Check PHP is compiled with cURL support.');
}
}
/* Abstract methods. */
/**
* Magic setter method. Concrete classes must define this to handle the
* _additionalParametersvariable. It should check and set all valid additional
* parameters for the given API.
*
* @param string $name Name of the additional parameter to set.
* @param string $value Value to set the parameter to.
*/
abstract public function __set($name, $value);
}