-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreinstall.php
More file actions
3833 lines (3249 loc) · 94.9 KB
/
Copy pathpreinstall.php
File metadata and controls
3833 lines (3249 loc) · 94.9 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2008 Bharat Mediratta
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either Version 2 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* Script to:
* - download the gallery2.zip / tar.gz from a known server directly to the
* server where the script is running.
* - extract the gallery2.zip / tar.gz archive directly on the server
* @package Preinstaller
* @author: Andy Staudacher <ast@gmx.ch>
* @version $Revision: 20999 $
* @versionId 2.3.2
*/
/**
* Refactored for PHP 7.3 (Backward Compatible with PHP 5.6) by Dayo Akanji
* Date: 29 June 2018
*/
error_reporting(E_ALL);
set_time_limit(900);
// ---------------------- P A S S P H R A S E
// Enter a one time passphrase with at least 6 characters
$passPhrase = '';
// ---------------------- C L A S S E S
class preInstallerConfig {
// Pre-Installer Version
public $scriptVersion = '2.0.0';
// General Gallery 2 Release Tags
public $stableReleaseTag;
public $releaseCandidateTag;
// Gallery 2 Repository
public $g2Repo = 'dakanji/G2Project';
// Local name of the gallery2 archive (without extension )
public $archiveBaseName = 'gallery2';
// A list of folder permissions available for chmodding
public $folderPermissionList = array('777', '755', '555');
// Archive extensions available for download
public $availableExtensions = array('zip', 'tar.gz');
// Available codebases of Gallery 2
public $availableVersions = array('official', 'stable', 'tag', 'alpha', 'beta', 'master');
// Last Official Version Tag Name
public $officialReleaseTag = 'v2.3.2';
// PHP allow_url_fopen status
public $allowFOpen = false;
// Implementation Stage
public $stuckOnTwo = false;
// PHP allow_url_fopen status
public $authenticated = false;
public function __construct() {
$arrSubsetAll = array();
$arrSubsetStable = array();
// Default to master
$latestPathAll = "https://github.com/$this->g2Repo/archive/master";
$latestPathStable = $latestPathAll;
// Last Stable Release Tag Name.
// Default to Last Official Release Tag
$this->stableReleaseTag = $this->officialReleaseTag;
// Last Release Candidate Tag Name.
// Default to Last Stable Release Tag
$this->releaseCandidateTag = $this->stableReleaseTag;
if (ini_get('allow_url_fopen')) {
$this->allowFOpen = true;
// Get Releases from Github Repo
$url = "https://api.github.com/repos/$this->g2Repo/releases";
$opts = array(
'http' => array(
'method' => 'GET',
'header' => array(
'User-Agent: G2Project-Preinstaller',
),
),
);
$json = file_get_contents($url, false, stream_context_create($opts));
$releases = json_decode($json);
}
if ($this->allowFOpen && $releases) {
foreach ($releases as $release) {
// Put a Subset of Stable Releases into an Array
if ($release->prerelease === false) {
$arrSubsetStable[] = array(
'created_at' => $release->created_at,
'zipball_url' => $release->zipball_url,
'tag_name' => $release->tag_name,
);
}
// Put a Subset of All Releases into an Array
$arrSubsetAll[] = array(
'created_at' => $release->created_at,
'zipball_url' => $release->zipball_url,
'tag_name' => $release->tag_name,
);
}
// Sort Subset of All Releases by Date (In Desecnding Order - Latest First)
// Then Get Path of First Item in Sorted Array
$arrSubsetAll = $this->arraySorter($arrSubsetAll, 'created_at');
$latestPathAll = $arrSubsetAll[0]['zipball_url'];
// Sort Subset of Stable Releases by Date (In Desecnding Order - Latest First)
// Then Get Path of First Item in Sorted Array
$arrSubsetStable = $this->arraySorter($arrSubsetStable, 'created_at');
$latestPathStable = $arrSubsetStable[0]['zipball_url'];
// Update Last Stable Release Tag Name.
if ($arrSubsetStable[0]['tag_name']) {
$this->stableReleaseTag = $arrSubsetStable[0]['tag_name'];
}
// Update Last Release Candidate Tag Name.
if ($arrSubsetAll[0]['tag_name']) {
$this->releaseCandidateTag = $arrSubsetAll[0]['tag_name'];
}
// Paths to Codebase Releases
$this->downloadUrls = array(
'official' => "https://github.com/$this->g2Repo/archive/v2.3.2",
'stable' => $latestPathStable,
'tag' => $latestPathAll,
'master' => "https://github.com/$this->g2Repo/archive/master",
'alpha' => "https://github.com/$this->g2Repo/archive/alpha",
'beta' => "https://github.com/$this->g2Repo/archive/beta",
);
}
}
protected function arraySorter($array, $on, $order = SORT_DESC) {
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
}
class preInstaller {
private $_extractMethods;
private $_transferMethods;
public function main() {
global $config, $server, $page;
// Authentication
$this->authenticate();
// Register Tranfer Methods
$this->_transferMethods = array(
new CurlDownloader(),
new WgetDownloader(),
new FopenDownloader(),
new FsockopenDownloader(),
);
// Register Extraction Methods
$this->_extractMethods = array(
new UnzipExtractor(),
new PhpUnzipExtractor(),
new TarGzExtractor(),
new PhpTarGzExtractor(),
);
// Make sure we can write to the current server folder
if (!$server->isDirectoryWritable()) {
$page->render(
'results',
array(
'failure' => 'Server Folder: <em>' . __DIR__ . '</em> is not writeable',
'fix' => 'ftp > chmod 777 ' . basename(__DIR__),
)
);
}
// Handle the request
if (empty($_POST['command'])) {
$command = '';
} else {
$command = trim($_POST['command']);
}
switch ($command) {
case 'download':
// Input validation / sanitation
if (empty($_POST['method'])
|| !preg_match('/^[a-z]+downloader$/', $_POST['method'])
) {
$downloader = '';
} else {
$downloader = trim($_POST['method']);
}
// ... archive extension
if (empty($_POST['extension'])) {
$extension = '';
} else {
$extension = trim($_POST['extension']);
}
if (!preg_match('/^([a-z]{2,4}\.)?[a-z]{2,4}$/', $extension)) {
$page->render(
'results',
array(
'failure' => 'Filetype for download not defined. Please retry',
)
);
}
if (!in_array($extension, $config->availableExtensions)) {
$extension = 'zip';
}
// Gallery 2 Codebase ('official', 'stable', 'tag', 'alpha', 'beta', 'master')
if (empty($_POST['codebase']) || !in_array($_POST['codebase'], $config->availableVersions)) {
$codebase = 'stable';
} else {
$codebase = trim($_POST['codebase']);
}
// Handle the request
if (class_exists($downloader)) {
$method = new $downloader();
if ($method->isSupported()) {
$archiveName = __DIR__ . '/' . $config->archiveBaseName . '.' . $extension;
// Delete previous versions with the same file name
// Just in case someone tries to download multiple times
if (file_exists($archiveName)) {
unlink($archiveName);
}
// Assemble the downlod URL
$url = $this->getDownloadUrl($codebase, $extension);
$results = $method->download($url, $archiveName);
if ($results === true) {
if (file_exists($archiveName)) {
@chmod($archiveName, 0777);
$page->render(
'results',
array(
'success' => 'Gallery 2 Archive File Successfully Transfered to this Webserver',
)
);
} else {
$page->render(
'results',
array(
'failure' => "Transfer Failed. Local Gallery 2 Archive File <em>$archiveName</em> Does not Exist",
)
);
}
} else {
$page->render(
'results',
array(
'failure' => $results,
)
);
}
} else {
$page->render(
'results',
array(
'failure' => "File Transfer Method: <em>$method</em> is not supported by this webserver",
)
);
}
} else {
$page->render(
'results',
array(
'failure' => 'File Transfer Method is not defined or does not exist!',
)
);
}
break;
case 'extract':
// Input validation / sanitation
if (empty($_POST['method'])
|| !preg_match('/^[a-z]+extractor$/', $_POST['method'])
) {
$extractor = '';
} else {
$extractor = trim($_POST['method']);
}
// Handle the request
if (class_exists($extractor)) {
$method = new $extractor();
if ($method->isSupported()) {
$archiveName = __DIR__ . '/' .
$config->archiveBaseName . '.' . $method->getSupportedExtension();
if (file_exists($archiveName)) {
$results = $method->extract($archiveName);
if ($results === true) {
// Make sure the dirs and files were extracted successfully
if (!$this->integrityCheck()) {
$page->render(
'results',
array(
'failure' => '<h4>Archive Successfully Extracted</h4> Basic integrity check failed however',
)
);
} else {
// Get the name of the Gallery 2 folder
$folderName = $this->findGallery2Folder();
if ($folderName) {
// Get the php_sapi
$sapi_type = php_sapi_name();
if ((substr($sapi_type, 0, 3) == 'cgi')
|| (substr($sapi_type, 0, 3) == 'fpm')
) {
// We are using PHP CGI/FPM
// So set permissions to 0755
$folderPerm = '0755';
$infoString = 'Folder permissions have been set to <em>0755</em> (Read/Write for "Owner" and Read Only for Others) as we are using PHP CGI/FPM';
} else {
// We are NOT using PHP CGI/FPM
// So set permissions to 0777
$folderPerm = '0777';
$infoString = 'Folder permissions have been set to <em>0777</em> (Read/Write for Everybody) as we are NOT using PHP CGI/FPM.<br>Please use the provided convenience function to change permissions to <em>0755</em> or <em>0555</em> to secure your installation once Gallery 2 is up and running';
}
// Set the permissions
@chmod(__DIR__ . '/' . $folderName, $folderPerm);
}
// Render the results
$page->render(
'results',
array(
'success' => '<h4>Archive Successfully Extracted</h4>' . $infoString,
)
);
}
} else {
$page->render(
'results',
array(
'failure' => $results,
)
);
}
} else {
$page->render(
'results',
array(
'failure' => "Archive <em>$archiveName</em> does not exist in the current server folder",
)
);
}
} else {
$page->render(
'results',
array(
'failure' => "Extraction Method: <em>$method</em> is not supported by this webserver",
)
);
}
} else {
$page->render(
'results',
array(
'failure' => 'Extraction Method not defined or does not exist!',
)
);
}
break;
case 'chmod':
// Input validation / sanitation
if (empty($_POST['folderName'])) {
$folderName = '';
} else {
$folderName = trim($_POST['folderName']);
}
// Remove trailing / leading slashes
$folderName = str_replace(array('/', '\\', '..'), '', $folderName);
if (!$folderName) {
$page->render(
'results',
array(
'failure' => 'Please type in a folder name',
)
);
}
if (!preg_match('/^[\w-]+$/', $folderName)) {
$page->render(
'results',
array(
'failure' => "Folder <em>$folderName</em> has invalid characters. Can only change the permissions of folders in the current server folder.",
)
);
}
$folderName = __DIR__ . '/' . $folderName;
if (!file_exists($folderName)) {
$page->render(
'results',
array(
'failure' => "Folder <em>$folderName</em> does not exist!",
)
);
}
if (empty($_POST['folderPermissions'])) {
$folderPermissions = '';
} else {
$folderPermissions = trim($_POST['folderPermissions']);
}
// Handle the request
if (in_array($folderPermissions, $config->folderPermissionList)) {
$permissionsLong = (string)('0' . (int)$folderPermissions);
if ($permissionsLong === substr(sprintf('%o', fileperms($folderName)), -4)) {
$page->render(
'results',
array(
'info' => "Folder $folderName already has <em>$folderPermissions</em> permissions",
)
);
}
$success = @chmod($folderName, octdec($permissionsLong));
if (!$success) {
$page->render(
'results',
array(
'failure' => "Attempt to change permissions of folder $folderName to <em>$folderPermissions</em> failed!",
)
);
} else {
$page->render(
'results',
array(
'success' => "Successfully changed permissions of $folderName to <em>$folderPermissions</em>",
)
);
}
} else {
$page->render(
'results',
array(
'failure' => "Invalid permissions $folderPermissions",
)
);
}
break;
case 'rename':
if (empty($_POST['folderName'])) {
$folderName = '';
} else {
$folderName = trim($_POST['folderName']);
}
// Remove trailing / leading slashes
$folderName = str_replace(array('/', '\\', '.'), '', $folderName);
if (!preg_match('/^[\w-]+$/', $folderName)) {
$page->render(
'results',
array(
'failure' => "Folder name <em>$folderName</em> has invalid characters. Can only rename within the current server folder.",
)
);
}
$folderNamePath = __DIR__ . '/' . $folderName;
$oldFolderName = $this->findGallery2Folder();
$oldFolderNamePath = __DIR__ . '/' . $oldFolderName;
if (empty($oldFolderName) || !file_exists($oldFolderNamePath)) {
$page->render(
'results',
array(
'failure' => 'Gallery 2 folder not found in current server folder',
)
);
}
if ($oldFolderName == $folderName) {
$page->render(
'results',
array(
'info' => "Current Gallery 2 folder:<br><br>$oldFolderNamePath<br>already has <em>$folderName</em> as folder name!",
)
);
}
$success = @rename($oldFolderNamePath, $folderNamePath);
if (!$success) {
$page->render(
'results',
array(
'failure' => "Attempt to Rename <br> $oldFolderNamePath <br>to<br> <em>$folderNamePath</em> <br>Failed",
)
);
} else {
$page->render(
'results',
array(
'success' => "Successfully Renamed <br> $oldFolderNamePath <br>to<br> <em>$folderNamePath</em>",
)
);
}
break;
default:
// Discover the capabilities of this PHP installation / platform
$capabilities = $this->discoverCapabilities();
$capabilities['gallery2FolderName'] = $this->findGallery2Folder();
if (!empty($capabilities['gallery2FolderName'])) {
$statusMessage = 'Ready for installation (Gallery 2 Folder: <em>' . $capabilities['gallery2FolderName'] . '</em> found)';
} elseif (!empty($capabilities['anyArchiveExists'])) {
$statusMessage = 'Gallery 2 Archive Detected in Current Server Folder<br><br>Please Continue with Implementation Step 2: <em>Extraction Methods</em>';
$config->stuckOnTwo = true;
} else {
$statusMessage = 'Gallery 2 Archive not Detected in Current Server Folder<br><br>Please Start with Implementation Step 1: <em>Transfer Methods</em>';
}
$capabilities['statusMessage'] = $statusMessage;
// Are we in RC stage?
if (!empty($capabilities['transferMethods'])) {
foreach ($capabilities['transferMethods'] as $dMethod) {
if ($dMethod['isSupported']) {
$capabilities['showTagRelease'] = $this->shouldShowTagRelease();
$capabilities['showStableRelease'] = $this->shouldShowStableRelease();
break;
}
}
}
$page->render('options', $capabilities);
}
}
public function authenticate() {
global $config, $passPhrase, $page;
// Check authentication
if (empty($passPhrase)) {
$page->render('missingPassword');
}
if (strlen($passPhrase) < 6) {
$page->render('passwordTooShort');
}
if (!empty($_COOKIE['G2PREINSTALLER'])
&& trim($_COOKIE['G2PREINSTALLER']) == md5($passPhrase)
) {
// Already logged in, got a cookie
$config->authenticated = true;
return $config->authenticated;
}
if (!empty($_POST['g2_password'])) {
// Login attempt
if ($_POST['g2_password'] == $passPhrase) {
setcookie('G2PREINSTALLER', md5($passPhrase), 0);
$config->authenticated = true;
return $config->authenticated;
}
$page->render(
'passwordForm',
array(
'incorrectPassword' => 1,
)
);
}
$page->render('passwordForm');
}
public function discoverCapabilities() {
$capabilities = array();
global $config;
$extractMethods = array();
$extensions = array();
$anyExtensionSupported = 0;
$anyArchiveExists = 0;
foreach ($this->_extractMethods as $method) {
$archiveName = $config->archiveBaseName . '.' . $method->getSupportedExtension();
$archiveExists = file_exists(__DIR__ . '/' . $archiveName);
$isSupported = $method->isSupported();
$extractMethods[] = array(
'isSupported' => $isSupported,
'name' => $method->getName(),
'command' => strtolower(get_class($method)),
'archiveExists' => $archiveExists,
'archiveName' => $archiveName,
);
if (empty($extensions[$method->getSupportedExtension()])) {
$extensions[$method->getSupportedExtension()] = (int)$isSupported;
}
if ($isSupported) {
$anyExtensionSupported = 1;
}
if ($archiveExists) {
$anyArchiveExists = 1;
}
}
$capabilities['extractMethods'] = $extractMethods;
$capabilities['extensions'] = $extensions;
$capabilities['anyExtensionSupported'] = $anyExtensionSupported;
$capabilities['anyArchiveExists'] = $anyArchiveExists;
$transferMethods = array();
foreach ($this->_transferMethods as $method) {
$transferMethods[] = array(
'isSupported' => $method->isSupported(),
'name' => $method->getName(),
'command' => strtolower(get_class($method)),
);
}
$capabilities['transferMethods'] = $transferMethods;
return $capabilities;
}
public function findGallery2Folder() {
global $server;
// Search in the current folder for a gallery2 folder
$latestPathAll = __DIR__ . '/';
if (file_exists($latestPathAll . 'gallery2')
&& file_exists($latestPathAll . 'gallery2/install/index.php')
) {
return 'gallery2';
}
if (!$server->isPhpFunctionSupported('opendir')
|| !$server->isPhpFunctionSupported('readdir')
) {
return false;
}
$handle = opendir($latestPathAll);
if (!$handle) {
return false;
}
while (($fileName = readdir($handle)) !== false) {
if ($fileName == '.' || $fileName == '..') {
continue;
}
if (file_exists($latestPathAll . $fileName . '/install/index.php')) {
return $fileName;
}
}
closedir($handle);
return false;
}
public function integrityCheck() {
// TODO, check for the existence of modules, lib, themes, main.php
return true;
}
public function getDownloadUrl($codebase, $extension) {
global $config;
// Get defined codebases
$url = $config->downloadUrls[$codebase];
// Try to get the latest codebase string
if ($codebase != 'stable' && $codebase != 'tag') {
$url .= '.' . $extension;
} elseif ($extension == 'tar.gz') {
str_replace('/zipball/', '/tarball/', $url);
}
return $url;
}
public function shouldShowTagRelease() {
global $config;
// Only show if we are in a release candidate stage
return $config->stableReleaseTag != $config->releaseCandidateTag;
}
public function shouldShowStableRelease() {
global $config;
// Only show if not same as official release
return $config->stableReleaseTag != $config->officialReleaseTag;
}
}
class serverPlatform {
// Check if a specific php function is available
public function isPhpFunctionSupported($functionName) {
if (in_array($functionName, preg_split('/,\s*/', ini_get('disable_functions'))) || !function_exists($functionName)) {
return false;
}
return true;
}
// Check if a specific command line tool is available
public function isBinaryAvailable($binaryName) {
$binaryPath = $this->getBinaryPath($binaryName);
return !empty($binaryPath);
}
// Return the path to a binary or false if it's not available
public function getBinaryPath($binaryName) {
if (!$this->isPhpFunctionSupported('exec')) {
return false;
}
// First try 'which'
$ret = array();
exec('which ' . $binaryName, $ret);
if (strpos(join(' ', $ret), $binaryName) !== false && is_executable(join('', $ret))) {
return $binaryName;// it's in the path
}
// Try a bunch of likely seeming paths to see if any of them work.
$paths = array();
if (!strncasecmp(PHP_OS, 'win', 3)) {
$separator = ';';
$slash = '\\';
$extension = '.exe';
$paths[] = "C:\\Program Files\\$binaryName\\";
$paths[] = 'C:\\apps$binaryName\\';
$paths[] = "C:\\$binaryName\\";
} else {
$separator = ':';
$slash = '/';
$extension = '';
$paths[] = '/usr/bin/';
$paths[] = '/usr/local/bin/';
$paths[] = '/bin/';
$paths[] = '/sw/bin/';
}
$paths[] = './';
foreach (explode($separator, getenv('PATH')) as $path) {
$path = trim($path);
if (empty($path)) {
continue;
}
if ($path[strlen($path) - 1] != $slash) {
$path .= $slash;
}
$paths[] = $path;
}
// Now try each path in turn to see which ones work
foreach ($paths as $path) {
$execPath = $path . $binaryName . $extension;
if (file_exists($execPath) && is_executable($execPath)) {
// We have a winner
return $execPath;
}
}
return false;
}
// Check if we can write to this directory (download, extract)
public function isDirectoryWritable() {
return is_writable(__DIR__);
}
public function extendTimeLimit() {
if (function_exists('apache_reset_timeout')) {
@apache_reset_timeout();
}
@set_time_limit(600);
}
}
class DownloadMethod {
public function download($url, $outputFile) {
return false;
}
public function isSupported() {
return false;
}
public function getName() {
return '';
}
}
class WgetDownloader extends DownloadMethod {
public function download($url, $outputFile) {
global $server;
$status = 0;
$output = array();
$wget = $server->getBinaryPath('wget');
exec("$wget -O$outputFile $url ", $output, $status);
if ($status) {
$msg = 'exec returned an error status ';
$msg .= is_array($output) ? implode('<br>', $output) : '';
return $msg;
}
return true;
}
public function isSupported() {
global $server;
return $server->isBinaryAvailable('wget');
}
public function getName() {
return 'Transfer using Wget';
}
}
class FopenDownloader extends DownloadMethod {
public function download($url, $outputFile) {
global $server;
if (!$server->isDirectoryWritable()) {
return 'Unable to write to current server folder';
}
$start = time();
$server->extendTimeLimit();
$fh = fopen($url, 'rb');
if (empty($fh)) {
return 'Unable to open url';
}
$ofh = fopen($outputFile, 'wb');
if (!$ofh) {
fclose($fh);
return 'Unable to open output file in writing mode';
}
$failed = $results = false;
while (!feof($fh) && !$failed) {
$buf = fread($fh, 4096);
if (!$buf) {
$results = 'Error during download';
$failed = true;
break;
}
if (fwrite($ofh, $buf) != strlen($buf)) {
$failed = true;
$results = 'Error during writing';
break;
}
if (time() - $start > 55) {
$server->extendTimeLimit();
$start = time();
}
}
fclose($ofh);
fclose($fh);
if ($failed) {
return $results;
}
return true;
}
public function isSupported() {
global $server;
$actual = ini_get('allow_url_fopen');
if (in_array($actual, array(1, 'On', 'on')) && $server->isPhpFunctionSupported('fopen')) {
return true;
}
return false;
}
public function getName() {
return 'Transfer using PHP fopen()';
}
}
class FsockopenDownloader extends DownloadMethod {
public function download($url, $outputFile, $maxRedirects = 10) {
global $server;
// Code from WebHelper_simple.class