· 9 years ago · Jun 10, 2017, 09:54 PM
1<?php
2
3 /*
4 * **************************************************
5 * CHANGE THESE IF RUNNING ON SEPARATE SERVER
6 * **************************************************
7 * Database connection details.
8 * Note: If you are running this script on another server, ensure your database
9 * isn't locked down to just localhost. It'll need privileges to allow connections
10 * from this host.
11 */
12 $databaseHost = "";
13 $databaseUser = "";
14 $databasePass = "";
15 $databaseName = "";
16
17 $directFileServers = array();
18 /*
19 * **************************************************
20 * DIRECT FILE SERVER ACCESS DETAILS
21 * **************************************************
22 * Set these if you have direct file servers. Create a new set of the following values for
23 * each file server. The 'file_server_id' must match the id set in your database
24 * table 'file_server'. The 'file_storage_path' is the full base path, generally ending with
25 * '/files'. Exclude the final forward slash.
26 *
27 $directFileServers[] = array(
28 'file_server_id' => 2,
29 'ssh_host' => 'fs1.yourhost.com',
30 'ssh_port' => '22',
31 'ssh_username' => 'username',
32 'ssh_password' => 'password',
33 'file_storage_path' => '/path/to/your/files',
34 )
35
36 /*
37 * **************************************************
38 * DONT CHANGE ANYTHING BELOW HERE
39 * **************************************************
40 */
41
42 // if this is running in the same location as the script
43 define('DOC_ROOT', dirname(__FILE__));
44 $configPath = DOC_ROOT . '/../../../_config.inc.php';
45 if (file_exists($configPath))
46 {
47 include_once($configPath);
48
49 $databaseHost = _CONFIG_DB_HOST;
50 $databaseUser = _CONFIG_DB_USER;
51 $databasePass = _CONFIG_DB_PASS;
52 $databaseName = _CONFIG_DB_NAME;
53
54 define('ON_SCRIPT_INSTALL', true);
55 }
56 else
57 {
58 define('ON_SCRIPT_INSTALL', false);
59 }
60
61 define("DATABASE_HOST", $databaseHost);
62 define("DATABASE_USER", $databaseUser);
63 define("DATABASE_PASS", $databasePass);
64 define("DATABASE_NAME", $databaseName);
65
66 // make file server ssh details available in constant
67 define("DIRECT_FILE_SERVER_DETAILS", serialize($directFileServers));
68
69 /*
70 * Connect database and load config from plugin settings.
71 */
72 try
73 {
74 $db = dbConnect();
75 if ($db)
76 {
77 $stmt = $db->query("SELECT * FROM plugin WHERE folder_name='mediaconverter' LIMIT 1");
78 $pluginDetails = $stmt->fetch(PDO::FETCH_ASSOC);
79 $pluginSettings = $pluginDetails['plugin_settings'];
80 if ($pluginSettings)
81 {
82 $pluginSettingsArr = json_decode($pluginSettings, true);
83 }
84 }
85 }
86 catch (Exception $e)
87 {
88 echo "\n" . $e->getMessage() . "\n";
89 exit;
90 }
91
92 /*
93 * For local storage this script needs to have access via SSH to the files. Set
94 * the SSH details below.
95 */
96 define("LOCAL_STORAGE_SSH_HOST", $pluginSettingsArr['ssh_host']);
97 define("LOCAL_STORAGE_SSH_USER", $pluginSettingsArr['ssh_user']);
98 define("LOCAL_STORAGE_SSH_PASS", $pluginSettingsArr['ssh_password']);
99 define("LOCAL_STORAGE_DEFAULT_PATH", $pluginSettingsArr['local_storage_path']);
100
101 /*
102 * General config.
103 */
104
105 // change this to set the maximum conversions that can be done at once.
106 define("VIDEO_SCREENSHOT_ID", $pluginSettingsArr['video_screenshot_id']);
107
108 // FFMPEG path
109 define("FFMPEG_PATH", "ffmpeg");
110
111 // show output, used for debugging
112 define("SHOW_OUTPUT", $pluginSettingsArr['output_messages']);
113
114 // local paths, shouldn't need changed
115 define("SCRIPT_ROOT_FOLDER", dirname(__FILE__));
116 define("CACHE_PATH", SCRIPT_ROOT_FOLDER . '/_cache');
117 define("CACHE_SCREENSHOT_PATH", sys_get_temp_dir());
118 define("SCREENSHOT_SECONDS", '15'); // in 2 digit format, i.e. 05 = 5 seconds.
119
120 // export file type
121 define("EXPORT_FILE_EXTENSION", $pluginSettingsArr['output_type']);
122 define("EXPORT_FILE_MIMETYPE", "video/".$pluginSettingsArr['output_type']);
123
124 /*
125 * External includes
126 */
127 set_include_path(get_include_path() . PATH_SEPARATOR . SCRIPT_ROOT_FOLDER . '/phpseclib');
128
129 include_once('Net/SFTP.php'); define("CACHE_SCREENSHOT_PATH", sys_get_temp_dir());
130
131 /*
132 * Connect database and load config from plugin settings.
133 */
134 try
135 {
136 $db = dbConnect();
137 if ($db)
138 {
139 $stmt = $db->query("SELECT * FROM plugin WHERE folder_name='mediaconverter' LIMIT 1");
140 $pluginDetails = $stmt->fetch(PDO::FETCH_ASSOC);
141 $pluginSettings = $pluginDetails['plugin_settings'];
142 if ($pluginSettings)
143 {
144 $pluginSettingsArr = json_decode($pluginSettings, true);
145 }
146 }
147 }
148 catch (Exception $e)
149 {
150 echo "\n" . $e->getMessage() . "\n";
151 exit;
152 }
153
154
155 try {
156 $db = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USER, DATABASE_PASS);
157
158 $stmt = $db->query("SELECT * FROM file WHERE id=" . VIDEO_SCREENSHOT_ID);
159 $files = $stmt->fetchAll();
160
161 } catch(Exception $e) {
162 echo "Error: " . $e->getMessage();
163 }
164
165 foreach($files as $file) {
166 $localFile = '/home/teranode/public_html/files/' . $file['localFilePath'];
167
168 // log
169 output("Getting " . SCREENSHOT_SECONDS . " second screenshot...\n");
170
171 // thumb path
172 $thumbFilename = current(explode(".", MD5($file['id'])));
173 $fullThumbPath = CACHE_SCREENSHOT_PATH;
174 $fullThumbPath .= '/' . $thumbFilename . '.jpg';
175
176 // ensure it doesn't exist from a previous convert
177 if(file_exists($fullThumbPath))
178 {
179 unlink($fullThumbPath);
180 }
181
182 // default time to get the image
183 $second = 1;
184
185 // get the duration and a random place within that
186 $thumbPathCmd = "ffmpeg -i $localFile 2>&1";
187 if (preg_match('/Duration: ((\d+):(\d+):(\d+))/s', `$thumbPathCmd`, $time)) {
188 $total = ($time[2] * 3600) + ($time[3] * 60) + $time[4];
189 $second = rand(1, ($total - 1));
190 }
191
192 // get the screenshot
193 $thumbPathCmd = "ffmpeg -ss $second -i $localFile -deinterlace -an -t 00:00:01 -r 1 -y -q:v 1 -vframes 1 $fullThumbPath";
194
195 if (SHOW_OUTPUT != 1)
196 {
197 $thumbPathCmd .= ' 2>&1';
198 }
199 $output = shell_exec($thumbPathCmd);
200
201 // prepare notes
202 $notesMessage = "ScreenShot Command:\n";
203 $notesMessage .= $thumbPathCmd . "\n\n";
204 $notesMessage .= "Result:\n";
205 $notesMessage .= $output;
206 output($notesMessage);
207 output("\n");
208
209 // if screen exists, move it to the core server for storage
210 if ((file_exists($fullThumbPath)) && (filesize($fullThumbPath) > 0))
211 {
212 $remoteScriptRoot = $pluginSettingsArr['script_path_root'];
213 $remoteScriptThumbPath = $remoteScriptRoot . '/core/cache/plugins/mediaconverter/'.$file['id'].'/original_thumb.jpg';
214
215 // first try setting the file locally
216 $done = false;
217 if (ON_SCRIPT_INSTALL == true)
218 {
219 if (!file_exists($remoteScriptThumbPath))
220 {
221 @mkdir(dirname($remoteScriptThumbPath), 0777, true);
222 }
223 $done = rename($fullThumbPath, $remoteScriptThumbPath);
224 }
225
226 // try over ssh
227 if ($done == false)
228 {
229 // connect to 'local' storage via SSH
230 $sftp = new Net_SFTP(LOCAL_STORAGE_SSH_HOST);
231 if (!$sftp->login(LOCAL_STORAGE_SSH_USER, LOCAL_STORAGE_SSH_PASS))
232 {
233 output("Error: Failed logging into " . LOCAL_STORAGE_SSH_HOST . " via SSH to transfer screenshot.\n");
234 }
235 else
236 {
237 // create folder structure
238 $sftp->mkdir($remoteScriptRoot . '/core/cache/plugins/');
239 $sftp->mkdir($remoteScriptRoot . '/core/cache/plugins/mediaconverter/');
240 $sftp->mkdir($remoteScriptRoot . '/core/cache/plugins/mediaconverter/'.$file['id'].'/');
241
242 // set folder to chmod 777
243 //$sftp->chmod(0777, $remoteScriptRoot . '/core/cache/plugins/mediaconverter/'.$file['id'].'/');
244
245 // upload screen
246 $rs = $sftp->put($remoteScriptThumbPath, $fullThumbPath, NET_SFTP_LOCAL_FILE);
247 if (!$rs)
248 {
249 output("Error: Failed uploading thumb to " . LOCAL_STORAGE_SSH_HOST . " via SSH. Local file: " . $fullThumbPath . ". Remote path: " . $remoteScriptThumbPath . "\n");
250 }
251 @unlink($fullThumbPath);
252
253 // set file to chmod 777
254 //$sftp->chmod(0777, $remoteScriptThumbPath);
255 }
256 }
257 }
258 }
259
260 function dbConnect()
261 {
262 return new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USER, DATABASE_PASS);
263 }
264
265 function getFileContent($db, $file)
266 {
267 // setup local cached file
268 $localFilename = MD5(microtime()) . '.' . $file['extension'];
269 $localFilePath = CACHE_PATH . '/' . $localFilename;
270
271 // figure out server storage setup
272 $storageType = 'local';
273 $storageLocation = LOCAL_STORAGE_DEFAULT_PATH;
274 $uploadServerDetails = loadServer($db, $file);
275 if ($uploadServerDetails != false)
276 {
277 $storageLocation = $uploadServerDetails['storagePath'];
278 $storageType = $uploadServerDetails['serverType'];
279
280 // if no storage path set & local, use system default
281 if ((strlen($storageLocation) == 0) && ($storageType == 'local'))
282 {
283 $storageLocation = LOCAL_STORAGE_DEFAULT_PATH;
284 }
285
286 if ($storageType == 'direct')
287 {
288 $storageLocation = LOCAL_STORAGE_DEFAULT_PATH;
289 }
290 }
291
292 // use ssh to get contents of 'local' files
293 if (($storageType == 'local') || ($storageType == 'direct'))
294 {
295 // get remote file path
296 $remoteFilePath = $storageLocation . $file['localFilePath'];
297
298 // first try getting the file locally
299 $done = false;
300 if ((ON_SCRIPT_INSTALL == true) && file_exists($remoteFilePath))
301 {
302
303 $done = copy($remoteFilePath, $localFilePath);
304 if ($done)
305 {
306 return $localFilePath;
307 }
308 }
309
310 // try over ssh
311 if ($done == false)
312 {
313 $sshHost = LOCAL_STORAGE_SSH_HOST;
314 $sshUser = LOCAL_STORAGE_SSH_USER;
315 $sshPass = LOCAL_STORAGE_SSH_PASS;
316
317 // if 'direct' file server, get SSH details
318 $serverDetails = getDirectFileServerSSHDetails($file['serverId']);
319 if($serverDetails)
320 {
321 $sshHost = $serverDetails['ssh_host'];
322 $sshPort = $serverDetails['ssh_port'];
323 $sshUser = $serverDetails['ssh_username'];
324 $sshPass = $serverDetails['ssh_password'];
325 $basePath = $serverDetails['file_storage_path'];
326 if(substr($basePath, strlen($basePath)-1, 1) == '/')
327 {
328 $basePath = substr($basePath, 0, strlen($basePath)-1);
329 }
330 $remoteFilePath = $basePath . '/' . $file['localFilePath'];
331 }
332
333 if(strlen($sshPort) == 0)
334 {
335 $sshPort = 22;
336 }
337
338 // connect to 'local' storage via SSH
339 $sftp = new Net_SFTP($sshHost, $sshPort);
340 if (!$sftp->login($sshUser, $sshPass))
341 {
342 output("Error: Failed logging into " . $sshHost . " (port: ".$sshPort.") via SSH..\n");
343
344 return false;
345 }
346
347 // get file
348 $rs = $sftp->get($remoteFilePath, $localFilePath);
349 if ($rs)
350 {
351 return $localFilePath;
352 }
353 }
354
355 return false;
356 }
357
358 // ftp
359 if ($storageType == 'ftp')
360 {
361 // setup full path
362 $prePath = $uploadServerDetails['storagePath'];
363 if (substr($prePath, strlen($prePath) - 1, 1) == '/')
364 {
365 $prePath = substr($prePath, 0, strlen($prePath) - 1);
366 }
367 $remoteFilePath = $prePath . '/' . $file['localFilePath'];
368
369 // connect via ftp
370 $conn_id = ftp_connect($uploadServerDetails['ipAddress'], $uploadServerDetails['ftpPort'], 30);
371 if ($conn_id === false)
372 {
373 output('Could not connect to ' . $uploadServerDetails['ipAddress'] . ' to upload file.');
374 return false;
375 }
376
377 // authenticate
378 $login_result = ftp_login($conn_id, $uploadServerDetails['ftpUsername'], $uploadServerDetails['ftpPassword']);
379 if ($login_result === false)
380 {
381 output('Could not login to ' . $uploadServerDetails['ipAddress'] . ' with supplied credentials.');
382 return false;
383 }
384
385 // get content
386 $ret = ftp_get($conn_id, $localFilePath, $remoteFilePath, FTP_BINARY);
387 while ($ret == FTP_MOREDATA)
388 {
389 $ret = ftp_nb_continue($conn_id);
390 }
391 }
392
393 if (file_exists($localFilePath) && (filesize($localFilePath) > 0))
394 {
395 return $localFilePath;
396 }
397
398 return false;
399 }
400 function loadServer($db, $file)
401 {
402 // load the server the file is on
403 if ((int) $file['serverId'])
404 {
405 // load from the db
406 $db = dbConnect();
407 $stmt = $db->query("SELECT * FROM file_server WHERE id = " . (int) $file['serverId']);
408 $uploadServerDetails = $stmt->fetch(PDO::FETCH_ASSOC);
409 if (!$uploadServerDetails)
410 {
411 return false;
412 }
413
414 return $uploadServerDetails;
415 }
416
417 return false;
418 }
419
420 function getDirectFileServerSSHDetails($serverId)
421 {
422 // get direct file server ssh details
423 $directFileServers = unserialize(DIRECT_FILE_SERVER_DETAILS);
424 if(COUNT($directFileServers) == 0)
425 {
426 return false;
427 }
428
429 foreach($directFileServers AS $directFileServer)
430 {
431 if($directFileServer['file_server_id'] == $serverId)
432 {
433 return $directFileServer;
434 }
435 }
436
437 return false;
438 }
439
440 /*
441 * Functions
442 */
443
444 function output($msg)
445 {
446 if (SHOW_OUTPUT == 0)
447 {
448 echo $msg;
449 }
450 }
451
452?>