Packages.php 92 KB

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