comparison forum/Sources/Subs-Package.php @ 76:e3e11437ecea website

Add forum code
author Chris Cannam
date Sun, 07 Jul 2013 11:25:48 +0200
parents
children
comparison
equal deleted inserted replaced
75:72f59aa7e503 76:e3e11437ecea
1 <?php
2
3 /**
4 * Simple Machines Forum (SMF)
5 *
6 * @package SMF
7 * @author Simple Machines http://www.simplemachines.org
8 * @copyright 2011 Simple Machines
9 * @license http://www.simplemachines.org/about/smf/license.php BSD
10 *
11 * @version 2.0.1
12 */
13
14 if (!defined('SMF'))
15 die('Hacking attempt...');
16
17 /* This file's central purpose of existence is that of making the package
18 manager work nicely. It contains functions for handling tar.gz and zip
19 files, as well as a simple xml parser to handle the xml package stuff.
20 Not to mention a few functions to make file handling easier.
21
22 array read_tgz_file(string filename, string destination,
23 bool single_file = false, bool overwrite = false, array files_to_extract = null)
24 - reads a .tar.gz file, filename, in and extracts file(s) from it.
25 - essentially just a shortcut for read_tgz_data().
26
27 array read_tgz_data(string data, string destination,
28 bool single_file = false, bool overwrite = false, array files_to_extract = null)
29 - extracts a file or files from the .tar.gz contained in data.
30 - detects if the file is really a .zip file, and if so returns the
31 result of read_zip_data
32 - if destination is null, returns a list of files in the archive.
33 - if single_file is true, returns the contents of the file specified
34 by destination, if it exists, or false.
35 - if single_file is true, destination can start with * and / to
36 signify that the file may come from any directory.
37 - destination should not begin with a / if single_file is true.
38 - overwrites existing files with newer modification times if and
39 only if overwrite is true.
40 - creates the destination directory if it doesn't exist, and is
41 is specified.
42 - requires zlib support be built into PHP.
43 - returns an array of the files extracted.
44 - if files_to_extract is not equal to null only extracts file within this array.
45
46 array read_zip_data(string data, string destination,
47 bool single_file = false, bool overwrite = false, array files_to_extract = null)
48 - extracts a file or files from the .zip contained in data.
49 - if destination is null, returns a list of files in the archive.
50 - if single_file is true, returns the contents of the file specified
51 by destination, if it exists, or false.
52 - if single_file is true, destination can start with * and / to
53 signify that the file may come from any directory.
54 - destination should not begin with a / if single_file is true.
55 - overwrites existing files with newer modification times if and
56 only if overwrite is true.
57 - creates the destination directory if it doesn't exist, and is
58 is specified.
59 - requires zlib support be built into PHP.
60 - returns an array of the files extracted.
61 - if files_to_extract is not equal to null only extracts file within this array.
62
63 bool url_exists(string url)
64 - checks to see if url is valid, and returns a 200 status code.
65 - will return false if the file is "moved permanently" or similar.
66 - returns true if the remote url exists.
67
68 array loadInstalledPackages()
69 - loads and returns an array of installed packages.
70 - gets this information from Packages/installed.list.
71 - returns the array of data.
72
73 array getPackageInfo(string filename)
74 - loads a package's information and returns a representative array.
75 - expects the file to be a package in Packages/.
76 - returns a error string if the package-info is invalid.
77 - returns a basic array of id, version, filename, and similar
78 information.
79 - in the array returned, an xmlArray is available in 'xml'.
80
81 void packageRequireFTP(string destination_url, array files = none, bool return = false)
82 // !!!
83
84 array parsePackageInfo(xmlArray &package, bool testing_only = true,
85 string method = 'install', string previous_version = '')
86 - parses the actions in package-info.xml files from packages.
87 - package should be an xmlArray with package-info as its base.
88 - testing_only should be true if the package should not actually be
89 applied.
90 - method is upgrade, install, or uninstall. Its default is install.
91 - previous_version should be set to the previous installed version
92 of this package, if any.
93 - does not handle failure terribly well; testing first is always
94 better.
95 - returns an array of those changes made.
96
97 bool matchPackageVersion(string version, string versions)
98 - checks if version matches any of the versions in versions.
99 - supports comma separated version numbers, with or without
100 whitespace.
101 - supports lower and upper bounds. (1.0-1.2)
102 - returns true if the version matched.
103
104 int compareVersions(string version1, string version2)
105 - compares two versions.
106 - returns 0 if version1 is equal to version2.
107 - returns -1 if version1 is lower than version2.
108 - returns 1 if version1 is higher than version2.
109
110 string parse_path(string path)
111 - parses special identifiers out of the specified path.
112 - returns the parsed path.
113
114 void deltree(string path, bool delete_directory = true)
115 - deletes a directory, and all the files and direcories inside it.
116 - requires access to delete these files.
117
118 bool mktree(string path, int mode)
119 - creates the specified tree structure with the mode specified.
120 - creates every directory in path until it finds one that already
121 exists.
122 - returns true if successful, false otherwise.
123
124 void copytree(string source, string destination)
125 - copies one directory structure over to another.
126 - requires the destination to be writable.
127
128 void listtree(string path, string sub_path = none)
129 // !!!
130
131 array parseModification(string file, bool testing = true, bool undo = false, array theme_paths = array())
132 - parses a xml-style modification file (file).
133 - testing tells it the modifications shouldn't actually be saved.
134 - undo specifies that the modifications the file requests should be
135 undone; this doesn't work with everything (regular expressions.)
136 - returns an array of those changes made.
137
138 array parseBoardMod(string file, bool testing = true, bool undo = false, array theme_paths = array())
139 - parses a boardmod-style modification file (file).
140 - testing tells it the modifications shouldn't actually be saved.
141 - undo specifies that the modifications the file requests should be
142 undone.
143 - returns an array of those changes made.
144
145 // !!!
146
147 int package_put_contents(string filename, string data)
148 - writes data to a file, almost exactly like the file_put_contents()
149 function.
150 - uses FTP to create/chmod the file when necessary and available.
151 - uses text mode for text mode file extensions.
152 - returns the number of bytes written.
153
154 void package_chmod(string filename)
155 // !!!
156
157 string package_crypt(string password)
158 // !!!
159
160 string fetch_web_data(string url, string post_data = '',
161 bool keep_alive = false)
162 // !!!
163
164 Creating your own package server:
165 ---------------------------------------------------------------------------
166 // !!!
167
168 Creating your own package:
169 ---------------------------------------------------------------------------
170 // !!!
171 */
172
173 // Get the data from the file and extract it.
174 function read_tgz_file($gzfilename, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
175 {
176 if (substr($gzfilename, 0, 7) == 'http://')
177 {
178 $data = fetch_web_data($gzfilename);
179
180 if ($data === false)
181 return false;
182 }
183 else
184 {
185 $data = @file_get_contents($gzfilename);
186
187 if ($data === false)
188 return false;
189 }
190
191 return read_tgz_data($data, $destination, $single_file, $overwrite, $files_to_extract);
192 }
193
194 // Extract tar.gz data. If destination is null, return a listing.
195 function read_tgz_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
196 {
197 // Make sure we have this loaded.
198 loadLanguage('Packages');
199
200 // This function sorta needs gzinflate!
201 if (!function_exists('gzinflate'))
202 fatal_lang_error('package_no_zlib', 'critical');
203
204 umask(0);
205 if (!$single_file && $destination !== null && !file_exists($destination))
206 mktree($destination, 0777);
207
208 // No signature?
209 if (strlen($data) < 2)
210 return false;
211
212 $id = unpack('H2a/H2b', substr($data, 0, 2));
213 if (strtolower($id['a'] . $id['b']) != '1f8b')
214 {
215 // Okay, this ain't no tar.gz, but maybe it's a zip file.
216 if (substr($data, 0, 2) == 'PK')
217 return read_zip_data($data, $destination, $single_file, $overwrite, $files_to_extract);
218 else
219 return false;
220 }
221
222 $flags = unpack('Ct/Cf', substr($data, 2, 2));
223
224 // Not deflate!
225 if ($flags['t'] != 8)
226 return false;
227 $flags = $flags['f'];
228
229 $offset = 10;
230 $octdec = array('mode', 'uid', 'gid', 'size', 'mtime', 'checksum', 'type');
231
232 // "Read" the filename and comment. // !!! Might be mussed.
233 if ($flags & 12)
234 {
235 while ($flags & 8 && $data{$offset++} != "\0")
236 continue;
237 while ($flags & 4 && $data{$offset++} != "\0")
238 continue;
239 }
240
241 $crc = unpack('Vcrc32/Visize', substr($data, strlen($data) - 8, 8));
242 $data = @gzinflate(substr($data, $offset, strlen($data) - 8 - $offset));
243
244 // smf_crc32 and crc32 may not return the same results, so we accept either.
245 if ($crc['crc32'] != smf_crc32($data) && $crc['crc32'] != crc32($data))
246 return false;
247
248 $blocks = strlen($data) / 512 - 1;
249 $offset = 0;
250
251 $return = array();
252
253 while ($offset < $blocks)
254 {
255 $header = substr($data, $offset << 9, 512);
256 $current = unpack('a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1type/a100linkname/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor/a155path', $header);
257
258 // Blank record? This is probably at the end of the file.
259 if (empty($current['filename']))
260 {
261 $offset += 512;
262 continue;
263 }
264
265 if ($current['type'] == 5 && substr($current['filename'], -1) != '/')
266 $current['filename'] .= '/';
267
268 foreach ($current as $k => $v)
269 {
270 if (in_array($k, $octdec))
271 $current[$k] = octdec(trim($v));
272 else
273 $current[$k] = trim($v);
274 }
275
276 $checksum = 256;
277 for ($i = 0; $i < 148; $i++)
278 $checksum += ord($header{$i});
279 for ($i = 156; $i < 512; $i++)
280 $checksum += ord($header{$i});
281
282 if ($current['checksum'] != $checksum)
283 break;
284
285 $size = ceil($current['size'] / 512);
286 $current['data'] = substr($data, ++$offset << 9, $current['size']);
287 $offset += $size;
288
289 // Not a directory and doesn't exist already...
290 if (substr($current['filename'], -1, 1) != '/' && !file_exists($destination . '/' . $current['filename']))
291 $write_this = true;
292 // File exists... check if it is newer.
293 elseif (substr($current['filename'], -1, 1) != '/')
294 $write_this = $overwrite || filemtime($destination . '/' . $current['filename']) < $current['mtime'];
295 // Folder... create.
296 elseif ($destination !== null && !$single_file)
297 {
298 // Protect from accidental parent directory writing...
299 $current['filename'] = strtr($current['filename'], array('../' => '', '/..' => ''));
300
301 if (!file_exists($destination . '/' . $current['filename']))
302 mktree($destination . '/' . $current['filename'], 0777);
303 $write_this = false;
304 }
305 else
306 $write_this = false;
307
308 if ($write_this && $destination !== null)
309 {
310 if (strpos($current['filename'], '/') !== false && !$single_file)
311 mktree($destination . '/' . dirname($current['filename']), 0777);
312
313 // Is this the file we're looking for?
314 if ($single_file && ($destination == $current['filename'] || $destination == '*/' . basename($current['filename'])))
315 return $current['data'];
316 // If we're looking for another file, keep going.
317 elseif ($single_file)
318 continue;
319 // Looking for restricted files?
320 elseif ($files_to_extract !== null && !in_array($current['filename'], $files_to_extract))
321 continue;
322
323 package_put_contents($destination . '/' . $current['filename'], $current['data']);
324 }
325
326 if (substr($current['filename'], -1, 1) != '/')
327 $return[] = array(
328 'filename' => $current['filename'],
329 'md5' => md5($current['data']),
330 'preview' => substr($current['data'], 0, 100),
331 'size' => $current['size'],
332 'skipped' => false
333 );
334 }
335
336 if ($destination !== null && !$single_file)
337 package_flush_cache();
338
339 if ($single_file)
340 return false;
341 else
342 return $return;
343 }
344
345 // Extract zip data. If destination is null, return a listing.
346 function read_zip_data($data, $destination, $single_file = false, $overwrite = false, $files_to_extract = null)
347 {
348 umask(0);
349 if ($destination !== null && !file_exists($destination) && !$single_file)
350 mktree($destination, 0777);
351
352 // Look for the PK header...
353 if (substr($data, 0, 2) != 'PK')
354 return false;
355
356 // Find the central whosamawhatsit at the end; if there's a comment it's a pain.
357 if (substr($data, -22, 4) == 'PK' . chr(5) . chr(6))
358 $p = -22;
359 else
360 {
361 // Have to find where the comment begins, ugh.
362 for ($p = -22; $p > -strlen($data); $p--)
363 {
364 if (substr($data, $p, 4) == 'PK' . chr(5) . chr(6))
365 break;
366 }
367 }
368
369 $return = array();
370
371 // Get the basic zip file info.
372 $zip_info = unpack('vfiles/Vsize/Voffset', substr($data, $p + 10, 10));
373
374 $p = $zip_info['offset'];
375 for ($i = 0; $i < $zip_info['files']; $i++)
376 {
377 // Make sure this is a file entry...
378 if (substr($data, $p, 4) != 'PK' . chr(1) . chr(2))
379 return false;
380
381 // Get all the important file information.
382 $file_info = unpack('Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', substr($data, $p + 16, 30));
383 $file_info['filename'] = substr($data, $p + 46, $file_info['filename_len']);
384
385 // Skip all the information we don't care about anyway.
386 $p += 46 + $file_info['filename_len'] + $file_info['extra_len'] + $file_info['comment_len'];
387
388 // If this is a file, and it doesn't exist.... happy days!
389 if (substr($file_info['filename'], -1, 1) != '/' && !file_exists($destination . '/' . $file_info['filename']))
390 $write_this = true;
391 // If the file exists, we may not want to overwrite it.
392 elseif (substr($file_info['filename'], -1, 1) != '/')
393 $write_this = $overwrite;
394 // This is a directory, so we're gonna want to create it. (probably...)
395 elseif ($destination !== null && !$single_file)
396 {
397 // Just a little accident prevention, don't mind me.
398 $file_info['filename'] = strtr($file_info['filename'], array('../' => '', '/..' => ''));
399
400 if (!file_exists($destination . '/' . $file_info['filename']))
401 mktree($destination . '/' . $file_info['filename'], 0777);
402 $write_this = false;
403 }
404 else
405 $write_this = false;
406
407 // Check that the data is there and does exist.
408 if (substr($data, $file_info['offset'], 4) != 'PK' . chr(3) . chr(4))
409 return false;
410
411 // Get the actual compressed data.
412 $file_info['data'] = substr($data, $file_info['offset'] + 30 + $file_info['filename_len'], $file_info['compressed_size']);
413
414 // Only inflate it if we need to ;).
415 if ($file_info['compressed_size'] != $file_info['size'])
416 $file_info['data'] = @gzinflate($file_info['data']);
417
418 // Okay! We can write this file, looks good from here...
419 if ($write_this && $destination !== null)
420 {
421 if (strpos($file_info['filename'], '/') !== false && !$single_file)
422 mktree($destination . '/' . dirname($file_info['filename']), 0777);
423
424 // If we're looking for a specific file, and this is it... ka-bam, baby.
425 if ($single_file && ($destination == $file_info['filename'] || $destination == '*/' . basename($file_info['filename'])))
426 return $file_info['data'];
427 // Oh? Another file. Fine. You don't like this file, do you? I know how it is. Yeah... just go away. No, don't apologize. I know this file's just not *good enough* for you.
428 elseif ($single_file)
429 continue;
430 // Don't really want this?
431 elseif ($files_to_extract !== null && !in_array($file_info['filename'], $files_to_extract))
432 continue;
433
434 package_put_contents($destination . '/' . $file_info['filename'], $file_info['data']);
435 }
436
437 if (substr($file_info['filename'], -1, 1) != '/')
438 $return[] = array(
439 'filename' => $file_info['filename'],
440 'md5' => md5($file_info['data']),
441 'preview' => substr($file_info['data'], 0, 100),
442 'size' => $file_info['size'],
443 'skipped' => false
444 );
445 }
446
447 if ($destination !== null && !$single_file)
448 package_flush_cache();
449
450 if ($single_file)
451 return false;
452 else
453 return $return;
454 }
455
456 // Checks the existence of a remote file since file_exists() does not do remote.
457 function url_exists($url)
458 {
459 $a_url = parse_url($url);
460
461 if (!isset($a_url['scheme']))
462 return false;
463
464 // Attempt to connect...
465 $temp = '';
466 $fid = fsockopen($a_url['host'], !isset($a_url['port']) ? 80 : $a_url['port'], $temp, $temp, 8);
467 if (!$fid)
468 return false;
469
470 fputs($fid, 'HEAD ' . $a_url['path'] . ' HTTP/1.0' . "\r\n" . 'Host: ' . $a_url['host'] . "\r\n\r\n");
471 $head = fread($fid, 1024);
472 fclose($fid);
473
474 return preg_match('~^HTTP/.+\s+(20[01]|30[127])~i', $head) == 1;
475 }
476
477 // Load the installed packages.
478 function loadInstalledPackages()
479 {
480 global $boarddir, $smcFunc;
481
482 // First, check that the database is valid, installed.list is still king.
483 $install_file = implode('', file($boarddir . '/Packages/installed.list'));
484 if (trim($install_file) == '')
485 {
486 $smcFunc['db_query']('', '
487 UPDATE {db_prefix}log_packages
488 SET install_state = {int:not_installed}',
489 array(
490 'not_installed' => 0,
491 )
492 );
493
494 // Don't have anything left, so send an empty array.
495 return array();
496 }
497
498 // Load the packages from the database - note this is ordered by install time to ensure latest package uninstalled first.
499 $request = $smcFunc['db_query']('', '
500 SELECT id_install, package_id, filename, name, version
501 FROM {db_prefix}log_packages
502 WHERE install_state != {int:not_installed}
503 ORDER BY time_installed DESC',
504 array(
505 'not_installed' => 0,
506 )
507 );
508 $installed = array();
509 $found = array();
510 while ($row = $smcFunc['db_fetch_assoc']($request))
511 {
512 // Already found this? If so don't add it twice!
513 if (in_array($row['package_id'], $found))
514 continue;
515
516 $found[] = $row['package_id'];
517
518 $installed[] = array(
519 'id' => $row['id_install'],
520 'name' => $row['name'],
521 'filename' => $row['filename'],
522 'package_id' => $row['package_id'],
523 'version' => $row['version'],
524 );
525 }
526 $smcFunc['db_free_result']($request);
527
528 return $installed;
529 }
530
531 function getPackageInfo($gzfilename)
532 {
533 global $boarddir;
534
535 // Extract package-info.xml from downloaded file. (*/ is used because it could be in any directory.)
536 if (strpos($gzfilename, 'http://') !== false)
537 $packageInfo = read_tgz_data(fetch_web_data($gzfilename, '', true), '*/package-info.xml', true);
538 else
539 {
540 if (!file_exists($boarddir . '/Packages/' . $gzfilename))
541 return 'package_get_error_not_found';
542
543 if (is_file($boarddir . '/Packages/' . $gzfilename))
544 $packageInfo = read_tgz_file($boarddir . '/Packages/' . $gzfilename, '*/package-info.xml', true);
545 elseif (file_exists($boarddir . '/Packages/' . $gzfilename . '/package-info.xml'))
546 $packageInfo = file_get_contents($boarddir . '/Packages/' . $gzfilename . '/package-info.xml');
547 else
548 return 'package_get_error_missing_xml';
549 }
550
551 // Nothing?
552 if (empty($packageInfo))
553 return 'package_get_error_is_zero';
554
555 // Parse package-info.xml into an xmlArray.
556 loadClassFile('Class-Package.php');
557 $packageInfo = new xmlArray($packageInfo);
558
559 // !!! Error message of some sort?
560 if (!$packageInfo->exists('package-info[0]'))
561 return 'package_get_error_packageinfo_corrupt';
562
563 $packageInfo = $packageInfo->path('package-info[0]');
564
565 $package = $packageInfo->to_array();
566 $package['xml'] = $packageInfo;
567 $package['filename'] = $gzfilename;
568
569 if (!isset($package['type']))
570 $package['type'] = 'modification';
571
572 return $package;
573 }
574
575 // Create a chmod control for chmoding files.
576 function create_chmod_control($chmodFiles = array(), $chmodOptions = array(), $restore_write_status = false)
577 {
578 global $context, $modSettings, $package_ftp, $boarddir, $txt, $sourcedir, $scripturl;
579
580 // If we're restoring the status of existing files prepare the data.
581 if ($restore_write_status && isset($_SESSION['pack_ftp']) && !empty($_SESSION['pack_ftp']['original_perms']))
582 {
583 function list_restoreFiles($dummy1, $dummy2, $dummy3, $do_change)
584 {
585 global $txt;
586
587 $restore_files = array();
588 foreach ($_SESSION['pack_ftp']['original_perms'] as $file => $perms)
589 {
590 // Check the file still exists, and the permissions were indeed different than now.
591 $file_permissions = @fileperms($file);
592 if (!file_exists($file) || $file_permissions == $perms)
593 {
594 unset($_SESSION['pack_ftp']['original_perms'][$file]);
595 continue;
596 }
597
598 // Are we wanting to change the permission?
599 if ($do_change && isset($_POST['restore_files']) && in_array($file, $_POST['restore_files']))
600 {
601 // Use FTP if we have it.
602 if (!empty($package_ftp))
603 {
604 $ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
605 $package_ftp->chmod($ftp_file, $perms);
606 }
607 else
608 @chmod($file, $perms);
609
610 $new_permissions = @fileperms($file);
611 $result = $new_permissions == $perms ? 'success' : 'failure';
612 unset($_SESSION['pack_ftp']['original_perms'][$file]);
613 }
614 elseif ($do_change)
615 {
616 $new_permissions = '';
617 $result = 'skipped';
618 unset($_SESSION['pack_ftp']['original_perms'][$file]);
619 }
620
621 // Record the results!
622 $restore_files[] = array(
623 'path' => $file,
624 'old_perms_raw' => $perms,
625 'old_perms' => substr(sprintf('%o', $perms), -4),
626 'cur_perms' => substr(sprintf('%o', $file_permissions), -4),
627 'new_perms' => isset($new_permissions) ? substr(sprintf('%o', $new_permissions), -4) : '',
628 'result' => isset($result) ? $result : '',
629 'writable_message' => '<span style="color: ' . (@is_writable($file) ? 'green' : 'red') . '">' . (@is_writable($file) ? $txt['package_file_perms_writable'] : $txt['package_file_perms_not_writable']) . '</span>',
630 );
631 }
632
633 return $restore_files;
634 }
635
636 $listOptions = array(
637 'id' => 'restore_file_permissions',
638 'title' => $txt['package_restore_permissions'],
639 'get_items' => array(
640 'function' => 'list_restoreFiles',
641 'params' => array(
642 !empty($_POST['restore_perms']),
643 ),
644 ),
645 'columns' => array(
646 'path' => array(
647 'header' => array(
648 'value' => $txt['package_restore_permissions_filename'],
649 ),
650 'data' => array(
651 'db' => 'path',
652 'class' => 'smalltext',
653 ),
654 ),
655 'old_perms' => array(
656 'header' => array(
657 'value' => $txt['package_restore_permissions_orig_status'],
658 ),
659 'data' => array(
660 'db' => 'old_perms',
661 'class' => 'smalltext',
662 ),
663 ),
664 'cur_perms' => array(
665 'header' => array(
666 'value' => $txt['package_restore_permissions_cur_status'],
667 ),
668 'data' => array(
669 'function' => create_function('$rowData', '
670 global $txt;
671
672 $formatTxt = $rowData[\'result\'] == \'\' || $rowData[\'result\'] == \'skipped\' ? $txt[\'package_restore_permissions_pre_change\'] : $txt[\'package_restore_permissions_post_change\'];
673 return sprintf($formatTxt, $rowData[\'cur_perms\'], $rowData[\'new_perms\'], $rowData[\'writable_message\']);
674 '),
675 'class' => 'smalltext',
676 ),
677 ),
678 'check' => array(
679 'header' => array(
680 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
681 ),
682 'data' => array(
683 'sprintf' => array(
684 'format' => '<input type="checkbox" name="restore_files[]" value="%1$s" class="input_check" />',
685 'params' => array(
686 'path' => false,
687 ),
688 ),
689 'style' => 'text-align: center',
690 ),
691 ),
692 'result' => array(
693 'header' => array(
694 'value' => $txt['package_restore_permissions_result'],
695 ),
696 'data' => array(
697 'function' => create_function('$rowData', '
698 global $txt;
699
700 return $txt[\'package_restore_permissions_action_\' . $rowData[\'result\']];
701 '),
702 'class' => 'smalltext',
703 ),
704 ),
705 ),
706 'form' => array(
707 'href' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : $scripturl . '?action=admin;area=packages;sa=perms;restore;' . $context['session_var'] . '=' . $context['session_id'],
708 ),
709 'additional_rows' => array(
710 array(
711 'position' => 'below_table_data',
712 'value' => '<input type="submit" name="restore_perms" value="' . $txt['package_restore_permissions_restore'] . '" class="button_submit" />',
713 'class' => 'titlebg',
714 'style' => 'text-align: right;',
715 ),
716 array(
717 'position' => 'after_title',
718 'value' => '<span class="smalltext">' . $txt['package_restore_permissions_desc'] . '</span>',
719 'class' => 'windowbg2',
720 ),
721 ),
722 );
723
724 // Work out what columns and the like to show.
725 if (!empty($_POST['restore_perms']))
726 {
727 $listOptions['additional_rows'][1]['value'] = sprintf($txt['package_restore_permissions_action_done'], $scripturl . '?action=admin;area=packages;sa=perms;' . $context['session_var'] . '=' . $context['session_id']);
728 unset($listOptions['columns']['check'], $listOptions['form'], $listOptions['additional_rows'][0]);
729
730 $context['sub_template'] = 'show_list';
731 $context['default_list'] = 'restore_file_permissions';
732 }
733 else
734 {
735 unset($listOptions['columns']['result']);
736 }
737
738 // Create the list for display.
739 require_once($sourcedir . '/Subs-List.php');
740 createList($listOptions);
741
742 // If we just restored permissions then whereever we are, we are now done and dusted.
743 if (!empty($_POST['restore_perms']))
744 obExit();
745 }
746 // Otherwise, it's entirely irrelevant?
747 elseif ($restore_write_status)
748 return true;
749
750 // This is where we report what we got up to.
751 $return_data = array(
752 'files' => array(
753 'writable' => array(),
754 'notwritable' => array(),
755 ),
756 );
757
758 // If we have some FTP information already, then let's assume it was required and try to get ourselves connected.
759 if (!empty($_SESSION['pack_ftp']['connected']))
760 {
761 // Load the file containing the ftp_connection class.
762 loadClassFile('Class-Package.php');
763
764 $package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
765 }
766
767 // Just got a submission did we?
768 if (empty($package_ftp) && isset($_POST['ftp_username']))
769 {
770 loadClassFile('Class-Package.php');
771 $ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
772
773 // We're connected, jolly good!
774 if ($ftp->error === false)
775 {
776 // Common mistake, so let's try to remedy it...
777 if (!$ftp->chdir($_POST['ftp_path']))
778 {
779 $ftp_error = $ftp->last_message;
780 $ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
781 }
782
783 if (!in_array($_POST['ftp_path'], array('', '/')))
784 {
785 $ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
786 if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || substr($_POST['ftp_path'], 0, 1) == '/'))
787 $ftp_root = substr($ftp_root, 0, -1);
788 }
789 else
790 $ftp_root = $boarddir;
791
792 $_SESSION['pack_ftp'] = array(
793 'server' => $_POST['ftp_server'],
794 'port' => $_POST['ftp_port'],
795 'username' => $_POST['ftp_username'],
796 'password' => package_crypt($_POST['ftp_password']),
797 'path' => $_POST['ftp_path'],
798 'root' => $ftp_root,
799 'connected' => true,
800 );
801
802 if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
803 updateSettings(array('package_path' => $_POST['ftp_path']));
804
805 // This is now the primary connection.
806 $package_ftp = $ftp;
807 }
808 }
809
810 // Now try to simply make the files writable, with whatever we might have.
811 if (!empty($chmodFiles))
812 {
813 foreach ($chmodFiles as $k => $file)
814 {
815 // Sometimes this can somehow happen maybe?
816 if (empty($file))
817 unset($chmodFiles[$k]);
818 // Already writable?
819 elseif (@is_writable($file))
820 $return_data['files']['writable'][] = $file;
821 else
822 {
823 // Now try to change that.
824 $return_data['files'][package_chmod($file, 'writable', true) ? 'writable' : 'notwritable'][] = $file;
825 }
826 }
827 }
828
829 // Have we still got nasty files which ain't writable? Dear me we need more FTP good sir.
830 if (empty($package_ftp) && (!empty($return_data['files']['notwritable']) || !empty($chmodOptions['force_find_error'])))
831 {
832 if (!isset($ftp) || $ftp->error !== false)
833 {
834 if (!isset($ftp))
835 {
836 loadClassFile('Class-Package.php');
837 $ftp = new ftp_connection(null);
838 }
839 elseif ($ftp->error !== false && !isset($ftp_error))
840 $ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
841
842 list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
843
844 if ($found_path)
845 $_POST['ftp_path'] = $detect_path;
846 elseif (!isset($_POST['ftp_path']))
847 $_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
848
849 if (!isset($_POST['ftp_username']))
850 $_POST['ftp_username'] = $username;
851 }
852
853 $context['package_ftp'] = array(
854 'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
855 'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
856 'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
857 'path' => $_POST['ftp_path'],
858 'error' => empty($ftp_error) ? null : $ftp_error,
859 'destination' => !empty($chmodOptions['destination_url']) ? $chmodOptions['destination_url'] : '',
860 );
861
862 // Which files failed?
863 if (!isset($context['notwritable_files']))
864 $context['notwritable_files'] = array();
865 $context['notwritable_files'] = array_merge($context['notwritable_files'], $return_data['files']['notwritable']);
866
867 // Sent here to die?
868 if (!empty($chmodOptions['crash_on_error']))
869 {
870 $context['page_title'] = $txt['package_ftp_necessary'];
871 $context['sub_template'] = 'ftp_required';
872 obExit();
873 }
874 }
875
876 return $return_data;
877 }
878
879 function packageRequireFTP($destination_url, $files = null, $return = false)
880 {
881 global $context, $modSettings, $package_ftp, $boarddir, $txt;
882
883 // Try to make them writable the manual way.
884 if ($files !== null)
885 {
886 foreach ($files as $k => $file)
887 {
888 // If this file doesn't exist, then we actually want to look at the directory, no?
889 if (!file_exists($file))
890 $file = dirname($file);
891
892 // This looks odd, but it's an attempt to work around PHP suExec.
893 if (!@is_writable($file))
894 @chmod($file, 0755);
895 if (!@is_writable($file))
896 @chmod($file, 0777);
897 if (!@is_writable(dirname($file)))
898 @chmod($file, 0755);
899 if (!@is_writable(dirname($file)))
900 @chmod($file, 0777);
901
902 $fp = is_dir($file) ? @opendir($file) : @fopen($file, 'rb');
903 if (@is_writable($file) && $fp)
904 {
905 unset($files[$k]);
906 if (!is_dir($file))
907 fclose($fp);
908 else
909 closedir($fp);
910 }
911 }
912
913 // No FTP required!
914 if (empty($files))
915 return array();
916 }
917
918 // They've opted to not use FTP, and try anyway.
919 if (isset($_SESSION['pack_ftp']) && $_SESSION['pack_ftp'] == false)
920 {
921 if ($files === null)
922 return array();
923
924 foreach ($files as $k => $file)
925 {
926 // This looks odd, but it's an attempt to work around PHP suExec.
927 if (!file_exists($file))
928 {
929 mktree(dirname($file), 0755);
930 @touch($file);
931 @chmod($file, 0755);
932 }
933
934 if (!@is_writable($file))
935 @chmod($file, 0777);
936 if (!@is_writable(dirname($file)))
937 @chmod(dirname($file), 0777);
938
939 if (@is_writable($file))
940 unset($files[$k]);
941 }
942
943 return $files;
944 }
945 elseif (isset($_SESSION['pack_ftp']))
946 {
947 // Load the file containing the ftp_connection class.
948 loadClassFile('Class-Package.php');
949
950 $package_ftp = new ftp_connection($_SESSION['pack_ftp']['server'], $_SESSION['pack_ftp']['port'], $_SESSION['pack_ftp']['username'], package_crypt($_SESSION['pack_ftp']['password']));
951
952 if ($files === null)
953 return array();
954
955 foreach ($files as $k => $file)
956 {
957 $ftp_file = strtr($file, array($_SESSION['pack_ftp']['root'] => ''));
958
959 // This looks odd, but it's an attempt to work around PHP suExec.
960 if (!file_exists($file))
961 {
962 mktree(dirname($file), 0755);
963 $package_ftp->create_file($ftp_file);
964 $package_ftp->chmod($ftp_file, 0755);
965 }
966
967 if (!@is_writable($file))
968 $package_ftp->chmod($ftp_file, 0777);
969 if (!@is_writable(dirname($file)))
970 $package_ftp->chmod(dirname($ftp_file), 0777);
971
972 if (@is_writable($file))
973 unset($files[$k]);
974 }
975
976 return $files;
977 }
978
979 if (isset($_POST['ftp_none']))
980 {
981 $_SESSION['pack_ftp'] = false;
982
983 $files = packageRequireFTP($destination_url, $files, $return);
984 return $files;
985 }
986 elseif (isset($_POST['ftp_username']))
987 {
988 loadClassFile('Class-Package.php');
989 $ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
990
991 if ($ftp->error === false)
992 {
993 // Common mistake, so let's try to remedy it...
994 if (!$ftp->chdir($_POST['ftp_path']))
995 {
996 $ftp_error = $ftp->last_message;
997 $ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
998 }
999 }
1000 }
1001
1002 if (!isset($ftp) || $ftp->error !== false)
1003 {
1004 if (!isset($ftp))
1005 {
1006 loadClassFile('Class-Package.php');
1007 $ftp = new ftp_connection(null);
1008 }
1009 elseif ($ftp->error !== false && !isset($ftp_error))
1010 $ftp_error = $ftp->last_message === null ? '' : $ftp->last_message;
1011
1012 list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
1013
1014 if ($found_path)
1015 $_POST['ftp_path'] = $detect_path;
1016 elseif (!isset($_POST['ftp_path']))
1017 $_POST['ftp_path'] = isset($modSettings['package_path']) ? $modSettings['package_path'] : $detect_path;
1018
1019 if (!isset($_POST['ftp_username']))
1020 $_POST['ftp_username'] = $username;
1021
1022 $context['package_ftp'] = array(
1023 'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : (isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost'),
1024 'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : (isset($modSettings['package_port']) ? $modSettings['package_port'] : '21'),
1025 'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : (isset($modSettings['package_username']) ? $modSettings['package_username'] : ''),
1026 'path' => $_POST['ftp_path'],
1027 'error' => empty($ftp_error) ? null : $ftp_error,
1028 'destination' => $destination_url,
1029 );
1030
1031 // If we're returning dump out here.
1032 if ($return)
1033 return $files;
1034
1035 $context['page_title'] = $txt['package_ftp_necessary'];
1036 $context['sub_template'] = 'ftp_required';
1037 obExit();
1038 }
1039 else
1040 {
1041 if (!in_array($_POST['ftp_path'], array('', '/')))
1042 {
1043 $ftp_root = strtr($boarddir, array($_POST['ftp_path'] => ''));
1044 if (substr($ftp_root, -1) == '/' && ($_POST['ftp_path'] == '' || substr($_POST['ftp_path'], 0, 1) == '/'))
1045 $ftp_root = substr($ftp_root, 0, -1);
1046 }
1047 else
1048 $ftp_root = $boarddir;
1049
1050 $_SESSION['pack_ftp'] = array(
1051 'server' => $_POST['ftp_server'],
1052 'port' => $_POST['ftp_port'],
1053 'username' => $_POST['ftp_username'],
1054 'password' => package_crypt($_POST['ftp_password']),
1055 'path' => $_POST['ftp_path'],
1056 'root' => $ftp_root,
1057 );
1058
1059 if (!isset($modSettings['package_path']) || $modSettings['package_path'] != $_POST['ftp_path'])
1060 updateSettings(array('package_path' => $_POST['ftp_path']));
1061
1062 $files = packageRequireFTP($destination_url, $files, $return);
1063 }
1064
1065 return $files;
1066 }
1067
1068 // Parses a package-info.xml file - method can be 'install', 'upgrade', or 'uninstall'.
1069 function parsePackageInfo(&$packageXML, $testing_only = true, $method = 'install', $previous_version = '')
1070 {
1071 global $boarddir, $forum_version, $context, $temp_path, $language;
1072
1073 // Mayday! That action doesn't exist!!
1074 if (empty($packageXML) || !$packageXML->exists($method))
1075 return array();
1076
1077 // We haven't found the package script yet...
1078 $script = false;
1079 $the_version = strtr($forum_version, array('SMF ' => ''));
1080
1081 // Emulation support...
1082 if (!empty($_SESSION['version_emulate']))
1083 $the_version = $_SESSION['version_emulate'];
1084
1085 // Get all the versions of this method and find the right one.
1086 $these_methods = $packageXML->set($method);
1087 foreach ($these_methods as $this_method)
1088 {
1089 // They specified certain versions this part is for.
1090 if ($this_method->exists('@for'))
1091 {
1092 // Don't keep going if this won't work for this version of SMF.
1093 if (!matchPackageVersion($the_version, $this_method->fetch('@for')))
1094 continue;
1095 }
1096
1097 // Upgrades may go from a certain old version of the mod.
1098 if ($method == 'upgrade' && $this_method->exists('@from'))
1099 {
1100 // Well, this is for the wrong old version...
1101 if (!matchPackageVersion($previous_version, $this_method->fetch('@from')))
1102 continue;
1103 }
1104
1105 // We've found it!
1106 $script = $this_method;
1107 break;
1108 }
1109
1110 // Bad news, a matching script wasn't found!
1111 if ($script === false)
1112 return array();
1113
1114 // Find all the actions in this method - in theory, these should only be allowed actions. (* means all.)
1115 $actions = $script->set('*');
1116 $return = array();
1117
1118 $temp_auto = 0;
1119 $temp_path = $boarddir . '/Packages/temp/' . (isset($context['base_path']) ? $context['base_path'] : '');
1120
1121 $context['readmes'] = array();
1122 // This is the testing phase... nothing shall be done yet.
1123 foreach ($actions as $action)
1124 {
1125 $actionType = $action->name();
1126
1127 if ($actionType == 'readme' || $actionType == 'code' || $actionType == 'database' || $actionType == 'modification' || $actionType == 'redirect')
1128 {
1129 // Allow for translated readme files.
1130 if ($actionType == 'readme')
1131 {
1132 if ($action->exists('@lang'))
1133 {
1134 // Auto-select a readme language based on either request variable or current language.
1135 if ((isset($_REQUEST['readme']) && $action->fetch('@lang') == $_REQUEST['readme']) || (!isset($_REQUEST['readme']) && $action->fetch('@lang') == $language))
1136 {
1137 // In case the user put the readme blocks in the wrong order.
1138 if (isset($context['readmes']['selected']) && $context['readmes']['selected'] == 'default')
1139 $context['readmes'][] = 'default';
1140
1141 $context['readmes']['selected'] = htmlspecialchars($action->fetch('@lang'));
1142 }
1143 else
1144 {
1145 // We don't want this readme now, but we'll allow the user to select to read it.
1146 $context['readmes'][] = htmlspecialchars($action->fetch('@lang'));
1147 continue;
1148 }
1149 }
1150 // Fallback readme. Without lang parameter.
1151 else
1152 {
1153
1154 // Already selected a readme.
1155 if (isset($context['readmes']['selected']))
1156 {
1157 $context['readmes'][] = 'default';
1158 continue;
1159 }
1160 else
1161 $context['readmes']['selected'] = 'default';
1162 }
1163 }
1164
1165 // !!! TODO: Make sure the file actually exists? Might not work when testing?
1166 if ($action->exists('@type') && $action->fetch('@type') == 'inline')
1167 {
1168 $filename = $temp_path . '$auto_' . $temp_auto++ . ($actionType == 'readme' || $actionType == 'redirect' ? '.txt' : ($actionType == 'code' || $actionType == 'database' ? '.php' : '.mod'));
1169 package_put_contents($filename, $action->fetch('.'));
1170 $filename = strtr($filename, array($temp_path => ''));
1171 }
1172 else
1173 $filename = $action->fetch('.');
1174
1175 $return[] = array(
1176 'type' => $actionType,
1177 'filename' => $filename,
1178 'description' => '',
1179 'reverse' => $action->exists('@reverse') && $action->fetch('@reverse') == 'true',
1180 'boardmod' => $action->exists('@format') && $action->fetch('@format') == 'boardmod',
1181 'redirect_url' => $action->exists('@url') ? $action->fetch('@url') : '',
1182 'redirect_timeout' => $action->exists('@timeout') ? (int) $action->fetch('@timeout') : '',
1183 'parse_bbc' => $action->exists('@parsebbc') && $action->fetch('@parsebbc') == 'true',
1184 'language' => ($actionType == 'readme' && $action->exists('@lang') && $action->fetch('@lang') == $language) ? $language : '',
1185 );
1186
1187 continue;
1188 }
1189 elseif ($actionType == 'error')
1190 {
1191 $return[] = array(
1192 'type' => 'error',
1193 );
1194 }
1195
1196 $this_action = &$return[];
1197 $this_action = array(
1198 'type' => $actionType,
1199 'filename' => $action->fetch('@name'),
1200 'description' => $action->fetch('.')
1201 );
1202
1203 // If there is a destination, make sure it makes sense.
1204 if (substr($actionType, 0, 6) != 'remove')
1205 {
1206 $this_action['unparsed_destination'] = $action->fetch('@destination');
1207 $this_action['destination'] = parse_path($action->fetch('@destination')) . '/' . basename($this_action['filename']);
1208 }
1209 else
1210 {
1211 $this_action['unparsed_filename'] = $this_action['filename'];
1212 $this_action['filename'] = parse_path($this_action['filename']);
1213 }
1214
1215 // If we're moving or requiring (copying) a file.
1216 if (substr($actionType, 0, 4) == 'move' || substr($actionType, 0, 7) == 'require')
1217 {
1218 if ($action->exists('@from'))
1219 $this_action['source'] = parse_path($action->fetch('@from'));
1220 else
1221 $this_action['source'] = $temp_path . $this_action['filename'];
1222 }
1223
1224 // Check if these things can be done. (chmod's etc.)
1225 if ($actionType == 'create-dir')
1226 {
1227 if (!mktree($this_action['destination'], false))
1228 {
1229 $temp = $this_action['destination'];
1230 while (!file_exists($temp) && strlen($temp) > 1)
1231 $temp = dirname($temp);
1232
1233 $return[] = array(
1234 'type' => 'chmod',
1235 'filename' => $temp
1236 );
1237 }
1238 }
1239 elseif ($actionType == 'create-file')
1240 {
1241 if (!mktree(dirname($this_action['destination']), false))
1242 {
1243 $temp = dirname($this_action['destination']);
1244 while (!file_exists($temp) && strlen($temp) > 1)
1245 $temp = dirname($temp);
1246
1247 $return[] = array(
1248 'type' => 'chmod',
1249 'filename' => $temp
1250 );
1251 }
1252
1253 if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1254 $return[] = array(
1255 'type' => 'chmod',
1256 'filename' => $this_action['destination']
1257 );
1258 }
1259 elseif ($actionType == 'require-dir')
1260 {
1261 if (!mktree($this_action['destination'], false))
1262 {
1263 $temp = $this_action['destination'];
1264 while (!file_exists($temp) && strlen($temp) > 1)
1265 $temp = dirname($temp);
1266
1267 $return[] = array(
1268 'type' => 'chmod',
1269 'filename' => $temp
1270 );
1271 }
1272 }
1273 elseif ($actionType == 'require-file')
1274 {
1275 if ($action->exists('@theme'))
1276 $this_action['theme_action'] = $action->fetch('@theme');
1277
1278 if (!mktree(dirname($this_action['destination']), false))
1279 {
1280 $temp = dirname($this_action['destination']);
1281 while (!file_exists($temp) && strlen($temp) > 1)
1282 $temp = dirname($temp);
1283
1284 $return[] = array(
1285 'type' => 'chmod',
1286 'filename' => $temp
1287 );
1288 }
1289
1290 if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1291 $return[] = array(
1292 'type' => 'chmod',
1293 'filename' => $this_action['destination']
1294 );
1295 }
1296 elseif ($actionType == 'move-dir' || $actionType == 'move-file')
1297 {
1298 if (!mktree(dirname($this_action['destination']), false))
1299 {
1300 $temp = dirname($this_action['destination']);
1301 while (!file_exists($temp) && strlen($temp) > 1)
1302 $temp = dirname($temp);
1303
1304 $return[] = array(
1305 'type' => 'chmod',
1306 'filename' => $temp
1307 );
1308 }
1309
1310 if (!is_writable($this_action['destination']) && (file_exists($this_action['destination']) || !is_writable(dirname($this_action['destination']))))
1311 $return[] = array(
1312 'type' => 'chmod',
1313 'filename' => $this_action['destination']
1314 );
1315 }
1316 elseif ($actionType == 'remove-dir')
1317 {
1318 if (!is_writable($this_action['filename']) && file_exists($this_action['destination']))
1319 $return[] = array(
1320 'type' => 'chmod',
1321 'filename' => $this_action['filename']
1322 );
1323 }
1324 elseif ($actionType == 'remove-file')
1325 {
1326 if (!is_writable($this_action['filename']) && file_exists($this_action['filename']))
1327 $return[] = array(
1328 'type' => 'chmod',
1329 'filename' => $this_action['filename']
1330 );
1331 }
1332 }
1333
1334 // Only testing - just return a list of things to be done.
1335 if ($testing_only)
1336 return $return;
1337
1338 umask(0);
1339
1340 $failure = false;
1341 $not_done = array(array('type' => '!'));
1342 foreach ($return as $action)
1343 {
1344 if ($action['type'] == 'modification' || $action['type'] == 'code' || $action['type'] == 'database' || $action['type'] == 'redirect')
1345 $not_done[] = $action;
1346
1347 if ($action['type'] == 'create-dir')
1348 {
1349 if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1350 $failure |= !mktree($action['destination'], 0777);
1351 }
1352 elseif ($action['type'] == 'create-file')
1353 {
1354 if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1355 $failure |= !mktree(dirname($action['destination']), 0777);
1356
1357 // Create an empty file.
1358 package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1359
1360 if (!file_exists($action['destination']))
1361 $failure = true;
1362 }
1363 elseif ($action['type'] == 'require-dir')
1364 {
1365 copytree($action['source'], $action['destination']);
1366 // Any other theme folders?
1367 if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1368 foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1369 copytree($action['source'], $theme_destination);
1370 }
1371 elseif ($action['type'] == 'require-file')
1372 {
1373 if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1374 $failure |= !mktree(dirname($action['destination']), 0777);
1375
1376 package_put_contents($action['destination'], package_get_contents($action['source']), $testing_only);
1377
1378 $failure |= !copy($action['source'], $action['destination']);
1379
1380 // Any other theme files?
1381 if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['destination']]))
1382 foreach ($context['theme_copies'][$action['type']][$action['destination']] as $theme_destination)
1383 {
1384 if (!mktree(dirname($theme_destination), 0755) || !is_writable(dirname($theme_destination)))
1385 $failure |= !mktree(dirname($theme_destination), 0777);
1386
1387 package_put_contents($theme_destination, package_get_contents($action['source']), $testing_only);
1388
1389 $failure |= !copy($action['source'], $theme_destination);
1390 }
1391 }
1392 elseif ($action['type'] == 'move-file')
1393 {
1394 if (!mktree(dirname($action['destination']), 0755) || !is_writable(dirname($action['destination'])))
1395 $failure |= !mktree(dirname($action['destination']), 0777);
1396
1397 $failure |= !rename($action['source'], $action['destination']);
1398 }
1399 elseif ($action['type'] == 'move-dir')
1400 {
1401 if (!mktree($action['destination'], 0755) || !is_writable($action['destination']))
1402 $failure |= !mktree($action['destination'], 0777);
1403
1404 $failure |= !rename($action['source'], $action['destination']);
1405 }
1406 elseif ($action['type'] == 'remove-dir')
1407 {
1408 deltree($action['filename']);
1409
1410 // Any other theme folders?
1411 if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1412 foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1413 deltree($theme_destination);
1414 }
1415 elseif ($action['type'] == 'remove-file')
1416 {
1417 // Make sure the file exists before deleting it.
1418 if (file_exists($action['filename']))
1419 {
1420 package_chmod($action['filename']);
1421 $failure |= !unlink($action['filename']);
1422 }
1423 // The file that was supposed to be deleted couldn't be found.
1424 else
1425 $failure = true;
1426
1427 // Any other theme folders?
1428 if (!empty($context['theme_copies']) && !empty($context['theme_copies'][$action['type']][$action['filename']]))
1429 foreach ($context['theme_copies'][$action['type']][$action['filename']] as $theme_destination)
1430 if (file_exists($theme_destination))
1431 $failure |= !unlink($theme_destination);
1432 else
1433 $failure = true;
1434 }
1435 }
1436
1437 return $not_done;
1438 }
1439
1440 // This function tries to match $version into any of the ranges given in $versions
1441 function matchPackageVersion($version, $versions)
1442 {
1443 // Make sure everything is lowercase and clean of spaces and unpleasant history.
1444 $version = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1445 $versions = explode(',', str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($versions)));
1446
1447 // Perhaps we do accept anything?
1448 if (in_array('all', $versions))
1449 return true;
1450
1451 // Loop through each version.
1452 foreach ($versions as $for)
1453 {
1454 // Wild card spotted?
1455 if (strpos($for, '*') !== false)
1456 $for = str_replace('*', '0dev0', $for) . '-' . str_replace('*', '999', $for);
1457
1458 // Do we have a range?
1459 if (strpos($for, '-') !== false)
1460 {
1461 list ($lower, $upper) = explode('-', $for);
1462
1463 // Compare the version against lower and upper bounds.
1464 if (compareVersions($version, $lower) > -1 && compareVersions($version, $upper) < 1)
1465 return true;
1466 }
1467 // Otherwise check if they are equal...
1468 elseif (compareVersions($version, $for) === 0)
1469 return true;
1470 }
1471
1472 return false;
1473 }
1474
1475 // The geek version of versioning checks for dummies, which basically compares two versions.
1476 function compareVersions($version1, $version2)
1477 {
1478 static $categories;
1479
1480 $versions = array();
1481 foreach (array(1 => $version1, $version2) as $id => $version)
1482 {
1483 // Clean the version and extract the version parts.
1484 $clean = str_replace(array(' ', '2.0rc1-1'), array('', '2.0rc1.1'), strtolower($version));
1485 preg_match('~(\d+)(?:\.(\d+|))?(?:\.)?(\d+|)(?:(alpha|beta|rc)(\d+|)(?:\.)?(\d+|))?(?:(dev))?(\d+|)~', $clean, $parts);
1486
1487 // Build an array of parts.
1488 $versions[$id] = array(
1489 'major' => (int) $parts[1],
1490 'minor' => !empty($parts[2]) ? (int) $parts[2] : 0,
1491 'patch' => !empty($parts[3]) ? (int) $parts[3] : 0,
1492 'type' => empty($parts[4]) ? 'stable' : $parts[4],
1493 'type_major' => !empty($parts[6]) ? (int) $parts[5] : 0,
1494 'type_minor' => !empty($parts[6]) ? (int) $parts[6] : 0,
1495 'dev' => !empty($parts[7]),
1496 );
1497 }
1498
1499 // Are they the same, perhaps?
1500 if ($versions[1] === $versions[2])
1501 return 0;
1502
1503 // Get version numbering categories...
1504 if (!isset($categories))
1505 $categories = array_keys($versions[1]);
1506
1507 // Loop through each category.
1508 foreach ($categories as $category)
1509 {
1510 // Is there something for us to calculate?
1511 if ($versions[1][$category] !== $versions[2][$category])
1512 {
1513 // Dev builds are a problematic exception.
1514 // (stable) dev < (stable) but (unstable) dev = (unstable)
1515 if ($category == 'type')
1516 return $versions[1][$category] > $versions[2][$category] ? ($versions[1]['dev'] ? -1 : 1) : ($versions[2]['dev'] ? 1 : -1);
1517 elseif ($category == 'dev')
1518 return $versions[1]['dev'] ? ($versions[2]['type'] == 'stable' ? -1 : 0) : ($versions[1]['type'] == 'stable' ? 1 : 0);
1519 // Otherwise a simple comparison.
1520 else
1521 return $versions[1][$category] > $versions[2][$category] ? 1 : -1;
1522 }
1523 }
1524
1525 // They are the same!
1526 return 0;
1527 }
1528
1529 function parse_path($path)
1530 {
1531 global $modSettings, $boarddir, $sourcedir, $settings, $temp_path;
1532
1533 $dirs = array(
1534 '\\' => '/',
1535 '$boarddir' => $boarddir,
1536 '$sourcedir' => $sourcedir,
1537 '$avatardir' => $modSettings['avatar_directory'],
1538 '$avatars_dir' => $modSettings['avatar_directory'],
1539 '$themedir' => $settings['default_theme_dir'],
1540 '$imagesdir' => $settings['default_theme_dir'] . '/' . basename($settings['default_images_url']),
1541 '$themes_dir' => $boarddir . '/Themes',
1542 '$languagedir' => $settings['default_theme_dir'] . '/languages',
1543 '$languages_dir' => $settings['default_theme_dir'] . '/languages',
1544 '$smileysdir' => $modSettings['smileys_dir'],
1545 '$smileys_dir' => $modSettings['smileys_dir'],
1546 );
1547
1548 // do we parse in a package directory?
1549 if (!empty($temp_path))
1550 $dirs['$package'] = $temp_path;
1551
1552 if (strlen($path) == 0)
1553 trigger_error('parse_path(): There should never be an empty filename', E_USER_ERROR);
1554
1555 return strtr($path, $dirs);
1556 }
1557
1558 function deltree($dir, $delete_dir = true)
1559 {
1560 global $package_ftp;
1561
1562 if (!file_exists($dir))
1563 return;
1564
1565 $current_dir = @opendir($dir);
1566 if ($current_dir == false)
1567 {
1568 if ($delete_dir && isset($package_ftp))
1569 {
1570 $ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1571 if (!is_writable($dir . '/' . $entryname))
1572 $package_ftp->chmod($ftp_file, 0777);
1573 $package_ftp->unlink($ftp_file);
1574 }
1575
1576 return;
1577 }
1578
1579 while ($entryname = readdir($current_dir))
1580 {
1581 if (in_array($entryname, array('.', '..')))
1582 continue;
1583
1584 if (is_dir($dir . '/' . $entryname))
1585 deltree($dir . '/' . $entryname);
1586 else
1587 {
1588 // Here, 755 doesn't really matter since we're deleting it anyway.
1589 if (isset($package_ftp))
1590 {
1591 $ftp_file = strtr($dir . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1592
1593 if (!is_writable($dir . '/' . $entryname))
1594 $package_ftp->chmod($ftp_file, 0777);
1595 $package_ftp->unlink($ftp_file);
1596 }
1597 else
1598 {
1599 if (!is_writable($dir . '/' . $entryname))
1600 @chmod($dir . '/' . $entryname, 0777);
1601 unlink($dir . '/' . $entryname);
1602 }
1603 }
1604 }
1605
1606 closedir($current_dir);
1607
1608 if ($delete_dir)
1609 {
1610 if (isset($package_ftp))
1611 {
1612 $ftp_file = strtr($dir, array($_SESSION['pack_ftp']['root'] => ''));
1613 if (!is_writable($dir . '/' . $entryname))
1614 $package_ftp->chmod($ftp_file, 0777);
1615 $package_ftp->unlink($ftp_file);
1616 }
1617 else
1618 {
1619 if (!is_writable($dir))
1620 @chmod($dir, 0777);
1621 @rmdir($dir);
1622 }
1623 }
1624 }
1625
1626 function mktree($strPath, $mode)
1627 {
1628 global $package_ftp;
1629
1630 if (is_dir($strPath))
1631 {
1632 if (!is_writable($strPath) && $mode !== false)
1633 {
1634 if (isset($package_ftp))
1635 $package_ftp->chmod(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')), $mode);
1636 else
1637 @chmod($strPath, $mode);
1638 }
1639
1640 $test = @opendir($strPath);
1641 if ($test)
1642 {
1643 closedir($test);
1644 return is_writable($strPath);
1645 }
1646 else
1647 return false;
1648 }
1649 // Is this an invalid path and/or we can't make the directory?
1650 if ($strPath == dirname($strPath) || !mktree(dirname($strPath), $mode))
1651 return false;
1652
1653 if (!is_writable(dirname($strPath)) && $mode !== false)
1654 {
1655 if (isset($package_ftp))
1656 $package_ftp->chmod(dirname(strtr($strPath, array($_SESSION['pack_ftp']['root'] => ''))), $mode);
1657 else
1658 @chmod(dirname($strPath), $mode);
1659 }
1660
1661 if ($mode !== false && isset($package_ftp))
1662 return $package_ftp->create_dir(strtr($strPath, array($_SESSION['pack_ftp']['root'] => '')));
1663 elseif ($mode === false)
1664 {
1665 $test = @opendir(dirname($strPath));
1666 if ($test)
1667 {
1668 closedir($test);
1669 return true;
1670 }
1671 else
1672 return false;
1673 }
1674 else
1675 {
1676 @mkdir($strPath, $mode);
1677 $test = @opendir($strPath);
1678 if ($test)
1679 {
1680 closedir($test);
1681 return true;
1682 }
1683 else
1684 return false;
1685 }
1686 }
1687
1688 function copytree($source, $destination)
1689 {
1690 global $package_ftp;
1691
1692 if (!file_exists($destination) || !is_writable($destination))
1693 mktree($destination, 0755);
1694 if (!is_writable($destination))
1695 mktree($destination, 0777);
1696
1697 $current_dir = opendir($source);
1698 if ($current_dir == false)
1699 return;
1700
1701 while ($entryname = readdir($current_dir))
1702 {
1703 if (in_array($entryname, array('.', '..')))
1704 continue;
1705
1706 if (isset($package_ftp))
1707 $ftp_file = strtr($destination . '/' . $entryname, array($_SESSION['pack_ftp']['root'] => ''));
1708
1709 if (is_file($source . '/' . $entryname))
1710 {
1711 if (isset($package_ftp) && !file_exists($destination . '/' . $entryname))
1712 $package_ftp->create_file($ftp_file);
1713 elseif (!file_exists($destination . '/' . $entryname))
1714 @touch($destination . '/' . $entryname);
1715 }
1716
1717 package_chmod($destination . '/' . $entryname);
1718
1719 if (is_dir($source . '/' . $entryname))
1720 copytree($source . '/' . $entryname, $destination . '/' . $entryname);
1721 elseif (file_exists($destination . '/' . $entryname))
1722 package_put_contents($destination . '/' . $entryname, package_get_contents($source . '/' . $entryname));
1723 else
1724 copy($source . '/' . $entryname, $destination . '/' . $entryname);
1725 }
1726
1727 closedir($current_dir);
1728 }
1729
1730 function listtree($path, $sub_path = '')
1731 {
1732 $data = array();
1733
1734 $dir = @dir($path . $sub_path);
1735 if (!$dir)
1736 return array();
1737 while ($entry = $dir->read())
1738 {
1739 if ($entry == '.' || $entry == '..')
1740 continue;
1741
1742 if (is_dir($path . $sub_path . '/' . $entry))
1743 $data = array_merge($data, listtree($path, $sub_path . '/' . $entry));
1744 else
1745 $data[] = array(
1746 'filename' => $sub_path == '' ? $entry : $sub_path . '/' . $entry,
1747 'size' => filesize($path . $sub_path . '/' . $entry),
1748 'skipped' => false,
1749 );
1750 }
1751 $dir->close();
1752
1753 return $data;
1754 }
1755
1756 // Parse an xml based modification file.
1757 function parseModification($file, $testing = true, $undo = false, $theme_paths = array())
1758 {
1759 global $boarddir, $sourcedir, $settings, $txt, $modSettings, $package_ftp;
1760
1761 @set_time_limit(600);
1762 loadClassFile('Class-Package.php');
1763 $xml = new xmlArray(strtr($file, array("\r" => '')));
1764 $actions = array();
1765 $everything_found = true;
1766
1767 if (!$xml->exists('modification') || !$xml->exists('modification/file'))
1768 {
1769 $actions[] = array(
1770 'type' => 'error',
1771 'filename' => '-',
1772 'debug' => $txt['package_modification_malformed']
1773 );
1774 return $actions;
1775 }
1776
1777 // Get the XML data.
1778 $files = $xml->set('modification/file');
1779
1780 // Use this for holding all the template changes in this mod.
1781 $template_changes = array();
1782 // This is needed to hold the long paths, as they can vary...
1783 $long_changes = array();
1784
1785 // First, we need to build the list of all the files likely to get changed.
1786 foreach ($files as $file)
1787 {
1788 // What is the filename we're currently on?
1789 $filename = parse_path(trim($file->fetch('@name')));
1790
1791 // Now, we need to work out whether this is even a template file...
1792 foreach ($theme_paths as $id => $theme)
1793 {
1794 // If this filename is relative, if so take a guess at what it should be.
1795 $real_filename = $filename;
1796 if (strpos($filename, 'Themes') === 0)
1797 $real_filename = $boarddir . '/' . $filename;
1798
1799 if (strpos($real_filename, $theme['theme_dir']) === 0)
1800 {
1801 $template_changes[$id][] = substr($real_filename, strlen($theme['theme_dir']) + 1);
1802 $long_changes[$id][] = $filename;
1803 }
1804 }
1805 }
1806
1807 // Custom themes to add.
1808 $custom_themes_add = array();
1809
1810 // If we have some template changes, we need to build a master link of what new ones are required for the custom themes.
1811 if (!empty($template_changes[1]))
1812 {
1813 foreach ($theme_paths as $id => $theme)
1814 {
1815 // Default is getting done anyway, so no need for involvement here.
1816 if ($id == 1)
1817 continue;
1818
1819 // For every template, do we want it? Yea, no, maybe?
1820 foreach ($template_changes[1] as $index => $template_file)
1821 {
1822 // What, it exists and we haven't already got it?! Lordy, get it in!
1823 if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id]) || !in_array($template_file, $template_changes[$id])))
1824 {
1825 // Now let's add it to the "todo" list.
1826 $custom_themes_add[$long_changes[1][$index]][$id] = $theme['theme_dir'] . '/' . $template_file;
1827 }
1828 }
1829 }
1830 }
1831
1832 foreach ($files as $file)
1833 {
1834 // This is the actual file referred to in the XML document...
1835 $files_to_change = array(
1836 1 => parse_path(trim($file->fetch('@name'))),
1837 );
1838
1839 // Sometimes though, we have some additional files for other themes, if we have add them to the mix.
1840 if (isset($custom_themes_add[$files_to_change[1]]))
1841 $files_to_change += $custom_themes_add[$files_to_change[1]];
1842
1843 // Now, loop through all the files we're changing, and, well, change them ;)
1844 foreach ($files_to_change as $theme => $working_file)
1845 {
1846 if ($working_file[0] != '/' && $working_file[1] != ':')
1847 {
1848 trigger_error('parseModification(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
1849
1850 $working_file = $boarddir . '/' . $working_file;
1851 }
1852
1853 // Doesn't exist - give an error or what?
1854 if (!file_exists($working_file) && (!$file->exists('@error') || !in_array(trim($file->fetch('@error')), array('ignore', 'skip'))))
1855 {
1856 $actions[] = array(
1857 'type' => 'missing',
1858 'filename' => $working_file,
1859 'debug' => $txt['package_modification_missing']
1860 );
1861
1862 $everything_found = false;
1863 continue;
1864 }
1865 // Skip the file if it doesn't exist.
1866 elseif (!file_exists($working_file) && $file->exists('@error') && trim($file->fetch('@error')) == 'skip')
1867 {
1868 $actions[] = array(
1869 'type' => 'skipping',
1870 'filename' => $working_file,
1871 );
1872 continue;
1873 }
1874 // Okay, we're creating this file then...?
1875 elseif (!file_exists($working_file))
1876 $working_data = '';
1877 // Phew, it exists! Load 'er up!
1878 else
1879 $working_data = str_replace("\r", '', package_get_contents($working_file));
1880
1881 $actions[] = array(
1882 'type' => 'opened',
1883 'filename' => $working_file
1884 );
1885
1886 $operations = $file->exists('operation') ? $file->set('operation') : array();
1887 foreach ($operations as $operation)
1888 {
1889 // Convert operation to an array.
1890 $actual_operation = array(
1891 'searches' => array(),
1892 'error' => $operation->exists('@error') && in_array(trim($operation->fetch('@error')), array('ignore', 'fatal', 'required')) ? trim($operation->fetch('@error')) : 'fatal',
1893 );
1894
1895 // The 'add' parameter is used for all searches in this operation.
1896 $add = $operation->exists('add') ? $operation->fetch('add') : '';
1897
1898 // Grab all search items of this operation (in most cases just 1).
1899 $searches = $operation->set('search');
1900 foreach ($searches as $i => $search)
1901 $actual_operation['searches'][] = array(
1902 'position' => $search->exists('@position') && in_array(trim($search->fetch('@position')), array('before', 'after', 'replace', 'end')) ? trim($search->fetch('@position')) : 'replace',
1903 'is_reg_exp' => $search->exists('@regexp') && trim($search->fetch('@regexp')) === 'true',
1904 'loose_whitespace' => $search->exists('@whitespace') && trim($search->fetch('@whitespace')) === 'loose',
1905 'search' => $search->fetch('.'),
1906 'add' => $add,
1907 'preg_search' => '',
1908 'preg_replace' => '',
1909 );
1910
1911 // At least one search should be defined.
1912 if (empty($actual_operation['searches']))
1913 {
1914 $actions[] = array(
1915 'type' => 'failure',
1916 'filename' => $working_file,
1917 'search' => $search['search'],
1918 'is_custom' => $theme > 1 ? $theme : 0,
1919 );
1920
1921 // Skip to the next operation.
1922 continue;
1923 }
1924
1925 // Reverse the operations in case of undoing stuff.
1926 if ($undo)
1927 {
1928 foreach ($actual_operation['searches'] as $i => $search)
1929 {
1930
1931 // Reverse modification of regular expressions are not allowed.
1932 if ($search['is_reg_exp'])
1933 {
1934 if ($actual_operation['error'] === 'fatal')
1935 $actions[] = array(
1936 'type' => 'failure',
1937 'filename' => $working_file,
1938 'search' => $search['search'],
1939 'is_custom' => $theme > 1 ? $theme : 0,
1940 );
1941
1942 // Continue to the next operation.
1943 continue 2;
1944 }
1945
1946 // The replacement is now the search subject...
1947 if ($search['position'] === 'replace' || $search['position'] === 'end')
1948 $actual_operation['searches'][$i]['search'] = $search['add'];
1949 else
1950 {
1951 // Reversing a before/after modification becomes a replacement.
1952 $actual_operation['searches'][$i]['position'] = 'replace';
1953
1954 if ($search['position'] === 'before')
1955 $actual_operation['searches'][$i]['search'] .= $search['add'];
1956 elseif ($search['position'] === 'after')
1957 $actual_operation['searches'][$i]['search'] = $search['add'] . $search['search'];
1958 }
1959
1960 // ...and the search subject is now the replacement.
1961 $actual_operation['searches'][$i]['add'] = $search['search'];
1962 }
1963 }
1964
1965 // Sort the search list so the replaces come before the add before/after's.
1966 if (count($actual_operation['searches']) !== 1)
1967 {
1968 $replacements = array();
1969
1970 foreach ($actual_operation['searches'] as $i => $search)
1971 {
1972 if ($search['position'] === 'replace')
1973 {
1974 $replacements[] = $search;
1975 unset($actual_operation['searches'][$i]);
1976 }
1977 }
1978 $actual_operation['searches'] = array_merge($replacements, $actual_operation['searches']);
1979 }
1980
1981 // Create regular expression replacements from each search.
1982 foreach ($actual_operation['searches'] as $i => $search)
1983 {
1984 // Not much needed if the search subject is already a regexp.
1985 if ($search['is_reg_exp'])
1986 $actual_operation['searches'][$i]['preg_search'] = $search['search'];
1987 else
1988 {
1989 // Make the search subject fit into a regular expression.
1990 $actual_operation['searches'][$i]['preg_search'] = preg_quote($search['search'], '~');
1991
1992 // Using 'loose', a random amount of tabs and spaces may be used.
1993 if ($search['loose_whitespace'])
1994 $actual_operation['searches'][$i]['preg_search'] = preg_replace('~[ \t]+~', '[ \t]+', $actual_operation['searches'][$i]['preg_search']);
1995 }
1996
1997 // Shuzzup. This is done so we can safely use a regular expression. ($0 is bad!!)
1998 $actual_operation['searches'][$i]['preg_replace'] = strtr($search['add'], array('$' => '[$PACK' . 'AGE1$]', '\\' => '[$PACK' . 'AGE2$]'));
1999
2000 // Before, so the replacement comes after the search subject :P
2001 if ($search['position'] === 'before')
2002 {
2003 $actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2004 $actual_operation['searches'][$i]['preg_replace'] = '$1' . $actual_operation['searches'][$i]['preg_replace'];
2005 }
2006
2007 // After, after what?
2008 elseif ($search['position'] === 'after')
2009 {
2010 $actual_operation['searches'][$i]['preg_search'] = '(' . $actual_operation['searches'][$i]['preg_search'] . ')';
2011 $actual_operation['searches'][$i]['preg_replace'] .= '$1';
2012 }
2013
2014 // Position the replacement at the end of the file (or just before the closing PHP tags).
2015 elseif ($search['position'] === 'end')
2016 {
2017 if ($undo)
2018 {
2019 $actual_operation['searches'][$i]['preg_replace'] = '';
2020 }
2021 else
2022 {
2023 $actual_operation['searches'][$i]['preg_search'] = '(\\n\\?\\>)?$';
2024 $actual_operation['searches'][$i]['preg_replace'] .= '$1';
2025 }
2026 }
2027
2028 // Testing 1, 2, 3...
2029 $failed = preg_match('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $working_data) === 0;
2030
2031 // Nope, search pattern not found.
2032 if ($failed && $actual_operation['error'] === 'fatal')
2033 {
2034 $actions[] = array(
2035 'type' => 'failure',
2036 'filename' => $working_file,
2037 'search' => $actual_operation['searches'][$i]['preg_search'],
2038 'search_original' => $actual_operation['searches'][$i]['search'],
2039 'replace_original' => $actual_operation['searches'][$i]['add'],
2040 'position' => $search['position'],
2041 'is_custom' => $theme > 1 ? $theme : 0,
2042 'failed' => $failed,
2043 );
2044
2045 $everything_found = false;
2046 continue;
2047 }
2048
2049 // Found, but in this case, that means failure!
2050 elseif (!$failed && $actual_operation['error'] === 'required')
2051 {
2052 $actions[] = array(
2053 'type' => 'failure',
2054 'filename' => $working_file,
2055 'search' => $actual_operation['searches'][$i]['preg_search'],
2056 'search_original' => $actual_operation['searches'][$i]['search'],
2057 'replace_original' => $actual_operation['searches'][$i]['add'],
2058 'position' => $search['position'],
2059 'is_custom' => $theme > 1 ? $theme : 0,
2060 'failed' => $failed,
2061 );
2062
2063 $everything_found = false;
2064 continue;
2065 }
2066
2067 // Replace it into nothing? That's not an option...unless it's an undoing end.
2068 if ($search['add'] === '' && ($search['position'] !== 'end' || !$undo))
2069 continue;
2070
2071 // Finally, we're doing some replacements.
2072 $working_data = preg_replace('~' . $actual_operation['searches'][$i]['preg_search'] . '~s', $actual_operation['searches'][$i]['preg_replace'], $working_data, 1);
2073
2074 $actions[] = array(
2075 'type' => 'replace',
2076 'filename' => $working_file,
2077 'search' => $actual_operation['searches'][$i]['preg_search'],
2078 'replace' => $actual_operation['searches'][$i]['preg_replace'],
2079 'search_original' => $actual_operation['searches'][$i]['search'],
2080 'replace_original' => $actual_operation['searches'][$i]['add'],
2081 'position' => $search['position'],
2082 'failed' => $failed,
2083 'ignore_failure' => $failed && $actual_operation['error'] === 'ignore',
2084 'is_custom' => $theme > 1 ? $theme : 0,
2085 );
2086 }
2087 }
2088
2089 // Fix any little helper symbols ;).
2090 $working_data = strtr($working_data, array('[$PACK' . 'AGE1$]' => '$', '[$PACK' . 'AGE2$]' => '\\'));
2091
2092 package_chmod($working_file);
2093
2094 if ((file_exists($working_file) && !is_writable($working_file)) || (!file_exists($working_file) && !is_writable(dirname($working_file))))
2095 $actions[] = array(
2096 'type' => 'chmod',
2097 'filename' => $working_file
2098 );
2099
2100 if (basename($working_file) == 'Settings_bak.php')
2101 continue;
2102
2103 if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2104 {
2105 // No, no, not Settings.php!
2106 if (basename($working_file) == 'Settings.php')
2107 @copy($working_file, dirname($working_file) . '/Settings_bak.php');
2108 else
2109 @copy($working_file, $working_file . '~');
2110 }
2111
2112 // Always call this, even if in testing, because it won't really be written in testing mode.
2113 package_put_contents($working_file, $working_data, $testing);
2114
2115 $actions[] = array(
2116 'type' => 'saved',
2117 'filename' => $working_file,
2118 'is_custom' => $theme > 1 ? $theme : 0,
2119 );
2120 }
2121 }
2122
2123 $actions[] = array(
2124 'type' => 'result',
2125 'status' => $everything_found
2126 );
2127
2128 return $actions;
2129 }
2130
2131 // Parses a BoardMod format mod file...
2132 function parseBoardMod($file, $testing = true, $undo = false, $theme_paths = array())
2133 {
2134 global $boarddir, $sourcedir, $settings, $txt, $modSettings;
2135
2136 @set_time_limit(600);
2137 $file = strtr($file, array("\r" => ''));
2138
2139 $working_file = null;
2140 $working_search = null;
2141 $working_data = '';
2142 $replace_with = null;
2143
2144 $actions = array();
2145 $everything_found = true;
2146
2147 // This holds all the template changes in the standard mod file.
2148 $template_changes = array();
2149 // This is just the temporary file.
2150 $temp_file = $file;
2151 // This holds the actual changes on a step counter basis.
2152 $temp_changes = array();
2153 $counter = 0;
2154 $step_counter = 0;
2155
2156 // Before we do *anything*, let's build a list of what we're editing, as it's going to be used for other theme edits.
2157 while (preg_match('~<(edit file|file|search|search for|add|add after|replace|add before|add above|above|before)>\n(.*?)\n</\\1>~is', $temp_file, $code_match) != 0)
2158 {
2159 $counter++;
2160
2161 // Get rid of the old stuff.
2162 $temp_file = substr_replace($temp_file, '', strpos($temp_file, $code_match[0]), strlen($code_match[0]));
2163
2164 // No interest to us?
2165 if ($code_match[1] != 'edit file' && $code_match[1] != 'file')
2166 {
2167 // It's a step, let's add that to the current steps.
2168 if (isset($temp_changes[$step_counter]))
2169 $temp_changes[$step_counter]['changes'][] = $code_match[0];
2170 continue;
2171 }
2172
2173 // We've found a new edit - let's make ourself heard, kind of.
2174 $step_counter = $counter;
2175 $temp_changes[$step_counter] = array(
2176 'title' => $code_match[0],
2177 'changes' => array(),
2178 );
2179
2180 $filename = parse_path($code_match[2]);
2181
2182 // Now, is this a template file, and if so, which?
2183 foreach ($theme_paths as $id => $theme)
2184 {
2185 // If this filename is relative, if so take a guess at what it should be.
2186 if (strpos($filename, 'Themes') === 0)
2187 $filename = $boarddir . '/' . $filename;
2188
2189 if (strpos($filename, $theme['theme_dir']) === 0)
2190 $template_changes[$id][$counter] = substr($filename, strlen($theme['theme_dir']) + 1);
2191 }
2192 }
2193
2194 // Anything above $counter must be for custom themes.
2195 $custom_template_begin = $counter;
2196 // Reference for what theme ID this action belongs to.
2197 $theme_id_ref = array();
2198
2199 // Now we know what templates we need to touch, cycle through each theme and work out what we need to edit.
2200 if (!empty($template_changes[1]))
2201 {
2202 foreach ($theme_paths as $id => $theme)
2203 {
2204 // Don't do default, it means nothing to me.
2205 if ($id == 1)
2206 continue;
2207
2208 // Now, for each file do we need to edit it?
2209 foreach ($template_changes[1] as $pos => $template_file)
2210 {
2211 // It does? Add it to the list darlin'.
2212 if (file_exists($theme['theme_dir'] . '/' . $template_file) && (!isset($template_changes[$id][$pos]) || !in_array($template_file, $template_changes[$id][$pos])))
2213 {
2214 // Actually add it to the mod file too, so we can see that it will work ;)
2215 if (!empty($temp_changes[$pos]['changes']))
2216 {
2217 $file .= "\n\n" . '<edit file>' . "\n" . $theme['theme_dir'] . '/' . $template_file . "\n" . '</edit file>' . "\n\n" . implode("\n\n", $temp_changes[$pos]['changes']);
2218 $theme_id_ref[$counter] = $id;
2219 $counter += 1 + count($temp_changes[$pos]['changes']);
2220 }
2221 }
2222 }
2223 }
2224 }
2225
2226 $counter = 0;
2227 $is_custom = 0;
2228 while (preg_match('~<(edit file|file|search|search for|add|add after|replace|add before|add above|above|before)>\n(.*?)\n</\\1>~is', $file, $code_match) != 0)
2229 {
2230 // This is for working out what we should be editing.
2231 $counter++;
2232
2233 // Edit a specific file.
2234 if ($code_match[1] == 'file' || $code_match[1] == 'edit file')
2235 {
2236 // Backup the old file.
2237 if ($working_file !== null)
2238 {
2239 package_chmod($working_file);
2240
2241 // Don't even dare.
2242 if (basename($working_file) == 'Settings_bak.php')
2243 continue;
2244
2245 if (!is_writable($working_file))
2246 $actions[] = array(
2247 'type' => 'chmod',
2248 'filename' => $working_file
2249 );
2250
2251 if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2252 {
2253 if (basename($working_file) == 'Settings.php')
2254 @copy($working_file, dirname($working_file) . '/Settings_bak.php');
2255 else
2256 @copy($working_file, $working_file . '~');
2257 }
2258
2259 package_put_contents($working_file, $working_data, $testing);
2260 }
2261
2262 if ($working_file !== null)
2263 $actions[] = array(
2264 'type' => 'saved',
2265 'filename' => $working_file,
2266 'is_custom' => $is_custom,
2267 );
2268
2269 // Is this "now working on" file a theme specific one?
2270 $is_custom = isset($theme_id_ref[$counter - 1]) ? $theme_id_ref[$counter - 1] : 0;
2271
2272 // Make sure the file exists!
2273 $working_file = parse_path($code_match[2]);
2274
2275 if ($working_file[0] != '/' && $working_file[1] != ':')
2276 {
2277 trigger_error('parseBoardMod(): The filename \'' . $working_file . '\' is not a full path!', E_USER_WARNING);
2278
2279 $working_file = $boarddir . '/' . $working_file;
2280 }
2281
2282 if (!file_exists($working_file))
2283 {
2284 $places_to_check = array($boarddir, $sourcedir, $settings['default_theme_dir'], $settings['default_theme_dir'] . '/languages');
2285
2286 foreach ($places_to_check as $place)
2287 if (file_exists($place . '/' . $working_file))
2288 {
2289 $working_file = $place . '/' . $working_file;
2290 break;
2291 }
2292 }
2293
2294 if (file_exists($working_file))
2295 {
2296 // Load the new file.
2297 $working_data = str_replace("\r", '', package_get_contents($working_file));
2298
2299 $actions[] = array(
2300 'type' => 'opened',
2301 'filename' => $working_file
2302 );
2303 }
2304 else
2305 {
2306 $actions[] = array(
2307 'type' => 'missing',
2308 'filename' => $working_file
2309 );
2310
2311 $working_file = null;
2312 $everything_found = false;
2313 }
2314
2315 // Can't be searching for something...
2316 $working_search = null;
2317 }
2318 // Search for a specific string.
2319 elseif (($code_match[1] == 'search' || $code_match[1] == 'search for') && $working_file !== null)
2320 {
2321 if ($working_search !== null)
2322 {
2323 $actions[] = array(
2324 'type' => 'error',
2325 'filename' => $working_file
2326 );
2327
2328 $everything_found = false;
2329 }
2330
2331 $working_search = $code_match[2];
2332 }
2333 // Must've already loaded a search string.
2334 elseif ($working_search !== null)
2335 {
2336 // This is the base string....
2337 $replace_with = $code_match[2];
2338
2339 // Add this afterward...
2340 if ($code_match[1] == 'add' || $code_match[1] == 'add after')
2341 $replace_with = $working_search . "\n" . $replace_with;
2342 // Add this beforehand.
2343 elseif ($code_match[1] == 'before' || $code_match[1] == 'add before' || $code_match[1] == 'above' || $code_match[1] == 'add above')
2344 $replace_with .= "\n" . $working_search;
2345 // Otherwise.. replace with $replace_with ;).
2346 }
2347
2348 // If we have a search string, replace string, and open file..
2349 if ($working_search !== null && $replace_with !== null && $working_file !== null)
2350 {
2351 // Make sure it's somewhere in the string.
2352 if ($undo)
2353 {
2354 $temp = $replace_with;
2355 $replace_with = $working_search;
2356 $working_search = $temp;
2357 }
2358
2359 if (strpos($working_data, $working_search) !== false)
2360 {
2361 $working_data = str_replace($working_search, $replace_with, $working_data);
2362
2363 $actions[] = array(
2364 'type' => 'replace',
2365 'filename' => $working_file,
2366 'search' => $working_search,
2367 'replace' => $replace_with,
2368 'search_original' => $working_search,
2369 'replace_original' => $replace_with,
2370 'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2371 'is_custom' => $is_custom,
2372 'failed' => false,
2373 );
2374 }
2375 // It wasn't found!
2376 else
2377 {
2378 $actions[] = array(
2379 'type' => 'failure',
2380 'filename' => $working_file,
2381 'search' => $working_search,
2382 'is_custom' => $is_custom,
2383 'search_original' => $working_search,
2384 'replace_original' => $replace_with,
2385 'position' => $code_match[1] == 'replace' ? 'replace' : ($code_match[1] == 'add' || $code_match[1] == 'add after' ? 'before' : 'after'),
2386 'is_custom' => $is_custom,
2387 'failed' => true,
2388 );
2389
2390 $everything_found = false;
2391 }
2392
2393 // These don't hold any meaning now.
2394 $working_search = null;
2395 $replace_with = null;
2396 }
2397
2398 // Get rid of the old tag.
2399 $file = substr_replace($file, '', strpos($file, $code_match[0]), strlen($code_match[0]));
2400 }
2401
2402 // Backup the old file.
2403 if ($working_file !== null)
2404 {
2405 package_chmod($working_file);
2406
2407 if (!is_writable($working_file))
2408 $actions[] = array(
2409 'type' => 'chmod',
2410 'filename' => $working_file
2411 );
2412
2413 if (!$testing && !empty($modSettings['package_make_backups']) && file_exists($working_file))
2414 {
2415 if (basename($working_file) == 'Settings.php')
2416 @copy($working_file, dirname($working_file) . '/Settings_bak.php');
2417 else
2418 @copy($working_file, $working_file . '~');
2419 }
2420
2421 package_put_contents($working_file, $working_data, $testing);
2422 }
2423
2424 if ($working_file !== null)
2425 $actions[] = array(
2426 'type' => 'saved',
2427 'filename' => $working_file,
2428 'is_custom' => $is_custom,
2429 );
2430
2431 $actions[] = array(
2432 'type' => 'result',
2433 'status' => $everything_found
2434 );
2435
2436 return $actions;
2437 }
2438
2439 function package_get_contents($filename)
2440 {
2441 global $package_cache, $modSettings;
2442
2443 if (!isset($package_cache))
2444 {
2445 // Windows doesn't seem to care about the memory_limit.
2446 if (!empty($modSettings['package_disable_cache']) || ini_set('memory_limit', '128M') !== false || strpos(strtolower(PHP_OS), 'win') !== false)
2447 $package_cache = array();
2448 else
2449 $package_cache = false;
2450 }
2451
2452 if (strpos($filename, 'Packages/') !== false || $package_cache === false || !isset($package_cache[$filename]))
2453 return file_get_contents($filename);
2454 else
2455 return $package_cache[$filename];
2456 }
2457
2458 function package_put_contents($filename, $data, $testing = false)
2459 {
2460 global $package_ftp, $package_cache, $modSettings;
2461 static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2462
2463 if (!isset($package_cache))
2464 {
2465 // Try to increase the memory limit - we don't want to run out of ram!
2466 if (!empty($modSettings['package_disable_cache']) || ini_set('memory_limit', '128M') !== false || strpos(strtolower(PHP_OS), 'win') !== false)
2467 $package_cache = array();
2468 else
2469 $package_cache = false;
2470 }
2471
2472 if (isset($package_ftp))
2473 $ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2474
2475 if (!file_exists($filename) && isset($package_ftp))
2476 $package_ftp->create_file($ftp_file);
2477 elseif (!file_exists($filename))
2478 @touch($filename);
2479
2480 package_chmod($filename);
2481
2482 if (!$testing && (strpos($filename, 'Packages/') !== false || $package_cache === false))
2483 {
2484 $fp = @fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2485
2486 // We should show an error message or attempt a rollback, no?
2487 if (!$fp)
2488 return false;
2489
2490 fwrite($fp, $data);
2491 fclose($fp);
2492 }
2493 elseif (strpos($filename, 'Packages/') !== false || $package_cache === false)
2494 return strlen($data);
2495 else
2496 {
2497 $package_cache[$filename] = $data;
2498
2499 // Permission denied, eh?
2500 $fp = @fopen($filename, 'r+');
2501 if (!$fp)
2502 return false;
2503 fclose($fp);
2504 }
2505
2506 return strlen($data);
2507 }
2508
2509 function package_flush_cache($trash = false)
2510 {
2511 global $package_ftp, $package_cache;
2512 static $text_filetypes = array('php', 'txt', '.js', 'css', 'vbs', 'tml', 'htm');
2513
2514 if (empty($package_cache))
2515 return;
2516
2517 // First, let's check permissions!
2518 foreach ($package_cache as $filename => $data)
2519 {
2520 if (isset($package_ftp))
2521 $ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2522
2523 if (!file_exists($filename) && isset($package_ftp))
2524 $package_ftp->create_file($ftp_file);
2525 elseif (!file_exists($filename))
2526 @touch($filename);
2527
2528 package_chmod($filename);
2529
2530 $fp = fopen($filename, 'r+');
2531 if (!$fp && !$trash)
2532 {
2533 // We should have package_chmod()'d them before, no?!
2534 trigger_error('package_flush_cache(): some files are still not writable', E_USER_WARNING);
2535 return;
2536 }
2537 fclose($fp);
2538 }
2539
2540 if ($trash)
2541 {
2542 $package_cache = array();
2543 return;
2544 }
2545
2546 foreach ($package_cache as $filename => $data)
2547 {
2548 $fp = fopen($filename, in_array(substr($filename, -3), $text_filetypes) ? 'w' : 'wb');
2549 fwrite($fp, $data);
2550 fclose($fp);
2551 }
2552
2553 $package_cache = array();
2554 }
2555
2556 // Try to make a file writable. Return true if it worked, false if it didn't.
2557 function package_chmod($filename, $perm_state = 'writable', $track_change = false)
2558 {
2559 global $package_ftp;
2560
2561 if (file_exists($filename) && is_writable($filename) && $perm_state == 'writable')
2562 return true;
2563
2564 // Start off checking without FTP.
2565 if (!isset($package_ftp) || $package_ftp === false)
2566 {
2567 for ($i = 0; $i < 2; $i++)
2568 {
2569 $chmod_file = $filename;
2570
2571 // Start off with a less agressive test.
2572 if ($i == 0)
2573 {
2574 // If this file doesn't exist, then we actually want to look at whatever parent directory does.
2575 $subTraverseLimit = 2;
2576 while (!file_exists($chmod_file) && $subTraverseLimit)
2577 {
2578 $chmod_file = dirname($chmod_file);
2579 $subTraverseLimit--;
2580 }
2581
2582 // Keep track of the writable status here.
2583 $file_permissions = @fileperms($chmod_file);
2584 }
2585 else
2586 {
2587 // This looks odd, but it's an attempt to work around PHP suExec.
2588 if (!file_exists($chmod_file) && $perm_state == 'writable')
2589 {
2590 $file_permissions = @fileperms(dirname($chmod_file));
2591
2592 mktree(dirname($chmod_file), 0755);
2593 @touch($chmod_file);
2594 @chmod($chmod_file, 0755);
2595 }
2596 else
2597 $file_permissions = @fileperms($chmod_file);
2598 }
2599
2600 // This looks odd, but it's another attempt to work around PHP suExec.
2601 if ($perm_state != 'writable')
2602 @chmod($chmod_file, $perm_state == 'execute' ? 0755 : 0644);
2603 else
2604 {
2605 if (!@is_writable($chmod_file))
2606 @chmod($chmod_file, 0755);
2607 if (!@is_writable($chmod_file))
2608 @chmod($chmod_file, 0777);
2609 if (!@is_writable(dirname($chmod_file)))
2610 @chmod($chmod_file, 0755);
2611 if (!@is_writable(dirname($chmod_file)))
2612 @chmod($chmod_file, 0777);
2613 }
2614
2615 // The ultimate writable test.
2616 if ($perm_state == 'writable')
2617 {
2618 $fp = is_dir($chmod_file) ? @opendir($chmod_file) : @fopen($chmod_file, 'rb');
2619 if (@is_writable($chmod_file) && $fp)
2620 {
2621 if (!is_dir($chmod_file))
2622 fclose($fp);
2623 else
2624 closedir($fp);
2625
2626 // It worked!
2627 if ($track_change)
2628 $_SESSION['pack_ftp']['original_perms'][$chmod_file] = $file_permissions;
2629
2630 return true;
2631 }
2632 }
2633 elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$chmod_file]))
2634 unset($_SESSION['pack_ftp']['original_perms'][$chmod_file]);
2635 }
2636
2637 // If we're here we're a failure.
2638 return false;
2639 }
2640 // Otherwise we do have FTP?
2641 elseif ($package_ftp !== false && !empty($_SESSION['pack_ftp']))
2642 {
2643 $ftp_file = strtr($filename, array($_SESSION['pack_ftp']['root'] => ''));
2644
2645 // This looks odd, but it's an attempt to work around PHP suExec.
2646 if (!file_exists($filename) && $perm_state == 'writable')
2647 {
2648 $file_permissions = @fileperms(dirname($filename));
2649
2650 mktree(dirname($filename), 0755);
2651 $package_ftp->create_file($ftp_file);
2652 $package_ftp->chmod($ftp_file, 0755);
2653 }
2654 else
2655 $file_permissions = @fileperms($filename);
2656
2657 if ($perm_state != 'writable')
2658 {
2659 $package_ftp->chmod($ftp_file, $perm_state == 'execute' ? 0755 : 0644);
2660 }
2661 else
2662 {
2663 if (!@is_writable($filename))
2664 $package_ftp->chmod($ftp_file, 0777);
2665 if (!@is_writable(dirname($filename)))
2666 $package_ftp->chmod(dirname($ftp_file), 0777);
2667 }
2668
2669 if (@is_writable($filename))
2670 {
2671 if ($track_change)
2672 $_SESSION['pack_ftp']['original_perms'][$filename] = $file_permissions;
2673
2674 return true;
2675 }
2676 elseif ($perm_state != 'writable' && isset($_SESSION['pack_ftp']['original_perms'][$filename]))
2677 unset($_SESSION['pack_ftp']['original_perms'][$filename]);
2678 }
2679
2680 // Oh dear, we failed if we get here.
2681 return false;
2682 }
2683
2684 function package_crypt($pass)
2685 {
2686 $n = strlen($pass);
2687
2688 $salt = session_id();
2689 while (strlen($salt) < $n)
2690 $salt .= session_id();
2691
2692 for ($i = 0; $i < $n; $i++)
2693 $pass{$i} = chr(ord($pass{$i}) ^ (ord($salt{$i}) - 32));
2694
2695 return $pass;
2696 }
2697
2698 function package_create_backup($id = 'backup')
2699 {
2700 global $sourcedir, $boarddir, $smcFunc;
2701
2702 $files = array();
2703
2704 $base_files = array('index.php', 'SSI.php', 'agreement.txt', 'ssi_examples.php', 'ssi_examples.shtml');
2705 foreach ($base_files as $file)
2706 {
2707 if (file_exists($boarddir . '/' . $file))
2708 $files[realpath($boarddir . '/' . $file)] = array(
2709 empty($_REQUEST['use_full_paths']) ? $file : $boarddir . '/' . $file,
2710 stat($boarddir . '/' . $file)
2711 );
2712 }
2713
2714 $dirs = array(
2715 $sourcedir => empty($_REQUEST['use_full_paths']) ? 'Sources/' : strtr($sourcedir . '/', '\\', '/')
2716 );
2717
2718 $request = $smcFunc['db_query']('', '
2719 SELECT value
2720 FROM {db_prefix}themes
2721 WHERE id_member = {int:no_member}
2722 AND variable = {string:theme_dir}',
2723 array(
2724 'no_member' => 0,
2725 'theme_dir' => 'theme_dir',
2726 )
2727 );
2728 while ($row = $smcFunc['db_fetch_assoc']($request))
2729 $dirs[$row['value']] = empty($_REQUEST['use_full_paths']) ? 'Themes/' . basename($row['value']) . '/' : strtr($row['value'] . '/', '\\', '/');
2730 $smcFunc['db_free_result']($request);
2731
2732 while (!empty($dirs))
2733 {
2734 list ($dir, $dest) = each($dirs);
2735 unset($dirs[$dir]);
2736
2737 $listing = @dir($dir);
2738 if (!$listing)
2739 continue;
2740 while ($entry = $listing->read())
2741 {
2742 if (preg_match('~^(\.{1,2}|CVS|backup.*|help|images|.*\~)$~', $entry) != 0)
2743 continue;
2744
2745 $filepath = realpath($dir . '/' . $entry);
2746 if (isset($files[$filepath]))
2747 continue;
2748
2749 $stat = stat($dir . '/' . $entry);
2750 if ($stat['mode'] & 040000)
2751 {
2752 $files[$filepath] = array($dest . $entry . '/', $stat);
2753 $dirs[$dir . '/' . $entry] = $dest . $entry . '/';
2754 }
2755 else
2756 $files[$filepath] = array($dest . $entry, $stat);
2757 }
2758 $listing->close();
2759 }
2760
2761 if (!file_exists($boarddir . '/Packages/backups'))
2762 mktree($boarddir . '/Packages/backups', 0777);
2763 if (!is_writable($boarddir . '/Packages/backups'))
2764 package_chmod($boarddir . '/Packages/backups');
2765 $output_file = $boarddir . '/Packages/backups/' . strftime('%Y-%m-%d_') . preg_replace('~[$\\\\/:<>|?*"\']~', '', $id);
2766 $output_ext = '.tar' . (function_exists('gzopen') ? '.gz' : '');
2767
2768 if (file_exists($output_file . $output_ext))
2769 {
2770 $i = 2;
2771 while (file_exists($output_file . '_' . $i . $output_ext))
2772 $i++;
2773 $output_file = $output_file . '_' . $i . $output_ext;
2774 }
2775 else
2776 $output_file .= $output_ext;
2777
2778 @set_time_limit(300);
2779 if (function_exists('apache_reset_timeout'))
2780 @apache_reset_timeout();
2781
2782 if (function_exists('gzopen'))
2783 {
2784 $fwrite = 'gzwrite';
2785 $fclose = 'gzclose';
2786 $output = gzopen($output_file, 'wb');
2787 }
2788 else
2789 {
2790 $fwrite = 'fwrite';
2791 $fclose = 'fclose';
2792 $output = fopen($output_file, 'wb');
2793 }
2794
2795 foreach ($files as $real_file => $file)
2796 {
2797 if (!file_exists($real_file))
2798 continue;
2799
2800 $stat = $file[1];
2801 if (substr($file[0], -1) == '/')
2802 $stat['size'] = 0;
2803
2804 $current = pack('a100a8a8a8a12a12a8a1a100a6a2a32a32a8a8a155a12', $file[0], decoct($stat['mode']), sprintf('%06d', decoct($stat['uid'])), sprintf('%06d', decoct($stat['gid'])), decoct($stat['size']), decoct($stat['mtime']), '', 0, '', '', '', '', '', '', '', '', '');
2805
2806 $checksum = 256;
2807 for ($i = 0; $i < 512; $i++)
2808 $checksum += ord($current{$i});
2809
2810 $fwrite($output, substr($current, 0, 148) . pack('a8', decoct($checksum)) . substr($current, 156, 511));
2811
2812 if ($stat['size'] == 0)
2813 continue;
2814
2815 $fp = fopen($real_file, 'rb');
2816 while (!feof($fp))
2817 $fwrite($output, fread($fp, 16384));
2818 fclose($fp);
2819
2820 $fwrite($output, pack('a' . (512 - $stat['size'] % 512), ''));
2821 }
2822
2823 $fwrite($output, pack('a1024', ''));
2824 $fclose($output);
2825 }
2826
2827 // Get the contents of a URL, irrespective of allow_url_fopen.
2828 function fetch_web_data($url, $post_data = '', $keep_alive = false, $redirection_level = 0)
2829 {
2830 global $webmaster_email;
2831 static $keep_alive_dom = null, $keep_alive_fp = null;
2832
2833 preg_match('~^(http|ftp)(s)?://([^/:]+)(:(\d+))?(.+)$~', $url, $match);
2834
2835 // An FTP url. We should try connecting and RETRieving it...
2836 if (empty($match[1]))
2837 return false;
2838 elseif ($match[1] == 'ftp')
2839 {
2840 // Include the file containing the ftp_connection class.
2841 loadClassFile('Class-Package.php');
2842
2843 // Establish a connection and attempt to enable passive mode.
2844 $ftp = new ftp_connection(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? 21 : $match[5], 'anonymous', $webmaster_email);
2845 if ($ftp->error !== false || !$ftp->passive())
2846 return false;
2847
2848 // I want that one *points*!
2849 fwrite($ftp->connection, 'RETR ' . $match[6] . "\r\n");
2850
2851 // Since passive mode worked (or we would have returned already!) open the connection.
2852 $fp = @fsockopen($ftp->pasv['ip'], $ftp->pasv['port'], $err, $err, 5);
2853 if (!$fp)
2854 return false;
2855
2856 // The server should now say something in acknowledgement.
2857 $ftp->check_response(150);
2858
2859 $data = '';
2860 while (!feof($fp))
2861 $data .= fread($fp, 4096);
2862 fclose($fp);
2863
2864 // All done, right? Good.
2865 $ftp->check_response(226);
2866 $ftp->close();
2867 }
2868 // This is more likely; a standard HTTP URL.
2869 elseif (isset($match[1]) && $match[1] == 'http')
2870 {
2871 if ($keep_alive && $match[3] == $keep_alive_dom)
2872 $fp = $keep_alive_fp;
2873 if (empty($fp))
2874 {
2875 // Open the socket on the port we want...
2876 $fp = @fsockopen(($match[2] ? 'ssl://' : '') . $match[3], empty($match[5]) ? ($match[2] ? 443 : 80) : $match[5], $err, $err, 5);
2877 if (!$fp)
2878 return false;
2879 }
2880
2881 if ($keep_alive)
2882 {
2883 $keep_alive_dom = $match[3];
2884 $keep_alive_fp = $fp;
2885 }
2886
2887 // I want this, from there, and I'm not going to be bothering you for more (probably.)
2888 if (empty($post_data))
2889 {
2890 fwrite($fp, 'GET ' . $match[6] . ' HTTP/1.0' . "\r\n");
2891 fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? ($match[2] ? ':443' : '') : ':' . $match[5]) . "\r\n");
2892 fwrite($fp, 'User-Agent: PHP/SMF' . "\r\n");
2893 if ($keep_alive)
2894 fwrite($fp, 'Connection: Keep-Alive' . "\r\n\r\n");
2895 else
2896 fwrite($fp, 'Connection: close' . "\r\n\r\n");
2897 }
2898 else
2899 {
2900 fwrite($fp, 'POST ' . $match[6] . ' HTTP/1.0' . "\r\n");
2901 fwrite($fp, 'Host: ' . $match[3] . (empty($match[5]) ? ($match[2] ? ':443' : '') : ':' . $match[5]) . "\r\n");
2902 fwrite($fp, 'User-Agent: PHP/SMF' . "\r\n");
2903 if ($keep_alive)
2904 fwrite($fp, 'Connection: Keep-Alive' . "\r\n");
2905 else
2906 fwrite($fp, 'Connection: close' . "\r\n");
2907 fwrite($fp, 'Content-Type: application/x-www-form-urlencoded' . "\r\n");
2908 fwrite($fp, 'Content-Length: ' . strlen($post_data) . "\r\n\r\n");
2909 fwrite($fp, $post_data);
2910 }
2911
2912 $response = fgets($fp, 768);
2913
2914 // Redirect in case this location is permanently or temporarily moved.
2915 if ($redirection_level < 3 && preg_match('~^HTTP/\S+\s+30[127]~i', $response) === 1)
2916 {
2917 $header = '';
2918 $location = '';
2919 while (!feof($fp) && trim($header = fgets($fp, 4096)) != '')
2920 if (strpos($header, 'Location:') !== false)
2921 $location = trim(substr($header, strpos($header, ':') + 1));
2922
2923 if (empty($location))
2924 return false;
2925 else
2926 {
2927 if (!$keep_alive)
2928 fclose($fp);
2929 return fetch_web_data($location, $post_data, $keep_alive, $redirection_level + 1);
2930 }
2931 }
2932
2933 // Make sure we get a 200 OK.
2934 elseif (preg_match('~^HTTP/\S+\s+20[01]~i', $response) === 0)
2935 return false;
2936
2937 // Skip the headers...
2938 while (!feof($fp) && trim($header = fgets($fp, 4096)) != '')
2939 {
2940 if (preg_match('~content-length:\s*(\d+)~i', $header, $match) != 0)
2941 $content_length = $match[1];
2942 elseif (preg_match('~connection:\s*close~i', $header) != 0)
2943 {
2944 $keep_alive_dom = null;
2945 $keep_alive = false;
2946 }
2947
2948 continue;
2949 }
2950
2951 $data = '';
2952 if (isset($content_length))
2953 {
2954 while (!feof($fp) && strlen($data) < $content_length)
2955 $data .= fread($fp, $content_length - strlen($data));
2956 }
2957 else
2958 {
2959 while (!feof($fp))
2960 $data .= fread($fp, 4096);
2961 }
2962
2963 if (!$keep_alive)
2964 fclose($fp);
2965 }
2966 else
2967 {
2968 // Umm, this shouldn't happen?
2969 trigger_error('fetch_web_data(): Bad URL', E_USER_NOTICE);
2970 $data = false;
2971 }
2972
2973 return $data;
2974 }
2975
2976 // crc32 doesn't work as expected on 64-bit functions - make our own.
2977 // http://www.php.net/crc32#79567
2978 if (!function_exists('smf_crc32'))
2979 {
2980 function smf_crc32($number)
2981 {
2982 $crc = crc32($number);
2983
2984 if ($crc & 0x80000000)
2985 {
2986 $crc ^= 0xffffffff;
2987 $crc += 1;
2988 $crc = -$crc;
2989 }
2990
2991 return $crc;
2992 }
2993 }
2994
2995 ?>