Packages.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551
  1. <?php
  2. /**
  3. * This file is the main Package Manager.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * This is the notoriously defunct package manager..... :/.
  18. */
  19. function Packages()
  20. {
  21. global $txt, $scripturl, $sourcedir, $context;
  22. // @todo Remove this!
  23. if (isset($_GET['get']) || isset($_GET['pgdownload']))
  24. {
  25. require_once($sourcedir . '/PackageGet.php');
  26. return PackageGet();
  27. }
  28. isAllowedTo('admin_forum');
  29. // Load all the basic stuff.
  30. require_once($sourcedir . '/Subs-Package.php');
  31. loadLanguage('Packages');
  32. loadTemplate('Packages', 'admin');
  33. $context['page_title'] = $txt['package'];
  34. // Delegation makes the world... that is, the package manager go 'round.
  35. $subActions = array(
  36. 'browse' => 'PackageBrowse',
  37. 'remove' => 'PackageRemove',
  38. 'list' => 'PackageList',
  39. 'ftptest' => 'PackageFTPTest',
  40. 'install' => 'PackageInstallTest',
  41. 'install2' => 'PackageInstall',
  42. 'uninstall' => 'PackageInstallTest',
  43. 'uninstall2' => 'PackageInstall',
  44. 'installed' => 'PackageBrowse',
  45. 'options' => 'PackageOptions',
  46. 'perms' => 'PackagePermissions',
  47. 'flush' => 'FlushInstall',
  48. 'examine' => 'ExamineFile',
  49. 'showoperations' => 'ViewOperations',
  50. );
  51. // Work out exactly who it is we are calling.
  52. if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
  53. $context['sub_action'] = $_REQUEST['sa'];
  54. else
  55. $context['sub_action'] = 'browse';
  56. // Set up some tabs...
  57. $context[$context['admin_menu_name']]['tab_data'] = array(
  58. 'title' => $txt['package_manager'],
  59. // @todo 'help' => 'registrations',
  60. 'description' => $txt['package_manager_desc'],
  61. 'tabs' => array(
  62. 'browse' => array(
  63. ),
  64. 'packageget' => array(
  65. 'description' => $txt['download_packages_desc'],
  66. ),
  67. 'installed' => array(
  68. 'description' => $txt['installed_packages_desc'],
  69. ),
  70. 'perms' => array(
  71. 'description' => $txt['package_file_perms_desc'],
  72. ),
  73. 'options' => array(
  74. 'description' => $txt['package_install_options_desc'],
  75. ),
  76. ),
  77. );
  78. // Call the function we're handing control to.
  79. $subActions[$context['sub_action']]();
  80. }
  81. /**
  82. * Test install a package.
  83. */
  84. function PackageInstallTest()
  85. {
  86. global $boarddir, $txt, $context, $scripturl, $sourcedir, $modSettings, $smcFunc, $settings;
  87. // You have to specify a file!!
  88. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  89. redirectexit('action=admin;area=packages');
  90. $context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);
  91. // Do we have an existing id, for uninstalls and the like.
  92. $context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;
  93. require_once($sourcedir . '/Subs-Package.php');
  94. // Load up the package FTP information?
  95. create_chmod_control();
  96. // Make sure temp directory exists and is empty.
  97. if (file_exists($boarddir . '/Packages/temp'))
  98. deltree($boarddir . '/Packages/temp', false);
  99. if (!mktree($boarddir . '/Packages/temp', 0755))
  100. {
  101. deltree($boarddir . '/Packages/temp', false);
  102. if (!mktree($boarddir . '/Packages/temp', 0777))
  103. {
  104. deltree($boarddir . '/Packages/temp', false);
  105. create_chmod_control(array($boarddir . '/Packages/temp/delme.tmp'), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package'], 'crash_on_error' => true));
  106. deltree($boarddir . '/Packages/temp', false);
  107. if (!mktree($boarddir . '/Packages/temp', 0777))
  108. fatal_lang_error('package_cant_download', false);
  109. }
  110. }
  111. $context['uninstalling'] = $_REQUEST['sa'] == 'uninstall';
  112. // Change our last link tree item for more information on this Packages area.
  113. $context['linktree'][count($context['linktree']) - 1] = array(
  114. 'url' => $scripturl . '?action=admin;area=packages;sa=browse',
  115. 'name' => $context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']
  116. );
  117. $context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['package_uninstall_actions'] : $txt['install_actions']);
  118. $context['sub_template'] = 'view_package';
  119. if (!file_exists($boarddir . '/Packages/' . $context['filename']))
  120. {
  121. deltree($boarddir . '/Packages/temp');
  122. fatal_lang_error('package_no_file', false);
  123. }
  124. // Extract the files so we can get things like the readme, etc.
  125. if (is_file($boarddir . '/Packages/' . $context['filename']))
  126. {
  127. $context['extracted_files'] = read_tgz_file($boarddir . '/Packages/' . $context['filename'], $boarddir . '/Packages/temp');
  128. if ($context['extracted_files'] && !file_exists($boarddir . '/Packages/temp/package-info.xml'))
  129. foreach ($context['extracted_files'] as $file)
  130. if (basename($file['filename']) == 'package-info.xml')
  131. {
  132. $context['base_path'] = dirname($file['filename']) . '/';
  133. break;
  134. }
  135. if (!isset($context['base_path']))
  136. $context['base_path'] = '';
  137. }
  138. elseif (is_dir($boarddir . '/Packages/' . $context['filename']))
  139. {
  140. copytree($boarddir . '/Packages/' . $context['filename'], $boarddir . '/Packages/temp');
  141. $context['extracted_files'] = listtree($boarddir . '/Packages/temp');
  142. $context['base_path'] = '';
  143. }
  144. else
  145. fatal_lang_error('no_access', false);
  146. // Load up any custom themes we may want to install into...
  147. $request = $smcFunc['db_query']('', '
  148. SELECT id_theme, variable, value
  149. FROM {db_prefix}themes
  150. WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
  151. AND variable IN ({string:name}, {string:theme_dir})',
  152. array(
  153. 'known_theme_list' => explode(',', $modSettings['knownThemes']),
  154. 'default_theme' => 1,
  155. 'name' => 'name',
  156. 'theme_dir' => 'theme_dir',
  157. )
  158. );
  159. $theme_paths = array();
  160. while ($row = $smcFunc['db_fetch_assoc']($request))
  161. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  162. $smcFunc['db_free_result']($request);
  163. // Get the package info...
  164. $packageInfo = getPackageInfo($context['filename']);
  165. if (!is_array($packageInfo))
  166. fatal_lang_error($packageInfo);
  167. $packageInfo['filename'] = $context['filename'];
  168. $context['package_name'] = isset($packageInfo['name']) ? $packageInfo['name'] : $context['filename'];
  169. // Set the type of extraction...
  170. $context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';
  171. // The mod isn't installed.... unless proven otherwise.
  172. $context['is_installed'] = false;
  173. // See if it is installed?
  174. $request = $smcFunc['db_query']('', '
  175. SELECT version, themes_installed, db_changes
  176. FROM {db_prefix}log_packages
  177. WHERE package_id = {string:current_package}
  178. AND install_state != {int:not_installed}
  179. ORDER BY time_installed DESC
  180. LIMIT 1',
  181. array(
  182. 'not_installed' => 0,
  183. 'current_package' => $packageInfo['id'],
  184. )
  185. );
  186. while ($row = $smcFunc['db_fetch_assoc']($request))
  187. {
  188. $old_themes = explode(',', $row['themes_installed']);
  189. $old_version = $row['version'];
  190. $db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
  191. }
  192. $smcFunc['db_free_result']($request);
  193. $context['database_changes'] = array();
  194. if (!empty($db_changes))
  195. {
  196. foreach ($db_changes as $change)
  197. {
  198. if (isset($change[2]) && isset($txt['package_db_' . $change[0]]))
  199. $context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1], $change[2]);
  200. elseif (isset($txt['package_db_' . $change[0]]))
  201. $context['database_changes'][] = sprintf($txt['package_db_' . $change[0]], $change[1]);
  202. else
  203. $context['database_changes'][] = $change[0] . '-' . $change[1] . (isset($change[2]) ? '-' . $change[2] : '');
  204. }
  205. }
  206. // Uninstalling?
  207. if ($context['uninstalling'])
  208. {
  209. // Wait, it's not installed yet!
  210. if (!isset($old_version) && $context['uninstalling'])
  211. {
  212. deltree($boarddir . '/Packages/temp');
  213. fatal_lang_error('package_cant_uninstall', false);
  214. }
  215. $actions = parsePackageInfo($packageInfo['xml'], true, 'uninstall');
  216. // Gadzooks! There's no uninstaller at all!?
  217. if (empty($actions))
  218. {
  219. deltree($boarddir . '/Packages/temp');
  220. fatal_lang_error('package_uninstall_cannot', false);
  221. }
  222. // Can't edit the custom themes it's edited if you're unisntalling, they must be removed.
  223. $context['themes_locked'] = true;
  224. // Only let them uninstall themes it was installed into.
  225. foreach ($theme_paths as $id => $data)
  226. if ($id != 1 && !in_array($id, $old_themes))
  227. unset($theme_paths[$id]);
  228. }
  229. elseif (isset($old_version) && $old_version != $packageInfo['version'])
  230. {
  231. // Look for an upgrade...
  232. $actions = parsePackageInfo($packageInfo['xml'], true, 'upgrade', $old_version);
  233. // There was no upgrade....
  234. if (empty($actions))
  235. $context['is_installed'] = true;
  236. else
  237. {
  238. // Otherwise they can only upgrade themes from the first time around.
  239. foreach ($theme_paths as $id => $data)
  240. if ($id != 1 && !in_array($id, $old_themes))
  241. unset($theme_paths[$id]);
  242. }
  243. }
  244. elseif (isset($old_version) && $old_version == $packageInfo['version'])
  245. $context['is_installed'] = true;
  246. if (!isset($old_version) || $context['is_installed'])
  247. $actions = parsePackageInfo($packageInfo['xml'], true, 'install');
  248. $context['actions'] = array();
  249. $context['ftp_needed'] = false;
  250. $context['has_failure'] = false;
  251. $chmod_files = array();
  252. // no actions found, return so we can display an error
  253. if (empty($actions))
  254. return;
  255. // This will hold data about anything that can be installed in other themes.
  256. $themeFinds = array(
  257. 'candidates' => array(),
  258. 'other_themes' => array(),
  259. );
  260. // Now prepare things for the template.
  261. foreach ($actions as $action)
  262. {
  263. // Not failed until proven otherwise.
  264. $failed = false;
  265. if ($action['type'] == 'chmod')
  266. {
  267. $chmod_files[] = $action['filename'];
  268. continue;
  269. }
  270. elseif ($action['type'] == 'readme' || $action['type'] == 'license')
  271. {
  272. $type = 'package_' . $action['type'];
  273. if (file_exists($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']))
  274. $context[$type] = htmlspecialchars(trim(file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']), "\n\r"));
  275. elseif (file_exists($action['filename']))
  276. $context[$type] = htmlspecialchars(trim(file_get_contents($action['filename']), "\n\r"));
  277. if (!empty($action['parse_bbc']))
  278. {
  279. require_once($sourcedir . '/Subs-Post.php');
  280. preparsecode($context[$type]);
  281. $context[$type] = parse_bbc($context[$type]);
  282. }
  283. else
  284. $context[$type] = nl2br($context[$type]);
  285. continue;
  286. }
  287. // Don't show redirects.
  288. elseif ($action['type'] == 'redirect')
  289. continue;
  290. elseif ($action['type'] == 'error')
  291. $context['has_failure'] = true;
  292. elseif ($action['type'] == 'modification')
  293. {
  294. if (!file_exists($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']))
  295. {
  296. $context['has_failure'] = true;
  297. $context['actions'][] = array(
  298. 'type' => $txt['execute_modification'],
  299. 'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.'))),
  300. 'description' => $txt['package_action_error'],
  301. 'failed' => true,
  302. );
  303. }
  304. if ($action['boardmod'])
  305. $mod_actions = parseBoardMod(@file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
  306. else
  307. $mod_actions = parseModification(@file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']), true, $action['reverse'], $theme_paths);
  308. if (count($mod_actions) == 1 && isset($mod_actions[0]) && $mod_actions[0]['type'] == 'error' && $mod_actions[0]['filename'] == '-')
  309. $mod_actions[0]['filename'] = $action['filename'];
  310. foreach ($mod_actions as $key => $mod_action)
  311. {
  312. // Lets get the last section of the file name.
  313. if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
  314. $actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
  315. elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
  316. $actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
  317. else
  318. $actual_filename = $key;
  319. if ($mod_action['type'] == 'opened')
  320. $failed = false;
  321. elseif ($mod_action['type'] == 'failure')
  322. {
  323. if (empty($mod_action['is_custom']))
  324. $context['has_failure'] = true;
  325. $failed = true;
  326. }
  327. elseif ($mod_action['type'] == 'chmod')
  328. {
  329. $chmod_files[] = $mod_action['filename'];
  330. }
  331. elseif ($mod_action['type'] == 'saved')
  332. {
  333. if (!empty($mod_action['is_custom']))
  334. {
  335. if (!isset($context['theme_actions'][$mod_action['is_custom']]))
  336. $context['theme_actions'][$mod_action['is_custom']] = array(
  337. 'name' => $theme_paths[$mod_action['is_custom']]['name'],
  338. 'actions' => array(),
  339. 'has_failure' => $failed,
  340. );
  341. else
  342. $context['theme_actions'][$mod_action['is_custom']]['has_failure'] |= $failed;
  343. $context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename] = array(
  344. 'type' => $txt['execute_modification'],
  345. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  346. 'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
  347. 'failed' => $failed,
  348. );
  349. }
  350. elseif (!isset($context['actions'][$actual_filename]))
  351. {
  352. $context['actions'][$actual_filename] = array(
  353. 'type' => $txt['execute_modification'],
  354. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  355. 'description' => $failed ? $txt['package_action_failure'] : $txt['package_action_success'],
  356. 'failed' => $failed,
  357. );
  358. }
  359. else
  360. {
  361. $context['actions'][$actual_filename]['failed'] |= $failed;
  362. $context['actions'][$actual_filename]['description'] = $context['actions'][$actual_filename]['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'];
  363. }
  364. }
  365. elseif ($mod_action['type'] == 'skipping')
  366. {
  367. $context['actions'][$actual_filename] = array(
  368. 'type' => $txt['execute_modification'],
  369. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  370. 'description' => $txt['package_action_skipping']
  371. );
  372. }
  373. elseif ($mod_action['type'] == 'missing' && empty($mod_action['is_custom']))
  374. {
  375. $context['has_failure'] = true;
  376. $context['actions'][$actual_filename] = array(
  377. 'type' => $txt['execute_modification'],
  378. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  379. 'description' => $txt['package_action_missing'],
  380. 'failed' => true,
  381. );
  382. }
  383. elseif ($mod_action['type'] == 'error')
  384. $context['actions'][$actual_filename] = array(
  385. 'type' => $txt['execute_modification'],
  386. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  387. 'description' => $txt['package_action_error'],
  388. 'failed' => true,
  389. );
  390. }
  391. // We need to loop again just to get the operations down correctly.
  392. foreach ($mod_actions as $operation_key => $mod_action)
  393. {
  394. // Lets get the last section of the file name.
  395. if (isset($mod_action['filename']) && substr($mod_action['filename'], -13) != '.template.php')
  396. $actual_filename = strtolower(substr(strrchr($mod_action['filename'], '/'), 1) . '||' . $action['filename']);
  397. elseif (isset($mod_action['filename']) && preg_match('~([\w]*)/([\w]*)\.template\.php$~', $mod_action['filename'], $matches))
  398. $actual_filename = strtolower($matches[1] . '/' . $matches[2] . '.template.php' . '||' . $action['filename']);
  399. else
  400. $actual_filename = $key;
  401. // We just need it for actual parse changes.
  402. if (!in_array($mod_action['type'], array('error', 'result', 'opened', 'saved', 'end', 'missing', 'skipping', 'chmod')))
  403. {
  404. if (empty($mod_action['is_custom']))
  405. $context['actions'][$actual_filename]['operations'][] = array(
  406. 'type' => $txt['execute_modification'],
  407. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  408. 'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
  409. 'position' => $mod_action['position'],
  410. 'operation_key' => $operation_key,
  411. 'filename' => $action['filename'],
  412. 'is_boardmod' => $action['boardmod'],
  413. 'failed' => $mod_action['failed'],
  414. 'ignore_failure' => !empty($mod_action['ignore_failure']),
  415. );
  416. // Themes are under the saved type.
  417. if (isset($mod_action['is_custom']) && isset($context['theme_actions'][$mod_action['is_custom']]))
  418. $context['theme_actions'][$mod_action['is_custom']]['actions'][$actual_filename]['operations'][] = array(
  419. 'type' => $txt['execute_modification'],
  420. 'action' => $smcFunc['htmlspecialchars'](strtr($mod_action['filename'], array($boarddir => '.'))),
  421. 'description' => $mod_action['failed'] ? $txt['package_action_failure'] : $txt['package_action_success'],
  422. 'position' => $mod_action['position'],
  423. 'operation_key' => $operation_key,
  424. 'filename' => $action['filename'],
  425. 'is_boardmod' => $action['boardmod'],
  426. 'failed' => $mod_action['failed'],
  427. 'ignore_failure' => !empty($mod_action['ignore_failure']),
  428. );
  429. }
  430. }
  431. // Don't add anything else.
  432. $thisAction = array();
  433. }
  434. elseif ($action['type'] == 'code')
  435. {
  436. $thisAction = array(
  437. 'type' => $txt['execute_code'],
  438. 'action' => $smcFunc['htmlspecialchars']($action['filename']),
  439. );
  440. }
  441. elseif ($action['type'] == 'database')
  442. {
  443. $thisAction = array(
  444. 'type' => $txt['execute_database_changes'],
  445. 'action' => $smcFunc['htmlspecialchars']($action['filename']),
  446. );
  447. }
  448. elseif (in_array($action['type'], array('create-dir', 'create-file')))
  449. {
  450. $thisAction = array(
  451. 'type' => $txt['package_create'] . ' ' . ($action['type'] == 'create-dir' ? $txt['package_tree'] : $txt['package_file']),
  452. 'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
  453. );
  454. }
  455. elseif ($action['type'] == 'hook')
  456. {
  457. $action['description'] = !isset($action['hook'], $action['function']) ? $txt['package_action_failure'] : $txt['package_action_success'];
  458. if (!isset($action['hook'], $action['function']))
  459. $context['has_failure'] = true;
  460. $thisAction = array(
  461. 'type' => $action['reverse'] ? $txt['execute_hook_remove'] : $txt['execute_hook_add'],
  462. 'action' => sprintf($txt['execute_hook_action'], $smcFunc['htmlspecialchars']($action['hook'])),
  463. );
  464. }
  465. elseif ($action['type'] == 'credits')
  466. {
  467. $thisAction = array(
  468. 'type' => $txt['execute_credits_add'],
  469. 'action' => sprintf($txt['execute_credits_action'], $smcFunc['htmlspecialchars']($action['title'])),
  470. );
  471. }
  472. elseif ($action['type'] == 'requires')
  473. {
  474. $installed = false;
  475. $version = true;
  476. // package missing required values?
  477. if (!isset($action['id']))
  478. $context['has_failure'] = true;
  479. else
  480. {
  481. // See if this dependancy is installed
  482. $request = $smcFunc['db_query']('', '
  483. SELECT version
  484. FROM {db_prefix}log_packages
  485. WHERE package_id = {string:current_package}
  486. AND install_state != {int:not_installed}
  487. ORDER BY time_installed DESC
  488. LIMIT 1',
  489. array(
  490. 'not_installed' => 0,
  491. 'current_package' => $action['id'],
  492. )
  493. );
  494. $installed = ($smcFunc['db_num_rows']($request) !== 0);
  495. if ($installed)
  496. list($version) = $smcFunc['db_fetch_row']($request);
  497. $smcFunc['db_free_result']($request);
  498. // do a version level check (if requested) in the most basic way
  499. $version = (isset($action['version']) ? $version == $action['version'] : true);
  500. }
  501. // Set success or failure information
  502. $action['description'] = ($installed && $version) ? $txt['package_action_success'] : $txt['package_action_failure'];
  503. $context['has_failure'] = !($installed && $version);
  504. $thisAction = array(
  505. 'type' => $txt['package_requires'],
  506. 'action' => $txt['package_check_for'] . ' ' . $action['id'] . (isset($action['version']) ? (' / ' . ($version ? $action['version'] : '<span class="error">' . $action['version'] . '</span>')) : ''),
  507. );
  508. }
  509. elseif (in_array($action['type'], array('require-dir', 'require-file')))
  510. {
  511. // Do this one...
  512. $thisAction = array(
  513. 'type' => $txt['package_extract'] . ' ' . ($action['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
  514. 'action' => $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
  515. );
  516. // Could this be theme related?
  517. if (!empty($action['unparsed_destination']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_destination'], $matches))
  518. {
  519. // Is the action already stated?
  520. $theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
  521. // If it's not auto do we think we have something we can act upon?
  522. if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
  523. $theme_action = '';
  524. // ... or if it's auto do we even want to do anything?
  525. elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
  526. $theme_action = '';
  527. // So, we still want to do something?
  528. if ($theme_action != '')
  529. $themeFinds['candidates'][] = $action;
  530. // Otherwise is this is going into another theme record it.
  531. elseif ($matches[1] == 'themes_dir')
  532. $themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_destination']), array('\\' => '/')) . '/' . basename($action['filename']));
  533. }
  534. }
  535. elseif (in_array($action['type'], array('move-dir', 'move-file')))
  536. $thisAction = array(
  537. 'type' => $txt['package_move'] . ' ' . ($action['type'] == 'move-dir' ? $txt['package_tree'] : $txt['package_file']),
  538. 'action' => $smcFunc['htmlspecialchars'](strtr($action['source'], array($boarddir => '.'))) . ' => ' . $smcFunc['htmlspecialchars'](strtr($action['destination'], array($boarddir => '.')))
  539. );
  540. elseif (in_array($action['type'], array('remove-dir', 'remove-file')))
  541. {
  542. $thisAction = array(
  543. 'type' => $txt['package_delete'] . ' ' . ($action['type'] == 'remove-dir' ? $txt['package_tree'] : $txt['package_file']),
  544. 'action' => $smcFunc['htmlspecialchars'](strtr($action['filename'], array($boarddir => '.')))
  545. );
  546. // Could this be theme related?
  547. if (!empty($action['unparsed_filename']) && preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir|themes_dir)~i', $action['unparsed_filename'], $matches))
  548. {
  549. // Is the action already stated?
  550. $theme_action = !empty($action['theme_action']) && in_array($action['theme_action'], array('no', 'yes', 'auto')) ? $action['theme_action'] : 'auto';
  551. $action['unparsed_destination'] = $action['unparsed_filename'];
  552. // If it's not auto do we think we have something we can act upon?
  553. if ($theme_action != 'auto' && !in_array($matches[1], array('languagedir', 'languages_dir', 'imagesdir', 'themedir')))
  554. $theme_action = '';
  555. // ... or if it's auto do we even want to do anything?
  556. elseif ($theme_action == 'auto' && $matches[1] != 'imagesdir')
  557. $theme_action = '';
  558. // So, we still want to do something?
  559. if ($theme_action != '')
  560. $themeFinds['candidates'][] = $action;
  561. // Otherwise is this is going into another theme record it.
  562. elseif ($matches[1] == 'themes_dir')
  563. $themeFinds['other_themes'][] = strtolower(strtr(parse_path($action['unparsed_filename']), array('\\' => '/')) . '/' . basename($action['filename']));
  564. }
  565. }
  566. if (empty($thisAction))
  567. continue;
  568. // @todo None given?
  569. $thisAction['description'] = isset($action['description']) ? $action['description'] : '';
  570. $context['actions'][] = $thisAction;
  571. }
  572. // Have we got some things which we might want to do "multi-theme"?
  573. if (!empty($themeFinds['candidates']))
  574. {
  575. foreach ($themeFinds['candidates'] as $action_data)
  576. {
  577. // Get the part of the file we'll be dealing with.
  578. preg_match('~^\$(languagedir|languages_dir|imagesdir|themedir)(\\|/)*(.+)*~i', $action_data['unparsed_destination'], $matches);
  579. if ($matches[1] == 'imagesdir')
  580. $path = '/' . basename($settings['default_images_url']);
  581. elseif ($matches[1] == 'languagedir' || $matches[1] == 'languages_dir')
  582. $path = '/languages';
  583. else
  584. $path = '';
  585. if (!empty($matches[3]))
  586. $path .= $matches[3];
  587. if (!$context['uninstalling'])
  588. $path .= '/' . basename($action_data['filename']);
  589. // Loop through each custom theme to note it's candidacy!
  590. foreach ($theme_paths as $id => $theme_data)
  591. {
  592. if (isset($theme_data['theme_dir']) && $id != 1)
  593. {
  594. $real_path = $theme_data['theme_dir'] . $path;
  595. // Confirm that we don't already have this dealt with by another entry.
  596. if (!in_array(strtolower(strtr($real_path, array('\\' => '/'))), $themeFinds['other_themes']))
  597. {
  598. // Check if we will need to chmod this.
  599. if (!mktree(dirname($real_path), false))
  600. {
  601. $temp = dirname($real_path);
  602. while (!file_exists($temp) && strlen($temp) > 1)
  603. $temp = dirname($temp);
  604. $chmod_files[] = $temp;
  605. }
  606. if ($action_data['type'] == 'require-dir' && !is_writable($real_path) && (file_exists($real_path) || !is_writable(dirname($real_path))))
  607. $chmod_files[] = $real_path;
  608. if (!isset($context['theme_actions'][$id]))
  609. $context['theme_actions'][$id] = array(
  610. 'name' => $theme_data['name'],
  611. 'actions' => array(),
  612. );
  613. if ($context['uninstalling'])
  614. $context['theme_actions'][$id]['actions'][] = array(
  615. 'type' => $txt['package_delete'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
  616. 'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
  617. 'description' => '',
  618. 'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['filename'], 'future' => $real_path, 'id' => $id))),
  619. 'not_mod' => true,
  620. );
  621. else
  622. $context['theme_actions'][$id]['actions'][] = array(
  623. 'type' => $txt['package_extract'] . ' ' . ($action_data['type'] == 'require-dir' ? $txt['package_tree'] : $txt['package_file']),
  624. 'action' => strtr($real_path, array('\\' => '/', $boarddir => '.')),
  625. 'description' => '',
  626. 'value' => base64_encode(serialize(array('type' => $action_data['type'], 'orig' => $action_data['destination'], 'future' => $real_path, 'id' => $id))),
  627. 'not_mod' => true,
  628. );
  629. }
  630. }
  631. }
  632. }
  633. }
  634. // Trash the cache... which will also check permissions for us!
  635. package_flush_cache(true);
  636. if (file_exists($boarddir . '/Packages/temp'))
  637. deltree($boarddir . '/Packages/temp');
  638. if (!empty($chmod_files))
  639. {
  640. $ftp_status = create_chmod_control($chmod_files);
  641. $context['ftp_needed'] = !empty($ftp_status['files']['notwritable']) && !empty($context['package_ftp']);
  642. }
  643. checkSubmitOnce('register');
  644. }
  645. /**
  646. * Apply another type of (avatar, language, etc.) package.
  647. */
  648. function PackageInstall()
  649. {
  650. global $boarddir, $txt, $context, $boardurl, $scripturl, $sourcedir, $modSettings;
  651. global $user_info, $smcFunc;
  652. // Make sure we don't install this mod twice.
  653. checkSubmitOnce('check');
  654. checkSession();
  655. // If there's no file, what are we installing?
  656. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  657. redirectexit('action=admin;area=packages');
  658. $context['filename'] = $_REQUEST['package'];
  659. // If this is an uninstall, we'll have an id.
  660. $context['install_id'] = isset($_REQUEST['pid']) ? (int) $_REQUEST['pid'] : 0;
  661. require_once($sourcedir . '/Subs-Package.php');
  662. // @todo Perhaps do it in steps, if necessary?
  663. $context['uninstalling'] = $_REQUEST['sa'] == 'uninstall2';
  664. // Set up the linktree for other.
  665. $context['linktree'][count($context['linktree']) - 1] = array(
  666. 'url' => $scripturl . '?action=admin;area=packages;sa=browse',
  667. 'name' => $context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']
  668. );
  669. $context['page_title'] .= ' - ' . ($context['uninstalling'] ? $txt['uninstall'] : $txt['extracting']);
  670. $context['sub_template'] = 'extract_package';
  671. if (!file_exists($boarddir . '/Packages/' . $context['filename']))
  672. fatal_lang_error('package_no_file', false);
  673. // Load up the package FTP information?
  674. create_chmod_control(array(), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=' . $_REQUEST['sa'] . ';package=' . $_REQUEST['package']));
  675. // Make sure temp directory exists and is empty!
  676. if (file_exists($boarddir . '/Packages/temp'))
  677. deltree($boarddir . '/Packages/temp', false);
  678. else
  679. mktree($boarddir . '/Packages/temp', 0777);
  680. // Let the unpacker do the work.
  681. if (is_file($boarddir . '/Packages/' . $context['filename']))
  682. {
  683. $context['extracted_files'] = read_tgz_file($boarddir . '/Packages/' . $context['filename'], $boarddir . '/Packages/temp');
  684. if (!file_exists($boarddir . '/Packages/temp/package-info.xml'))
  685. foreach ($context['extracted_files'] as $file)
  686. if (basename($file['filename']) == 'package-info.xml')
  687. {
  688. $context['base_path'] = dirname($file['filename']) . '/';
  689. break;
  690. }
  691. if (!isset($context['base_path']))
  692. $context['base_path'] = '';
  693. }
  694. elseif (is_dir($boarddir . '/Packages/' . $context['filename']))
  695. {
  696. copytree($boarddir . '/Packages/' . $context['filename'], $boarddir . '/Packages/temp');
  697. $context['extracted_files'] = listtree($boarddir . '/Packages/temp');
  698. $context['base_path'] = '';
  699. }
  700. else
  701. fatal_lang_error('no_access', false);
  702. // Are we installing this into any custom themes?
  703. $custom_themes = array(1);
  704. $known_themes = explode(',', $modSettings['knownThemes']);
  705. if (!empty($_POST['custom_theme']))
  706. {
  707. foreach ($_POST['custom_theme'] as $tid)
  708. if (in_array($tid, $known_themes))
  709. $custom_themes[] = (int) $tid;
  710. }
  711. // Now load up the paths of the themes that we need to know about.
  712. $request = $smcFunc['db_query']('', '
  713. SELECT id_theme, variable, value
  714. FROM {db_prefix}themes
  715. WHERE id_theme IN ({array_int:custom_themes})
  716. AND variable IN ({string:name}, {string:theme_dir})',
  717. array(
  718. 'custom_themes' => $custom_themes,
  719. 'name' => 'name',
  720. 'theme_dir' => 'theme_dir',
  721. )
  722. );
  723. $theme_paths = array();
  724. $themes_installed = array(1);
  725. while ($row = $smcFunc['db_fetch_assoc']($request))
  726. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  727. $smcFunc['db_free_result']($request);
  728. // Are there any theme copying that we want to take place?
  729. $context['theme_copies'] = array(
  730. 'require-file' => array(),
  731. 'require-dir' => array(),
  732. );
  733. if (!empty($_POST['theme_changes']))
  734. {
  735. foreach ($_POST['theme_changes'] as $change)
  736. {
  737. if (empty($change))
  738. continue;
  739. $theme_data = unserialize(base64_decode($change));
  740. if (empty($theme_data['type']))
  741. continue;
  742. $themes_installed[] = $theme_data['id'];
  743. $context['theme_copies'][$theme_data['type']][$theme_data['orig']][] = $theme_data['future'];
  744. }
  745. }
  746. // Get the package info...
  747. $packageInfo = getPackageInfo($context['filename']);
  748. if (!is_array($packageInfo))
  749. fatal_lang_error($packageInfo);
  750. $packageInfo['filename'] = $context['filename'];
  751. // Set the type of extraction...
  752. $context['extract_type'] = isset($packageInfo['type']) ? $packageInfo['type'] : 'modification';
  753. // Create a backup file to roll back to! (but if they do this more than once, don't run it a zillion times.)
  754. if (!empty($modSettings['package_make_full_backups']) && (!isset($_SESSION['last_backup_for']) || $_SESSION['last_backup_for'] != $context['filename'] . ($context['uninstalling'] ? '$$' : '$')))
  755. {
  756. $_SESSION['last_backup_for'] = $context['filename'] . ($context['uninstalling'] ? '$$' : '$');
  757. // @todo Internationalize this?
  758. package_create_backup(($context['uninstalling'] ? 'backup_' : 'before_') . strtok($context['filename'], '.'));
  759. }
  760. // The mod isn't installed.... unless proven otherwise.
  761. $context['is_installed'] = false;
  762. // Is it actually installed?
  763. $request = $smcFunc['db_query']('', '
  764. SELECT version, themes_installed, db_changes
  765. FROM {db_prefix}log_packages
  766. WHERE package_id = {string:current_package}
  767. AND install_state != {int:not_installed}
  768. ORDER BY time_installed DESC
  769. LIMIT 1',
  770. array(
  771. 'not_installed' => 0,
  772. 'current_package' => $packageInfo['id'],
  773. )
  774. );
  775. while ($row = $smcFunc['db_fetch_assoc']($request))
  776. {
  777. $old_themes = explode(',', $row['themes_installed']);
  778. $old_version = $row['version'];
  779. $db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
  780. }
  781. $smcFunc['db_free_result']($request);
  782. // Wait, it's not installed yet!
  783. // @todo Replace with a better error message!
  784. if (!isset($old_version) && $context['uninstalling'])
  785. {
  786. deltree($boarddir . '/Packages/temp');
  787. fatal_error('Hacker?', false);
  788. }
  789. // Uninstalling?
  790. elseif ($context['uninstalling'])
  791. {
  792. $install_log = parsePackageInfo($packageInfo['xml'], false, 'uninstall');
  793. // Gadzooks! There's no uninstaller at all!?
  794. if (empty($install_log))
  795. fatal_lang_error('package_uninstall_cannot', false);
  796. // They can only uninstall from what it was originally installed into.
  797. foreach ($theme_paths as $id => $data)
  798. if ($id != 1 && !in_array($id, $old_themes))
  799. unset($theme_paths[$id]);
  800. }
  801. elseif (isset($old_version) && $old_version != $packageInfo['version'])
  802. {
  803. // Look for an upgrade...
  804. $install_log = parsePackageInfo($packageInfo['xml'], false, 'upgrade', $old_version);
  805. // There was no upgrade....
  806. if (empty($install_log))
  807. $context['is_installed'] = true;
  808. else
  809. {
  810. // Upgrade previous themes only!
  811. foreach ($theme_paths as $id => $data)
  812. if ($id != 1 && !in_array($id, $old_themes))
  813. unset($theme_paths[$id]);
  814. }
  815. }
  816. elseif (isset($old_version) && $old_version == $packageInfo['version'])
  817. $context['is_installed'] = true;
  818. if (!isset($old_version) || $context['is_installed'])
  819. $install_log = parsePackageInfo($packageInfo['xml'], false, 'install');
  820. $context['install_finished'] = false;
  821. // @todo Make a log of any errors that occurred and output them?
  822. if (!empty($install_log))
  823. {
  824. $failed_steps = array();
  825. $failed_count = 0;
  826. foreach ($install_log as $action)
  827. {
  828. $failed_count++;
  829. if ($action['type'] == 'modification' && !empty($action['filename']))
  830. {
  831. if ($action['boardmod'])
  832. $mod_actions = parseBoardMod(file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
  833. else
  834. $mod_actions = parseModification(file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']), false, $action['reverse'], $theme_paths);
  835. // Any errors worth noting?
  836. foreach ($mod_actions as $key => $action)
  837. {
  838. if ($action['type'] == 'failure')
  839. $failed_steps[] = array(
  840. 'file' => $action['filename'],
  841. 'large_step' => $failed_count,
  842. 'sub_step' => $key,
  843. 'theme' => 1,
  844. );
  845. // Gather the themes we installed into.
  846. if (!empty($action['is_custom']))
  847. $themes_installed[] = $action['is_custom'];
  848. }
  849. }
  850. elseif ($action['type'] == 'code' && !empty($action['filename']))
  851. {
  852. // This is just here as reference for what is available.
  853. global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $forum_version, $smcFunc;
  854. // Now include the file and be done with it ;).
  855. require($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']);
  856. }
  857. elseif ($action['type'] == 'credits')
  858. {
  859. // Time to build the billboard
  860. $credits_tag = array(
  861. 'url' => $action['url'],
  862. 'license' => $action['license'],
  863. 'copyright' => $action['copyright'],
  864. 'title' => $action['title'],
  865. );
  866. }
  867. elseif ($action['type'] == 'hook' && isset($action['hook'], $action['function']))
  868. {
  869. if ($action['reverse'])
  870. remove_integration_function($action['hook'], $action['function']);
  871. else
  872. add_integration_function($action['hook'], $action['function']);
  873. }
  874. // Only do the database changes on uninstall if requested.
  875. elseif ($action['type'] == 'database' && !empty($action['filename']) && (!$context['uninstalling'] || !empty($_POST['do_db_changes'])))
  876. {
  877. // These can also be there for database changes.
  878. global $txt, $boarddir, $sourcedir, $modSettings, $context, $settings, $forum_version, $smcFunc;
  879. global $db_package_log;
  880. // We'll likely want the package specific database functionality!
  881. db_extend('packages');
  882. // Let the file work its magic ;)
  883. require($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']);
  884. }
  885. // Handle a redirect...
  886. elseif ($action['type'] == 'redirect' && !empty($action['redirect_url']))
  887. {
  888. $context['redirect_url'] = $action['redirect_url'];
  889. $context['redirect_text'] = !empty($action['filename']) && file_exists($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']) ? file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $action['filename']) : ($context['uninstalling'] ? $txt['package_uninstall_done'] : $txt['package_installed_done']);
  890. $context['redirect_timeout'] = $action['redirect_timeout'];
  891. // Parse out a couple of common urls.
  892. $urls = array(
  893. '$boardurl' => $boardurl,
  894. '$scripturl' => $scripturl,
  895. '$session_var' => $context['session_var'],
  896. '$session_id' => $context['session_id'],
  897. );
  898. $context['redirect_url'] = strtr($context['redirect_url'], $urls);
  899. }
  900. }
  901. package_flush_cache();
  902. // First, ensure this change doesn't get removed by putting a stake in the ground (So to speak).
  903. package_put_contents($boarddir . '/Packages/installed.list', time());
  904. // See if this is already installed, and change it's state as required.
  905. $request = $smcFunc['db_query']('', '
  906. SELECT package_id, install_state, db_changes
  907. FROM {db_prefix}log_packages
  908. WHERE install_state != {int:not_installed}
  909. AND package_id = {string:current_package}
  910. ' . ($context['install_id'] ? ' AND id_install = {int:install_id} ' : '') . '
  911. ORDER BY time_installed DESC
  912. LIMIT 1',
  913. array(
  914. 'not_installed' => 0,
  915. 'install_id' => $context['install_id'],
  916. 'current_package' => $packageInfo['id'],
  917. )
  918. );
  919. $is_upgrade = false;
  920. while ($row = $smcFunc['db_fetch_assoc']($request))
  921. {
  922. // Uninstalling?
  923. if ($context['uninstalling'])
  924. {
  925. $smcFunc['db_query']('', '
  926. UPDATE {db_prefix}log_packages
  927. SET install_state = {int:not_installed}, member_removed = {string:member_name}, id_member_removed = {int:current_member},
  928. time_removed = {int:current_time}
  929. WHERE package_id = {string:package_id}
  930. AND id_install = {int:install_id}',
  931. array(
  932. 'current_member' => $user_info['id'],
  933. 'not_installed' => 0,
  934. 'current_time' => time(),
  935. 'package_id' => $row['package_id'],
  936. 'member_name' => $user_info['name'],
  937. 'install_id' => $context['install_id'],
  938. )
  939. );
  940. }
  941. // Otherwise must be an upgrade.
  942. else
  943. {
  944. $is_upgrade = true;
  945. $old_db_changes = empty($row['db_changes']) ? array() : unserialize($row['db_changes']);
  946. }
  947. }
  948. // Assuming we're not uninstalling, add the entry.
  949. if (!$context['uninstalling'])
  950. {
  951. // Any db changes from older version?
  952. if (!empty($old_db_changes))
  953. $db_package_log = empty($db_package_log) ? $old_db_changes : array_merge($old_db_changes, $db_package_log);
  954. // If there are some database changes we might want to remove then filter them out.
  955. if (!empty($db_package_log))
  956. {
  957. // We're really just checking for entries which are create table AND add columns (etc).
  958. $tables = array();
  959. function sort_table_first($a, $b)
  960. {
  961. if ($a[0] == $b[0])
  962. return 0;
  963. return $a[0] == 'remove_table' ? -1 : 1;
  964. }
  965. usort($db_package_log, 'sort_table_first');
  966. foreach ($db_package_log as $k => $log)
  967. {
  968. if ($log[0] == 'remove_table')
  969. $tables[] = $log[1];
  970. elseif (in_array($log[1], $tables))
  971. unset($db_package_log[$k]);
  972. }
  973. $db_changes = serialize($db_package_log);
  974. }
  975. else
  976. $db_changes = '';
  977. // What themes did we actually install?
  978. $themes_installed = array_unique($themes_installed);
  979. $themes_installed = implode(',', $themes_installed);
  980. // What failed steps?
  981. $failed_step_insert = serialize($failed_steps);
  982. // Credits tag?
  983. $credits_tag = (empty($credits_tag)) ? '' : serialize($credits_tag);
  984. $smcFunc['db_insert']('',
  985. '{db_prefix}log_packages',
  986. array(
  987. 'filename' => 'string', 'name' => 'string', 'package_id' => 'string', 'version' => 'string',
  988. 'id_member_installed' => 'int', 'member_installed' => 'string','time_installed' => 'int',
  989. 'install_state' => 'int', 'failed_steps' => 'string', 'themes_installed' => 'string',
  990. 'member_removed' => 'int', 'db_changes' => 'string', 'credits' => 'string',
  991. ),
  992. array(
  993. $packageInfo['filename'], $packageInfo['name'], $packageInfo['id'], $packageInfo['version'],
  994. $user_info['id'], $user_info['name'], time(),
  995. $is_upgrade ? 2 : 1, $failed_step_insert, $themes_installed,
  996. 0, $db_changes, $credits_tag,
  997. ),
  998. array('id_install')
  999. );
  1000. }
  1001. $smcFunc['db_free_result']($request);
  1002. $context['install_finished'] = true;
  1003. }
  1004. // If there's database changes - and they want them removed - let's do it last!
  1005. if (!empty($db_changes) && !empty($_POST['do_db_changes']))
  1006. {
  1007. // We're gonna be needing the package db functions!
  1008. db_extend('packages');
  1009. foreach ($db_changes as $change)
  1010. {
  1011. if ($change[0] == 'remove_table' && isset($change[1]))
  1012. $smcFunc['db_drop_table']($change[1]);
  1013. elseif ($change[0] == 'remove_column' && isset($change[2]))
  1014. $smcFunc['db_remove_column']($change[1], $change[2]);
  1015. elseif ($change[0] == 'remove_index' && isset($change[2]))
  1016. $smcFunc['db_remove_index']($change[1], $change[2]);
  1017. }
  1018. }
  1019. // Clean house... get rid of the evidence ;).
  1020. if (file_exists($boarddir . '/Packages/temp'))
  1021. deltree($boarddir . '/Packages/temp');
  1022. // Log what we just did.
  1023. logAction($context['uninstalling'] ? 'uninstall_package' : (!empty($is_upgrade) ? 'upgrade_package' : 'install_package'), array('package' => $smcFunc['htmlspecialchars']($packageInfo['name']), 'version' => $smcFunc['htmlspecialchars']($packageInfo['version'])), 'admin');
  1024. // Just in case, let's clear the whole cache to avoid anything going up the swanny.
  1025. clean_cache();
  1026. // Restore file permissions?
  1027. create_chmod_control(array(), array(), true);
  1028. }
  1029. /**
  1030. * List the files in a package.
  1031. */
  1032. function PackageList()
  1033. {
  1034. global $txt, $scripturl, $boarddir, $context, $sourcedir;
  1035. require_once($sourcedir . '/Subs-Package.php');
  1036. // No package? Show him or her the door.
  1037. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  1038. redirectexit('action=admin;area=packages');
  1039. $context['linktree'][] = array(
  1040. 'url' => $scripturl . '?action=admin;area=packages;sa=list;package=' . $_REQUEST['package'],
  1041. 'name' => $txt['list_file']
  1042. );
  1043. $context['page_title'] .= ' - ' . $txt['list_file'];
  1044. $context['sub_template'] = 'list';
  1045. // The filename...
  1046. $context['filename'] = $_REQUEST['package'];
  1047. // Let the unpacker do the work.
  1048. if (is_file($boarddir . '/Packages/' . $context['filename']))
  1049. $context['files'] = read_tgz_file($boarddir . '/Packages/' . $context['filename'], null);
  1050. elseif (is_dir($boarddir . '/Packages/' . $context['filename']))
  1051. $context['files'] = listtree($boarddir . '/Packages/' . $context['filename']);
  1052. }
  1053. /**
  1054. * Display one of the files in a package.
  1055. */
  1056. function ExamineFile()
  1057. {
  1058. global $txt, $scripturl, $boarddir, $context, $sourcedir;
  1059. require_once($sourcedir . '/Subs-Package.php');
  1060. // No package? Show him or her the door.
  1061. if (!isset($_REQUEST['package']) || $_REQUEST['package'] == '')
  1062. redirectexit('action=admin;area=packages');
  1063. // No file? Show him or her the door.
  1064. if (!isset($_REQUEST['file']) || $_REQUEST['file'] == '')
  1065. redirectexit('action=admin;area=packages');
  1066. $_REQUEST['package'] = preg_replace('~[\.]+~', '.', strtr($_REQUEST['package'], array('/' => '_', '\\' => '_')));
  1067. $_REQUEST['file'] = preg_replace('~[\.]+~', '.', $_REQUEST['file']);
  1068. if (isset($_REQUEST['raw']))
  1069. {
  1070. if (is_file($boarddir . '/Packages/' . $_REQUEST['package']))
  1071. echo read_tgz_file($boarddir . '/Packages/' . $_REQUEST['package'], $_REQUEST['file'], true);
  1072. elseif (is_dir($boarddir . '/Packages/' . $_REQUEST['package']))
  1073. echo file_get_contents($boarddir . '/Packages/' . $_REQUEST['package'] . '/' . $_REQUEST['file']);
  1074. obExit(false);
  1075. }
  1076. $context['linktree'][count($context['linktree']) - 1] = array(
  1077. 'url' => $scripturl . '?action=admin;area=packages;sa=list;package=' . $_REQUEST['package'],
  1078. 'name' => $txt['package_examine_file']
  1079. );
  1080. $context['page_title'] .= ' - ' . $txt['package_examine_file'];
  1081. $context['sub_template'] = 'examine';
  1082. // The filename...
  1083. $context['package'] = $_REQUEST['package'];
  1084. $context['filename'] = $_REQUEST['file'];
  1085. // Let the unpacker do the work.... but make sure we handle images properly.
  1086. if (in_array(strtolower(strrchr($_REQUEST['file'], '.')), array('.bmp', '.gif', '.jpeg', '.jpg', '.png')))
  1087. $context['filedata'] = '<img src="' . $scripturl . '?action=admin;area=packages;sa=examine;package=' . $_REQUEST['package'] . ';file=' . $_REQUEST['file'] . ';raw" alt="' . $_REQUEST['file'] . '" />';
  1088. else
  1089. {
  1090. if (is_file($boarddir . '/Packages/' . $_REQUEST['package']))
  1091. $context['filedata'] = htmlspecialchars(read_tgz_file($boarddir . '/Packages/' . $_REQUEST['package'], $_REQUEST['file'], true));
  1092. elseif (is_dir($boarddir . '/Packages/' . $_REQUEST['package']))
  1093. $context['filedata'] = htmlspecialchars(file_get_contents($boarddir . '/Packages/' . $_REQUEST['package'] . '/' . $_REQUEST['file']));
  1094. if (strtolower(strrchr($_REQUEST['file'], '.')) == '.php')
  1095. $context['filedata'] = highlight_php_code($context['filedata']);
  1096. }
  1097. }
  1098. /**
  1099. * List the installed packages.
  1100. */
  1101. function InstalledList()
  1102. {
  1103. global $txt, $scripturl, $context;
  1104. $context['page_title'] .= ' - ' . $txt['installed_packages'];
  1105. $context['sub_template'] = 'view_installed';
  1106. // Load the installed mods and send them to the template.
  1107. $context['installed_mods'] = loadInstalledPackages();
  1108. }
  1109. /**
  1110. * Empty out the installed list.
  1111. */
  1112. function FlushInstall()
  1113. {
  1114. global $boarddir, $sourcedir, $smcFunc;
  1115. // Always check the session.
  1116. checkSession('get');
  1117. include_once($sourcedir . '/Subs-Package.php');
  1118. // Record when we last did this.
  1119. package_put_contents($boarddir . '/Packages/installed.list', time());
  1120. // Set everything as uninstalled.
  1121. $smcFunc['db_query']('', '
  1122. UPDATE {db_prefix}log_packages
  1123. SET install_state = {int:not_installed}',
  1124. array(
  1125. 'not_installed' => 0,
  1126. )
  1127. );
  1128. redirectexit('action=admin;area=packages;sa=installed');
  1129. }
  1130. /**
  1131. * Delete a package.
  1132. */
  1133. function PackageRemove()
  1134. {
  1135. global $scripturl, $boarddir;
  1136. // Check it.
  1137. checkSession('get');
  1138. // Ack, don't allow deletion of arbitrary files here, could become a security hole somehow!
  1139. if (!isset($_GET['package']) || $_GET['package'] == 'index.php' || $_GET['package'] == 'installed.list' || $_GET['package'] == 'backups')
  1140. redirectexit('action=admin;area=packages;sa=browse');
  1141. $_GET['package'] = preg_replace('~[\.]+~', '.', strtr($_GET['package'], array('/' => '_', '\\' => '_')));
  1142. // Can't delete what's not there.
  1143. if (file_exists($boarddir . '/Packages/' . $_GET['package']) && (substr($_GET['package'], -4) == '.zip' || substr($_GET['package'], -4) == '.tgz' || substr($_GET['package'], -7) == '.tar.gz' || is_dir($boarddir . '/Packages/' . $_GET['package'])) && $_GET['package'] != 'backups' && substr($_GET['package'], 0, 1) != '.')
  1144. {
  1145. create_chmod_control(array($boarddir . '/Packages/' . $_GET['package']), array('destination_url' => $scripturl . '?action=admin;area=packages;sa=remove;package=' . $_GET['package'], 'crash_on_error' => true));
  1146. if (is_dir($boarddir . '/Packages/' . $_GET['package']))
  1147. deltree($boarddir . '/Packages/' . $_GET['package']);
  1148. else
  1149. {
  1150. @chmod($boarddir . '/Packages/' . $_GET['package'], 0777);
  1151. unlink($boarddir . '/Packages/' . $_GET['package']);
  1152. }
  1153. }
  1154. redirectexit('action=admin;area=packages;sa=browse');
  1155. }
  1156. /**
  1157. * Browse a list of installed packages.
  1158. */
  1159. function PackageBrowse()
  1160. {
  1161. global $txt, $boarddir, $scripturl, $context, $forum_version, $sourcedir, $settings;
  1162. $context['page_title'] .= ' - ' . $txt['browse_packages'];
  1163. $context['forum_version'] = $forum_version;
  1164. $context['modification_types'] = array('modification', 'avatar', 'language', 'unknown');
  1165. $installed = $context['sub_action'] == 'installed' ? true : false;
  1166. require_once($sourcedir . '/Subs-List.php');
  1167. foreach ($context['modification_types'] as $type)
  1168. {
  1169. // Use the standard templates for showing this.
  1170. $listOptions = array(
  1171. 'id' => 'packages_lists_' . $type,
  1172. 'title' => $installed ? $txt['view_and_remove'] : $txt[$type . '_package'],
  1173. 'no_items_label' => $txt['no_packages'],
  1174. 'get_items' => array(
  1175. 'function' => 'list_getPackages',
  1176. 'params' => array('type' => $type, 'installed' => $installed),
  1177. ),
  1178. 'columns' => array(
  1179. 'id' => array(
  1180. 'header' => array(
  1181. 'value' => '',
  1182. 'style' => 'width: 32px;',
  1183. ),
  1184. 'data' => array(
  1185. 'function' => create_function('$packages', '
  1186. static $packageCounter;
  1187. if (empty($packageCounter))
  1188. $packageCounter = 1;
  1189. return $packageCounter++ . \'.\';
  1190. '),
  1191. ),
  1192. ),
  1193. 'mod_name' => array(
  1194. 'header' => array(
  1195. 'value' => $txt['mod_name'],
  1196. 'style' => 'width: 25%;',
  1197. ),
  1198. 'data' => array(
  1199. 'function' => create_function('$package_md5', '
  1200. global $context;
  1201. if (isset($context[\'available_' . $type . '\'][$package_md5]))
  1202. return $context[\'available_' . $type . '\'][$package_md5][\'name\'];'
  1203. ),
  1204. ),
  1205. ),
  1206. 'version' => array(
  1207. 'header' => array(
  1208. 'value' => $txt['mod_version'],
  1209. 'style' => 'width: 25%;',
  1210. ),
  1211. 'data' => array(
  1212. 'function' => create_function('$package_md5', '
  1213. global $context;
  1214. if (isset($context[\'available_' . $type . '\'][$package_md5]))
  1215. return $context[\'available_' . $type . '\'][$package_md5][\'version\'];'
  1216. ),
  1217. ),
  1218. ),
  1219. 'operations' => array(
  1220. 'header' => array(
  1221. 'value' => '',
  1222. ),
  1223. 'data' => array(
  1224. 'function' => create_function('$package_md5', '
  1225. global $context, $scripturl, $txt;
  1226. if (!isset($context[\'available_' . $type . '\'][$package_md5]))
  1227. return \'\';
  1228. // Rewrite shortcut
  1229. $package = $context[\'available_' . $type . '\'][$package_md5];
  1230. $return = \'\';
  1231. if ($package[\'can_uninstall\'])
  1232. $return = \'
  1233. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=uninstall;package=\' . $package[\'filename\'] . \';pid=\' . $package[\'installed_id\'] . \'">[ \' . $txt[\'uninstall\'] . \' ]</a>\';
  1234. elseif ($package[\'can_emulate_uninstall\'])
  1235. $return = \'
  1236. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=uninstall;ve=\' . $package[\'can_emulate_uninstall\'] . \';package=\' . $package[\'filename\'] . \';pid=\' . $package[\'installed_id\'] . \'">[ \' . $txt[\'package_emulate_uninstall\'] . \' \' . $package[\'can_emulate_uninstall\'] . \' ]</a>\';
  1237. elseif ($package[\'can_upgrade\'])
  1238. $return = \'
  1239. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=install;package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'package_upgrade\'] . \' ]</a>\';
  1240. elseif ($package[\'can_install\'])
  1241. $return = \'
  1242. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=install;package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'install_mod\'] . \' ]</a>\';
  1243. elseif ($package[\'can_emulate_install\'])
  1244. $return = \'
  1245. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=install;ve=\' . $package[\'can_emulate_install\'] . \';package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'package_emulate_install\'] . \' \' . $package[\'can_emulate_install\'] . \' ]</a>\';
  1246. return $return . \'
  1247. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=list;package=\' . $package[\'filename\'] . \'">[ \' . $txt[\'list_files\'] . \' ]</a>
  1248. <a href="\' . $scripturl . \'?action=admin;area=packages;sa=remove;package=\' . $package[\'filename\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'] . \'"\' . ($package[\'is_installed\'] && $package[\'is_current\'] ? \' onclick="return confirm(\\\'\' . $txt[\'package_delete_bad\'] . \'\\\');"\' : \'\') . \'>[ \' . $txt[\'package_delete\'] . \' ]</a>\';'
  1249. ),
  1250. 'style' => 'text-align: right;',
  1251. ),
  1252. ),
  1253. ),
  1254. 'additional_rows' => array(
  1255. array(
  1256. 'position' => 'bottom_of_list',
  1257. 'value' => (
  1258. $context['sub_action'] == 'browse' ? '
  1259. <div class="padding smalltext floatleft">
  1260. ' . $txt['package_installed_key'] . '
  1261. <img src="' . $settings['images_url'] . '/icons/package_installed.png" alt="" class="centericon" style="margin-left: 1ex;" /> ' . $txt['package_installed_current'] . '
  1262. <img src="' . $settings['images_url'] . '/icons/package_old.png" alt="" class="centericon" style="margin-left: 2ex;" /> ' . $txt['package_installed_old'] . '
  1263. </div>' : '<a class="button_link" href="' . $scripturl . '?action=admin;area=packages;sa=flush;' . $context['session_var'] . '=' . $context['session_id'] . '" onclick="return confirm(\'' . $txt['package_delete_list_warning'] . '\');">' . $txt['delete_list'] . '</a><span style="float: right; margin:.5em;"></span><a class="button_link" href="#" onclick="document.getElementById(\'advanced_box\').style.display = document.getElementById(\'advanced_box\').style.display == \'\' ? \'none\' : \'\'; return false;">' . $txt['package_advanced_button'] . '</a>'),
  1264. ),
  1265. ),
  1266. );
  1267. createList($listOptions);
  1268. }
  1269. $context['sub_template'] = 'browse';
  1270. $context['default_list'] = 'packages_lists';
  1271. // Empty lists for now.
  1272. $context['available_mods'] = array();
  1273. $context['available_avatars'] = array();
  1274. $context['available_languages'] = array();
  1275. $context['available_other'] = array();
  1276. $context['available_all'] = array();
  1277. }
  1278. function list_getPackages($start, $items_per_page, $sort, $params, $installed)
  1279. {
  1280. global $boarddir, $scripturl, $context, $forum_version;
  1281. static $instmods, $packages;
  1282. // Start things up
  1283. if (!isset($packages[$params]))
  1284. $packages[$params] = array();
  1285. // We need the packages directory to be writable for this.
  1286. if (!@is_writable($boarddir . '/Packages'))
  1287. create_chmod_control(array($boarddir . '/Packages'), array('destination_url' => $scripturl . '?action=admin;area=packages', 'crash_on_error' => true));
  1288. $the_version = strtr($forum_version, array('SMF ' => ''));
  1289. // Here we have a little code to help those who class themselves as something of gods, version emulation ;)
  1290. if (isset($_GET['version_emulate']))
  1291. {
  1292. if (($_GET['version_emulate'] === 0 || $_GET['version_emulate'] === $forum_version) && isset($_SESSION['version_emulate']))
  1293. unset($_SESSION['version_emulate']);
  1294. elseif ($_GET['version_emulate'] !== 0)
  1295. $_SESSION['version_emulate'] = strtr($_GET['version_emulate'], array('-' => ' ', '+' => ' ', 'SMF ' => ''));
  1296. }
  1297. if (!empty($_SESSION['version_emulate']))
  1298. {
  1299. $context['forum_version'] = 'SMF ' . $_SESSION['version_emulate'];
  1300. $the_version = $_SESSION['version_emulate'];
  1301. }
  1302. if (isset($_SESSION['single_version_emulate']))
  1303. unset($_SESSION['single_version_emulate']);
  1304. if (empty($instmods))
  1305. {
  1306. $instmods = loadInstalledPackages();
  1307. $installed_mods = array();
  1308. // Look through the list of installed mods...
  1309. foreach ($instmods as $installed_mod)
  1310. $installed_mods[$installed_mod['package_id']] = array(
  1311. 'id' => $installed_mod['id'],
  1312. 'version' => $installed_mod['version'],
  1313. );
  1314. // Get a list of all the ids installed, so the latest packages won't include already installed ones.
  1315. $context['installed_mods'] = array_keys($installed_mods);
  1316. }
  1317. if ($installed)
  1318. {
  1319. foreach ($instmods as $installed_mod)
  1320. {
  1321. $packages['modification'][] = $installed_mod['package_id'];
  1322. $context['available_modification'][$installed_mod['package_id']] = array(
  1323. 'can_uninstall' => true,
  1324. 'name' => $installed_mod['name'],
  1325. 'filename' => $installed_mod['filename'],
  1326. 'installed_id' => $installed_mod['id'],
  1327. 'version' => $installed_mod['version'],
  1328. 'is_installed' => true,
  1329. 'is_current' => true,
  1330. );
  1331. }
  1332. return $packages['modification'];
  1333. }
  1334. if (empty($packages))
  1335. $packages = array('modification' => array(), 'avatar' => array(), 'language' => array(), 'unknown' => array());
  1336. if ($dir = @opendir($boarddir . '/Packages'))
  1337. {
  1338. $dirs = array();
  1339. while ($package = readdir($dir))
  1340. {
  1341. if ($package == '.' || $package == '..' || $package == 'temp' || (!(is_dir($boarddir . '/Packages/' . $package) && file_exists($boarddir . '/Packages/' . $package . '/package-info.xml')) && substr(strtolower($package), -7) != '.tar.gz' && substr(strtolower($package), -4) != '.tgz' && substr(strtolower($package), -4) != '.zip'))
  1342. continue;
  1343. $skip = false;
  1344. foreach ($context['modification_types'] as $type)
  1345. if (isset($context['available_' . $type][md5($package)]))
  1346. $skip = true;
  1347. if ($skip)
  1348. continue;
  1349. // Skip directories or files that are named the same.
  1350. if (is_dir($boarddir . '/Packages/' . $package))
  1351. {
  1352. if (in_array($package, $dirs))
  1353. continue;
  1354. $dirs[] = $package;
  1355. }
  1356. elseif (substr(strtolower($package), -7) == '.tar.gz')
  1357. {
  1358. if (in_array(substr($package, 0, -7), $dirs))
  1359. continue;
  1360. $dirs[] = substr($package, 0, -7);
  1361. }
  1362. elseif (substr(strtolower($package), -4) == '.zip' || substr(strtolower($package), -4) == '.tgz')
  1363. {
  1364. if (in_array(substr($package, 0, -4), $dirs))
  1365. continue;
  1366. $dirs[] = substr($package, 0, -4);
  1367. }
  1368. $packageInfo = getPackageInfo($package);
  1369. if (!is_array($packageInfo))
  1370. continue;
  1371. if (!empty($packageInfo))
  1372. {
  1373. $packageInfo['installed_id'] = isset($installed_mods[$packageInfo['id']]) ? $installed_mods[$packageInfo['id']]['id'] : 0;
  1374. $packageInfo['is_installed'] = isset($installed_mods[$packageInfo['id']]);
  1375. $packageInfo['is_current'] = $packageInfo['is_installed'] && ($installed_mods[$packageInfo['id']]['version'] == $packageInfo['version']);
  1376. $packageInfo['is_newer'] = $packageInfo['is_installed'] && ($installed_mods[$packageInfo['id']]['version'] > $packageInfo['version']);
  1377. $packageInfo['can_install'] = false;
  1378. $packageInfo['can_uninstall'] = false;
  1379. $packageInfo['can_upgrade'] = false;
  1380. $packageInfo['can_emulate_install'] = false;
  1381. $packageInfo['can_emulate_uninstall'] = false;
  1382. // This package is currently NOT installed. Check if it can be.
  1383. if (!$packageInfo['is_installed'] && $packageInfo['xml']->exists('install'))
  1384. {
  1385. // Check if there's an install for *THIS* version of SMF.
  1386. $installs = $packageInfo['xml']->set('install');
  1387. foreach ($installs as $install)
  1388. {
  1389. if (!$install->exists('@for') || matchPackageVersion($the_version, $install->fetch('@for')))
  1390. {
  1391. // Okay, this one is good to go.
  1392. $packageInfo['can_install'] = true;
  1393. break;
  1394. }
  1395. }
  1396. // no install found for this version, lets see if one exists for another
  1397. if ($packageInfo['can_install'] === false && $install->exists('@for') && empty($_SESSION['version_emulate']))
  1398. {
  1399. $reset = true;
  1400. // Get the highest install version that is available from the package
  1401. foreach ($installs as $install)
  1402. {
  1403. $packageInfo['can_emulate_install'] = matchHighestPackageVersion($install->fetch('@for'), $reset, $the_version);
  1404. $reset = false;
  1405. }
  1406. }
  1407. }
  1408. // An already installed, but old, package. Can we upgrade it?
  1409. elseif ($packageInfo['is_installed'] && !$packageInfo['is_current'] && $packageInfo['xml']->exists('upgrade'))
  1410. {
  1411. $upgrades = $packageInfo['xml']->set('upgrade');
  1412. // First go through, and check against the current version of SMF.
  1413. foreach ($upgrades as $upgrade)
  1414. {
  1415. // Even if it is for this SMF, is it for the installed version of the mod?
  1416. if (!$upgrade->exists('@for') || matchPackageVersion($the_version, $upgrade->fetch('@for')))
  1417. if (!$upgrade->exists('@from') || matchPackageVersion($installed_mods[$packageInfo['id']]['version'], $upgrade->fetch('@from')))
  1418. {
  1419. $packageInfo['can_upgrade'] = true;
  1420. break;
  1421. }
  1422. }
  1423. }
  1424. // Note that it has to be the current version to be uninstallable. Shucks.
  1425. elseif ($packageInfo['is_installed'] && $packageInfo['is_current'] && $packageInfo['xml']->exists('uninstall'))
  1426. {
  1427. $uninstalls = $packageInfo['xml']->set('uninstall');
  1428. // Can we find any uninstallation methods that work for this SMF version?
  1429. foreach ($uninstalls as $uninstall)
  1430. {
  1431. if (!$uninstall->exists('@for') || matchPackageVersion($the_version, $uninstall->fetch('@for')))
  1432. {
  1433. $packageInfo['can_uninstall'] = true;
  1434. break;
  1435. }
  1436. }
  1437. // no uninstall found for this version, lets see if one exists for another
  1438. if ($packageInfo['can_uninstall'] === false && $uninstall->exists('@for') && empty($_SESSION['version_emulate']))
  1439. {
  1440. $reset = true;
  1441. // Get the highest install version that is available from the package
  1442. foreach ($uninstalls as $uninstall)
  1443. {
  1444. $packageInfo['can_emulate_uninstall'] = matchHighestPackageVersion($uninstall->fetch('@for'), $reset, $the_version);
  1445. $reset = false;
  1446. }
  1447. }
  1448. }
  1449. // Modification.
  1450. if ($packageInfo['type'] == 'modification' || $packageInfo['type'] == 'mod')
  1451. {
  1452. $packages['modification'][] = md5($package);
  1453. $context['available_modification'][md5($package)] = $packageInfo;
  1454. }
  1455. // Avatar package.
  1456. elseif ($packageInfo['type'] == 'avatar')
  1457. {
  1458. $packages['avatar'][] = md5($package);
  1459. $context['available_avatar'][md5($package)] = $packageInfo;
  1460. }
  1461. // Language package.
  1462. elseif ($packageInfo['type'] == 'language')
  1463. {
  1464. $packages['language'][] = md5($package);
  1465. $context['available_language'][md5($package)] = $packageInfo;
  1466. }
  1467. // Other stuff.
  1468. else
  1469. {
  1470. $packages['unknown'][] = md5($package);
  1471. $context['available_unknown'][md5($package)] = $packageInfo;
  1472. }
  1473. }
  1474. }
  1475. closedir($dir);
  1476. }
  1477. return $packages[$params];
  1478. }
  1479. function PackageOptions()
  1480. {
  1481. global $txt, $scripturl, $context, $sourcedir, $modSettings, $smcFunc;
  1482. if (isset($_POST['save']))
  1483. {
  1484. checkSession('post');
  1485. updateSettings(array(
  1486. 'package_server' => trim($smcFunc['htmlspecialchars']($_POST['pack_server'])),
  1487. 'package_port' => trim($smcFunc['htmlspecialchars']($_POST['pack_port'])),
  1488. 'package_username' => trim($smcFunc['htmlspecialchars']($_POST['pack_user'])),
  1489. 'package_make_backups' => !empty($_POST['package_make_backups']),
  1490. 'package_make_full_backups' => !empty($_POST['package_make_full_backups'])
  1491. ));
  1492. redirectexit('action=admin;area=packages;sa=options');
  1493. }
  1494. if (preg_match('~^/home\d*/([^/]+?)/public_html~', $_SERVER['DOCUMENT_ROOT'], $match))
  1495. $default_username = $match[1];
  1496. else
  1497. $default_username = '';
  1498. $context['page_title'] = $txt['package_settings'];
  1499. $context['sub_template'] = 'install_options';
  1500. $context['package_ftp_server'] = isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost';
  1501. $context['package_ftp_port'] = isset($modSettings['package_port']) ? $modSettings['package_port'] : '21';
  1502. $context['package_ftp_username'] = isset($modSettings['package_username']) ? $modSettings['package_username'] : $default_username;
  1503. $context['package_make_backups'] = !empty($modSettings['package_make_backups']);
  1504. $context['package_make_full_backups'] = !empty($modSettings['package_make_full_backups']);
  1505. }
  1506. /**
  1507. * List operations
  1508. */
  1509. function ViewOperations()
  1510. {
  1511. global $context, $txt, $boarddir, $sourcedir, $smcFunc, $modSettings;
  1512. // Can't be in here buddy.
  1513. isAllowedTo('admin_forum');
  1514. // We need to know the operation key for the search and replace, mod file looking at, is it a board mod?
  1515. if (!isset($_REQUEST['operation_key'], $_REQUEST['filename']) && !is_numeric($_REQUEST['operation_key']))
  1516. fatal_lang_error('operation_invalid', 'general');
  1517. // Load the required file.
  1518. require_once($sourcedir . '/Subs-Package.php');
  1519. // Uninstalling the mod?
  1520. $reverse = isset($_REQUEST['reverse']) ? true : false;
  1521. // Get the base name.
  1522. $context['filename'] = preg_replace('~[\.]+~', '.', $_REQUEST['package']);
  1523. // We need to extract this again.
  1524. if (is_file($boarddir . '/Packages/' . $context['filename']))
  1525. {
  1526. $context['extracted_files'] = read_tgz_file($boarddir . '/Packages/' . $context['filename'], $boarddir . '/Packages/temp');
  1527. if ($context['extracted_files'] && !file_exists($boarddir . '/Packages/temp/package-info.xml'))
  1528. foreach ($context['extracted_files'] as $file)
  1529. if (basename($file['filename']) == 'package-info.xml')
  1530. {
  1531. $context['base_path'] = dirname($file['filename']) . '/';
  1532. break;
  1533. }
  1534. if (!isset($context['base_path']))
  1535. $context['base_path'] = '';
  1536. }
  1537. elseif (is_dir($boarddir . '/Packages/' . $context['filename']))
  1538. {
  1539. copytree($boarddir . '/Packages/' . $context['filename'], $boarddir . '/Packages/temp');
  1540. $context['extracted_files'] = listtree($boarddir . '/Packages/temp');
  1541. $context['base_path'] = '';
  1542. }
  1543. // Load up any custom themes we may want to install into...
  1544. $request = $smcFunc['db_query']('', '
  1545. SELECT id_theme, variable, value
  1546. FROM {db_prefix}themes
  1547. WHERE (id_theme = {int:default_theme} OR id_theme IN ({array_int:known_theme_list}))
  1548. AND variable IN ({string:name}, {string:theme_dir})',
  1549. array(
  1550. 'known_theme_list' => explode(',', $modSettings['knownThemes']),
  1551. 'default_theme' => 1,
  1552. 'name' => 'name',
  1553. 'theme_dir' => 'theme_dir',
  1554. )
  1555. );
  1556. $theme_paths = array();
  1557. while ($row = $smcFunc['db_fetch_assoc']($request))
  1558. $theme_paths[$row['id_theme']][$row['variable']] = $row['value'];
  1559. $smcFunc['db_free_result']($request);
  1560. // Boardmod?
  1561. if (isset($_REQUEST['boardmod']))
  1562. $mod_actions = parseBoardMod(@file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $_REQUEST['filename']), true, $reverse, $theme_paths);
  1563. else
  1564. $mod_actions = parseModification(@file_get_contents($boarddir . '/Packages/temp/' . $context['base_path'] . $_REQUEST['filename']), true, $reverse, $theme_paths);
  1565. // Ok lets get the content of the file.
  1566. $context['operations'] = array(
  1567. 'search' => strtr(htmlspecialchars($mod_actions[$_REQUEST['operation_key']]['search_original']), array('[' => '&#91;', ']' => '&#93;')),
  1568. 'replace' => strtr(htmlspecialchars($mod_actions[$_REQUEST['operation_key']]['replace_original']), array('[' => '&#91;', ']' => '&#93;')),
  1569. 'position' => $mod_actions[$_REQUEST['operation_key']]['position'],
  1570. );
  1571. // Let's do some formatting...
  1572. $operation_text = $context['operations']['position'] == 'replace' ? 'operation_replace' : ($context['operations']['position'] == 'before' ? 'operation_after' : 'operation_before');
  1573. $context['operations']['search'] = parse_bbc('[code=' . $txt['operation_find'] . ']' . ($context['operations']['position'] == 'end' ? '?&gt;' : $context['operations']['search']) . '[/code]');
  1574. $context['operations']['replace'] = parse_bbc('[code=' . $txt[$operation_text] . ']' . $context['operations']['replace'] . '[/code]');
  1575. // No layers
  1576. $context['template_layers'] = array();
  1577. $context['sub_template'] = 'view_operations';
  1578. }
  1579. /**
  1580. * Allow the admin to reset permissions on files.
  1581. */
  1582. function PackagePermissions()
  1583. {
  1584. global $context, $txt, $modSettings, $boarddir, $sourcedir, $cachedir, $smcFunc, $package_ftp;
  1585. // Let's try and be good, yes?
  1586. checkSession('get');
  1587. // If we're restoring permissions this is just a pass through really.
  1588. if (isset($_GET['restore']))
  1589. {
  1590. create_chmod_control(array(), array(), true);
  1591. fatal_lang_error('no_access', false);
  1592. }
  1593. // This is a memory eat.
  1594. setMemoryLimit('128M');
  1595. @set_time_limit(600);
  1596. // Load up some FTP stuff.
  1597. create_chmod_control();
  1598. if (empty($package_ftp) && !isset($_POST['skip_ftp']))
  1599. {
  1600. require_once($sourcedir . '/Class-Package.php');
  1601. $ftp = new ftp_connection(null);
  1602. list ($username, $detect_path, $found_path) = $ftp->detect_path($boarddir);
  1603. $context['package_ftp'] = array(
  1604. 'server' => isset($modSettings['package_server']) ? $modSettings['package_server'] : 'localhost',
  1605. 'port' => isset($modSettings['package_port']) ? $modSettings['package_port'] : '21',
  1606. 'username' => empty($username) ? (isset($modSettings['package_username']) ? $modSettings['package_username'] : '') : $username,
  1607. 'path' => $detect_path,
  1608. 'form_elements_only' => true,
  1609. );
  1610. }
  1611. else
  1612. $context['ftp_connected'] = true;
  1613. // Define the template.
  1614. $context['page_title'] = $txt['package_file_perms'];
  1615. $context['sub_template'] = 'file_permissions';
  1616. // Define what files we're interested in, as a tree.
  1617. $context['file_tree'] = array(
  1618. strtr($boarddir, array('\\' => '/')) => array(
  1619. 'type' => 'dir',
  1620. 'contents' => array(
  1621. 'agreement.txt' => array(
  1622. 'type' => 'file',
  1623. 'writable_on' => 'standard',
  1624. ),
  1625. 'Settings.php' => array(
  1626. 'type' => 'file',
  1627. 'writable_on' => 'restrictive',
  1628. ),
  1629. 'Settings_bak.php' => array(
  1630. 'type' => 'file',
  1631. 'writable_on' => 'restrictive',
  1632. ),
  1633. 'attachments' => array(
  1634. 'type' => 'dir',
  1635. 'writable_on' => 'restrictive',
  1636. ),
  1637. 'avatars' => array(
  1638. 'type' => 'dir',
  1639. 'writable_on' => 'standard',
  1640. ),
  1641. 'cache' => array(
  1642. 'type' => 'dir',
  1643. 'writable_on' => 'restrictive',
  1644. ),
  1645. 'custom_avatar_dir' => array(
  1646. 'type' => 'dir',
  1647. 'writable_on' => 'restrictive',
  1648. ),
  1649. 'Smileys' => array(
  1650. 'type' => 'dir_recursive',
  1651. 'writable_on' => 'standard',
  1652. ),
  1653. 'Sources' => array(
  1654. 'type' => 'dir',
  1655. 'list_contents' => true,
  1656. 'writable_on' => 'standard',
  1657. ),
  1658. 'Themes' => array(
  1659. 'type' => 'dir_recursive',
  1660. 'writable_on' => 'standard',
  1661. 'contents' => array(
  1662. 'default' => array(
  1663. 'type' => 'dir_recursive',
  1664. 'list_contents' => true,
  1665. 'contents' => array(
  1666. 'languages' => array(
  1667. 'type' => 'dir',
  1668. 'list_contents' => true,
  1669. ),
  1670. ),
  1671. ),
  1672. ),
  1673. ),
  1674. 'Packages' => array(
  1675. 'type' => 'dir',
  1676. 'writable_on' => 'standard',
  1677. 'contents' => array(
  1678. 'temp' => array(
  1679. 'type' => 'dir',
  1680. ),
  1681. 'backup' => array(
  1682. 'type' => 'dir',
  1683. ),
  1684. 'installed.list' => array(
  1685. 'type' => 'file',
  1686. 'writable_on' => 'standard',
  1687. ),
  1688. ),
  1689. ),
  1690. ),
  1691. ),
  1692. );
  1693. // Directories that can move.
  1694. if (substr($sourcedir, 0, strlen($boarddir)) != $boarddir)
  1695. {
  1696. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['Sources']);
  1697. $context['file_tree'][strtr($sourcedir, array('\\' => '/'))] = array(
  1698. 'type' => 'dir',
  1699. 'list_contents' => true,
  1700. 'writable_on' => 'standard',
  1701. );
  1702. }
  1703. // Moved the cache?
  1704. if (substr($cachedir, 0, strlen($boarddir)) != $boarddir)
  1705. {
  1706. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['cache']);
  1707. $context['file_tree'][strtr($cachedir, array('\\' => '/'))] = array(
  1708. 'type' => 'dir',
  1709. 'list_contents' => false,
  1710. 'writable_on' => 'restrictive',
  1711. );
  1712. }
  1713. // Are we using multiple attachment directories?
  1714. if (!empty($modSettings['currentAttachmentUploadDir']))
  1715. {
  1716. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['attachments']);
  1717. if (!is_array($modSettings['attachmentUploadDir']))
  1718. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1719. // @todo Should we suggest non-current directories be read only?
  1720. foreach ($modSettings['attachmentUploadDir'] as $dir)
  1721. $context['file_tree'][strtr($dir, array('\\' => '/'))] = array(
  1722. 'type' => 'dir',
  1723. 'writable_on' => 'restrictive',
  1724. );
  1725. }
  1726. elseif (substr($modSettings['attachmentUploadDir'], 0, strlen($boarddir)) != $boarddir)
  1727. {
  1728. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['attachments']);
  1729. $context['file_tree'][strtr($modSettings['attachmentUploadDir'], array('\\' => '/'))] = array(
  1730. 'type' => 'dir',
  1731. 'writable_on' => 'restrictive',
  1732. );
  1733. }
  1734. if (substr($modSettings['smileys_dir'], 0, strlen($boarddir)) != $boarddir)
  1735. {
  1736. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['Smileys']);
  1737. $context['file_tree'][strtr($modSettings['smileys_dir'], array('\\' => '/'))] = array(
  1738. 'type' => 'dir_recursive',
  1739. 'writable_on' => 'standard',
  1740. );
  1741. }
  1742. if (substr($modSettings['avatar_directory'], 0, strlen($boarddir)) != $boarddir)
  1743. {
  1744. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['avatars']);
  1745. $context['file_tree'][strtr($modSettings['avatar_directory'], array('\\' => '/'))] = array(
  1746. 'type' => 'dir',
  1747. 'writable_on' => 'standard',
  1748. );
  1749. }
  1750. if (isset($modSettings['custom_avatar_dir']) && substr($modSettings['custom_avatar_dir'], 0, strlen($boarddir)) != $boarddir)
  1751. {
  1752. unset($context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['custom_avatar_dir']);
  1753. $context['file_tree'][strtr($modSettings['custom_avatar_dir'], array('\\' => '/'))] = array(
  1754. 'type' => 'dir',
  1755. 'writable_on' => 'restrictive',
  1756. );
  1757. }
  1758. // Load up any custom themes.
  1759. $request = $smcFunc['db_query']('', '
  1760. SELECT value
  1761. FROM {db_prefix}themes
  1762. WHERE id_theme > {int:default_theme_id}
  1763. AND id_member = {int:guest_id}
  1764. AND variable = {string:theme_dir}
  1765. ORDER BY value ASC',
  1766. array(
  1767. 'default_theme_id' => 1,
  1768. 'guest_id' => 0,
  1769. 'theme_dir' => 'theme_dir',
  1770. )
  1771. );
  1772. while ($row = $smcFunc['db_fetch_assoc']($request))
  1773. {
  1774. if (substr(strtolower(strtr($row['value'], array('\\' => '/'))), 0, strlen($boarddir) + 7) == strtolower(strtr($boarddir, array('\\' => '/')) . '/Themes'))
  1775. $context['file_tree'][strtr($boarddir, array('\\' => '/'))]['contents']['Themes']['contents'][substr($row['value'], strlen($boarddir) + 8)] = array(
  1776. 'type' => 'dir_recursive',
  1777. 'list_contents' => true,
  1778. 'contents' => array(
  1779. 'languages' => array(
  1780. 'type' => 'dir',
  1781. 'list_contents' => true,
  1782. ),
  1783. ),
  1784. );
  1785. else
  1786. {
  1787. $context['file_tree'][strtr($row['value'], array('\\' => '/'))] = array(
  1788. 'type' => 'dir_recursive',
  1789. 'list_contents' => true,
  1790. 'contents' => array(
  1791. 'languages' => array(
  1792. 'type' => 'dir',
  1793. 'list_contents' => true,
  1794. ),
  1795. ),
  1796. );
  1797. }
  1798. }
  1799. $smcFunc['db_free_result']($request);
  1800. // If we're submitting then let's move on to another function to keep things cleaner..
  1801. if (isset($_POST['action_changes']))
  1802. return PackagePermissionsAction();
  1803. $context['look_for'] = array();
  1804. // Are we looking for a particular tree - normally an expansion?
  1805. if (!empty($_REQUEST['find']))
  1806. $context['look_for'][] = base64_decode($_REQUEST['find']);
  1807. // Only that tree?
  1808. $context['only_find'] = isset($_GET['xml']) && !empty($_REQUEST['onlyfind']) ? $_REQUEST['onlyfind'] : '';
  1809. if ($context['only_find'])
  1810. $context['look_for'][] = $context['only_find'];
  1811. // Have we got a load of back-catalogue trees to expand from a submit etc?
  1812. if (!empty($_GET['back_look']))
  1813. {
  1814. $potententialTrees = unserialize(base64_decode($_GET['back_look']));
  1815. foreach ($potententialTrees as $tree)
  1816. $context['look_for'][] = $tree;
  1817. }
  1818. // ... maybe posted?
  1819. if (!empty($_POST['back_look']))
  1820. $context['only_find'] = array_merge($context['only_find'], $_POST['back_look']);
  1821. $context['back_look_data'] = base64_encode(serialize(array_slice($context['look_for'], 0, 15)));
  1822. // Are we finding more files than first thought?
  1823. $context['file_offset'] = !empty($_REQUEST['fileoffset']) ? (int) $_REQUEST['fileoffset'] : 0;
  1824. // Don't list more than this many files in a directory.
  1825. $context['file_limit'] = 150;
  1826. // How many levels shall we show?
  1827. $context['default_level'] = empty($context['only_find']) ? 2 : 25;
  1828. // This will be used if we end up catching XML data.
  1829. $context['xml_data'] = array(
  1830. 'roots' => array(
  1831. 'identifier' => 'root',
  1832. 'children' => array(
  1833. array(
  1834. 'value' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
  1835. ),
  1836. ),
  1837. ),
  1838. 'folders' => array(
  1839. 'identifier' => 'folder',
  1840. 'children' => array(),
  1841. ),
  1842. );
  1843. foreach ($context['file_tree'] as $path => $data)
  1844. {
  1845. // Run this directory.
  1846. if (file_exists($path) && (empty($context['only_find']) || substr($context['only_find'], 0, strlen($path)) == $path))
  1847. {
  1848. // Get the first level down only.
  1849. fetchPerms__recursive($path, $context['file_tree'][$path], 1);
  1850. $context['file_tree'][$path]['perms'] = array(
  1851. 'chmod' => @is_writable($path),
  1852. 'perms' => @fileperms($path),
  1853. );
  1854. }
  1855. else
  1856. unset($context['file_tree'][$path]);
  1857. }
  1858. // Is this actually xml?
  1859. if (isset($_GET['xml']))
  1860. {
  1861. loadTemplate('Xml');
  1862. $context['sub_template'] = 'generic_xml';
  1863. $context['template_layers'] = array();
  1864. }
  1865. }
  1866. function fetchPerms__recursive($path, &$data, $level)
  1867. {
  1868. global $context;
  1869. $isLikelyPath = false;
  1870. foreach ($context['look_for'] as $possiblePath)
  1871. if (substr($possiblePath, 0, strlen($path)) == $path)
  1872. $isLikelyPath = true;
  1873. // Is this where we stop?
  1874. if (isset($_GET['xml']) && !empty($context['look_for']) && !$isLikelyPath)
  1875. return;
  1876. elseif ($level > $context['default_level'] && !$isLikelyPath)
  1877. return;
  1878. // Are we actually interested in saving this data?
  1879. $save_data = empty($context['only_find']) || $context['only_find'] == $path;
  1880. // @todo Shouldn't happen - but better error message?
  1881. if (!is_dir($path))
  1882. fatal_lang_error('no_access', false);
  1883. // This is where we put stuff we've found for sorting.
  1884. $foundData = array(
  1885. 'files' => array(),
  1886. 'folders' => array(),
  1887. );
  1888. $dh = opendir($path);
  1889. while ($entry = readdir($dh))
  1890. {
  1891. // Some kind of file?
  1892. if (is_file($path . '/' . $entry))
  1893. {
  1894. // Are we listing PHP files in this directory?
  1895. if ($save_data && !empty($data['list_contents']) && substr($entry, -4) == '.php')
  1896. $foundData['files'][$entry] = true;
  1897. // A file we were looking for.
  1898. elseif ($save_data && isset($data['contents'][$entry]))
  1899. $foundData['files'][$entry] = true;
  1900. }
  1901. // It's a directory - we're interested one way or another, probably...
  1902. elseif ($entry != '.' && $entry != '..')
  1903. {
  1904. // Going further?
  1905. if ((!empty($data['type']) && $data['type'] == 'dir_recursive') || (isset($data['contents'][$entry]) && (!empty($data['contents'][$entry]['list_contents']) || (!empty($data['contents'][$entry]['type']) && $data['contents'][$entry]['type'] == 'dir_recursive'))))
  1906. {
  1907. if (!isset($data['contents'][$entry]))
  1908. $foundData['folders'][$entry] = 'dir_recursive';
  1909. else
  1910. $foundData['folders'][$entry] = true;
  1911. // If this wasn't expected inherit the recusiveness...
  1912. if (!isset($data['contents'][$entry]))
  1913. // We need to do this as we will be going all recursive.
  1914. $data['contents'][$entry] = array(
  1915. 'type' => 'dir_recursive',
  1916. );
  1917. // Actually do the recursive stuff...
  1918. fetchPerms__recursive($path . '/' . $entry, $data['contents'][$entry], $level + 1);
  1919. }
  1920. // Maybe it is a folder we are not descending into.
  1921. elseif (isset($data['contents'][$entry]))
  1922. $foundData['folders'][$entry] = true;
  1923. // Otherwise we stop here.
  1924. }
  1925. }
  1926. closedir($dh);
  1927. // Nothing to see here?
  1928. if (!$save_data)
  1929. return;
  1930. // Now actually add the data, starting with the folders.
  1931. ksort($foundData['folders']);
  1932. foreach ($foundData['folders'] as $folder => $type)
  1933. {
  1934. $additional_data = array(
  1935. 'perms' => array(
  1936. 'chmod' => @is_writable($path . '/' . $folder),
  1937. 'perms' => @fileperms($path . '/' . $folder),
  1938. ),
  1939. );
  1940. if ($type !== true)
  1941. $additional_data['type'] = $type;
  1942. // If there's an offset ignore any folders in XML mode.
  1943. if (isset($_GET['xml']) && $context['file_offset'] == 0)
  1944. {
  1945. $context['xml_data']['folders']['children'][] = array(
  1946. 'attributes' => array(
  1947. 'writable' => $additional_data['perms']['chmod'] ? 1 : 0,
  1948. 'permissions' => substr(sprintf('%o', $additional_data['perms']['perms']), -4),
  1949. 'folder' => 1,
  1950. 'path' => $context['only_find'],
  1951. 'level' => $level,
  1952. 'more' => 0,
  1953. 'offset' => $context['file_offset'],
  1954. 'my_ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find'] . '/' . $folder),
  1955. 'ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
  1956. ),
  1957. 'value' => $folder,
  1958. );
  1959. }
  1960. elseif (!isset($_GET['xml']))
  1961. {
  1962. if (isset($data['contents'][$folder]))
  1963. $data['contents'][$folder] = array_merge($data['contents'][$folder], $additional_data);
  1964. else
  1965. $data['contents'][$folder] = $additional_data;
  1966. }
  1967. }
  1968. // Now we want to do a similar thing with files.
  1969. ksort($foundData['files']);
  1970. $counter = -1;
  1971. foreach ($foundData['files'] as $file => $dummy)
  1972. {
  1973. $counter++;
  1974. // Have we reached our offset?
  1975. if ($context['file_offset'] > $counter)
  1976. continue;
  1977. // Gone too far?
  1978. if ($counter > ($context['file_offset'] + $context['file_limit']))
  1979. continue;
  1980. $additional_data = array(
  1981. 'perms' => array(
  1982. 'chmod' => @is_writable($path . '/' . $file),
  1983. 'perms' => @fileperms($path . '/' . $file),
  1984. ),
  1985. );
  1986. // XML?
  1987. if (isset($_GET['xml']))
  1988. {
  1989. $context['xml_data']['folders']['children'][] = array(
  1990. 'attributes' => array(
  1991. 'writable' => $additional_data['perms']['chmod'] ? 1 : 0,
  1992. 'permissions' => substr(sprintf('%o', $additional_data['perms']['perms']), -4),
  1993. 'folder' => 0,
  1994. 'path' => $context['only_find'],
  1995. 'level' => $level,
  1996. 'more' => $counter == ($context['file_offset'] + $context['file_limit']) ? 1 : 0,
  1997. 'offset' => $context['file_offset'],
  1998. 'my_ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find'] . '/' . $file),
  1999. 'ident' => preg_replace('~[^A-Za-z0-9_\-=:]~', ':-:', $context['only_find']),
  2000. ),
  2001. 'value' => $file,
  2002. );
  2003. }
  2004. elseif ($counter != ($context['file_offset'] + $context['file_limit']))
  2005. {
  2006. if (isset($data['contents'][$file]))
  2007. $data['contents'][$file] = array_merge($data['contents'][$file], $additional_data);
  2008. else
  2009. $data['contents'][$file] = $additional_data;
  2010. }
  2011. }
  2012. }
  2013. /**
  2014. * Actually action the permission changes they want.
  2015. */
  2016. function PackagePermissionsAction()
  2017. {
  2018. global $context, $txt, $time_start, $package_ftp;
  2019. umask(0);
  2020. $timeout_limit = 5;
  2021. $context['method'] = $_POST['method'] == 'individual' ? 'individual' : 'predefined';
  2022. $context['sub_template'] = 'action_permissions';
  2023. $context['page_title'] = $txt['package_file_perms_applying'];
  2024. $context['back_look_data'] = isset($_POST['back_look']) ? $_POST['back_look'] : array();
  2025. // Skipping use of FTP?
  2026. if (empty($package_ftp))
  2027. $context['skip_ftp'] = true;
  2028. // We'll start off in a good place, security. Make sure that if we're dealing with individual files that they seem in the right place.
  2029. if ($context['method'] == 'individual')
  2030. {
  2031. // Only these path roots are legal.
  2032. $legal_roots = array_keys($context['file_tree']);
  2033. $context['custom_value'] = (int) $_POST['custom_value'];
  2034. // Continuing?
  2035. if (isset($_POST['toProcess']))
  2036. $_POST['permStatus'] = unserialize(base64_decode($_POST['toProcess']));
  2037. if (isset($_POST['permStatus']))
  2038. {
  2039. $context['to_process'] = array();
  2040. $validate_custom = false;
  2041. foreach ($_POST['permStatus'] as $path => $status)
  2042. {
  2043. // Nothing to see here?
  2044. if ($status == 'no_change')
  2045. continue;
  2046. $legal = false;
  2047. foreach ($legal_roots as $root)
  2048. if (substr($path, 0, strlen($root)) == $root)
  2049. $legal = true;
  2050. if (!$legal)
  2051. continue;
  2052. // Check it exists.
  2053. if (!file_exists($path))
  2054. continue;
  2055. if ($status == 'custom')
  2056. $validate_custom = true;
  2057. // Now add it.
  2058. $context['to_process'][$path] = $status;
  2059. }
  2060. $context['total_items'] = isset($_POST['totalItems']) ? (int) $_POST['totalItems'] : count($context['to_process']);
  2061. // Make sure the chmod status is valid?
  2062. if ($validate_custom)
  2063. {
  2064. if (preg_match('~^[4567][4567][4567]$~', $context['custom_value']) == false)
  2065. fatal_error($txt['chmod_value_invalid']);
  2066. }
  2067. // Nothing to do?
  2068. if (empty($context['to_process']))
  2069. redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode(serialize($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
  2070. }
  2071. // Should never get here,
  2072. else
  2073. fatal_lang_error('no_access', false);
  2074. // Setup the custom value.
  2075. $custom_value = octdec('0' . $context['custom_value']);
  2076. // Start processing items.
  2077. foreach ($context['to_process'] as $path => $status)
  2078. {
  2079. if (in_array($status, array('execute', 'writable', 'read')))
  2080. package_chmod($path, $status);
  2081. elseif ($status == 'custom' && !empty($custom_value))
  2082. {
  2083. // Use FTP if we have it.
  2084. if (!empty($package_ftp) && !empty($_SESSION['pack_ftp']))
  2085. {
  2086. $ftp_file = strtr($path, array($_SESSION['pack_ftp']['root'] => ''));
  2087. $package_ftp->chmod($ftp_file, $custom_value);
  2088. }
  2089. else
  2090. @chmod($path, $custom_value);
  2091. }
  2092. // This fish is fried...
  2093. unset($context['to_process'][$path]);
  2094. // See if we're out of time?
  2095. if (time() - array_sum(explode(' ', $time_start)) > $timeout_limit)
  2096. return false;
  2097. }
  2098. }
  2099. // If predefined this is a little different.
  2100. else
  2101. {
  2102. $context['predefined_type'] = isset($_POST['predefined']) ? $_POST['predefined'] : 'restricted';
  2103. $context['total_items'] = isset($_POST['totalItems']) ? (int) $_POST['totalItems'] : 0;
  2104. $context['directory_list'] = isset($_POST['dirList']) ? unserialize(base64_decode($_POST['dirList'])) : array();
  2105. $context['file_offset'] = isset($_POST['fileOffset']) ? (int) $_POST['fileOffset'] : 0;
  2106. // Haven't counted the items yet?
  2107. if (empty($context['total_items']))
  2108. {
  2109. function count_directories__recursive($dir)
  2110. {
  2111. global $context;
  2112. $count = 0;
  2113. $dh = @opendir($dir);
  2114. while ($entry = readdir($dh))
  2115. {
  2116. if ($entry != '.' && $entry != '..' && is_dir($dir . '/' . $entry))
  2117. {
  2118. $context['directory_list'][$dir . '/' . $entry] = 1;
  2119. $count++;
  2120. $count += count_directories__recursive($dir . '/' . $entry);
  2121. }
  2122. }
  2123. closedir($dh);
  2124. return $count;
  2125. }
  2126. foreach ($context['file_tree'] as $path => $data)
  2127. {
  2128. if (is_dir($path))
  2129. {
  2130. $context['directory_list'][$path] = 1;
  2131. $context['total_items'] += count_directories__recursive($path);
  2132. $context['total_items']++;
  2133. }
  2134. }
  2135. }
  2136. // Have we built up our list of special files?
  2137. if (!isset($_POST['specialFiles']) && $context['predefined_type'] != 'free')
  2138. {
  2139. $context['special_files'] = array();
  2140. function build_special_files__recursive($path, &$data)
  2141. {
  2142. global $context;
  2143. if (!empty($data['writable_on']))
  2144. if ($context['predefined_type'] == 'standard' || $data['writable_on'] == 'restrictive')
  2145. $context['special_files'][$path] = 1;
  2146. if (!empty($data['contents']))
  2147. foreach ($data['contents'] as $name => $contents)
  2148. build_special_files__recursive($path . '/' . $name, $contents);
  2149. }
  2150. foreach ($context['file_tree'] as $path => $data)
  2151. build_special_files__recursive($path, $data);
  2152. }
  2153. // Free doesn't need special files.
  2154. elseif ($context['predefined_type'] == 'free')
  2155. $context['special_files'] = array();
  2156. else
  2157. $context['special_files'] = unserialize(base64_decode($_POST['specialFiles']));
  2158. // Now we definitely know where we are, we need to go through again doing the chmod!
  2159. foreach ($context['directory_list'] as $path => $dummy)
  2160. {
  2161. // Do the contents of the directory first.
  2162. $dh = @opendir($path);
  2163. $file_count = 0;
  2164. $dont_chmod = false;
  2165. while ($entry = readdir($dh))
  2166. {
  2167. $file_count++;
  2168. // Actually process this file?
  2169. if (!$dont_chmod && !is_dir($path . '/' . $entry) && (empty($context['file_offset']) || $context['file_offset'] < $file_count))
  2170. {
  2171. $status = $context['predefined_type'] == 'free' || isset($context['special_files'][$path . '/' . $entry]) ? 'writable' : 'execute';
  2172. package_chmod($path . '/' . $entry, $status);
  2173. }
  2174. // See if we're out of time?
  2175. if (!$dont_chmod && time() - array_sum(explode(' ', $time_start)) > $timeout_limit)
  2176. {
  2177. $dont_chmod = true;
  2178. // Don't do this again.
  2179. $context['file_offset'] = $file_count;
  2180. }
  2181. }
  2182. closedir($dh);
  2183. // If this is set it means we timed out half way through.
  2184. if ($dont_chmod)
  2185. {
  2186. $context['total_files'] = $file_count;
  2187. return false;
  2188. }
  2189. // Do the actual directory.
  2190. $status = $context['predefined_type'] == 'free' || isset($context['special_files'][$path]) ? 'writable' : 'execute';
  2191. package_chmod($path, $status);
  2192. // We've finished the directory so no file offset, and no record.
  2193. $context['file_offset'] = 0;
  2194. unset($context['directory_list'][$path]);
  2195. // See if we're out of time?
  2196. if (time() - array_sum(explode(' ', $time_start)) > $timeout_limit)
  2197. return false;
  2198. }
  2199. }
  2200. // If we're here we are done!
  2201. redirectexit('action=admin;area=packages;sa=perms' . (!empty($context['back_look_data']) ? ';back_look=' . base64_encode(serialize($context['back_look_data'])) : '') . ';' . $context['session_var'] . '=' . $context['session_id']);
  2202. }
  2203. /**
  2204. * Test an FTP connection.
  2205. */
  2206. function PackageFTPTest()
  2207. {
  2208. global $context, $txt, $package_ftp;
  2209. checkSession('get');
  2210. // Try to make the FTP connection.
  2211. create_chmod_control(array(), array('force_find_error' => true));
  2212. // Deal with the template stuff.
  2213. loadTemplate('Xml');
  2214. $context['sub_template'] = 'generic_xml';
  2215. $context['template_layers'] = array();
  2216. // Define the return data, this is simple.
  2217. $context['xml_data'] = array(
  2218. 'results' => array(
  2219. 'identifier' => 'result',
  2220. 'children' => array(
  2221. array(
  2222. 'attributes' => array(
  2223. 'success' => !empty($package_ftp) ? 1 : 0,
  2224. ),
  2225. 'value' => !empty($package_ftp) ? $txt['package_ftp_test_success'] : (isset($context['package_ftp'], $context['package_ftp']['error']) ? $context['package_ftp']['error'] : $txt['package_ftp_test_failed']),
  2226. ),
  2227. ),
  2228. ),
  2229. );
  2230. }
  2231. ?>